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,
The IAM policy "AmazonSSMManagedInstanceCore" should be attached to the instance. It is done using the IAM role.
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.
#!/bin/bash
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.
After logging into the console, navigate to AWS Systems Manager,
Select "Run Command" from the left-hand pane.
Select "AWS-RunShellScript" from the Command Document list. This command is used to run a shell script.
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>'
You can also set the "Working Directory".
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.
After you submit the command, it should get completed successfully and you can see the output as shown in the image below.
To capture the logs in CloudWatch Logs, simply enable the CloudWatch logs in the output options as shown below.
Now, the logs will be available under the "sampleproject" Log Group in AWS CloudWatch.
Subscribe to my newsletter
Read articles from Adhithiyan Azhagudurai directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by