0
votes

I currently have custom AWS AMI images and Terraform is not able to execute a script or inline code in the user_data section. It works for an AWS AMI image but not when I use my own.

data "template_file" "user_data" {
template = "${file("sample")}"
}


resource "aws_launch_configuration" "test" {
image_id = "ami-xxxxxx"
instance_type = "t2.medium"
security_groups = ["xxxxx", "xxxxxxx"]
key_name = "xxxxxxx"
}



resource "aws_instance" "ZC1" {
    ami = "ami-xxxxxxx" #ZC AMI IMAGE
    instance_type = "t2.medium"
    subnet_id = "subnet-xxxxx"
    private_ip = "x.x.x.x"
    key_name = "xxxxxx"
    vpc_security_group_ids = ["xxxxx", "xxxxxxx"]
    user_data = "${data.template_file.user_data.rendered}"
    tags {
    "Name" = "Terraform Script Test"
        }
}
1
When you say "script or inline code in the user_data section" do you mean a #cloud-config snippet? This sort of configuration is usually handled by the cloud-init package and needs to be installed and configured on your image (it is available by default on most popular AMIs). Can you edit your question to provide some more information on how the AMI is build or where it comes from and what the user_data looks like?Andy Shinn

1 Answers

2
votes

When setting user_data on an EC2 instance, AWS just makes this data available to the instance via the metadata API. Software installed within the AMI must then retrieve this data and decide what to do with it.

You can see this in practice by logging in to your instance and running a command like the following, assuming you have curl available:

curl http://169.254.169.254/latest/user-data

If working as expected, you should see here the value you specified for user_data.

The most common way to deal with user data is via cloud-init, which is a program designed to be run on instance boot (e.g. via systemd, init, etc) which retrieves the user_data and takes various actions depending on what it finds there. For example, if the retrieved data looks like a plain shell script then cloud-init will execute that script.

There are other alternatives to cloud-init, such as CoreOS Ignition. You are also free to write your own program to deal with boot-time configuration, if you have unique needs.

The simplest way to get up and running here is to ensure that cloud-init is installed as part of your AMI creation and configured to run on boot. You will then see the familiar boot-time configuration behavior of Amazon Linux or Ubuntu's AMIs.