简体   繁体   中英

shell script to start ec2 instances and ssh and introducing delay in second command

I have written a small shell script to automate the starting and loggin in to my aws instances via terminal.

#!/bin/bash
aws ec2 start-instances --instance-ids i-070107834ab273992


public_ip=aws ec2 describe-instances --instance-ids i-070107834ab273992 \
        --query 'Reservations[*].Instances[*].PublicDnsName' --output text


AWS_KEY="/home/debian/cs605 data management/assignment6/mumbai instance keys"

ssh -v -i "$AWS_KEY"/mumbai-instance-1.pem\
        ec2-user@$public_ip

~
~
The problem is public_ip variable I want it to be used in line ssh
1) how do I get value of a variable to use in a command.
2) The instance takes some time to boot when it is switched on from power off to power on so how do I keep checking that instances has been powered on after aws start instance command in the script or retrieve the public ip once it has started fully and then ssh into it. I am not good at python know just basics so is there a pythonic way of doing it.If there is an example script some where that would be better for me to have a look at it.

You do not set the variable public_ip in your script. It would not surprise me if the script complained about "ec2: command not found".

To set the variable:

public_ip=$(aws ec2 describe-instances --instance-ids i-070107834ab273992 --query 'Reservations[*].Instances[*].PublicDnsName' --output text)

(disclaimer: I have not used aws so I assume that the command is correct).

The information on whether an instance is running should be available with

aws ec2 describe-instance-status

You may want to apply some filters and/or grep for a specific result. You could try polling with a while loop:

while !  aws ec2 describe-instance-statusv --instance-ids i-070107834ab273992 | grep 'something that characterizes running' ; do
    sleep 5
done

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM