2
votes

I would like to get all IP addresses for the ec2 instance. I am looking at the CLI aws ec2 describe-instances and I see that we have 2 places where we have IP address. I understand each interface can have own public IP/private IP and can belong to different subnets hence the fields under Network Interfaces. But what is not clear to me why we have IP address (public/private) and subnet under instance. Won't that data be part of one of the interface. Is there anything this signifies. why this duplication?``

e.g. aws ec2 describe-instances

"Instances": [
    {
    *** I have IP address and subnet here ***
    "PrivateIpAddress": "10.0.0.19",
    "SubnetId": "subnet-12345678",
    "NetworkInterfaces": [
    ***I also have IP address, subnetId for each interface here**
    "PrivateIpAddress": "10.0.0.19",
    "SubnetId": "subnet-12345678",
    }
]
2
The NetworkInterfaces section contains a subset of the DescribeNetworkInterfaces API call (aws ec2 describe-network-interfaces command). This contains additional details about the network interfaces attached to the instance. Some people may find this information useful (like the mac address or the network interface id).krishna_mee2004
I understand that but my question was why put only one IP address and one subnet info under instances when an instance could have multiple of them which are rightfully present under interfaces. What is the relevance of ip address and subnet under the instance?saws
The first one shows the IP address of primary interface network interface.krishna_mee2004

2 Answers

4
votes

You will have to iterate with some programming language, since NetworkInterfaces is a list and so is PrivateIpAddresses.

https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-instances.html

JQ would give you the output needed.

aws ec2 describe-instances  --instance-id i-1234567890qwertyu --output json | jq .Reservations[].Instances[].NetworkInterfaces[].PrivateIpAddresses[].PrivateIpAddress -r
10.0.1.247
10.0.1.246
0
votes

The private Ip address is the primary IP assigned to the instance. Below is a code snippet in Python to get this:

ec2 = boto3.resource('ec2')

filters = [{
    <if-any>
     }]

instances = ec2.instances.filter(Filters=filters)

for instance in instances:
    print(instance.private_ip_address)