Menu
blog.headdesk.me
blog.headdesk.me

Using list and lookup in terraform HCL

Posted on 2017/12/062017/12/06

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"]
}

Loading

Leave a Reply Cancel reply

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

Full text search

Recent Posts

  • Generate secure password
  • AWS Compute Savings Plans
  • AWS Zonal Shift
  • Coffee break…
  • Prevent private key from being committed to git
  • aws (14)
  • coffee (2)
  • headfi (1)
  • linux (9)
  • others (61)
  • security (2)
  • tech (41)
  • terraform (3)
  • wordpress (2)

Loading

apache aws awscli azure backup boot cloud coffee docker ec2 EL8 ElasticBeanstalk espresso featured git kernel lelit linux lvm meltdown MFA nat gateway php power proliant python rdp Redhat RHEL rpm Ryzen scp security smartarray smart switch snapshot spectre tech terraform ubuntu ubuntu upgrade vpn windows wordpress workspace

©2026 blog.headdesk.me | Powered by SuperbThemes