Commands in user_data are not executed in terraform

和自甴很熟 提交于 2020-01-23 06:55:47

问题


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

回答1:


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.



来源:https://stackoverflow.com/questions/51882030/commands-in-user-data-are-not-executed-in-terraform

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!