参数化的地形模板

时间:2017-03-22 10:52:12

标签: templates cloud openstack terraform

我有一个terraform项目在Openstack中创建99个虚拟机我不能使用cloud-init而且我必须修改每台机器的主机名

hostname.tplt:

sudo sed -i -e "s/debian[7-9]/${host_name}/g" /etc/hostname
sudo invoke-rc.d hostname.sh start

sudo sed -i -e "s/127\.0\.1\.1.*/127.0.1.1\t${host_name}.${domain_name} ${host_name}/g" /etc/hosts
sudo apt-get update && sudo apt-get -y install dbus && sudo hostnamectl set-hostname ${host_name}

main.tf的一部分:

data "template_file" "hostname_servers" {
  template = "${file("templates/hostname.tplt")}"

  vars {
    host_name   = "${format("%s-proxy-%02d", var.prefix_name, count.index+1)}"
    domain_name = "${var.domain_name}"
  }
}

的ressource

resource "openstack_compute_instance_v2" "proxy-instance" {
  count       = "${var.count_proxy}"
  name        = "${format("%s-proxy-%02d", var.prefix_name, count.index+1)}"
  image_name  = "${var.image}"
  flavor_name = "${var.flavor_proxy}"

  network {
    name = "${format("%s-%s", var.prefix_name, var.network_name)}"
  }

  connection {
    user = "${var.user}"
  }

  provisioner "remote-exec" {
    inline = [
      "${data.template_file.hostname_servers.rendered}"
    ]
  }
}

用例: 当我启动一个terraform计划时,它适用于代理实例资源,但我需要为99台机器执行此操作, 我不想复制模板数据99次, 并且我不知道如何将模板进行parammetrize以便能够申请所有机器 任何想法?

1 个答案:

答案 0 :(得分:0)

如果在多个资源上将count设置为相同的值,则可以使用count.index创建一个块的实例与另一个块的实例之间的对应关系,如下所示:

data "template_file" "hostname_servers" {
  count = "${var.count_proxy}"

  template = "${file("templates/hostname.tplt")}"

  vars {
    host_name   = "${format("%s-proxy-%02d", var.prefix_name, count.index+1)}"
    domain_name = "${var.domain_name}"
  }
}

resource "openstack_compute_instance_v2" "proxy-instance" {
  count = "${var.count_proxy}"

  name        = "${format("%s-proxy-%02d", var.prefix_name, count.index+1)}"
  image_name  = "${var.image}"
  flavor_name = "${var.flavor_proxy}"

  network {
    name = "${format("%s-%s", var.prefix_name, var.network_name)}"
  }

  connection {
    user = "${var.user}"
  }

  provisioner "remote-exec" {
    inline = [
      # use count.index to match the template instance corresponding
      # to this compute instance instance.
      "${data.template_file.hostname_servers.*.rendered[count.index]}"
    ]
  }
}