SSM Agent to automate CLI

0

After connecting to a VPC instance via a private user declared with the built-in CLI ( script-shell.sh ). I need to enter commands to perform tasks. The problem is that after the connection, the linux command lines embedded in the (AWS CLI) are not executed, below is the code:

script_shell.sh

#!/bin/bash

# Etapa 1
# Configuração das credenciais da AWS e estabelecimento da conexão
echo "Estabelecendo conexão com a conta ( AWS ) . . ."
export AWS_ACCESS_KEY_ID="xxxxxxxxxxx"
export AWS_SECRET_ACCESS_KEY="xxxxxxxxxxx"
sleep 3
echo "Conexão estabelecida a conta ( AWS )."

# Etapa 2
# Listar as instancias ec2 e definir qual delas acessar
json=$(aws ec2 describe-instances --region us-east-1)
# Extrai o valor da chave InstanceId usando o jq
instance_id=$(echo "$json" | jq -r '.Reservations[0].Instances[0].InstanceId')

# Connect to an instance using the instance ID and an EC2 Instance Connect Endpoint
aws ec2-instance-connect ssh --instance-id $instance_id --connection-type eice --region us-east-1

# From here on down do the commands stop being executed in the terminal ?
# Wait for the connection to be established. . .
aws ec2 wait instance-ssh-connection-established --instance-id $instance_id --region us-east-1
# Start the session and sends linux commands. . .
aws ssm start-session --target $instance_id --document-name "AWS-StartInteractiveCommand" --parameters "commandLine=['sudo su -c \"cd /; ls\"']" --region us-east-1

0v0 ( How can I make linux commands run on the instance ? )

  • Hi John, Any update here, how it went. I'd like to hear from you, feel free to comment here if you are still having issues or have any additional questions. If this answers your question, please approve the answer for better community experience.

asked a year ago423 views
1 Answer
2

Hi John,

Here are the steps you need to follow:

a. Create a EC2 service role with *AmazonSSMFullAccess

b. Attach this role to ec2, go to Actions -> Security -> Modify IAM Role

c. Make sure, security group attached to EC2 instance, allow inbound traffic from your machine(for testing purpose you can allow All traffic, anywhere -not recommended though, and remove after testing)

d. After installing the SSM agent on ec2, follow these steps:

  1. aws ec2-instance-connect send-ssh-public-key --instance-id $instance_id --instance-os-user ec2-user --availability-zone us-east-1d --ssh-public-key file:///Users/abc/.ssh/id_rsa.pub --region us-east-1 --profile <awscli_profile_name>
  2. aws ssm send-command --instance-ids $instance_id --document-name "AWS-RunShellScript" --parameters '{"commands":["sudo su"]}' --region us-east-1 --profile <awscli_profile_name> --output text
  3. aws ssm send-command --instance-ids $instance_id --document-name "AWS-RunShellScript" --parameters '{"commands":["cd /"]}' --region us-east-1 --profile <awscli_profile_name> --output text
  4. aws ssm send-command --instance-ids $instance_id --document-name "AWS-RunShellScript" --parameters '{"commands":["ls"]}' --region us-east-1 --profile <awscli_profile_name> --output text

Make sure, in step-1, you pass your local machine ssh public key, from where you intend to connect to ec2 instance.

I'm attaching snapshot for your reference:

Enter image description here

Here is the script version of same attempt:

1. Script content and it's output:

Enter image description here

2. File which is present at root directory on EC2 instance and I'm doing 'cat' through SSM as mentioned above in the script content:

Enter image description here

3. Finally the command output from SSM console to verify it's working as expected:

Enter image description here

Hope you find this helpful, let me know how it works for you.

profile pictureAWS
EXPERT
answered a year ago
profile picture
EXPERT
reviewed a year ago
  • I tried and got the following message:

    Connecting to Account (AWS). . . Connection established to account ( AWS ).

    { "RequestId": "xxxxxxxxxxxxxxxxxxxxx", "Success": true }

    An error occurred (InvalidInstanceId) when calling the SendCommand operation: Instances [[i-xxxxxxxxxxxxxxxxxx]] not in a valid state for account xxxxxxxxxxxxxxxxxx

  • Glad to know that you are one step closer, I also faced this issue for couple of times. Can you make sure of following:

    1. Role which is attached to EC2 has AmazonSSMFullAccess and trust relationship for ec2.amazonaws.com with action sts:AssumeRole

    2. Instance have SSM agent installed and running(refer doc) and make sure you installed the right agent based on type of ec2 machine.

        sudo systemctl status amazon-ssm-agent
      
    3. Add security group allowing inbound traffic, after adding ALL Traffic/Anywhere(for testing purpose), waited for few minutes, then ran the script and worked.

    I can say from here that you are now in right direction. Keep me posted.

  • Hi John, Any update here, how it went. I'd like to hear from you, feel free to comment here if you are still having issues or have any additional questions. If this answers your question, please approve the answer for better community experience.

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.

Guidelines for Answering Questions