Hello,
I am trying to use hostvars to get an inventory hostname and a specific variable. The goal of this is to get from the app group, get each unique servers client_name. The below command works for just the first line as I am fairly confident the 0 means first item in the inventory file.
I need to get it to be a per line item of the inventory file so that each servers client name is read out. I have tried a couple variations but I can’t seem to get this correct. Can anyone provide any insight as to what I might be doing wrong.
“{{ hostvars[groups[‘apps’][0]][‘client_name’] }}”
inventory file
[apps]
server1 instance_user=fondinst client_name=fondprd1 server_ip=
server2 instance_user=kumcinst client_name=kumcprd1 `server_ip=
[proxy]
proxy1
Playbook
-
hosts: 127.0.0.1
connection: local
gather_facts: no
-
hosts: app
tasks:
-
name: debug
debug: msg={{ client_name }}
-
hosts: proxy
tasks:
-
name: debug
debug: msg=“{{ hostvars[groups[‘apps’][0]][‘client_name’] }}”
Summary
Correct syntax for hostvars calling from a certain group, for an inventory_hostname name, getting a variable
Linux Rhel6
Ansible version 2.4.4.4
component name:
Ansible
You need to loop over groups['apps'] with with_items.
- debug: msg="{{ item['client_name'] }}"
with_items: "{{ groups['apps'] }}"
When running the command it stated there was an undefined variable I made the below changes to the playbook
=> {“msg”: "The task includes an option with an undefined variable. The error was: ‘ansible.utils.unsafe_proxy.AnsibleUnsafeText object’ has no attribute ‘client_name’\n\nThe error appears to have been in ‘/etc/ansible/testing/prod_inov2.yml’
inventory file
[apps]
server1 instance_user=fondinst client_name=fondprd1 server_ip=
server2 instance_user=kumcinst client_name=kumcprd1 `server_ip=
[proxy]
proxy1
-
hosts: 127.0.0.1
connection: local
gather_facts: no
-
hosts: apps
tasks:
-
name: debug
debug: msg={{ client_name }}
-
hosts: proxy
tasks:
-
debug: msg=“{{ item[‘client_name’] }}”
with_items: “{{ groups[‘apps’] }}”
Sorry about that it should of course be
- debug: msg="{{ hostvars[item]['client_name'] }}"
with_items: "{{ groups['apps'] }}"
Yeah that worked for a debugging scenario so awesome and thanks for that.
Might you have any idea how to use those called variables to edit text
files? Namely here is the bigger playbook I am trying within the proxy
role. I am trying to have it change the name of the .conf file as well as
manipulate text within the prod_proxy_conf.j2. It keeps stating that there
is an undefined variable however any thoughts?
Without the actual output it's impossible to help.
proxy role main.yml
- name: " Proxy | Setup Proxy"
template:
src: /etc/ansible/files/proxy_files/prod_proxy_conf.j2
dest: /etc/httpd/conf.d/ "{{ hostvars[item]['client_name'] }}".conf
You can't use double quotes in dest, unless you filename actually contains quotes.
dest: /etc/httpd/conf.d/{{ hostvars[item]['client_name'] }}.conf