2
votes

i want data "template_file" in below terraform code to execute after provisioner "file" (basically ansible playbook) is copied to the ec2 instance. I am not able to successfully use "depends_on" in this scenario. Can some one please help me how can i achieve this? below is the sample code snippet.

resource "aws_eip" "opendj-source-ami-eip" {
  instance = "${aws_instance.opendj-source-ami-server.id}"
  vpc = true
  connection {
    host = "${aws_eip.opendj-source-ami-eip.public_ip}"
    user                = "ubuntu"
    timeout = "3m"
    agent = false
    private_key         = "${file(var.private_key)}"
  }
  provisioner "file" {
    source      = "./${var.copy_password_file}"
    destination = "/home/ubuntu/${var.copy_password_file}"
  }
  provisioner "file" {
    source      = "./${var.ansible_playbook}"
    destination = "/home/ubuntu/${var.ansible_playbook}"
  }
}

data "template_file" "run-ansible-playbooks" {
  template =  <<-EOF
              #!/bin/bash
              ansible-playbook /home/ubuntu/${var.copy_password_file} && ansible-playbook /home/ubuntu/${var.ansible_playbook}
              EOF
  #depends_on = ["<< not sure what to put here>>"]
}
1
Your template_file block here doesn't seem to actually depend on the result of the provisioner, so I'm not sure why you want to defer rendering it until after the provisioner is complete. Is your goal here to execute the script produced by that template via SSH to the remote host? - Martin Atkins
Well, i am adding the scripts as cloud-init to ec2 instance user-data so that they get executed when ec2 instance comes up. resource "aws_instance" "opendj-source-ami-server" { ..... user_data = "${data.template_file.run-ansible-playbooks.rendered}" .... } It just that some time it fails complaining scripts not found, certainly its failing into catch22 situation i guess.. - Deepak Prasad
The template_file data source doesn't have any side-effects, so its own rendering cannot fail as a result of missing scripts. Nothing in your example actually runs that script, but I assume you have something else in your configuration that is running it. - Martin Atkins
To make error searchable: Invalid depends_on reference, References in depends_on must be to a whole object (resource, etc), not to an attribute of an object. The error appears when you use something like depends_on=resource.aws_lambda_function.func_name. Use depends_on=aws_lambda_function.func_name instead. - Putnik

1 Answers

4
votes

The correct format for depends_on is pegged to the resource as a whole; so the format in your case would look like:

data "template_file" "run-ansible-playbooks" {
  template =  <<-EOF
              #!/bin/bash
              ansible-playbook /home/ubuntu/${var.copy_password_file} && ansible-playbook /home/ubuntu/${var.ansible_playbook}
              EOF
  depends_on = ["aws_eip.opendj-source-ami-eip"]
}