Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass a parameter to Ansible's dynamic inventory

I'm using Ansible to configure some virtual machines. I wrote a Python script which retrieves the hosts from a REST service.
My VMs are organized in "Environments". For example I have the "Test", "Red" and "Integration" environments, each with a subset of VMs.

This Python script requires the custom --environment <ENV> parameter to retrieve the hosts of the wanted environment.

The problem I'm having is passing the <ENV> to the ansible-playbook command. In fact the following command doesn't work

ansible-playbook thePlaybook.yml -i ./inventory/FromREST.py --environment Test

I get the error:

Usage: ansible-playbook playbook.yml

ansible-playbook: error: no such option: --environment

What is the right syntax to pass variables to a dynamic inventory script?

Update:

To better explain, the FromREST.py script accepts the following parameters:

  • Either the --list parameter or the --host <HOST> parameter, as per the Dynamic Inventory guidelines
  • The --environment <ENVIRONMENT> parameter, which I added to the ones required by Ansible to manage the different Environments
like image 657
gvdm Avatar asked Nov 25 '15 15:11

gvdm


People also ask

How do you use dynamic inventory in Ansible Tower?

How do we write Dynamic inventory scripts? You can write inventory scripts in any dynamic language that you have installed on the AWX machine such as shell or python. But you need to start with a normal script shebang line like #!/bin/bash or #!/usr/bin/python and it runs as the awx user.

How does Ansible dynamic inventory work?

In Ansible, Dynamic inventory is generated either by scripts which are written in a programming language like python, php etc. or using available inventory plugins. When using script, they gets all real time data from the target source environments, like Cloud platforms AWS, OpenStack, GCP etc.


2 Answers

I had similar issue, I didn't find any solution, so I just modified my dynamic inventory to use OS Environment variable if the user does not pass --env

Capture env var in your inventory as below:

import os
print os.environ['ENV']

Pass env var to ansible

export ENV=dev
ansible -i my_custom_inv.py all --list-host
like image 159
Rahul Patil Avatar answered Sep 23 '22 21:09

Rahul Patil


A workaround using $PPID to parse -e/--extra-vars from process snapshot.

ansible-playbook -i inventory.sh deploy.yml -e cluster=cl_01

inventory.sh file

#!/bin/bash
if [[ $1 != "--list" ]]; then exit 1; fi
extra_var=`ps -f -p $PPID | grep ansible-playbook | grep -oh "\w*=\w*" | grep cluster | cut -f2 -d=`
./inventory.py --cluster $extra_var

inventory.py returns JSON inventory for cluster cl_01.

Not pretty I know, but works.

like image 26
punkabbestia Avatar answered Sep 23 '22 21:09

punkabbestia