ansible_fqdn 的 Ansible 值不一致

Ansible inconsistent value for ansible_fqdn

变量{{ansible_fqdn}} 可以取两个不同的值:服务器的短名称(server300) 或长名称(server300.prod.x.y.z)。 当我们在 playbook 中使用此变量检索文件 {{ansible_fqdn}}.crt 时,根据选择的值,可能找不到文件,并且 playbook 将失败。 为了使服务器列表中的主机名具有一致的值,应该使用 {{ansible_hostname}}(来自 linux 命令 uname -n 的短主机名)和 {{inventory_hostname}}(来自“hosts”的长主机名“文件)代替? 或者有没有办法从 {{ansible_fqdn}}?

获得一致的值

问:”变量{{ ansible_fqdn }}可以取两个不同的值:服务器的短名称(server300)或其长名称(server300.prod.x.y.z)."

答:这取决于你如何配置hostname。看看uname -n。要么长

[admin@test_23 ~]$ uname -n
test_23.example.com

shell> ansible test_23 -m setup | grep ansible_fqdn
        "ansible_fqdn": "test_23.example.com",

,或者是短

[admin@test_11 ~]$ uname -n
test_11

shell> ansible test_11 -m setup | grep ansible_fqdn
        "ansible_fqdn": "test_11",

问:“是否应该使用 {{ ansible_hostname }}(来自 linux 命令 uname -n 的短主机名)和 {{ inventory_hostname }}(来自“hosts”文件的长主机名)?

答:这取决于你如何配置inventory. The variable ansible_hostname is not required. If you don't run setup (or get the variables from a cache),如果你没有明确声明它就不会被定义,例如

shell> cat hosts
test_23

shell> ansible test_23 -m debug -a var=inventory_hostname
test_23 | SUCCESS => {
    "inventory_hostname": "test_23"
}
shell> ansible test_23 -m debug -a var=ansible_hostname
test_23 | SUCCESS => {
    "ansible_hostname": "VARIABLE IS NOT DEFINED!"
}

您可以声明aliasansible_hostname,例如

shell> cat hosts
alias_of_test_23 ansible_hostname=test_23

shell> ansible alias_of_test_23 -m debug -a var=inventory_hostname
alias_of_test_23 | SUCCESS => {
    "inventory_hostname": "alias_of_test_23"
}
shell> ansible alias_of_test_23 -m debug -a var=ansible_hostname
alias_of_test_23 | SUCCESS => {
    "ansible_hostname": "test_23"
}

如果你 运行 setup ansible_hostname 的值是命令 uname -n,例如

shell> cat hosts
alias_of_test_23 ansible_host=test_23.example.com

shell> ansible alias_of_test_23 -m setup | grep ansible_hostname
        "ansible_hostname": "test_23",

问:“或者有没有办法从{{ ansible_fqdn }}中获取一致的值?”

答:还有更多选项:

  • 在远程主机上,配置主机名以向您提供 FQDN

  • 在清单中,声明别名的 FQDN 形式并使用 inventory_hostname

  • 如果上述选项不可行,您必须声明一个自定义变量。

一致性由您决定。