Terraform execute bash script into instance

terraform

What is the way of execute a sh script into ec2 instance when terraform is building resources?
I created an ami with some files in directory for execute, if i enter via ssh i can execute file as follow:

sh /home/resources/wso/bin/wso.sh

I have a start.tpl file with follow content:

#!/bin/bash

# update ubuntu
sudo apt-get update
# install nginx
sudo apt-get install nginx -y
sudo service nginx start

#start wso2
sh /home/resources/wso/bin/wso.sh

In my main.tf i have this:

data "template_file" "start" {
  template = "${file("start.tpl")}"  
}

resource "aws_instance" "wnginx" {
  ami                    = "${var.instance_ami}"
  instance_type          = "${var.instance_type}"    
  user_data = "${data.template_file.start.rendered}"
}

Nginx start good, but my start script wso.sh can't start.

Exist some configuration of terraform for debug my start.tpl?

Best Answer

You are using user data the wrong way. Please see the cloud-init documentation.

Your template should then contain something like this (YAML Format):

#cloud-config
write_files:
- path: /home/resources/wso/bin/wso.sh
    content: |
    #!/bin/bash

    # update ubuntu
    sudo apt-get update
    # install nginx
    sudo apt-get install nginx -y
    sudo service nginx start
runcmd:
- ["sh", "/home/resources/wso/bin/wso.sh"]

Since this can be improved with Little effort, I would propose to use this as template:

#cloud-config
packages:
  - nginx
package_update: true
runcmd:
  - [systemctl, daemon-reload]
  - [systemctl, enable, nginx]
  - [systemctl, start, nginx]

It will achieve the same as your script but use the System provided to provision a machine, and also remove the need e.g. for maintaining your own AMI, as you could then just apply a cloud-init configuration via user data and rely on the Debian/Ubuntu Images.

If this did not work, you can verify /var/log/cloud-init.log. Since the file format is YAML, be aware of it being broken by using improper indention.