AWS Session Manager (SSM) Tips & Tricks

AWS Session Manager (SSM) Tips & Tricks

Posted by

AWS Session Manager (SSM) is a great AWS tool that can be used to:

  • Connect to EC2 instances: SSM allows you to connect to your EC2 instances, even if they have private IP addresses.
  • Manage EC2 instances: SSM can be used to manage your EC2 instances, including executing commands, managing parameters and secrets, and automating tasks.
  • Server update: SSM can be used to update remote Linux or Windows boxes in automatic manner.

To make SSM work you need to make sure to install “SSM Agent” on each EC2 machine. It is automatically done if you apply a special “AmazonSSMRoleForInstancesQuickSetup” IAM role on the EC2 instances.

Connecting to EC2 with private ip

1. Crete the following file if it does not exists: ~/.ssh/config.
2. Add the following lines:

Host server-name
  IdentityFile ~/.ssh/server.pem
  ProxyCommand sh -c "aws --region us-west-1 --profile=prod ssm start-session --target i-0be844bb265909123 \
--document-name AWS-StartSSHSession --parameters 'portNumber=%p'"
  StrictHostKeyChecking no

After that you can connect to “server-name” using SSH:

ssh ubuntu@server-name

Example of server tunnel script

export AWS_PROFILE="prod"
export AWS_DEFAULT_REGION="us-west-1"
aws ec2 start-instances --instance-ids $INSTANCE
aws ec2 wait instance-running --instance-ids $INSTANCE
aws ssm start-session --target $INSTANCE --document-name AWS-StartPortForwardingSession \
--parameters '{"portNumber":["5050"],"localPortNumber":["5050"]}'

Publishing remote server using local ip and port

aws ssm start-session --region us-west-1 --profile=prod --target i-0be844bb265909123 \
--document-name AWS-StartPortForwardingSession --parameters '{"portNumber":["4440"],"localPortNumber":["4440"]}'

Running script on remove server

TAG=$(git rev-parse --abbrev-ref HEAD)
CMDID=$(aws ssm send-command --instance-ids i-0be844bb265909123 --document-name AWS-RunShellScript --comment "Start UI" --parameters commands='AWS_CONFIG_FILE=/home/ubuntu/.aws/credentials /home/ubuntu/ '$TAG';' --output text --query "Command.CommandId")
aws ssm get-command-invocation --command-id $CMDID --instance-id i-0be844bb265909123 --query "StandardOutputContent" --output text