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

facebookShare on Facebook
TwitterTweet

Leave a Reply Cancel reply

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

Full text search

Recent Posts

  • Dumping AWS Organization tree
  • Free is the most expensive
  • Terraform conditional resource and blocks
  • Upgrade Ubuntu 16.04 to latest release
  • Inspect and control network traffic on AWS
  • aws (8)
  • coffee (1)
  • headfi (1)
  • linux (7)
  • others (55)
  • security (2)
  • tech (36)
  • wordpress (2)

apache aws awscli azure backup cloud coffee coreos distributed filesystem docker ec2 EL8 elasticcache etckeeper featured heartbleed kernel linux mail meltdown mysql php pine python rdp rds Redhat Red Hat RHEL RHEL7 rpm Ryzen snapshot spectre SSL systemd tech terraform ubuntu ubuntu upgrade vector vpn wordpress xtreemfs yum

©2022 blog.headdesk.me | Powered by SuperbThemes & WordPress