使用terraform

时间:2019-04-13 06:06:37

标签: amazon-web-services amazon-ec2 terraform user-data terraform-provider-aws

我正在尝试使用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生成文件

1 个答案:

答案 0 :(得分:0)

在用户数据脚本中使用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