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:
-
Install the Latest Version of Ansible:
- Ensure you have the most up-to-date version of Ansible installed on your system.
-
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
- You can install it by running the following command:
-
Install the Python Module
hvac
:- Install the
hvac
module using pip:pip install hvac
- Install the
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:
-
Set the environment variables
ANSIBLE_HASHI_VAULT_TOKEN
andANSIBLE_HASHI_VAULT_AUTH_METHOD
:export ANSIBLE_HASHI_VAULT_TOKEN=YOURSECRETKEYYYYYYYYYYYY export ANSIBLE_HASHI_VAULT_AUTH_METHOD=token
-
Execute your playbook:
ansible-playbook -i inventory.ini vault.yml
After running your playbook, you'll securely retrieve secrets from HashiCorp Vault and be able to use them in your Ansible tasks.