Trying to fetch variable value in playbook, but is yielding to error as per below. Any suggestions to resolve variable?
Here is (eg dynamic ) inventory file ( where group name is not known in playbook )
$ cat ans_hosts
[gname_tools]
<machine_name_goes_here>
<machine_name_goes_here>
<machine_name_goes_here>
[gname_tools:vars]
group_name=gname_tools
clip_id=3
[email protected]
Here is playbook
$ cat var_access.yml
---
- hosts: all
connection: local
gather_facts: false
tasks:
- name: Print Inventory variable
shell: |
cmd: |
echo "{{hostvars['group_name']}}"
register: ExcepStatus
delegate_to: localhost
- debug: msg="{{ExcepStatus.stdout}}"
Here is result of running playbook
$ ansible-playbook -i ans_hosts var_access.yml
PLAY [all] **************************************************************************************************************************************************
TASK [Print Inventory variable] *****************************************************************************************************************************
fatal: [<machine_name_goes_here> -> localhost]: FAILED! => {"msg": "The task includes an option with an undefined variable. The error was: \"hostvars['group_name']\" is undefined\n\nThe error appears to be in '/home/gollip/ans/var_access.yml': line 7, column 6, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n tasks:\n - name: Print Inventory variable\n ^ here\n"}
PLAY RECAP **************************************************************************************************************************************************
<machine_name_goes_here> : ok=0 changed=0 unreachable=0 failed=1 skipped=0 rescued=0 ignored=0
hostvars is a dict of hosts, where each key is a dict of host variables. To fetch a variable from
hostvars, you should first specify the host whose variables you want to access: