Getting Secrets from HashiCorp Vault in Ansible Playbooks

September 15, 2023

Getting Secrets from HashiCorp Vault in Ansible Playbooks

In this blog post, I'll explain how to securely manage secret dependencies in your infrastructure using HashiCorp Vault and Ansible. Storing keys inside your repositories can be risky, and I'll show you a better way.


Prerequisites

Before we get started, make sure you have the following prerequisites in place:

  1. Install the Latest Version of Ansible:

    • Ensure you have the most up-to-date version of Ansible installed on your system.
  2. Install the Ansible Community HashiCorp Vault Collection:

    • You can install it by running the following command:
      ansible-galaxy collection install community.hashi_vault
    • To confirm the installation, run:
      ansible-galaxy collection list | grep  community.hashi_vault
  3. Install the Python Module hvac:

    • Install the hvac module using pip:
      pip install hvac

Create Your Ansible Playbooks

Here's an example of an Ansible playbook that retrieves secrets from HashiCorp Vault:

---
- name: Return all kv v2 secrets from a path
  hosts: test
  tasks:
    - name: Get required secret from Vault
      ansible.builtin.set_fact:
        apm: "{{ lookup('community.hashi_vault.vault_kv2_get', 'apm', url='https://your.vault-server.service') }}"

    - name: Display the APM Results
      ansible.builtin.debug:
        msg:
          - "Activeate : {{ apm.secret.ELASTIC_APM_ACTIVE }}"
          - "Environment : {{ apm.secret.ELASTIC_APM_ENVIRONMENT }}"
          - "The Secret: {{ apm.secret.ELASTIC_APM_SECRET_TOKEN }}"
          - "The URL : {{ apm.secret.ELASTIC_APM_SERVER_URL }}"

Run Your Ansible Playbooks

To run your Ansible playbooks securely with HashiCorp Vault, follow these steps:

  1. Set the environment variables ANSIBLE_HASHI_VAULT_TOKEN and ANSIBLE_HASHI_VAULT_AUTH_METHOD:

    export ANSIBLE_HASHI_VAULT_TOKEN=YOURSECRETKEYYYYYYYYYYYY
    export ANSIBLE_HASHI_VAULT_AUTH_METHOD=token
  2. Execute your playbook:

    ansible-playbook -i inventory.ini vault.yml

Result

After running your playbook, you'll securely retrieve secrets from HashiCorp Vault and be able to use them in your Ansible tasks.


Profile picture

Written by Nicolas Julian Seseorang yang mencoba berkarya. Chit Chat with me in Twitter