运行 创建后所有 EC2 实例上的 local-exec 供应商

Running local-exec provisioner on all EC2 instances after creation

我目前有一个用于在 AWS 上创建 EC2 实例的 Terraform 文件,如下所示:

resource "aws_instance" "influxdata" {
  count      = "${var.ec2-count-influx-data}"

  ami           = "${module.amis.rhel73_id}"
  instance_type = "${var.ec2-type-influx-data}"

  vpc_security_group_ids = ["${var.sg-ids}"]
  subnet_id              = "${element(module.infra.subnet,count.index)}"
  key_name               = "${var.KeyName}"
  iam_instance_profile   = "Custom-role"

  tags {
    Name               = "influx-data-node"
    ASV                = "${module.infra.ASV}"
    CMDBEnvironment    = "${module.infra.CMDBEnvironment}"
    OwnerContact       = "${module.infra.OwnerContact}"
    custodian_downtime = "off"
    OwnerEid           = "${var.OwnerEid}"
  }


  ebs_block_device {
    device_name = "/dev/sdg"
    volume_size = 500
    volume_type = "io1"
    iops = 2000
    encrypted = true
    delete_on_termination = true
  }

  user_data = "${file("terraform/attach_ebs.sh")}"

  connection {
    private_key = "${file("/Users/usr111/Downloads/usr111_CD.pem")}"
    user        = "ec2-user"
  }

  provisioner "remote-exec" {
    inline = ["echo just checking for ssh. ttyl. bye."]
  }

  provisioner "local-exec" {
    command = <<EOF
ansible-playbook base-data.yml --key-file=/Users/usr111/Downloads/usr111_CD.pem --user=ec2-user -b -i "${self.private_ip},"
    EOF
  }
}

resource "aws_route53_record" "influx-data-route" {

  count = "${var.ec2-count-influx-data}"
  zone_id = "${var.r53-zone}"
  name = "influx-data-0${count.index}"
  type = "A"
  ttl = "300"
  // matches up record N to instance N
  records = ["${element(aws_instance.influxdata.*.private_ip, count.index)}"]
}

resource "local_file" "inventory-meta" {
  filename = "inventory"

  content = <<-EOF
[meta]
${join("\n",aws_instance.influxmeta.*.private_ip)}

[data]
${join("\n",aws_instance.influxdata.*.private_ip)}
  EOF
}

我正在努力弄清楚的是 运行 在我创建清单文件后

  provisioner "local-exec" {
    command = <<EOF
ansible-playbook base-data.yml --key-file=/Users/usr111/Downloads/usr111_CD.pem --user=ec2-user -b -i "${self.private_ip},"
    EOF
  }

现在我正在将 IP 传递到 Ansible,但我想传递清单文件,该文件仅在 Terraform 提供所有实例后创建。

因为您使用的是 AWS,也许您可​​以尝试使用 Dynamic Inventory 脚本,您的配置器可能如下所示:

provisioner "local-exec" {
   command = "ansible-playbook -i ec2.py playbook.yml --limit ${self.public_ip}" }

在您的剧本中,您将需要等待 SSH 可用,因为 Ansible 正在建立连接而不是 Terraform。

- name: wait for ssh
  hosts: localhost
  gather_facts: no

  tasks:
    - local_action: wait_for port=22 host="{{ ip }}" search_regex=OpenSSH delay=10

所以命令应该是这样的:

provisioner "local-exec" {
   command = "ansible-playbook -i ec2.py playbook.yml --limit ${self.public_ip}" --extra-vars 'ip=${self.public_ip}'}

您也可以使用 "File Provisioner" 将 playbook 复制到主机,安装 ansible 并使用 "remote-exec" 在本地 运行 playbook,但这取决于您。