Search code examples
ansible

Ansible loop over a list of hashes but include a variable inside


I have a playbook which adds an user to a system, they passwords are encrypted in vault, using x_myuser_password variable. The vault part works great, I tried to print out the x_myuser_password and the right passwords are printed. However, adding the user to the target system not works as I expected. The relevant part of the playbook looks like:

- name: Add users
  user:
    name: "{{ item.name }}"
    uid: "{{ item.uid }}"
    comment: "{{ item.comment }}"
    home: "{{ item.home }}"
    shell: "{{ item.shell }}"
    group: "{{ item.group }}"
    password: "{{ item.password | password_hash('sha512') }}"
    groups: sudo
    append: yes
  loop:
    - { name: 'myuser', uid: '1000', comment: 'Myname', home: '/home/myuser', shell: '/bin/bash', group: 'mygroup', password: x_myuser_password }

Whenever I set up the password: with or without queotes, the target system locks out the user, there is not able to login until I switch back the password manually in the target system. In my opinion it is because it encrypts 'x_myuser_password' instead of the value of that variable and send that out to the target server. How can I send the value of the variable inside the loop?


Solution

  • Looks like the solution is more simple then I thought. This works:

    - name: Add users
      user:
        name: "{{ item.name }}"
        uid: "{{ item.uid }}"
        comment: "{{ item.comment }}"
        home: "{{ item.home }}"
        shell: "{{ item.shell }}"
        group: "{{ item.group }}"
        password: "{{ item.password | password_hash('sha512') }}"
        groups: sudo
        append: yes
      loop:
        - { name: 'myuser', uid: '1000', comment: 'Myname', home: '/home/myuser', shell: '/bin/bash', group: 'mygroup', password: '{{ x_myuser_password }}' }