amazon-web-servicesterraformaws-cloudformationiaas

Terraform - list of string required (cidr_blocks in AWS)


In Terraform I'm having problems inputting a list that will be stored in a variable.

While executing terraform plan, I get asked for a cidr_blocks (which should be a list of strings).

I tried to type several "forms" that might represent a list of strings but always get an error.

Examples:

1st attempt:

$terraform plan
...
var.monitoring_access_ips_mysystem
  Enter a value: "10.180.1.0/24", "10.180.2.0/25", "10.180.3.0/23"

2nd attempt:

var.monitoring_access_ips_mysystem
  Enter a value: ["10.180.1.0/24", "10.180.2.0/25", "10.180.3.0/23"]

3rd attempt:

var.monitoring_access_ips_mysystem
  Enter a value: '["10.180.1.0/24", "10.180.2.0/25", "10.180.3.0/23"]'

4th attempt:

var.monitoring_access_ips_mysystem
  Enter a value: "["10.180.1.0/24", "10.180.2.0/25", "10.180.3.0/23"]"

5th attempt:

var.monitoring_access_ips_mysystem
  Enter a value: "10.180.1.0/24"

For any attempt, the error is always the same:

Error: Incorrect attribute value type

  on ecs/security_group.tf line 10, in resource "aws_security_group" "ecs-cluster-sg":
  10:     cidr_blocks = var.monitoring_access_ips_mysystem

Inappropriate value for attribute "cidr_blocks": list of string required.

And the ecs/security_group.tf file looks like this ecs/security_group.tf:

resource "aws_security_group" "ecs-cluster-sg" {
  name   = "${var.app_name}-cluster-sg"
  vpc_id = var.vpc_id

  ingress {
    description = "Ingress from monitoring VPC on custom port"
    from_port   = 80
    to_port     = 80
    protocol    = "tcp"
    cidr_blocks = var.monitoring_access_ips_mysystem
  }
  ...

What valid format can I type/pass the IPs so that it is accepted as a 'list of strings'?


Solution

  • UI input (what you see when you are prompted after running a Terraform command without some variables defined) only supports string values so if you want to pass something that isn't a string then you will need to do so non interactively. This can be one of any of the listed options in the variables documentation. These are:

    • In a Terraform Cloud workspace.
    • Individually, with the -var command line option.
    • In variable definitions (.tfvars) files, either specified on the command line or automatically loaded.
    • As environment variables.

    In your case you could run a plan with the following command:

    terraform plan -var='monitoring_access_ips_mysystem=["10.180.1.0/24", "10.180.2.0/25", "10.180.3.0/23"]'
    

    Unless this is something that is likely to change on each run of Terraform then normally that should instead be put in a terraform.tfvars file like this:

    monitoring_access_ips_mysystem = [
      "10.180.1.0/24",
      "10.180.2.0/25",
      "10.180.3.0/23",
    ]