Molenpad
Molenpad

Reputation: 1044

Concat strings and list variable in terraform

I need to pass a list of cidr blocks to a module in the form of ["0.0.0.0/23","0.0.0.1/23",...] etc.

I have two cidr blocks which I'm getting from a subnet data source, which I can reference as an example as:

cidr_blocks = [data.aws_subnet.subnet1.id,data.aws_subnet.subnet2.id]

I also have a variable, depending on the environment, has a specific list of cidr_blocks to pass in, set as an example:

custom_cidrs = [""0.0.0.0/23","0.0.0.1/23","0.0.0.2/23"]

What I want to do is in the module, concat all these cidrs together to create one list. I have tried a few different things, including concat and list(). I just can't get the syntax right.

For some contexts, they'll be no custom cidr blocks to set, only the subnet cidrs, so in that instance my custom cidrs will be set to:

custom_cidrs = []

Any help on how to concat the two outputs and the custom list into one will be appreciated.

I'm thinking I may have to create a list from the two outputs first, then concat the two lists together, but not entirely sure. Can I do it in one command?

I am using terraform version 0.12.28

Upvotes: 6

Views: 10970

Answers (1)

ekeeling
ekeeling

Reputation: 381

If I'm understanding you correctly, you would like to concatenate the CIDR blocks from your data sources and the custom list. Here is an example of how you can do that.

        variable "custom_cidrs" {
          default = [
            "0.0.0.0/23",
            "0.0.0.1/23",
            "0.0.0.2/22"
          ]
        }
        
        data "aws_subnet" "private" {
          id = "subnet-000000qq"
        }
        
        data "aws_subnet" "public" {
          id = "subnet-000001qq"
        }
        
        locals {
          all_cidrs = setunion(
            [data.aws_subnet.private.cidr_block, data.aws_subnet.public.cidr_block],
            var.custom_cidrs
          )
        }
        
        output "all_cidrs" {
          value = local.all_cidrs
        }

The output looks like this.

        [PS][7.0.2] tst > terraform apply --auto-approve -var "region=us-west-2"
        data.aws_subnet.public: Refreshing state...
        data.aws_subnet.private: Refreshing state...
        
        Apply complete! Resources: 0 added, 0 changed, 0 destroyed.
        
        Outputs:
        
        all_cidrs = [
          "0.0.0.0/23",    # Custom CIDR block from var
          "0.0.0.1/23",    # Custom CIDR block from var
          "0.0.0.2/22",    # Custom CIDR block from var
          "xxx.xx.x.x/24", # Private subnet CIDR block
          "xxx.xx.x.x/24", # Public subnet CIDR block
        ]

To reference the concatenated list, reference local.all_cidrs.

Upvotes: 10

Related Questions