RousselTMLEARNING

Automation

Ansible: managing security (Vault, SSH, privileges and secrets)

Securing Ansible: Ansible Vault, SSH key authentication, become and sudo, no_log, hardening the controller and managing secrets in CI/CD.

1. Threats and principles #

Where are the risks?

The sensitive points of an Ansible chain #

Ansible has administrative access to your entire infrastructure: the control node is therefore a prime target. Classic risks are plain-text secrets in Git, shared SSH keys, passwords shown in logs and overly broad sudo rights.

  • Secrets: encrypted at rest (Vault) and never displayed (no_log).
  • Authentication: dedicated SSH keys, protected by a passphrase or agent, no root password.
  • Privileges: become only when necessary, limited sudo user.
  • Controller: restricted, logged access, never exposed to the Internet.

2. Ansible Vault #

Encrypting sensitive variables and files.

The essential commands #

Life cycle of a secret with Ansible Vault
The vault password is never versioned.
# Créer, éditer, afficher, chiffrer, déchiffrer
ansible-vault create group_vars/prod/vault.yml
ansible-vault edit   group_vars/prod/vault.yml
ansible-vault view   group_vars/prod/vault.yml
ansible-vault encrypt group_vars/prod/secrets.yml
ansible-vault decrypt group_vars/prod/secrets.yml
ansible-vault rekey   group_vars/prod/vault.yml       # changer le mot de passe

# Chiffrer une seule valeur (intégrable dans un fichier en clair)
ansible-vault encrypt_string 'S3cr3t!' --name 'db_password'
db_password: !vault |
          $ANSIBLE_VAULT;1.1;AES256
          61373030633036386239...

Using the vault at run time #

ansible-playbook site.yml --ask-vault-pass
ansible-playbook site.yml --vault-password-file ~/.vault_pass     # fichier hors dépôt, chmod 600
ansible-playbook site.yml --vault-id prod@prompt --vault-id dev@~/.vault_dev   # plusieurs vaults

# Dans ansible.cfg
[defaults]
vault_password_file = ~/.vault_pass
Good practice: Convention: put encrypted variables in vault.yml, prefixed with vault_, and reference them from a plain file (db_password: "{{ vault_db_password }}"): you see the names, not the values.
Common mistake: Never version the vault password file. Add it to .gitignore.

3. Authentication and privileges #

SSH, sudo and become.

Dedicated SSH keys #

# Clé dédiée à Ansible, protégée par passphrase
ssh-keygen -t ed25519 -f ~/.ssh/ansible_ed25519 -C "ansible-controller"

# Diffuser la clé publique avec Ansible lui-même
ansible all -m authorized_key -a "user=deploy key='{{ lookup('file','~/.ssh/ansible_ed25519.pub') }}' state=present" -k

# Agent SSH pour éviter de retaper la passphrase
eval "$(ssh-agent -s)" && ssh-add ~/.ssh/ansible_ed25519
# ansible.cfg
[defaults]
remote_user = deploy
private_key_file = ~/.ssh/ansible_ed25519
host_key_checking = True

[ssh_connection]
pipelining = True
ssh_args = -o ControlMaster=auto -o ControlPersist=60s

Limited sudo on the target #

# Autoriser l'utilisateur deploy à devenir root sans mot de passe
- name: Règle sudo pour deploy
  ansible.builtin.copy:
    dest: /etc/sudoers.d/deploy
    content: "deploy ALL=(ALL) NOPASSWD: ALL\n"
    mode: "0440"
    validate: visudo -cf %s

In sensitive environments, replace ALL with the list of commands actually needed.

4. Leaking nothing #

no_log, logs and CI/CD.

no_log and diff #

- name: Créer l'utilisateur de base de données
  community.postgresql.postgresql_user:
    name: app
    password: "{{ vault_db_password }}"
  no_log: true                     # masque les arguments et résultats dans les logs

- name: Déployer le fichier de secrets
  ansible.builtin.template:
    src: secrets.env.j2
    dest: /etc/app/secrets.env
    mode: "0600"
  diff: false                      # ne pas afficher le contenu avec --diff

In a CI/CD pipeline #

# GitLab CI : le mot de passe du vault vient d'une variable masquée
deploy:
  script:
    - echo "$VAULT_PASSWORD" > .vault_pass && chmod 600 .vault_pass
    - ansible-playbook site.yml -i inventories/prod --vault-password-file .vault_pass
    - shred -u .vault_pass

To go further, delegate secrets to a dedicated vault (HashiCorp Vault, AWS Secrets Manager) through the community.hashi_vault lookups: the secret is then never stored in the repository.

ansible-galaxy collection install community.hashi_vault
ansible-lint --profile production site.yml       # détecte les mauvaises pratiques de sécurité

Related articles

Ansible: the inventory (static, dynamic, groups and variables)

Understand and master the Ansible inventory: INI and YAML files, groups, host and group variables, patterns, …

Ansible: ad-hoc commands

Run immediate actions on a fleet of servers with ansible: the ping, command, shell, copy, apt, service and se…

Ansible: structuring your code with roles

Create, organize and reuse Ansible roles: directory layout, defaults, tasks, handlers, templates, dependencie…

Keep learning

Support us

♥ SUPPORT US

Support RousselTM Learning

Courses, articles, labs and certificates stay free with no intrusive ads. A voluntary contribution, of any amount you choose, pays for hosting, lab environments and new content.

Contribute with PayPal Any amount · card or PayPal accountLearn more
QR code PayPal
Or scan this QR code with your phone

Thank you, every contribution counts!