Bootstrap FreeKB - Terraform - Get output variables from terraform.tfstate using terraform_remote_state
Terraform - Get output variables from terraform.tfstate using terraform_remote_state

Updated:   |  Terraform articles

Let's say you have the following files on your Terraform server where you have two (or more) directories, foo and bar in this example.

├── required_providers.tf
├── foo (directory)
│   ├── data.tf
│   ├── outputs.tf
│   ├── provider.tf
│   ├── resources.tf
├── bar (directory)
│   ├── data.tf
│   ├── outputs.tf
│   ├── provider.tf
│   ├── remote_state.tf
│   ├── resources.tf

 

There will certainly be a situation where resources.tf in directory "a" needs an output variable from directory "b", and vice versa. This is where terraform_remote_state comes into play. Let's say the foo directory defines an output variable. Perhaps data.tf in the foo module contain the following to get the JSON for an Amazon Web Services (AWS) Security Group.

data "aws_security_group" "default-security-group" {
  filter {
    name = "group-name"
    values = ["default"]
  }
  filter {
    name = "tag:Name"
    values = ["default"]
  }
}

 

And outputs.tf in the foo directory outputs the JSON.

output "default_security_group" {
  value = data.aws_security_group.default-security-group
}

 

The terraform refresh command should update the terraform.tfstate file in the "foo" directory to contain the "default-security-group-id" output.

{
  "outputs": {
    "default-security-group-id": {
      "value": "sg-1234567891234",
      "type": "string"
    }
  }
}

 

Now let's say you want to use "default-security-group-id" in the "bar" directory. remote_state.tf in the bar directory would have something like this to read the terraform.tfstate file in the "foo" directory.

data "terraform_remote_state" "foo" {
  backend = "local"
  config = {
    path = "/path/to/foo/terraform.tfstate"
  }
}

 

And here is an example of how the "default-security-group-id" output could be used in the "bar" module.

resource "aws_lb" "my-application-load-balancer" {
  security_groups = [data.terraform_remote_state.foo.outputs.default-security-group-id]
}

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter a7b3bb in the box below so that we can be sure you are a human.