Reputation: 161
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
Upvotes: 3
Views: 1817
Reputation: 2080
By combining the various information, you can use user_data
argument of the resource "aws_launch_template"
block, to call a shell, itself may call in return a typical special metadata endpoint. For the private IP, it would be:
curl http://169.254.169.254/latest/meta-data/local-ipv4
Upvotes: 1
Reputation: 16806
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.
Upvotes: 2