Wrong use of hostvars in a Ansible lab

Hi guys!

While taking the lab Project - File Separation in the Ansible Advanced Course I found and issue.

One of the tasks for lampweb host, copies a config from a template (templates/index.php.j2).

In that template the following hostvars is defined:

$link = mysqli_connect("{{ hostvars['lamp-db']['ansible_facts']['eth0']['ipv4']['address'] }}", "{{ hostvars['lamp-db']['dbuser'] }}", "{{ hostvars['lamp-db']['dbpassword'] }}", "{{ hostvars['lamp-db']['dbname'] }}");

Here are two issues:

  1. eth0 is not directly defined in the host facts. It should be ansible_eth0 instead.
  2. When we use hostvars to access host variables from another host, we shouldn’t access them through ansible_facts as it’s in the previous hostvars: hostvars['lamp-db']['ansible_facts']['eth0']

Hostvars should be accessible directly. Like this: hostvars['lamp-db']['ansible_eth0']

FIX:
In the template file templates/index.php.j2

Replace:

$link = mysqli_connect("{{ hostvars['lamp-db']['ansible_facts']['eth0']['ipv4']['address'] }}", "{{ hostvars['lamp-db']['dbuser'] }}", "{{ hostvars['lamp-db']['dbpassword'] }}", "{{ hostvars['lamp-db']['dbname'] }}");

By:

$link = mysqli_connect("{{ hostvars['lamp-db']['ansible_eth0']['ipv4']['address'] }}", "{{ hostvars['lamp-db']['dbuser'] }}", "{{ hostvars['lamp-db']['dbpassword'] }}", "{{ hostvars['lamp-db']['dbname'] }}");

Without this change, the playbook execution will fail, after making the change I tested it, and confirmed the playbook is successfully executed.

Hi @maikycr28

Which question number are you working on, and what validation error are you facing? Could you please share a screenshot of the error?