简体   繁体   English

使用 terraform 创建 ec2 实例时生成包含“IP 地址”的用户数据

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

I am trying to spin 2 ec2 instances using terraform .我正在尝试使用terraform旋转 2 个ec2实例。 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 .template_file中,我想做的就是使用user_data生成一个配置文件,其中包含两个实例的IP Address ,但这失败了Cycle Error

Is there any way to get the file to generate with IP Address while the ec2 instances are coming up有什么方法可以在ec2实例出现时使用IP Address生成文件

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. 在userdata脚本中使用AWS Instance Metadata端点 ,以获取每个实例的IP地址并将其放入配置文件中。 Here is a Powershell example of a userdata script: 这是Userdata脚本的Powershell示例:

<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. 如果需要,您还可以通过这种方式获取实例的public-ipv4

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.通过组合各种信息,您可以使用resource "aws_launch_template"块的user_data参数来调用 shell,它本身可能会调用返回一个典型的特殊元数据端点。 For the private IP, it would be:对于私人 IP,它将是:
curl http://169.254.169.254/latest/meta-data/local-ipv4

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM