Search code examples
amazon-web-servicesamazon-ec2aws-cli

Use AWS CLI to start instance only if it's status is stopped


I'm running a Jenkins server which is the AWS CLI tools installed and working. The server is running Ubuntu 16.04.3

I can successful run a command to start and stop a particular AWS instance, which is:

aws ec2 start-instances --region eu-west-2 --instance-ids i-65a4sd654as

I can also run a command to find the status of that instance:

aws ec2 describe-instance-status --region eu-west-2 --instance-ids i-65a4sd654as

But what I need to do is run two Jenkins jobs which check the status of a particular instance, and then only runs the start-instances or 'stop-instances' command if the status is stopped or 'running', respectively.

Presumably there is a way to run one command and take the output, then make the next command conditional on that, but I can't figure out how to do this. I need the Jenkins job to show success if any of the following situations occur:

  • the start job find the status is running so doesn't run the start-instances command
  • the start job finds the status is stopped so does run the start-instances command, and succeeds
  • the stop job finds the status is stopped so doesn't run the stop-instances command
  • the stop job finds the status is running so does run the stop-instances command, and succeeds

And in all other instances to fail.

There's a wealth of information online about using each command, but nothing I can find about how to stitch them together.


Solution

  • If you're looking for a one liner on the command line, you could do something like this

    if [[ $(aws ec2 describe-instances --instance-ids i-abcd1234defg5678 --query 'Reservations[].Instances[].State[].Name' --output text) = "running" ]] ; then \
        aws ec2 stop-instances --instance-ids i-abcd1234defg5678; \
        elif [[ $(aws ec2 describe-instances --instance-ids i-abcd1234defg5678 --query 'Reservations[].Instances[].State[].Name' --output text) = "stopped" ]] ; then \
        aws ec2 start-instances --instance-ids i-abcd1234defg5678 ; \
        fi