Tag Archives: ec2

boto3 – discover ec2 internal IPs

🔐 Programmatically Discovering RHEL Ansible Node IPs in AWS (Boto3)


support@whitefeathers.org

In automated RHEL + Ansible environments on AWS, hardcoding host IPs doesn’t scale.
This small utility queries EC2 and prints private IP addresses for instances matching a naming
convention (ansible-rhel*) inside a specific VPC.

🧠 What this script does

  • Connects to EC2 in us-east-1
  • Filters by VPC ID and Name tag pattern ansible-rhel*
  • Limits results to instances in the running state
  • Returns/prints one private IP per line (ideal for inventory pipelines)

⚙️ Filters used

  • Region: us-east-1
  • VPC: vpc-0fc278c7fb8ffdbee (note: your comment references vpc-03ac09e77d044aabc)
  • Name tag: ansible-rhel*
  • State: running

Tip: If you meant the VPC in the header comment, update the filter to match it.

🧩 Source Code


# This function retrieves all internal IP addresses of RHEL Ansible nodes
# located in the 'us-east-1' region within the VPC 'vpc-03ac09e77d044aabc'.
# It returns a list of IP addresses, each on a new line, for instances
# whose names start with 'ansible-rhel*'.
# support@whitefeathers.org

import boto3  # Corrected import statement

def get_rhel_ansible_node_ips():
    """
    Retrieve the private IP addresses of running RHEL instances in a specified VPC.

    This function uses the Boto3 library to interact with the AWS EC2 service. It filters instances
    based on the provided VPC ID and a tag that matches 'ansible-rhel*'. The function returns a list
    of private IP addresses for all instances that are currently in the 'running' state.

    Returns:
        list: A list of private IP addresses of the matching EC2 instances.
    """
    ec2 = boto3.client('ec2', region_name='us-east-1')
    response = ec2.describe_instances(
        Filters=[
            {'Name': 'vpc-id', 'Values': ['vpc-0fc278c7fb8ffdbee']},
            {'Name': 'tag:Name', 'Values': ['ansible-rhel*']},
            {'Name': 'instance-state-name', 'Values': ['running']}
        ]
    )

    ip_addresses = []
    for reservation in response['Reservations']:
        for instance in reservation['Instances']:
            ip_addresses.append(instance['PrivateIpAddress'])

    return ip_addresses

def main():
    ip_addresses = get_rhel_ansible_node_ips()
    for ip in ip_addresses:
        print(ip)

if __name__ == "__main__":
    main()

📤 Example Output


10.20.4.17
10.20.4.23
10.20.5.11

🔄 Common extensions

  • Emit JSON for a dynamic Ansible inventory
  • Add additional filters (AMI, AZ, instance type)
  • Assume-role support for cross-account discovery
  • Pipe into post-patch validation workflows

© WhiteFeathers.org — automation patterns for AWS, RHEL, and Ansible.