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

  • Terraform and segregated permissions
  • LVM Compression and Deduplication
  • Edit gpg encrypted file with vim
  • Lelit Elizabeth PL92T Pressure Tuning
  • jq transformation
  • aws (8)
  • coffee (1)
  • headfi (1)
  • linux (6)
  • others (58)
  • security (2)
  • tech (36)
  • wordpress (2)

apache aws awscli azure backup clearlinux cloud coffee docker DOCP ec2 EL8 epyc espresso featured gpg jenkins kernel lelit linux lvm meltdown memory MFA mikrotik php python rdp Redhat RHEL roasting rpm Ryzen site-to-site snapshot spectre tech terraform tuning ubuntu ubuntu upgrade vim vpn wordpress xdotool

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