Skip to content

Instantly share code, notes, and snippets.

@alonsoir
Created January 5, 2024 12:41
Show Gist options
  • Save alonsoir/75c2bbce00d28d2b4523bbc4194fec2f to your computer and use it in GitHub Desktop.
Save alonsoir/75c2bbce00d28d2b4523bbc4194fec2f to your computer and use it in GitHub Desktop.
ansible script to gather VAULT_TOKEN from a VAULT server and run a process which need it. The idea is to maintain secrets in secure, deleting VAULT_TOKEN from file system and historic.
---
- name: Ejecutar Proceso con VAULT_TOKEN
hosts: localhost # Puedes ajustar los hosts según tu entorno
gather_facts: false # Desactivar recopilación de hechos
vars:
vault_address: "http://direccion-de-tu-vault:8200" # Ajusta la dirección de tu Vault Server
tasks:
- name: Establecer VAULT_TOKEN como variable de entorno
ansible.builtin.set_fact:
VAULT_TOKEN: "{{ lookup('env', 'vault_token') | default('') }}"
when: "'vault_token' in lookup('env')"
- name: Ejecutar el proceso que necesita el token
ansible.builtin.shell: "./main_process_sample"
environment:
VAULT_TOKEN: "{{ VAULT_TOKEN }}"
VAULT_ADDRESS: "{{ vault_address }}" # Pasa la URL del Vault Server al proceso
!#/bin/bash
export VAULT_TOKEN=$vault_token
# Obtener el PID del proceso principal
main_pid=$$
# Crear un archivo temporal para almacenar el token
token_file=$(mktemp)
# Ejecutar el proceso que necesita el token. Internamente va a hacer uso de VAULT_TOKEN
python tu_proceso_que_necesita_token.py &
# Obtener los PIDs de los procesos hijos
child_pids=$(pgrep -P $main_pid)
# Almacenar el token en el archivo temporal
echo "tu-token-aqui" > "$token_file"
# Establecer el token como una variable de entorno para el proceso actual
export VAULT_TOKEN=$(cat "$token_file")
# Comunicar el archivo temporal a los procesos hijos
for pid in $child_pids; do
echo "Enviando token a child process $pid"
echo "$token_file" > "/proc/$pid/fd/3" # Utiliza el descriptor de archivo 3 (puedes elegir otro)
done
# Reactivar historial
set -o history
# Borrar el token en la sesión actual
unset VAULT_TOKEN
# Limpiar el archivo temporal
shred -u "$token_file"
# Limpiar la variable de entorno en los procesos hijos
for pid in $child_pids; do
echo "Limpiando VAULT_TOKEN en child process $pid"
echo -n > "/proc/$pid/environ"
done
import os
import hvac
# Obtener el token de Vault de las variables de entorno
vault_token = os.getenv("VAULT_TOKEN")
# Crear un cliente de Vault
# vault_client = hvac.Client(url="http://direccion-de-tu-vault:8200", token=vault_token)
# Hacer algo con el cliente de Vault (por ejemplo, leer secretos)
# Luego, ejecutar tu proceso principal
# ...
# Limpiar el token en la sesión actual (opcional, dependiendo de tus requisitos)
# Puede que no lo necesites pues vas a tratar de borrar todo mediante bash.
os.environ.pop("VAULT_TOKEN", None)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment