Jiya
Jiya

Reputation: 243

How to run command on EC2 instance after starting session manager on it using bash script?

I am writing bash script to install missing patches on ec2 instance using session manager. I can start the session using script but I am not sure how can I run command on it using script?

    instanceid = "i-098xxxx"

    echo $instanceid
    echo "instance id"

    # Creating AMI 
    echo "-------------------------------Creation AMI-----------------------------------------"
    aws ec2 create-image --instance-id $instanceid --name "test ami" --description "Delete when 
    testing" --no-reboot --profile xyz

    # Start Session Manager
    aws ssm start-session --target $instanceid --profile xyz

 
    # Command to check for critical security patches and update/install it on ec2 instance
    echo "-------------------------------installing missing patches----------------------------- 
    ------------"
    sudo yum update-minimal --sec-severity=critical,important --bugfix 

I want to run sudo yum update-minimal --sec-severity=critical,important --bugfix command in ec2 instance using script.

Can someone guide me on this?

Upvotes: 5

Views: 7790

Answers (3)

lxop
lxop

Reputation: 8615

As an alternative to using run-command, if for some reason you need to use a session, you can do this by using the AWS-StartNonInteractiveCommand document, for example:

aws ssm start-session \
    --document-name 'AWS-StartNonInteractiveCommand' \
    --parameters '{"command": ["sudo yum -y update amazon-ssm-agent"]}' \
    --target "$instanceid"

To see the other parameters accepted by this document, run

aws ssm describe-document --name AWS-StartNonInteractiveCommand

Upvotes: 9

iam.awslagi
iam.awslagi

Reputation: 1

I think AWS Systems Manager is best way to resolve this case. https://docs.aws.amazon.com/systems-manager/latest/userguide/session-manager.html

Upvotes: -2

John Rotenstein
John Rotenstein

Reputation: 270104

The AWS Systems Manager Session Manager provides an SSH-like connection via a web browser.

However, if you wish to automate the execution of commands on instances, you should use the AWS Systems Manager Run Command, which can run commands on a single instance or hundreds of instances, and return results from each run.

Upvotes: 1

Related Questions