Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

generate user_data including "IP Address" while creating ec2 instance using terraform

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

like image 808
devnull Avatar asked Jun 20 '26 01:06

devnull


1 Answers

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.

like image 197
Adil B Avatar answered Jun 24 '26 03:06

Adil B



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!