Using list and lookup in terraform HCL

Posted under tech On By xpk

Terraform delivers consistent build and save a lot of time from clicking and scrolling. But when the resources, in this case ec2 resources are slightly different, it may be necessary to create a tf config for every instance. That defeats the purpose of automation.

By storing the differences in a list and use the lookup function to extract the values, I’m able to write the following tf config with little redundant code.

variable "FixInst" {
  default = [
  {
    inst_name = "Fix-01-A"
    subnet = "subnet-123"
    keypair = "uat"
  },
  {
    inst_name = "Fix-01-B"
    subnet = "subnet-234"
    keypair = "uat"
  },
  {
    inst_name = "Fix-01-C"
    subnet = "subnet-345"
    keypair = "Prod"
  },
  {
    inst_name = "Fix-01-D"
    subnet = "subnet-456"
    keypair = "Prod"
  }
]
}

resource "aws_instance" "ec2Fix" {
  count = "${length(var.FixInst)}"
  ami           = "ami-987"
  tags          = "${merge(var.globalTags, map("Name",lookup(var.FixInst[count.index], "inst_name")))}"
  instance_type = "t2.large"

  root_block_device {
    volume_size = "25"
    volume_type = "gp2"
  }

  ebs_block_device {
    device_name = "/dev/xvdo"
    volume_type = "gp2"
    volume_size = 100
    encrypted = true
  }

  subnet_id              = "${lookup(var.FixInst[count.index],"subnet")}"
  key_name               = "${lookup(var.FixInst[count.index],"keypair")}"
  vpc_security_group_ids = ["sg-123","sg-234","sg-345"]
}

 624 total views,  2 views today

Leave a comment

Your email address will not be published. Required fields are marked *