3

I have a scenario where I have the following encrypted variable in my inventory.yml

vars:
   username: admin
   password: !vault |
          $ANSIBLE_VAULT;1.2;AES256;dev
          30613233633461343837653833666333643061636561303338373661313838333565653635353162
          3263363434623733343538653462613064333634333464660a663633623939393439316636633863
          61636237636537333938306331383339353265363239643939666639386530626330633337633833
          6664656334373166630a363736393262666465663432613932613036303963343263623137386239
          6330

And in my role tasks main.yml

- name: Create a JIRA issue
  uri:
    url: https://your.jira.example.com/rest/api/2/issue/
    user: "{{ username }}"
    password: "{{ password }}"
    method: POST
    body: "{{ lookup('file','issue.json') }}"
    force_basic_auth: yes
    status_code: 201
    body_format: json

However, the URI module doesn't decrypt the vault variable. Is there a way we can decrypt a specific variable from within a file?

I am using Ansible version 2.8.

bignose
  • 30,281
  • 14
  • 77
  • 110
Sam Alex
  • 123
  • 1
  • 7

1 Answers1

-1

An easier and more flexible option is putting the secret into a separate file, e.g.

shell> cd vault/
shell> cat password.yml 
password: my_secret_password

shell> ansible-vault encrypt password.yml 
Encryption successful

shell> cat password.yml 
$ANSIBLE_VAULT;1.1;AES256
37363761663732363162633135323438633661656531343664646564326161323739383933316331
6438653039373933366532616631333938633039323062380a623463373331636335386566356564
62613063616537623937333336393532373233363263626464643838643830626663393366663234
3639366233653633640a336439313465663465333439333161373237383030356664343862373531
61633664363266353262626338343634353437643236303039376261393739633836

Then use it in a playbook, e.g.

- hosts: localhost
  vars_files:
    - vault/password.yml
  vars:
    username: admin
  tasks:
    - debug:
        msg: "{{ username }}: {{ password }}"

gives

  msg: 'admin: my_secret_password'

This way you can

  • easily share the secret among playbooks if needed
  • include the file in group_vars, host_vars, ...
  • update the secret without modification of the playbooks
  • ...

In addition to this, you can make the code safer and limit the scope of the password to a single task, e.g.

    - debug:
        msg: "{{ username }}: {{ _vault.password }}"
      vars:
        _vault: "{{ lookup('file', 'vault/password.yml')|from_yaml }}"

gives the same result

  msg: 'admin: my_secret_password'
Vladimir Botka
  • 58,131
  • 4
  • 32
  • 63
  • This is well written but unfortunately does not address the question. The questioner already has a file with a vault-encrypted variable, so needs to decrypt that one variable. – bignose Dec 29 '22 at 03:05