bash 将参数传递给 Ansible 的动态库存
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33920530/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Pass a parameter to Ansible's dynamic inventory
提问by gvdm
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.
我正在使用 Ansible 配置一些虚拟机。我编写了一个 Python 脚本,它从 REST 服务中检索主机。
我的虚拟机组织在“环境”中。例如,我有“测试”、“红色”和“集成”环境,每个环境都有一个虚拟机子集。
This Python script requires the custom --environment <ENV>
parameter to retrieve the hosts of the wanted environment.
此 Python 脚本需要自定义--environment <ENV>
参数来检索所需环境的主机。
The problem I'm having is passing the <ENV>
to the ansible-playbook
command.
In fact the following command doesn't work
我遇到的问题是将 传递<ENV>
给ansible-playbook
命令。事实上下面的命令不起作用
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:
为了更好地解释,该FromREST.py
脚本接受以下参数:
- 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
- 无论是
--list
参数或--host <HOST>
参数,按照该动态清单指南 - 该
--environment <ENVIRONMENT>
参数,我添加到 Ansible 管理不同环境所需的参数中
回答by Rahul Patil
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
我有类似的问题,我没有找到任何解决方案,所以我只是修改了我的动态清单以使用 OS Environment 变量,如果用户没有通过 --env
Capture env var in your inventory as below:
在您的清单中捕获 env var,如下所示:
import os
print os.environ['ENV']
import os
print os.environ['ENV']
Pass env var to ansible
将 env var 传递给 ansible
export ENV=dev
ansible -i my_custom_inv.py all --list-host
export ENV=dev
ansible -i my_custom_inv.py all --list-host
回答by punkabbestia
A workaround using $PPID
to parse -e
/--extra-vars
from process snapshot.
$PPID
用于解析-e
/--extra-vars
来自进程快照的解决方法。
ansible-playbook -i inventory.sh deploy.yml -e cluster=cl_01
inventory.sh
file
inventory.sh
文件
#!/bin/bash
if [[ != "--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
.
inventory.py
返回JSON
cluster 的库存cl_01
。
Not pretty I know, but works.
不漂亮,我知道,但有效。