Commands in user_data are not executed in terraform

12,664

I could see one issue with the code you have posted, the user_data variable should be like

user_data = "${data.template_file.user_data.rendered}"

Moreover, as a suggestion i will recommend you to try creating a log file in your script to check what all steps have been executed. It will also benefit you to know whether the script ran at all or not.

One sample from our code, you can modify it based on your standards

logdir=/var/log
logfile=${logdir}/mongo_setup.log
exec >> $logfile 2>&1

Hope this helps.

Share:
12,664
Smi
Author by

Smi

Updated on July 08, 2022

Comments

  • Smi
    Smi almost 2 years

    Hi EC2 instance is created, but commands as part of userdata.sh are not gettingexecuted. When I manually connect to EC2 via putty, i found that nginx is not installed in EC2 instance. To verify if the script is getting executed or not I added echo message, but no output is display in command prompt when i run terraform apply. How can i verify if the user-data is getting executed or not?

    I have installed Terraform in C drive and below script are present in same folder C:/Terraform/userdata.sh, C:/Terraform/main.tf, i tried giving path as ${file("./userdata.sh")}" but still it does not work.

    Please advice as I am just learning terraform. Thanks.

    #!/bin/bash -v
    echo "userdata-start"
    sudo apt-get update -y
    sudo apt-get install -y nginx > /tmp/nginx.log
    sudo service nginx start
    echo "userdata-end"
    

    This is been called in my terraform program [main.tf] as below:

    # resource "template_file" "user_data" {
    #    template = "userdata.sh"
    # }
    
    data "template_file" "user_data" {
    template = "${file("userdata.sh")}"
    }
    
    resource "aws_instance" "web" {
    instance_type = "t2.micro"
    
    ami = "ami-5e8bb23b"
    
    key_name = "sptest"
    
    vpc_security_group_ids = ["${aws_security_group.default.id}"]
    subnet_id              = "${aws_subnet.tf_test_subnet.id}"
    
    user_data               = "${data.template_file.user_data.template}"
    #user_data              = "${template_file.user_data.rendered}"
    #user_data              = "${file("userdata.sh")}"
    #user_data              = "${file("./userdata.sh")}"
    
    
    tags {
    Name = "tf-example-ec2"
    }
    }