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:
--list
parameter or the --host <HOST>
parameter, as per the Dynamic Inventory guidelines
--environment <ENVIRONMENT>
parameter, which I added to the ones required by Ansible to manage the different EnvironmentsHow 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.
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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With