Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use ec2.py and localhost at the same time

How can I use the ec2.py to get a dynamic list of ec2 hosts and also use localhost as a host. I have googled over and over and can't seem to find a good solution. I have come across some close answers but all seem to require breaking your tasks down into two separate playbooks that can't be run at the same time.

like image 891
kidbrax Avatar asked Jun 03 '14 20:06

kidbrax


3 Answers

This isn't the only solution—valid suggestions have been made—but what I almost always end up doing when using the EC2 inventory plugin is exploiting an Ansible feature that I think many people don't know about: you can use a directory as inventory.

Ansible looks for executables and flat files in a directory and merges their results. This is very helpful because you can use a flat file to make nice aliases for dynamic groups, and add localhost in there, possibly setting some variables for it.

$ tree inventory/staging
inventory/staging
├── base
├── ec2.ini
├── ec2.py
└── group_vars -> ../group_vars

An excerpt of the file base looks like this:

[localhost]
# I need to tell Ansible which Python on my system has boto for AWS
127.0.0.1 ansible_python_interpreter=/usr/local/bin/python

# The EC2 plugin will populate these groups, but we need to add empty entries
# here to make aliases for them below.
[tag_Stage_staging]
[tag_Role_webserver]

[staging:children]
tag_Stage_staging

[webservers:children]
tag_Role_webserver

You then just point to the directory for inventory:

$ ansible -i inventory/staging webservers -m ec2_facts
# OR
$ export ANSIBLE_HOSTS=inventory/staging
$ ansible webservers -m ec2_facts
like image 121
ches Avatar answered Oct 19 '22 03:10

ches


I was trying to solve a similar issue.

I had a bunch of hosts which accepted connections from the Ansible host. For security reasons the Ansible host was not allowed to connect to itself. However, I needed to run the Common play on all host.

I specified all hosts, excluded the Ansible host, and then added localhost:

- name: Common
  hosts: "tag_name_*:!tag_name_ansible:localhost"
  roles:
    - common

Adding localhost worked fine even when using the EC2 inventory script. I am using Ansible 1.7 with an up-to-date EC2 inventory script.

like image 43
JockeTF Avatar answered Oct 19 '22 03:10

JockeTF


I think you can achieve what you want to do using the -l parameter of the ansible-playbook command.

We do something similar and the ansible-playbook command we use looks similar to this

ansible-playbook -l tag_foo_bar:localhost -U username -i ec2.py playbook.yml

The part after the -l is just an ansible pattern (http://docs.ansible.com/intro_patterns.html) which means "limit execution to all instances with tag 'foo=bar' AND the localhost host". The important part is the colon which just means "and".

like image 43
Woodham Avatar answered Oct 19 '22 04:10

Woodham