Generating an Ansible Inventory

The main goal of this topic is to describe and give some examples about how to automatize your software deployment with Ansible.

Before reading this topic, you need to know how to use and create a playbook for Ansible. If you do not, see Ansible documentation.

Step 1: Create the Infrastructure

  1. Create VMs using boto2 with two reservations with the following characteristics based on front and database roles:

    reservation_front = outscale_fcu.run_instances(images_id='ami-xxxxxxx', key_name='my_keypair', security_group_ids=['sg-xxxxxx'], min_count=2, max_count=3, instance_type='t2.medium')
    reservation_database = outscale_fcu.run_instances(images_id='ami-xxxxxxx', key_name='my_keypair', security_group_ids=['sg-yyyyyy'], min_count=2, max_count=2, instance_type='tina.c4r12')
  2. For each VM, add the following roles tags:

    for instance in reservation_front.instances:
        instance.add_tag('roles', 'monitoring_agent,front_web')
    for instance in reservation_database:
        instance.add_tag('roles', 'monitoring_agent,database')

Step 2: Generate the inventory

To generate the inventory, you can use your Ansible playbook, based on the previous deployment on the OUTSCALE Cloud. The playbook requires the following elements:

  • All security groups need to allow the VM running the playbook on SSH port 22

  • The VM running the playbook needs to have the private key of the VMs

  • The playbook needs to run from within the VPC if you target a VPC deployment

  • To generate the inventory, run the following commands:

    code
    from ConfigParser import ConfigParser
    
    
    conf = ConfigParser(allow_no_value=True)
    
    for inst in outscale_fcu.get_only_instances():
        for role in inst.tags['roles'].split(','):
            if role not in conf.sections():
                conf.add_section(role)
            conf.set(role, inst.private_ip_address)
    with open('inventory', 'w') as inv:
        conf.write(inv)

These commands return the following result:

output
[database]
10.0.1.243
10.0.2.153
10.0.2.53
[front_web]
10.0.2.104
10.0.2.156
[rabbit_mq]
10.0.2.6
[intel]
10.0.2.154
10.0.2.203
10.0.2.155
10.0.2.243

Related Page