jamescompi
jamescompi

Reputation: 11

I am trying to get a public IP from an instance I am just starting up

I need to go from spinning up a server using the AWS CLI then to ssh into it all in one script. I can get as far as loading the instance id into a variable but I need to then reformat it to push it to AWS to then get the public IP.

#!/bin/bash

azid=`(hidden for obvious reasons)`
azpswd=`(hidden for obvious reasons)`
hostip=`curl http://icanhazip.com`
COUNTER=120

#make a file to hold json information
touch instance.txt

#login to azure requireing webpage (not needed on cloud9)
#az login -u $azid -p $azpswd

#make a key pair and add to a variable (only needed one time)
#mykey=`aws ec2 create-key-pair --key-name MyKeyPair`

#open ports on security group only needed one time
#aws ec2 authorize-security-group-ingress --group-id sg-################# --protocol tcp --port 22 --cidr $hostip/32
#aws ec2 authorize-security-group-ingress --group-id sg-################# --protocol tcp --port 80 --cidr 0.0.0.0/0
#aws ec2 authorize-security-group-ingress --group-id sg-################# --protocol tcp --port 8080 --cidr 0.0.0.0/0
#aws ec2 authorize-security-group-ingress --group-id sg-################# --protocol tcp --port 32400 --cidr 0.0.0.0/0

#launch instance and add ouptut to variable 
aws ec2 run-instances --image-id ami-024a64a6685d05041 --count 1 --instance-type t2.micro --key-name MyKeyPair --security-group-ids sg-################# --subnet-id subnet-################# > instance.txt 

#pull instance id from instance.txt
inid=`grep "InstanceId" instance.txt`

#testing
echo $inid

#wait for vm to spin up
for ((i=COUNTER; i>=1; i--))
do sleep 1
    echo $i
done

#get public ip from instance id
inip=`aws ec2 describe-instances --instance-ids $inid | grep PublicIpAddress`

#test
echo $inip

#ssh into freshly spun up server
ssh -i 'MyKeyPair.pem' ubuntu@$inip

Pulling an Instance ID from the json file then reformatting it to work with aws ec2 describe-instances to then pull down the public ip once the server is spun up. Then after all that ssh into it and push a kickstart file so that the freshly spun up server will run plex in a docker.

Upvotes: 0

Views: 173

Answers (1)

John Rotenstein
John Rotenstein

Reputation: 269666

If you wish to install software on an Amazon EC2 instance after it starts up for the first time, then you should provide a script via User Data.

See: Running Commands on Your Linux Instance at Launch - Amazon Elastic Compute Cloud

The script will run as root. To debug the script, look in:

/var/log/cloud-init-output.log

This technique is used by all AWS users and is much more reliable than the method you are attempting to accomplish.

Upvotes: 2

Related Questions