Save files encrypted with ansible vault

Hello,

I have a playbook to create wireguard configurations for an opnsense and would like to save the generated client configuration encrypted. It runs inside a devcontainer and the password is available in /run/secrets/ansible_vault (checked)

- name: Check the vault password
  no_log: true
  vars:
    _vault_pass: "{{ lookup('file', '/run/secrets/ansible_vault') }}"
  ansible.builtin.assert:
    that: _vault_pass | length > 0
    fail_msg: "Could not read vault password"

- name: Save WireGuard config encrypted
  no_log: true
  vars:
    _vault_pass: "{{ lookup('file', '/run/secrets/ansible_vault') }}"
    _wg_config: |
      [Interface]
      PrivateKey = {{ _client_privkey }}
      Address = {{ wg_client_ip }}
      DNS = {{ wg_server_ip }}

      [Peer]
      PublicKey = {{ wg_server_pubkey }}
      AllowedIPs = {{ wg_client_target_ips }}
      Endpoint = {{ wg_server_endpoint }}
      PersistentKeepalive = 25
  ansible.builtin.copy:
    content: "{{ _wg_config | ansible.builtin.vault(_vault_pass) }}"
    dest: "{{ wg_client_dir }}/{{ inventory_hostname }}.conf"
    mode: "0600"

Unfortunately the file is stored unencrypted - anyone an idea, why?
Thanks a lot!
Thomas

The default behavior of the copy module is to decrypt the data, by means of the default decrypt=True. Supplying decrypt: false should resolve the issue.

1 Like