Thursday, May 28, 2020

Ansible - accessing hostname defined in another group

I had a use case where the target server I was running the ansible playbook against needed to know the hostname of another group (defined in the hosts file) that I passed in as an environment variable named "target_env".

CentOS Linux release 7.3.1611 (Core)
ansible 2.9.9

The hosts file had three groups defined, with only one hostname associated with each group:
[development] ansible_connection=local



i.e. I need target server to know the hostname of target_env production.  In this case the target_env "production" had hostname associated to it.
ansible-playbook cherryshoe.yml -u YOUR_USER_ON_TARGET_SERVER -k -K -e '' 'target_env=production'

These ansible magic variables didn't work:
- debug: var=inventory_hostname - had the hostname where the script was being run against (in this example
- debug: var=ansible_hostname - had hostname localhost

There were two solutions to this problem:
1. Access it via hostvars magic variable
- debug: msg="{{hostvars[inventory_hostname]['groups'][target_env][0]}}"

This works because the hostvars magic variable holds the following type of information that you can see when you debug the variable
- debug: var=hostvars

The "groups" attribute inside hostvars[inventory_hostname] has the "target_env" production and if you access the first element in the array it's "", which is what we want:
"groups": {
    "all": [
    "development": [
    "test": [
    "production": [
    "ungrouped": []

2.  Another way to do this was a hash variable in a group variables file,

and access it using:
- debug: msg=""{{hostnames[target_env]}}"

These articles were helpful:

No comments:

Post a Comment

I appreciate your time in leaving a comment!