Iterate over multiple state file to get a list of strings in terraform

374 views Asked by At

I am new bee and have an issue while retrieving the value from state file. At present what I want is to retrieve the value of vpc_id from multiple state file and create a list of strings out of it so that it can be passed to a resource.

Input

locals.tf:


    locals {
      aws_regions = toset(["eu-west-1", "eu-central-1", "us-east-2", "us-west-2", "ap-south-1", "ap-southeast-1"])
      terraform_state_file = "eu-west-1/terraform.tfstate"
    #  terragrunt_state_file = "${each.value}/vpc-layout/terragrunt.tfstate"
    
    }

state.tf


    data "terraform_remote_state" "plt-network-state" {
      backend = "s3"
      for_each = toset(local.aws_regions)
      config = {
        bucket = "tfstate-316899010651"
        key    = each.value == "eu-west-1" ? local.terraform_state_file : "${each.value}/vpc-layout/terragrunt.tfstate"
        region = "eu-west-1"
      }
    }

Now I want to iterate over the state file received to get the value of vpc_id from the same:

terraform state file:


    {
      "version": 4,
      "terraform_version": "1.0.5",
      "serial": 1117,
      "lineage": "5a401d1e-ec22-5ae0-5170-aa5b484f89cb",
      "outputs": {
        "dev_vpc_id": {
          "value": "xxx",
          "type": "string"
        },
        "acc_vpc_id": {
          "value": "yyy",
          "type": "string"
        },

terragrunt state file


    {
      "version": 4,
      "terraform_version": "0.13.5",
      "serial": 13,
      "lineage": "6a1eb7fb-82c5-b70a-c8ec-8734102fafdd",
      "outputs": {
        "vpcs_all": {
          "value": [
            {
              "environment": "acceptance",
              "id": "xxx"
            },
            {
              "environment": "development",
              "id": "yyy"
            },
            {
              "environment": "production",
              "id": "zzz"
            }
          ]
        }
      }
    }

I want the list of all envs into a list of strings so that it can be passed to below resource:

Something like


    locals {
        all_vpc_ids = [
        data.terraform_remote_state.plt-network-state[each.key].outputs != "" ? data.terraform_remote_state.plt-network-state[each.key].outputs.development_vpc_id :  [for v in data.terraform_remote_state.plt-network-state[each.key].outputs.vpcs_all[*] : format("%q", v.id) if v.environment == "development" ],
      ]
    
    }

This needs to be passed to:


    resource "aws_route53_zone" "demo" {
      comment = "xyz.com"
      name    = "xyz.com"
      dynamic "vpc" {
        for_each = local.all_vpc_ids
        content {
          vpc_id = vpc.value
        }
      }
      tags = {}
    }

Any advice or help is much appreciated !!! Thanks in advance.

0

There are 0 answers