So you have an EC2 instance you’ve deployed from Terraform, but as part of the run of your template you want to run some other commands. Sure, you can use the “user data” section to run commands at deployment time, but what if you want to run something later on? Well, you can use a “Local-Exec” provisioner, in fact you can use this for all sorts of things.
In the example below we are just running a command on the EC2 instance, for this we first need to ensure that we have the instance ID of our EC2 instance. In my example the EC2 instance is known as “mgmt_host” within the Terraform templates, so the command aws_instance.mgmt_host.id will determine this ID automatically.
resource "null_resource" "run_ssm_command_unzip" {
provisioner "local-exec" {
command = <<-EOT
aws ssm send-command \
--instance-ids ${aws_instance.mgmt_host.id} \
--document-name "AWS-RunShellScript" \
--parameters commands="echo 'Hello!'" \
--region ${var.aws_region}
EOT
}
#depends_on = [null_resource.run_ssm_command_download]
}
When putting the commands in, you may have some “fun” with speech marks, and need to ensure that the these are not ending the command early.
You can troubleshoot the operation of the commands that you are running remotely by looking at the log file on the EC2 instance which can be found in: /var/log/amazon/ssm/amazon-ssm-agent.log