Jopa
Jopa

Reputation: 58

Ansible: Get Variable with inventory_hostname

I have the following passwords file vault.yml:

---
server1: "pass1"
server2: "pass2"
server3: "pass3"

I am loading these values in a variable called passwords:

- name: Get Secrets
  set_fact:
    passwords: "{{ lookup('template', './vault.yml')|from_yaml }}"
  delegate_to: localhost
- name: debug it
  debug:
    var: passwords.{{ inventory_hostname }}

The result of the debugging task shows me the result I want to get: The password for the specific host.

But if I set the following in a variables file:

---
ansible_user: root
ansible_password: passwords.{{ inventory_hostname }}

This will not give me the desired result. The ansible_password takes "passwords" literally and not as a variable.

How can I achieve the same result I got when debugging the passwords.{{ inventory_hostname }}?

Upvotes: 1

Views: 2042

Answers (1)

U880D
U880D

Reputation: 12009

Regarding the part

... if I set the following in a variables file ...

I am not sure since I miss some information about your use case and data flow. However, in general the syntax ansible_password: "{{ PASSWORDS[inventory_hostname] }}" might work for you.

---
- hosts: localhost
  become: false
  gather_facts: false

  vars:

    PASSWORDS:
      SERVER1: "pass1"
      SERVER2: "pass2"
      SERVER3: "pass3"
      localhost: "pass_local"

  tasks:

  - name: Debug var
    debug:
      var: PASSWORDS

  - name: Set Fact 'ansible_password'
    set_fact:
      ansible_password: "{{ PASSWORDS[inventory_hostname] }}"

  - name: Debug var
    debug:
      var: ansible_password

In that way you can access a element by name.

Upvotes: 2

Related Questions