2016-08-25 277 views
2

如果变量可能在库存文件或group_vars目录中,我如何从库存中获取变量的值?Ansible:如何从库存或group_vars文件中获取变量的值?

例如,region=place-a可能位于库存文件中或位于group_vars某处的文件中。我想要一个命令能够使用ansible或某些东西检索该值来检索该值。如:

$ ansible -i /somewhere/production/web --get-value region 
place-a 

这将帮助我部署和知道哪个区域正在部署到。

更详细的解释,以澄清,我的库存结构是这样的:

/somewhere/production/web 
/somewhere/production/group_vars/web 

内容与清单文件中的变量,/somewhere/production/web看起来是这样的:

[web:children] 
web1 ansible_ssh_host=10.0.0.1 
web2 ansible_ssh_host=10.0.0.2 

[web:vars] 
region=place-a 

我能得到只需简单地解析文件即可从清单文件中获取价值。像这样:

$ awk -F "=" '/^region/ {print $2}' /somewhere/production/web 
place-a 

但该变量也可能在group_vars文件中。例如:

$ cat /somewhere/production/group_vars/web 
region: place-a 

或者,它可能看起来像一个数组:

$ cat /somewhere/production/group_vars/web 
region: 
    - place-a 

我不想寻找和分析所有可能的文件。

Ansible是否有办法获取值?有点像--list-hosts?所有的

$ ansible web -i /somewhere/production/web --list-hosts 
    web1 
    web2 

回答

0

首先,你必须考虑变量优先如何Ansible工作。

确切的顺序在documentation中定义。下面是一个总结摘录:

基本上,凡是进入“角色的默认值”(默认的角色里面 文件夹)是最可延展的覆盖。 角色的vars目录中的任何内容都将覆盖命名空间中该变量的以前版本 。这里的想法是, 更清晰地显示在范围内,它的命令行优先顺序为 -e额外变量总是获胜。主机和/或库存 变量可以赢得角色默认值,但不明确包括像vars目录或include_vars任务的 。

随着该清理了,看看什么样的价值是可变回吐的唯一方法是使用debug任务如下:

- name: debug a variable 
    debug: 
    var: region 

这将打印出变量region的价值。

我的建议是保持一个值类型,即stringlist以防止tasks在不同的playbooks中混淆。

你可以使用这样的事情:

- name: deploy to regions 
    <task_type>: 
    <task_options>: <task_option_value> 
    // use the region variable as you wish 
    region: {{ item }} 
    ... 
    with_items: "{{ regions.split(',') }}" 

在这种情况下,你可以有一个变量regions=us-west,us-east逗号分隔。 with_items声明会将其拆分为,并对所有区域重复该任务。

最后,没有CLI选项来获取变量的值。

+0

>“不,没有CLI选项来获取变量的值。”太糟糕了,不过谢谢。这就是我想要确定的。 – user3358549

0

另一种更简单的解决方法通过CLI从ansible得到一个变量可能是这样的:

export tmp_file=/tmp/ansible.$RANDOM ansible -i <inventory> localhost -m copy -a "content={{ $VARIABLE_NAME }} dest=$tmp_file" export VARIBALE_VALUE=$(cat $tmp_file) rm -f $tmp_file

看起来很丑陋,但确实是有帮助的。

0

这个CLI版本对于试图连接其他系统的人很重要。在copy模块的使用建立在其他地方,如果你有一个POSIX mktempjq副本本地,然后在这里是一个bash一行程序,做的伎俩从CLI:

export TMP=`mktemp` && ansible localhost -c local -i inventory.yml -m copy -a "content={{hostvars['SOME_HOSTNAME']}} dest=${TMP}" >/dev/null && cat ${TMP}|jq -r .SOME_VAR_NAME && rm ${TMP} 

其分解

# create a tempfile 
export TMP=`mktemp` 

# quietly use Ansible in local only mode, loading inventory.yml 
# digging up the already-merged global/host/group vars 
# for SOME_HOSTNAME, copying them to our tempfile from before 
ansible localhost --connection local \ 
    --inventory inventory.yml --module-name copy \ 
    --args "content={{hostvars['SOME_HOSTNAME']}} dest=${TMP}" \ 
    > /dev/null 

# CLI-embedded ansible is a bit cumbersome. After all the data 
# is exported to JSON, we can use `jq` to get a lot more flexibility 
# out of queries/filters on this data. Here we just want a single 
# value though, so we parse out SOME_VAR_NAME from all the host variables 
# we saved before 
cat ${TMP}|jq -r .SOME_VAR_NAME 
rm ${TMP} 
相关问题