我有一个模板文件,用于创建配置文件,然后用于帮助配置实例。
如果模板文件发生变化,我希望“terraform apply”触发配置文件的重新生成,然后当配置文件发生变化时,我希望它触发实例的重新生成。
有没有办法用 Terraform 来做到这一点?
data "template_file" "instance_config" {
template = "${file("${path.module}/instance_config.tpl")}"
vars {
private_cidr_block = "${var.private_cidr_block}"
}
}
resource "null_resource" "export_instance_config" {
provisioner "local-exec" {
command = "cat >instance_config.json <<EOL\n${data.template_file.instance_config.rendered}\nEOL"
}
}
resource "aws_instance" "vpn" {
ami = "${data.aws_ami.my_ami.id}"
instance_type = "t2.micro"
key_name = "mykey"
subnet_id = "${var.subnet_id}"
associate_public_ip_address = true
security_groups = ["${aws_security_group.instance_sg.id}"]
connection {
type = "ssh"
user = "myuser"
private_key = "${file("mykey.pem")}"
agent = false
}
provisioner "file" {
source = "instance_config.json"
destination = "/home/myuser/instance_config.json"
}
provisioner "remote-exec" {
inline = [
"sudo /usr/bin/configure_instance /home/myuser/instance_config.json"
]
}
}
答案1
你可以利用列出的配置功能来降低复杂性并修复依赖链这里。
具体来说,我认为您可以删除null_resource
供应商并执行以下操作:
data "template_file" "instance_config" {
template = "${file("${path.module}/instance_config.tpl")}"
vars {
private_cidr_block = "${var.private_cidr_block}"
}
}
resource "aws_instance" "vpn" {
ami = "${data.aws_ami.my_ami.id}"
instance_type = "t2.micro"
key_name = "mykey"
subnet_id = "${var.subnet_id}"
associate_public_ip_address = true
security_groups = ["${aws_security_group.instance_sg.id}"]
connection {
type = "ssh"
user = "myuser"
private_key = "${file("mykey.pem")}"
agent = false
}
provisioner "file" {
content = "${data.template_file.instance_config.rendered}"
destination = "/home/myuser/instance_config.json"
}
provisioner "remote-exec" {
inline = [
"sudo /usr/bin/configure_instance /home/myuser/instance_config.json"
]
}
}