简体   繁体   English

将参数传递给 Ansible 的动态库存

[英]Pass a parameter to Ansible's dynamic inventory

I'm using Ansible to configure some virtual machines.我正在使用 Ansible 配置一些虚拟机。 I wrote a Python script which retrieves the hosts from a REST service.我编写了一个 Python 脚本,它从 REST 服务中检索主机。
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.此 Python 脚本需要自定义--environment <ENV>参数来检索所需环境的主机。

The problem I'm having is passing the <ENV> to the ansible-playbook command.我遇到的问题是将<ENV>传递给ansible-playbook命令。 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:为了更好地解释, FromREST.py脚本接受以下参数:

  • Either the --list parameter or the --host <HOST> parameter, as per the Dynamic Inventory guidelines --list参数或--host <HOST>参数,根据动态清单指南
  • The --environment <ENVIRONMENT> parameter, which I added to the ones required by Ansible to manage the different Environments --environment <ENVIRONMENT>参数,我将其添加到 Ansible 管理不同环境所需的参数中

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我有类似的问题,我没有找到任何解决方案,所以如果用户没有通过--env ,我只是修改了我的动态清单以使用 OS 环境变量

Capture env var in your inventory as below:在您的清单中捕获 env var,如下所示:

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

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 [[ $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 . inventory.py返回集群cl_01 JSON清单。

Not pretty I know, but works.我知道不漂亮,但有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM