Terraform更改远程证明的计数索引行为



尝试使用实例的主机名和私有IP修改/etc/hosts。例如,"/etc/hosts"文件应如下所示。

member-1 <some private ip>
member-2 <some private ip>

以下我从stackoverflow本身发现的代码将接近上面的操作,但是我很难理解在哪里将索引增加1(count.index 1),以便我可以获取所述的输出以上而不是成员-1为构件-0和成员-2是成员-1。

variable "cluster_member_count" {
  default = "2"
}
variable "cluster_member_name_prefix" {
  default = "member-"
}
variable "aws_keypair_privatekey_filepath" {
  default = "../mykey.pem"
}

resource "aws_instance" "example" {
//
  }

resource "null_resource" "hosts_file" {
  count = "${var.cluster_member_count}"
  # Changes to any instance of the cluster requires re-provisioning
  triggers {
    cluster_instance_ids = "${join(",", aws_instance.example.*.id)}"
  }
  connection {
    type = "ssh"
    host = "${element(aws_instance.example.*.public_ip, count.index)}"
    user = "ec2-user"
    private_key = "${file(var.aws_keypair_privatekey_filepath)}"
  }
  provisioner "remote-exec" {
    inline = [
      # Adds all cluster members' IP addresses to /etc/hosts (on each member)
      "echo '${join("n", formatlist("%v", aws_instance.example.*.private_ip))}' | awk 'BEGIN{ print "\n\n# Cluster members:" }; { print $0  ${var.cluster_member_name_prefix} NR-1 }' | sudo tee -a /etc/hosts > /dev/null",
    ]
  }
}

请新手可以得到一些帮助吗?

非常感谢

当我以前做过类似的事情时,我很确定我已经做了这样的事情:

resource "null_resource" "my_resource" {
  count = "${var.cluster_count}"
  name = "cluster-node-${count.index+1}"
}

因此,在您的示例中,您将要在提及$ {var.cluster_member_name_prefix}后要添加$ {count.index 1}我相信。

但是,正如 @Matt-Schuchard所提到的那样,可能是一种更好的方法,因为我认为您当前的实施不是很可读。

您应该能够将变量传递到模板中(例如您需要的成员数),然后使用循环使用该变量来生成所需的正确文件配置。

模板对于这种事情非常方便。

此外,如果您要在服务器上运行很多命令(用于安装等),则可能是Ansible这样的工具,而不是Terraform中的远程exec命令。

一些可能会有所帮助的链接:

https://www.terraform.io/docs/providers/template/index.htmlhttps://www.terraform.io/docs/configuration/expressions.html#string-templates

最新更新