The variable {{ansible_fqdn}} can take two different values: the server's short name (server300) or its long name (server300.prod.x.y.z).
When we use this variable in the playbook to retrieve a file {{ansible_fqdn}}.crt, depending on the value chosen, the file can be not found, and the playbook will fail.
To have a consistent value for hostnames over a list of servers, should one rather use {{ansible_hostname}} (short hostname from linux command uname -n) and {{inventory_hostname}} (long hostname from "hosts" file) instead?
Or is there a way to obtain a consistent value from {{ansible_fqdn}}?
Q: "The variable {{ ansible_fqdn }} can take two different values: the server's short name (server300) or its long name (server300.prod.x.y.z)."
A: It depends on how you configure hostname. Take a look at uname -n. Either it is long
[admin@test_23 ~]$ uname -n
test_23.example.com
shell> ansible test_23 -m setup | grep ansible_fqdn
"ansible_fqdn": "test_23.example.com",
, or it is short
[admin@test_11 ~]$ uname -n
test_11
shell> ansible test_11 -m setup | grep ansible_fqdn
"ansible_fqdn": "test_11",
Q: "Should one rather use {{ ansible_hostname }} (short hostname from linux command uname -n) and {{ inventory_hostname }} (long hostname from "hosts" file) instead?"
A: It depends on how you configure the inventory. The variable ansible_hostname is not required. If you don't run setup (or get the variables from a cache) and if you don't declare it explicitly it won't be defined, e.g.
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!"
}
You can declare alias and ansible_hostname, e.g.
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"
}
If you run setup the value of ansible_hostname is the short hostname from the command uname -n, e.g.
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",
Q: "Or is there a way to obtain a consistent value from {{ ansible_fqdn }}?"
A: There are more options:
At remote hosts, configure hostnames to provide you with the FQDN
In the inventory, declare the FQDN form of aliases and use inventory_hostname
If the options above are not feasible you'll have to declare a custom variable.
The consistency is up to you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With