Auto interaction with EC2 through the CLI.

0

I'm using a linux shell script file ( .sh ), writing commands ( CLI ) to be able to automate tasks in the account, such as: Create instances, list, connect and more... instantiates through the ( CLI ) declared in the.sh file, the other linux commands ( sudo su, cd / and others... ) are not automatically executed in the instance. How can I make it so? There is some kind of ( CLI ) AWS specifies for this, like ( aws ec2 sudo su )... Below is the code snippet related to the .sh file :

scrip-shell-linux.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="...."
export AWS_SECRET_ACCESS_KEY="...."
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

# ( 0v0 ) -> After the connection, the commands below are no longer interpreted by the instance ?
sudo su
cd /
apt update && sudo apt upgrade
asked a year ago419 views
2 Answers
2

Hi,

AWS Systems Manager does exactly what you need here. Please follow Walkthrough: Use the AWS CLI with Run Command step by step and you'd be easily able to do what you want to run on EC2 machine through SSM.

Here below is how would you do it:

  1. Attach an IAM role to instance: The ec2 instance should have an IAM role with policy AmazonSSMFullAccess. This would enable instance to communicate with the Systems Manager API.

  2. Install SSM Agent: Install SSM agent on EC2 instance. The SSM Agent process the run command requests & configure the instance as per command.

  3. Run command through CLI something like as below: aws ssm send-command --document-name "AWS-RunShellScript" --comment "running processes" --instance-ids "Instance-ID" --parameters commands="pe -ef" --region us-east-1 --output text

If you don't want to this way, you can always ssh to ec2 and then you are technically on EC2 instance and can run whatever you need.

profile pictureAWS
EXPERT
answered a year ago
profile pictureAWS
EXPERT
reviewed a year ago
  • In my root account, I assign permission ( AmazonSSMFullAccess ) to a certain private user.

    Inside the .sh file I defined command for:

    • Establish login to private user account using credentials
    • List the EC2 instance
    • Establish connection to the instance
    • Install the SSM Agent
    • Execute linux commands by ( CLI ) aws.

    Note: After I establish the connection with the EC2 instance by viewing the access via the terminal, I notice that the linux command embedded in the aws cli has not been executed? Below is the sequence of the command lines ( AWS ), embedded in the linux shell script file : ...

    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 aws ssm send-command --instance-ids $instance_id --document-name "AWS-RunShellScript" --parameters '{"commands":["sudo su"]}' --region us-east-1 --output text aws ssm send-command --instance-ids $instance_id --document-name "AWS-RunShellScript" --parameters '{"commands":["cd /"]}' --region us-east-1 --output text aws ssm send-command --instance-ids $instance_id --document-name "AWS-RunShellScript" --parameters '{"commands":["ls"]}' --region us-east-1 --output text

    0v0 ( Remembering that the SSM Agent was successfully installed and is running as a service. )

  • Hey John, You should use aws ec2-instance-connect send-ssh-public-key instead of just ssh. Refer cli-aws-ec2-instance-connect

    After installing the SSM agent on ec2, I exactly did, what you listed here and it worked absolutely fine for me.

    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> 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 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 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

    Let me know how it works for you.

  • 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

0

ec2-instance-connect is less flexible compared to ssh command. With ssh command you can run your commands line by line or pipe them to the ssh command but you cannot do that with EC2 Instance Connect. To see how to connect to your EC2 instance using ssh, you can look here.

AWS
EXPERT
answered a year ago
  • The EC2 instance I made is configured with VPC, Subnet, Security Group with permissions ( All traffic ) for SSH and a User with the necessary permissions to interact with the private EC2. I tried to establish a connection via ssh from the command line ( ssh -i "keypair.pem" ec2-user@myipprivado ) and it doesn't connect? The Key Pair has chmod 400 permission and the connection path is correct, I don't know why I can't establish a connection with the instance ?

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