How to access hostvars in playbook

hi folks
here is my host file

[target1] ansible_user=ec2-user ansible_ssh_private_key_file=/root/ansible_by_kodekloud/hybrid.pem

[target2] ansible_alias=target2 ansible_user=ec2-user ansible_ssh_private_key_file=/root/ansible_by_kodekloud/hybrid.pem dns_ip=

and the playbook is here

- name: variables
  hosts: all
  - shell:
      echo "{{hostvars['target2'][ansible_facts][mount]}}" > /tmp/my
  - debug:
      msg: "{{hostvars['target2'].dns_ip}}"

i want to access the variable of target2 but i am not able to access this info
if any idea where i am doing wrong let me know thanks

Hi @abhineetsaxena05, can you change your variable for ansible_host for example and try this:

hostvars is a hash with inventory hostnames as keys.
To access fields of each host, use hostvars['test-1'] , hostvars['test2-1'] , etc.

ansible_ssh_host is deprecated in favor of ansible_host since 2.0.
So you should first remove “_ssh” from inventory hosts arguments (i.e. to become “ansible_user”, “ansible_host”, and “ansible_port”), then in your role call it with:

{{ hostvars['your_host_group'].ansible_host }}

Vitor Jr.
KodeKloud Support