How to return private IP from ansible dynamic inventory on AWS?
Here is a working sample of ec2.ini (tested with ansible 2.1 & 2.3.1)
[ec2]
regions = us-east-1,us-west-2
regions_exclude =
destination_variable = private_ip_address
hostname_variable = peerio
vpc_destination_variable = private_ip_address
route53 = False
rds = False
elasticache = False
all_instances = False
#instance_states = pending, running, shutting-down, terminated, stopping, stopped
all_rds_instances = False
all_elasticache_replication_groups = False
all_elasticache_clusters = False
all_elasticache_nodes = False
cache_path = ~/.ansible/tmp
cache_max_age = 300
nested_groups = False
replace_dash_in_groups = True
expand_csv_tags = False
group_by_instance_id = True
group_by_region = True
group_by_availability_zone = True
group_by_ami_id = True
group_by_instance_type = True
group_by_key_pair = True
group_by_vpc_id = True
group_by_security_group = True
group_by_tag_keys = True
group_by_tag_none = True
group_by_route53_names = True
#pattern_include = staging-*
#pattern_exclude = staging-*
#instance_filters = instance-type=t1.micro,tag:env=staging
#only process items we tagged
instance_filters = tag:serviceclass=*
boto_profile = ansible
Then, instances should be listed using their private IP as identifier:
./ec2.py --list
{
"_meta": {
"hostvars": {
"10.255.100.138": {
"ansible_ssh_host": "10.255.100.138",
"ec2__in_monitoring_element": false,
"ec2_ami_launch_index": "0",
... "ec2_vpc_id": "vpc-57ed3733"
},
"10.255.100.142": {
"ansible_ssh_host": "10.255.100.142",
"ec2__in_monitoring_element": false,
...
Within ec2.ini, edit this line:
vpc_destination_variable = ip_address
To this:
vpc_destination_variable = private_ip_address
From ec2.ini:
# For server inside a VPC, using DNS names may not make sense. When an instance
# has 'subnet_id' set, this variable is used. If the subnet is public, setting
# this to 'ip_address' will return the public IP address. For instances in a
# private subnet, this should be set to 'private_ip_address', and Ansible must
# be run from within EC2. The key of an EC2 tag may optionally be used; however
# the boto instance variables hold precedence in the event of a collision.
# WARNING: - instances that are in the private vpc, _without_ public ip address
# will not be listed in the inventory until You set:
# vpc_destination_variable = private_ip_address
vpc_destination_variable = ip_address
https://github.com/ansible/ansible/blob/devel/contrib/inventory/ec2.ini