Retrieving resource ids with Terraform remote state

Occasional Contributor

So, if you want to retreive a rersource id of an Azure resource and share it between configurations when working with Terraform. 

 

To explain that, we can refer to this example : 

 

MohamedT_Trabelsi_1-1654882983187.png

 

Here, we will deploy via two pipeline to simplify this example  : 

 

-Infrastructure

---Networking

##Create the resource group
##Create Virtual Network
##Create Subnet Workload
##Create "AzureFirewallSubnet"
---Firewall
##Create the Firewall  Policy

##Create Firewall

 

NOTE THAT, we have two different state file : 

 

When you’re using multiple folders, you simply cannot have a single state file. 
You can have a single location where you store the different state files.

 

-- One for the networking deployment 

MohamedT_Trabelsi_0-1654886666754.png

 

 

-- Second for the firewall deployment 

MohamedT_Trabelsi_3-1654884159651.png

 

So, the first step is to deploy the network part :  ( state file is "networking.tfstate" )

 

MohamedT_Trabelsi_4-1654884352664.png

and outputs ,  that we will need it later 

 

MohamedT_Trabelsi_5-1654884423614.png

 

Here is the network deployment 

MohamedT_Trabelsi_2-1654887502708.png

 

 

 

After that, we need to create the firewall and here we need to use the RG, location and the "AzureFirewallSubnet" of the network folder. 

 

How ? 

 

NOTE :   To get the outputs of the first folder and make them available for the second folder, you can use terraform_remote_state (https://www.terraform.io/language/state/remote). The best practice is to use a data source to get the data you need, but that does require you to provide some info in the second folder. 

 

We need to add the configuration of the terraform_remote_state in the firewall.tf who is located at the folder Firewall 

 

MohamedT_Trabelsi_0-1654886155691.png

 

Then, we can refer for the resources from the folder Netwoking with the outputs of the networking part  : 

 

- RG :  

Output from netwokring 

MohamedT_Trabelsi_2-1654886847002.png

firewall.tf file 

MohamedT_Trabelsi_1-1654886179661.png

- location : 

Output from netwokring 

MohamedT_Trabelsi_3-1654886883262.png

firewall.tf file 

MohamedT_Trabelsi_2-1654886192061.png

- Subnet Firewall : 

Output from netwokring 

MohamedT_Trabelsi_4-1654886961938.png

firewall.tf file 

MohamedT_Trabelsi_3-1654886212080.png

-------------*********-------------

ALL the file firewall.tf : 

MohamedT_Trabelsi_4-1654886284673.png

 

We can see the deployment now : 

MohamedT_Trabelsi_1-1654887180753.png

 

 

 

I tried as much as possible to simplify things  :smile: :stareyes:

 

 

0 Replies