2

I frequently need to start AWS EC2 instances to work with from the command line to work with over SSH, and would like to write a short script to do this, but I'm stuck at the most basic steps.

For example, I can get started with

aws ec2 start-instances --instance-ids i-84Sd8jdf 

and would like to continue by grabbing the IP address assigned to the instance and using it as an environment variable or script variable to preform subsequent operations such as

ssh ubuntu@<theIP>

or

scp ubuntu@<theIP>:~/soruce_stuff/* ~/dest_folder/

but I can't figure out how to get the IP address from the start-instances command, or from any of the JSON emitted by other commands.

How do I script starting of EC2 instances, wearing for the IP to be assigned, and capturing the assigned IP address for subsequent use?

orome
  • 45,163
  • 57
  • 202
  • 418
  • Possible duplicate of [List public IP addresses of EC2 instances](http://stackoverflow.com/questions/24938971/list-public-ip-addresses-of-ec2-instances). Just call `describe-instances` a short while after your instance has started, following the example in this linked answer. – Anthony Neace May 20 '16 at 20:59
  • @AnthonyNeace: How do I get from the list of IP addresses to (a) the one for the just-launched instance that I can (b) assign to an environment variable (for example)? – orome May 20 '16 at 21:05
  • 2
    Since you know the instance id, you could use the `--instance-ids` parameter on `describe-instances` to filter down to the result for your single instance, and then use the query string from that answer to filter down to the single address that you're after. – Anthony Neace May 20 '16 at 21:09
  • @AnthonyNeace: Nice! This isn't quite a dup of the linked question; so I'd take that as the answer (esp. if it additionally showed how to pipe or whatever to an env variable and/or script variable). And even better: if there was a way to make the script wait until the IP address was available. – orome May 20 '16 at 21:12

2 Answers2

6

An example (based on this excellent answer) in bash where the instance is started, the script sleeps (specified in seconds), and the public ip address is saved to a local variable:

aws ec2 start-instances --instance-ids i-aaaa1111
sleep 10
ec2Address=$(aws ec2 describe-instances --instance-ids i-aaaa1111 --query "Reservations[*].Instances[*].PublicIpAddress" --output=text)

To verify:

echo $ec2Address
11.1.111.111
Community
  • 1
  • 1
Anthony Neace
  • 25,013
  • 7
  • 114
  • 129
4

Amazon offers wait condition to wait for the instance to be ready before you can perform other tasks on it. Here is an example might help you

aws ec2 start-instances --instance-ids $instance_id
aws ec2 wait instance-running --instance-ids $instance_id
aws ec2 describe-instances --instance-ids $instance_id --output text|grep ASSOCIATION |awk '{print $3}'|head -1
Prash
  • 558
  • 5
  • 8