Editing Ansible vault file from a playbook

Viewed 834

I have ansible encrypted vault file and have userid and passwords stored in it. I am creating a playbook to change passwords in that file.

I tried to use lineinfile but the text is getting added at then of the encrypted text.

Is there a possibility to edit a vault file thru a playbook

Vault files can be edited thru ansible-vault edit. Not thru vi filename. Vault file contents.

  user1:"abc$123098"
  user2:"qwe$123098"

I wanted to replace user2 line in the vault file.

  ansible code
  - name: chainging vault file
    lineinfile:
      path: /path/testvault.yaml
      regexp: '^user1:'
      line: 'user1:lkjh$123098'
1 Answers

As you have discovered, you can't use lineinfile to edit the file. The file is encrypted, and lineinfile is designed to work with plain text files.

Your only option would be to:

  1. Decrypt the file and store the contents in a variable (or a temporary file)
  2. Modify the un-encrypted data
  3. Re-encrypt the data and store it back in the file

Maybe something like:

- hosts: localhost
  gather_facts: false
  tasks:
    - name: read data from vaulted file
      command: >-
        ansible-vault view users.txt
      register: cleartext

    - name: update user1 password
      set_fact:
        newtext: >-
          {{ newtext + [item|regex_replace('user1:.*', 'user1:"newsecret"')] }}
      loop: "{{ cleartext.stdout_lines }}"
      vars:
        newtext: []

    - name: write data to file
      command: >-
        ansible-vault encrypt --output users.txt
      args:
        stdin: "{{ '\n'.join(newtext) }}"

Given an encrypted input file with the contents:

user1:"qwe$123098"
user2:"qwe$123098"

After running the playbook, the file will instead contain the encrypted version of:

user1:"newsecret"
user2:"qwe$123098"

This propbably requires that ansible-vault is able to determine the vault secret non-interactively.

I've put a runnable example here.

Related