Imagine you are cooking & preparing a candlelight dinner on Valentine’s Day to surprise your beloved and you need herbs to put in your dish that only your Neighbour has it. Now you cannot go and get it cos you are busy cooking. LOL, I know I always put you in that spot.

How about if you get an assistant, who can get that for you.

Well terraform_remote_state is that assistant.

So let us understand how the above situation is related with what we are going to study today.

Suppose you are working on two different projects –

Project Alpha – Under this project, you write a code in the configuration files to generate Elastic IP(EIP). When you execute the code, the state file (.tfstate) gets created on S3 backend.  Ofcourse, this state file would have information of the generated EIP.

Project Beta – Now in a different Project i.e. Beta, you are writing code in configuration files to create a security group in AWS. However, you have been given task to whitelist the EIP that is generated from Project Alpha. It is not expected from you open the state file of Project Alpha and manually copy the EIP and paste it in Project Beta code. Reason is because EIP would be dynamic, and you would not want to hardcode EIP in your code.

This is where terraform_remote_state plays its role. Using it as data source, we can make it connect with the state file of Project Alpha and fetch us the EIP, to be used in Project Beta.

Let us do it practically

Project Alpha

First, we will create code to provide path to save state file on a Remote Backend i.e. S3

Then we will generate EIP and save it in Output variable.

Let’s run terraform state pull command to read the State File of Project Alpha

Project Beta

In this project, we will create Security Group, however, we will white list the EIP generated in Project Alpha by referencing to Alpha’s state file via data source terraform_remote_state.

First, we need define terraform_remote_state in the data source by providing the backend path of S3 bucket where Project Alpha State File is saved.

Below screenshot shows the code that we have written to create Security Group. We also see that we are fetching EIP details from State file of Project Alpha

Let us run terraform plan to see if the EIP in Project Beta got successfully fetched from State file of Project Alpha

Hope you enjoyed learning today.