AWS EC2 Instance SSM Send Command

You can submit commands into an EC2 instance via SSM (Secure Systems Manager), rather than having to open SSH to the machine. From within an authenticated session using AWS CLI on your workstation machine, you can remotely send commands to be run within the instance itself.

The commands will typically be run as “root” within EC2. You’ll need to know the Instance ID of the AWS EC2 instance to add to the command.

Send Command to EC2 Instance – Download File from S3 Bucket

Note that you need to ensure that the EC2 instance (service) has permissions to access AWS S3 Bucket.

aws ssm send-command --instance-ids i-0bb6817f93fedc5a7 --document-name "AWS-RunShellScript" --parameters commands="aws s3 cp s3://my-bucket-name/myfile.txt /tmp/"

Send Command to EC2 Instance – Run Command

If you want to just run a command, the following will echo HELLO into a file locally on the EC2 instance, so you can prove it worked.

aws ssm send-command --instance-ids i-0bb6817f93fedc5a7 --document-name "AWS-RunShellScript" --parameters commands="echo HELLO > /tmp/ssm2.log"

Terraform

You can also run this from within Terraform using a null_resource and a provisioner, for example:

resource "null_resource" "run_ssm_command" {
  provisioner "local-exec" {
    command = <<-EOT
      aws ssm send-command \
       --instance-ids ${aws_instance.mgmt_host.id} \
         --document-name "AWS-RunShellScript" \
         --parameters commands="echo HELLO > /tmp/ssm2.log" \
         --region ${var.aws_region}
     EOT
   }

   depends_on = [aws_instance.mgmt_host]
 }

Leave a comment