0
votes

Terraform v0.12.6, provider.aws v2.23.0

Am trying to create two aws instances using the new for_each construct. Don't actually think this is an aws provider issue, more a terraform/for_each/provisioner issues.

Worked as advertised until I tried to add a local-exec provisioning step. Don't know how to modify the local-exec example to work with the for.each variable. Am getting a terraform error about a cycle.

locals {
  instances = {
    s1 = {
      private_ip = "192.168.47.191"
    },
    s2 = {
      private_ip = "192.168.47.192"
    },
  }
}

provider "aws" {
  profile    = "default"
  region     = "us-east-1"
}

resource "aws_instance" "example" {
  for_each = local.instances

  ami           = "ami-032138b8a0ee244c9"
  instance_type = "t2.micro"

  availability_zone = "us-east-1c"

  private_ip = each.value["private_ip"]

  ebs_block_device {
    device_name = "/dev/sda1"
    volume_size = 2
  }

  provisioner "local-exec" {
    command = "echo ${aws_instance.example[each.key].public_ip} >> ip_address.txt"
  }
}

But get this error.

./terraform apply

Error: Cycle: aws_instance.example["s2"], aws_instance.example["s1"]

Should the for_each each.key variable be expected to work in a provisioning step? There are other ways to get the public_ip later, by either using the testate file or querying aws given the instance ids, but accessing the resource variables within the local-exec provisioning would seem to come in handy in many ways.

1

1 Answers

1
votes

Try using the self variable:

  provisioner "local-exec" {
    command = "echo ${self.public_ip} >> ip_address.txt"
  }

Note to readers that resource-level for_each is a relatively new feature in Terraform and requires version >=0.12.6.