Skip to main content
Home
badllama.com
  • Search
  • Log In

How to manage a dynamic inventory using ansible on AWS

cpeters's picture

Mon, 09/05/2016 - 22:30 by cpeters

Building on the ansible tutorial from earlier, this tutorial shows you how to use your existing virtual environment to control your AWS ansible inventory. This saves you from having to upload playbooks and maintain ansible installations - basically you can run your playbooks from your work station using your workstation's ansible installation to send commands to your inventory over SSH.

Step 1: Download the dynamic inventory script from ansible

mkdir ~/Projects/27-python/ec2-dynamic-inventory/
cd ~/Projects/27-python/ec2-dynamic-inventory/
wget https://raw.githubusercontent.com/ansible/ansible/devel/contrib/inventory/ec2.py
chmod +x ec2.py
wget https://raw.githubusercontent.com/ansible/ansible/devel/contrib/inventory/ec2.ini
export ANSIBLE_HOSTS=/Users/[USERNAME]/Projects/27-python/ec2-dynamic-inventory/ec2.py

Step 2: Update the ec2.ini file

regions_exclude = ap-south-1,us-gov-west-1,cn-north-1

Step 3: Setup your project directory and private key

mkdir ~/Projects/27-python/hello-world/
cd ~/Projects/27-python/hello-world/
mv ~/inventory.ini ~/Projects/27-python/hello-world/
mv ~/hello-world.yml ~/Projects/27-python/hello-world/
wget https://raw.githubusercontent.com/ansible/ansible/devel/examples/ansible.cfg
cp ~/[KEYPAIR].pem ~/.ssh

Step 4: update ansible.cfg

remote_user = ec2-user
private_key_file = /Users/[USERNAME]/.ssh/[KEYPAIR].pem

Step 5: Set up an ssh agent and activate your virtual environment

The agent and the new keypair will be loaded by default the next time you start a terminal window, but for now we need to start a new agent.

~/Projects/27-python/$ ssh-agent bash
~/Projects/27-python/$ ssh-add ~/.ssh/[KEYPAIR].pem
~/Projects/27-python/$ source bin/activate

Check to make sure your keypair is loaded using

ssh-add -l

Test the inventory and the SSH connection

~/Projects/27-python/ec2-dynamic-inventory/ec2.py --list
~/Projects/27-python/hellow-world/ansible -m ping ec2
Tags: 
AWS ansible ec2 inventory
Powered by Backdrop CMS