Getting Public IP address of EC2 instance from outside using AWS-cli

An ec2 instance can be identified by its instance-id, which will never change, no matter how many times you stop and start the instance. So you can try this out if you have an instance id and you need its IP address.

For public IP address:

aws ec2 describe-instances --instance-ids i-b78a096f | grep PublicIpAddress | awk -F ":" '{print $2}' | sed 's/[",]//g'

For private IP address:

aws ec2 describe-instances --instance-ids i-b78a096f | grep PrivateIpAddress  | head -1 | awk -F ":" '{print $2}' | sed 's/[",]//g'

Still, I personally think that it would be much much better if you try the same thing in python. I have implemented same logic in my previous organization with the python boto library and it was much more simple and manageable.

setting up virtual env:

#!/usr/bin/env bash

set -e
HOME_DIR=/home/$(whoami)

#Dependencies
sudo apt-get install ncurses-devel patch openssl openssl-devel zlib-devel

# Install python locally
mkdir -p $HOME_DIR/src
mkdir -p $HOME_DIR/.localpython
cd $HOME_DIR/src
wget https://www.python.org/ftp/python/2.7.8/Python-2.7.8.tgz
tar -zxvf Python-2.7.8.tgz
cd Python-2.7.8
./configure --prefix=$HOME_DIR/.localpython 
make
make install

# Install virtualenv locally
cd $HOME_DIR/src
wget --no-check-certificate https://pypi.python.org/packages/source/v/virtualenv/virtualenv-1.11.6.tar.gz#md5=f61cdd983d2c4e6aeabb70b1060d6f49
tar -zxvf virtualenv-1.11.6.tar.gz
cd virtualenv-1.11.6/
~/.localpython/bin/python setup.py install 


# Create a test virtual environment
mkdir -p $HOME_DIR/virtualenvs
cd $HOME_DIR/virtualenvs
~/.localpython/bin/virtualenv my_virtual_env --python=$HOME_DIR/.localpython/bin/python2.7
cd my_virtual_env
source bin/activate
pip install awscli