Search code examples
ansiblevaransible-facts

How can I access a specific NIC IP address based on a var defined in my playbook?


I have different playbooks defined, using the same ROLE. In one of the ROLE templates, I have to write the IP address of a specific NIC card, which is defined in my playbook because it depends on the host.

So, In my playbook I have defined this var:

vars:
      # NIC I want to use
      - nic_card: ens192

And in my ROLE main.yml file, I tried to do that:

host_specific_address: "{{ ansible_facts['ansible_{{ nic_card }}']['ipv4']['address'] }}"

As you can see I tried to define the host_specific_address using ansible_facts and nic_card var.

Unfortunately that didn't work as expected. I tried other combinaisons but I think I'm on the wrong way.

How can I access a specific NIC IP address based on a var defined in my playbook?

Thank you for your help!


Solution

  • specific_address: "{{ ansible_facts[nic_card]['ipv4']['address'] }}"
    
    • when you are accessing facts via the ansible_facts dictionary, they are not prefixed by 'ansible_'
    • when you are specifying the key of a dictionary using the contents of a variable, you don't wrap in either quotes or {{}} Specifying a literal string = some_dict['key_name'] versus specifying a key based on a string stored in a variable = some_dict[var_containing_key_string]