Calling Ansible hostvars group variable at later point in play

ansible

During my playbook I create a variable for one set of machines the apps. Namely a password for a user db_password. It is within the group apps only at this point.

I am trying to recall that variable during a later part of the play for a different set of hosts that belong to a different group using hostvars. I have tried a number of things and it doesn't seem to work. Below is the main playbook as well as the main.yml for the 2 roles called.

My problem is it will not show the variable for the db_password when I try and debug it on the db servers. I think I am on the right track with the hostvars concept but open to new ideas. I know I could also write the output of the set_fact db_password to a file and then move it to the db server and have it be read from that but I am trying to keep this within this one playbook. Any thoughts and help is appreciated

- hosts: 127.0.0.1
  connection: local
  gather_facts: true

- hosts: apps
  roles:
- { role: test_app}

- hosts: db
  roles:
- { role: test_db }

main.yml for test_app

- name: "Setup TPMS {{ app_server_hostname }} | GENERATE password"
 set_fact: db_password={{lookup('password', '/dev/null 
 chars=ascii_letters,digits,hexdigits length=10')}}

 - name: user create
   user:
   name: testing
   update_password: always
   password: "{{ db_password}}"
   state: present

main.yml for test_db

- name: show var
  debug: "{{ hostvars[groups['apps'][0]]['db_password'] }}"

current error I am seeing I am expecting the password to return not hello world

 TASK [test_db : show var] 
 ok: [server104] => {
 "msg": "Hello world!"

Best Answer

The indentation is wrong. Correct indentation is below

- hosts: apps
  roles:
    - { role: test_app}
- hosts: db
  roles:
    - { role: test_db }

.

- name: "Setup TPMS {{ app_server_hostname }} | GENERATE password"
  set_fact:
    db_password: ...
    chars: ...

.

- name: user create
  user:
    name: testing
    update_password: always
    password: "{{ db_password}}"
    state: present