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

问题描述 投票:1回答:1

我试图使用ec2旋转2个terraform实例。像这样的东西

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)}"
  }
}

template_file我想要做的就是使用IP Address生成两个实例的user_data的配置文件,但这无法说Cycle Error

IP Address实例出现时,有没有办法让ec2生成文件

amazon-web-services amazon-ec2 terraform user-data terraform-provider-aws
1个回答
0
投票

在userdata脚本中使用AWS Instance Metadata endpoint获取每个实例的IP地址并将其放入配置文件中。以下是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>

如果需要,您也可以以这种方式获取实例的public-ipv4

© www.soinside.com 2019 - 2024. All rights reserved.