首页 > 解决方案 > 如何将 Terraform 配置器“local-exec”输出存储在局部变量中并在“remote-exec”中使用变量值

问题描述

我正在使用 Terraform 供应商。在一种情况下,我需要执行“local-exec”供应商并将命令的输出 [This is array of IP addesses] 用于下一个“remote-exec”供应商。

而且我无法将“local-exec”临时输出存储在局部变量中以供以后使用。我可以将它存储在本地文件中,但不能存储在中间变量中

count = "${length(data.local_file.instance_ips.content)}" 

这是行不通的。


resource "null_resource" "get-instance-ip-41" {
    provisioner "local-exec" {
         command = "${path.module}\\scripts\\findprivateip.bat  > ${data.template_file.PrivateIpAddress.rendered}"
    }
}


data "template_file" "PrivateIpAddress" {
    template = "/output.log"
}

data "local_file" "instance_ips" {
    filename = "${data.template_file.PrivateIpAddress.rendered}"
    depends_on = ["null_resource.get-instance-ip-41"]
}

output "IP-address" {
    value = "${data.local_file.instance_ips.content}"
}



# ---------------------------------------------------------------------------------------------------------------------
# Update the instnaces by installing newrelic agent using remote-exec
# ---------------------------------------------------------------------------------------------------------------------

resource "null_resource" "copy_file_newrelic_v_29" {

  depends_on = ["null_resource.get-instance-ip-41"]

  count = "${length(data.local_file.instance_ips.content)}"

  triggers = {
    cluster_instance_id =  "${element(values(data.local_file.instance_ips.content[count.index]), 0)}"
  }

  provisioner "remote-exec" {

    connection {
        agent               = "true"
        bastion_host        = "${aws_instance.bastion.*.public_ip}"
        bastion_user        = "ec2-user"
        bastion_port        = "22"
        bastion_private_key = "${file("C:/keys/nvirginia-key-pair-ajoy.pem")}"
        user                = "ec2-user"
        private_key         = "${file("C:/keys/nvirginia-key-pair-ajoy.pem")}"
        host                = "${self.triggers.cluster_instance_id}"
    }

    inline = [
      "echo 'license_key: 34adab374af99b1eaa148eb2a2fc2791faf70661' | sudo tee -a /etc/newrelic-infra.yml",
      "sudo curl -o /etc/yum.repos.d/newrelic-infra.repo https://download.newrelic.com/infrastructure_agent/linux/yum/el/6/x86_64/newrelic-infra.repo",
      "sudo yum -q makecache -y --disablerepo='*' --enablerepo='newrelic-infra'",
      "sudo yum install newrelic-infra -y" 
    ]
  }

} 

标签: variablesterraformterraform-provider-aws

解决方案


不幸的是你不能。我找到的解决方案是改用外部数据源块。您可以从那里运行命令并检索输出,唯一的问题是该命令需要将 json 生成到标准输出(stdout)。请参阅此处的文档。我希望这对其他试图解决这个问题的人有所帮助。


推荐阅读