Trying to use template file on remote-exec provisioner

2,716 views
Skip to first unread message

Sreekumar

unread,
Mar 19, 2016, 3:48:34 AM3/19/16
to Terraform
Hi all,

I am trying to use template file on remote-exec provisioner. But the problem is, it only execute the first command of the script. Can anyone help me on this?

resource "template_file" "user_data" {
    template = "${file("${path.module}/userdata.sh.tpl")}"

    vars {
        foo       = "${var.bar}"
    }
}

resource "aws_instance" "test"{
    ami           = "${var.ami}"
    instance_type = "${var.instance_type}"
    key_name      = "${var.key_name}"
    subnet_id     = "${var.subnet_id}"
    provisioner "remote-exec" {
        inline = ["${template_file.user_data.rendered}"]
        connection {
            user = "${var.user}"
            type = "ssh"
            private_key = "${file(var.private_key)}"
            timeout = "2m"
        }
    }

    vpc_security_group_ids = ["${aws_security_group.test.id}"]
    tags      { Name = "${var.name}" }
}

David Maze

unread,
Mar 19, 2016, 9:40:40 AM3/19/16
to Terraform
On Saturday, March 19, 2016 at 3:48:34 AM UTC-4, Sreekumar wrote:
I am trying to use template file on remote-exec provisioner. But the problem is, it only execute the first command of the script.

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

That seems consistent with the documentation for the remote-exec provisioner: if you want it to execute multiple commands, you need to put them in list form.

At the bottom of https://www.terraform.io/docs/provisioners/remote-exec.html there's an example that uploads a static script and invokes it with command-line arguments, which could presumably be Terraform variables.  That might be an easier way to accomplish your actual goals. 

Michael Daffin

unread,
Mar 19, 2016, 9:50:27 AM3/19/16
to Terraform
Try using a heredoc with the rendered template:

provisioner "remote-exec" {
    inline = <<EOF
$
{template_file.user_data.rendered}
EOF
}

Sreekumar

unread,
Mar 19, 2016, 12:09:50 PM3/19/16
to Terraform
heardoc method is seems to be not working, it throws 'invalid characters in heredoc anchor'. And for the file method, how can we create a file from template file.

Michael Daffin

unread,
Mar 19, 2016, 4:46:33 PM3/19/16
to Terraform
That suggest you have a problem with either the 
    inline = <<EOF
or
EOF

line rather than the template part. Can you post the exact code you tried to use? Note that spacing and indentation is important for heredocs to work.

Robert J

unread,
Aug 7, 2017, 3:38:57 PM8/7/17
to Terraform, mic...@daffin.io
Awesome!  This saved me quite a bit of time.  I was used to `bash` here docs and put a space between `<<` and my ending string, since bash is not picky and I think it looks nicer.  Apparently, you cannot do this in terraform.

Thanks for this post!
Reply all
Reply to author
Forward
0 new messages