0

I have a template file that is used to create a config file that is then used to help provision an instance.

If the template file changes I want "terraform apply" to trigger the regeneration of the config file and then when the config file changes I want that to trigger the regeneration of the instance.

Is there a way to do this with 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

You could reduce complexity and fix the dependency chain by utilizing the feature of provisioners outlined here.

Specifically, I think you can remove the null_resource provisioner and instead do the following:

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"
    ]
  }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.