Created
August 31, 2018 07:25
-
-
Save sarathsp06/91a4da9fb4dae3662934ddbb33c4f33a to your computer and use it in GitHub Desktop.
Ansible hosts files gerneration for AWS EC2 instances
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
import sys | |
from boto import ec2 | |
region = 'us-east-1' | |
region = 'ap-southeast-1' | |
region = 'ap-south-1' | |
INSTANCE_STATE_RUNNING = 16 | |
def get_services(conn): | |
rs = conn.get_all_instances(filters={"instance-state-code" : INSTANCE_STATE_RUNNING }) | |
instances = [instance for resource in rs for instance in resource.instances] | |
instance_dict = {} | |
for instance in instances: | |
name = instance.tags.get('Service',None) | |
if name is None: | |
continue | |
name = str(name) | |
private_ip_address = str(instance.private_ip_address) | |
instance_dict[name] = instance_dict.get(name,[]) | |
instance_dict[name].insert(0,private_ip_address) | |
return instance_dict | |
def main(): | |
connection = ec2.connect_to_region(region) | |
if connection is None: | |
print("Unable to connect to region %s", region) | |
with open('hosts', 'w') as the_file: | |
services = get_services(connection) | |
for service,ips in services.iteritems(): | |
if len(sys.argv) == 2 and sys.argv[1] == "local": | |
the_file.write("[%s]\n" % service) | |
the_file.write("localhost ansible_connection=local") | |
the_file.write("\n\n\n") | |
else: | |
if len(ips) > 0: | |
the_file.write("[%s]\n" % service) | |
the_file.write("\n".join(ips)) | |
the_file.write("\n\n\n") | |
if __name__ == "__main__": | |
main() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment