【问题标题】:generate user_data including "IP Address" while creating ec2 instance using terraform在使用 terraform 创建 ec2 实例时生成包含“IP 地址”的 user_data
【发布时间】:2019-09-03 20:44:44
【问题描述】:

我正在尝试使用 terraform 旋转 2 个 ec2 实例。像这样的

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

有什么方法可以在 ec2 实例出现时使用 IP Address 生成文件

【问题讨论】:

  • 向我们展示 template_file 代码
  • 你这里有一个“鸡还是蛋”的问题:user_data 必须在第一次创建实例时修复,此时实例还没有 IP 地址(除非你分配它是静态的)。为了解决这个问题,你需要引入一些新的东西。例如,您可以以可预测的名称创建一些 DNS 记录,然后您的实例可以在启动后读取这些记录以找到另一个记录,但您需要将其设计为能够应对在 DNS 之前创建实例后存在延迟的情况记录可用。
  • @MartinAtkins 我真的考虑过并尝试了外部DNSName 的东西。但是我的公司有一些愚蠢的逻辑,即安全性不允许在port 上连接到外部DNSName 任何其他443

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


【解决方案1】:

在您的用户数据脚本中使用AWS Instance Metadata endpoint 来获取每个实例的IP 地址并将其放入配置文件中。这是一个用户数据脚本的 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

【讨论】:

    猜你喜欢
    • 2021-04-19
    • 1970-01-01
    • 2022-07-29
    • 1970-01-01
    • 1970-01-01
    • 2020-05-03
    • 2018-07-30
    • 2020-07-02
    • 1970-01-01
    相关资源
    最近更新 更多