khteh
khteh

Reputation: 3874

How to get password from ansible vault to be used as variable?

I have the following ansible role:

- name: Get latest code from repository
  git:
    repo: 'https://{{ username }}:{{ password }}@{{ repository }}'
    dest: "{{ destination }}"
    force: yes

While username and repository can be variables, I am puzzled over how to retrieve password from ansible vault. Any advice and insight is appreciated.

Upvotes: 1

Views: 15877

Answers (1)

Stefano Martins
Stefano Martins

Reputation: 482

First, create a YAML file in vars/ folder (it can be in any folder, host_vars or group_vars are also valid, depending of what type of variables you're keeping) containing your variables. Let's call it vars/git-data.yml. Then, encrypt it using Vault with:

ansible-vault encrypt vars/git-data.yml

A password will be required. Remember it.

Then, you have two options for including your variables while running your playbook:

  • Option A: Including them in your playbook:
--- 
- hosts: localhost
  connection: local
  vars_files:
    -  vars/git-data.yml
  tasks:
    - name: Print variable
      ansible.builtin.debug:
       msg: "{{ username }}"
  • Option B: Referring them while you call ansible-playbook:
ansible-playbook --ask-vault-pass -e @vars/git-data.yml cloning-repository.yml

Vault's password will be asked. You can also use --vault-password-file ${file} or ANSIBLE_VAULT_PASSWORD_FILE environment variable indicating a password containing a password file.

Best regards.

Upvotes: 2

Related Questions