使用临时命令列出主机或组的所有 Ansible 变量?

0xC*_*22L 34 ansible

Ansible 变量来自各种来源。例如,可以通过在包含清单文件的文件夹中分别命名为host_vars和的子文件夹中创建 YAML 文件来提供 host_vars 和 group_vars group_vars

如何列出所有的变量Ansible知道一个剧本内的组或主机?注意:我尝试过ansible -m debug -e 'var=hostvars' hostansible -m debug -e '- debug: var=hostvars'但无济于事。

提示:ansible <group|host> -m setup不是正确的答案,因为它并没有包括所有来自其他来源的变量(只包含{ "ansible_facts" : { ... } }在事实上,它甚至不包括通过由动态库存脚本(提供变量。_meta等)。

Ansible 版本:1.9.1。

yae*_*shi 38

ansible -m debug -a "var=hostvars[inventory_hostname]"似乎工作。有效的变量源(host_varsgroup_vars_meta动态清单中的等)都被考虑在内。

使用动态库存脚本hosts.sh

#!/bin/sh
if test "$1" = "--host"; then
        echo {}
else
        cat <<EOF
{
  "ungrouped": [ "x.example.com", "y.example.com" ],
  "group1": [ "a.example.com" ],
  "group2": [ "b.example.com" ],
  "groups": {
    "children": [ "group1", "group2" ],
    "vars": { "ansible_ssh_user": "user" }
  },
  "_meta": {
    "hostvars": {
      "a.example.com": { "ansible_ssh_host": "10.0.0.1" },
      "b.example.com": { "ansible_ssh_host": "10.0.0.2" }
    }
  }
}
EOF
fi
Run Code Online (Sandbox Code Playgroud)

你可以得到:

$ chmod +x hosts.sh
$ ansible -i hosts.sh a.example.com -m debug -a "var=hostvars[inventory_hostname]"
a.example.com | success >> {
    "var": {
        "hostvars": {
            "ansible_ssh_host": "10.0.0.1", 
            "ansible_ssh_user": "user", 
            "group_names": [
                "group1", 
                "groups"
            ], 
            "groups": {
                "all": [
                    "x.example.com", 
                    "y.example.com", 
                    "a.example.com", 
                    "b.example.com"
                ], 
                "group1": [
                    "a.example.com"
                ], 
                "group2": [
                    "b.example.com"
                ], 
                "groups": [
                    "a.example.com", 
                    "b.example.com"
                ], 
                "ungrouped": [
                    "x.example.com", 
                    "y.example.com"
                ]
            }, 
            "inventory_hostname": "a.example.com", 
            "inventory_hostname_short": "a"
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


KCD*_*KCD 5

在上面的非常好的答案中添加一个小提示,如果您想以编程方式浏览,您可以

使用hostvars的现有答案:

ansible -m debug myhost -a "var=hostvars[inventory_hostname].ansible_version"
Run Code Online (Sandbox Code Playgroud)

ansible_facts是空的,因为debug不运行该setup模块。因此,您需要jq在修剪输出以使其有效的 json 之后尝试一些额外的操作。

ansible -m setup myhost | sed 's#.*SUCCESS =>##' | jq .ansible_facts.ansible_all_ipv4_addresses
Run Code Online (Sandbox Code Playgroud)

我认为人们在调查 ansible 事实中返回的巨大文本墙时可能会发现这很有用,当你只想要一件事时jq .ansible_facts.ansible_devices.vda.size