2
votes

I am trying to spin 2 ec2 instances using terraform. Something like this

resource "aws_instance" "example" {
  count                       = "${var.number_of_instances}"
  ami                         = "${var.ami_name}"
  associate_public_ip_address = "${var.associate_public_ip_address}"
  instance_type               = "${var.instance_type}"
  key_name                    = "${var.keyname}"
  subnet_id                   = "${element(var.subnet_ids, count.index)}"
  user_data                   = "${element(data.template_file.example.*.rendered, count.index)}"
  vpc_security_group_ids      = ["${aws_security_group.example.id}","${var.extra_security_group_id}"]
  root_block_device {
    volume_size = "${var.root_volume_size}"
    volume_type = "${var.root_volume_type}"
    iops        = "${var.root_volume_iops}"
  }
  tags {
    Name      = "${var.prefix}${var.name}${format("%02d", count.index + 1)}"
  }
}

In template_file all I am trying to do is to generate a config file with IP Address of both the instances using user_data but this fails saying Cycle Error.

Is there any way to get the file to generate with IP Address while the ec2 instances are coming up

1
Show us the template_file code - victor m
What you have here is a "chicken or egg" problem: user_data must be fixed when the instance is first created, and at that point the instance doesn't have an IP address yet (unless you assign it a static one). To solve this, you'll need to introduce something new. For example, you could create some DNS records at a predictable name which your instances can then read to find one another after boot, though you'd need to design it to be resilient to there being a delay after the instance is created before the DNS record becomes available. - Martin Atkins
@MartinAtkins I actually thought about it and tried the external DNSName thing. But I have some stupid logic here in my company where Security won't allow connecting to external DNSName on a port anything else 443. - devnull

1 Answers

1
votes

Make use of the AWS Instance Metadata endpoint in your userdata script to get each instance's IP address and put it into a config file. Here is a Powershell example of a userdata script:

<powershell>
$HostIp = (Invoke-RestMethod -URI 'http://169.254.169.254/latest/meta-data/local-ipv4' -UseBasicParsing)
Add-Content "C:\installer\config.txt" "HostIp:$HostIp"
</powershell>

You can also get the instance's public-ipv4 in this manner if that's desired instead.