Executing shell script in EC2 using AWS Systems Manager

In this article, we will see how to execute a shell script in EC2 using AWS Systems Manager (SSM) and capture the logs in AWS CloudWatch.

AWS SSM cannot perform any actions on EC2 instances by default. For an EC2 Instance to be managed by SSM,

  1. The IAM policy "AmazonSSMManagedInstanceCore" should be attached to the instance. It is done using the IAM role.

  2. The SSM Agent should be installed and running in the EC2 instance. By default, the majority of the Linux flavor comes with SMM Agent preinstalled.

Connect to the EC2 Instance and create a sample shell script as shown below.

set -e
echo "Script Started"
echo "Script Ended"
exit 0

Now, we will see how to run the script using AWS SSM using the management console.

  1. After logging into the console, navigate to AWS Systems Manager,

  2. Select "Run Command" from the left-hand pane.

  3. Select "AWS-RunShellScript" from the Command Document list. This command is used to run a shell script.

  4. You can provide the "Commands" to run.

    Note: AWS SSM will run the script or command as the root user. If you want to use any other user to run your script, use the below command.

     runuser -l <username> -c '<command>'

  5. You can also set the "Working Directory".

  6. In the Target Selection section, select "Choose instances manually" and select your instance from the list of managed instances. If your instance has been configured as explained above, it will get shown in the list.

  7. After you submit the command, it should get completed successfully and you can see the output as shown in the image below.

  8. To capture the logs in CloudWatch Logs, simply enable the CloudWatch logs in the output options as shown below.

  9. Now, the logs will be available under the "sampleproject" Log Group in AWS CloudWatch.