'How to define sudo passwords for multiple hosts in one file vault?

I want to run updates on multiple Linux servers that all have different user names and passwords. I think this is a common use case, but it's not covered in the documentation. There is SSH auth, but I need elevated access for the update process and Ansible tasks require way too many permissions to do this through the sudoers files.

How do I get the different ansible_password from the inventory in one file vault so I can run the playbook, enter only one password to decrypt all sudo passwords, and have it work?

Inventory:

[servers]
1.2.3.4    ansible_user=user1 ansible_password=password1
1.2.3.5    ansible_user=user2 ansible_password=password2
1.2.3.6    ansible_user=user3 ansible_password=password3

Playbook:

---
- hosts: servers
  become: yes
  become_method: sudo
  gather_facts: false
  vars:
    verbose: false
    log_dir: "/var/log/ansible/dist-upgrade/{{ inventory_hostname }}"
  pre_tasks:
    - name: Install python for Ansible
      raw: sudo bash -c "test -e /usr/bin/python || (apt -qqy update && apt install -qy python-minimal)"
      changed_when: false
  tasks:
    - name: Update packages
      apt:
        update_cache: yes
        upgrade: dist
        autoremove: no
      register: output

    - name: Check changes
      set_fact:
        updated: true
      when: not output.stdout is search("0 upgraded, 0 newly installed")

    - name: Display changes
      debug:
        msg: "{{ output.stdout_lines }}"
      when: verbose or updated is defined

    - block:
      - name: "Create log directory"
        file:
          path: "{{ log_dir }}"
          state: directory
        changed_when: false

      - name: "Write changes to logfile"
        copy:
          content: "{{ output.stdout }}"
          dest: "{{ log_dir }}/dist-upgrade_{{ ansible_date_time.iso8601 }}.log"
        changed_when: false

      when: updated is defined
      connection: local


Solution 1:[1]

Move ansible_user and ansible_password out of your inventory and into your host_vars directory. That is, make your inventory look like this:

[servers]
1.2.3.4
1.2.3.5
1.2.3.6

Then ansible-vault create host_vars/1.2.3.4.yml and give it the content:

ansible_user: user1
ansible_password: password1

And so on for the other hosts in your inventory.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 larsks