skip to Main Content

I’d like to create a bash script using aws cli that

  • start an ec2 image
  • clone a github repo
  • build a docker image
  • stops the ec2 image.

I managed to make the start and stop using
aws ec2 start-instances and aws ec2 stop-instances
But I am struggling to run the other bash commands.
I saw this: Run a command remotely on ec2
That explains how to run a bash command.

So I tried:

aws ssm send-command 
--instance-ids "i-02ae********" 
--region "us-east-2"
--document-name "AWS-RunShellScript" 
--parameters commands="git clone https://myrepo.git" 
--output text

But I get as output

COMMAND 77821510-9094-4d3d-b7c0-99a9d0c46716            0       0       AWS-RunShellScript      $DEFAULT        0       2022-08-07T01:04:19.705000+02:00        50      0                       us-east-2       2022-08-06T23:04:19.705000+02:00                Pending Pending 1       3600
CLOUDWATCHOUTPUTCONFIG          False
INSTANCEIDS     i-02aef7e********
NOTIFICATIONCONFIG              
COMMANDS        git clone https://github.com/myrepo.git

And if I ssh into the ec2 instance, I don’t see any effect of the command.
Can someone give me some hint on how to proceed?

2

Answers


  1. For the start and stop portion…

    If you want to run a script every time that an Amazon EC2 instance starts, simply place the script in:

    /var/lib/cloud/scripts/per-boot/
    

    Any script in that directory will run every time that the instance boots.

    When the script has finished processing, run:

    sudo shutdown now -h
    

    This will shutdown the instance from within the instance, rather than having to call an AWS API.

    For more details, see: Auto-Stop EC2 instances when they finish a task – DEV Community

    Login or Signup to reply.
  2. send-command executing an asynchronous execution. In the response, you have information about status of your command – pending.
    You can monitor the status of your execution using https://docs.aws.amazon.com/cli/latest/reference/ssm/get-command-invocation.html

    Btw, you can always find your command execution, with logs, in the AWS console – SSM service -> run command. There you will find the answer to your question.

    Btw2, it is strongly recommended to don’t use SSH, if you can use Systems Manager – I assume it is possible in you’re case, because you can use send-command API, so start-session should be allowed as well.
    https://docs.aws.amazon.com/cli/latest/reference/ssm/start-session.html

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search