Ansible Tutorial · Advanced Topics · Lesson 20 of 20
Ansible Best Practices
Conventions and patterns for maintainable automation.
Directory layout
ansible-project/
├── ansible.cfg
├── requirements.yml
├── inventory/
│ ├── production/
│ │ ├── hosts.yml
│ │ ├── group_vars/
│ │ │ ├── all.yml
│ │ │ └── webservers.yml
│ │ └── host_vars/
│ └── staging/
│ ├── hosts.yml
│ └── group_vars/
│ └── all.yml
├── playbooks/
│ ├── site.yml # master playbook
│ ├── webservers.yml
│ └── databases.yml
├── roles/
│ ├── common/
│ ├── nginx/
│ └── app_deploy/
├── templates/
├── files/
└── .ansible-lint
Naming conventions
- Playbook files:
site.yml,webservers.yml,deploy.yml— descriptive verbs or targets. - Role names: lowercase, hyphens:
nginx,app-deploy,security-baseline. - Variable names: lowercase, underscores:
app_port,db_password,nginx_worker_processes. - Task names: always set
name:on every task. Start with a verb: "Install nginx", "Copy app config". - Handlers: named after what they do: "restart nginx", "reload postgresql".
Idempotency
Every task should be safe to run multiple times. Avoid command / shell for tasks that have a
dedicated module:
# Bad: not idempotent
- command: apt install -y nginx
# Good: idempotent
- ansible.builtin.apt:
name: nginx
state: present
When you must use command, add creates or removes to skip it when unnecessary:
- name: Initialize the database
ansible.builtin.command: /opt/app/init_db.sh
args:
creates: /opt/app/.db_initialized
Use fully qualified collection names (FQCN)
# Old style (ambiguous)
- apt:
name: nginx
# Modern style (explicit)
- ansible.builtin.apt:
name: nginx
FQCN avoids name collisions when multiple collections provide the same module name.
Tags
- name: Install packages
ansible.builtin.apt:
name: nginx
tags: [packages, nginx]
- name: Deploy config
ansible.builtin.template:
src: nginx.conf.j2
dest: /etc/nginx/nginx.conf
tags: [config, nginx]
Run specific tags:
ansible-playbook site.yml --tags config
ansible-playbook site.yml --skip-tags packages
Tags let you run part of a playbook without commenting out tasks.
Secrets
- Encrypt all secrets with Ansible Vault.
- Never commit unencrypted passwords, API keys or private keys.
- Use
--vault-password-filein CI (password stored as a CI secret). - Prefer encrypted individual variables over encrypted whole files.
Version control
- Commit
ansible.cfg,requirements.yml, inventories and playbooks. .gitignore: vault password files,*.retry,.molecule/,__pycache__/.- Pin role and collection versions in
requirements.yml.
Documentation
- Write a
README.mdfor each role explaining what it does, its variables and dependencies. - Use
ansible-docand docstrings in custom modules. - Keep a
CHANGELOG.mdfor the project.
Security
- Run as a non-root user with
becomeonly where needed. - Use SSH key authentication, never passwords.
- Restrict
become: trueto tasks that need it, not entire plays. - Apply
any_errors_fatal: trueto critical deploys. - Disable
host_key_checkingonly in labs, never in production.
cat > /tmp/bp_demo.yml << 'EOF'
---
- name: Best practices demo
hosts: localhost
connection: local
gather_facts: false
tasks:
- name: Show FQCN module usage
ansible.builtin.debug:
msg: "Using fully qualified collection names is a best practice"
tags: [demo]
- name: Show idempotent pattern
ansible.builtin.file:
path: /tmp/ansible_bp_test
state: directory
mode: "0755"
tags: [demo, files]
EOF
ansible-playbook /tmp/bp_demo.yml --tags demo
Output
PLAY [Best practices demo] ****************************************************
TASK [Show FQCN module usage] *************************************************
ok: [localhost] => {
"msg": "Using fully qualified collection names is a best practice"
}
TASK [Show idempotent pattern] ************************************************
changed: [localhost]
PLAY RECAP ********************************************************************
localhost : ok=2 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0Run this on your computer — see “Get Started” for setup.
Test yourself
Why should you use fully qualified collection names (FQCN) for modules?
It makes playbooks run fasterIt avoids name collisions between collectionsIt is required by ansible-lintIt enables check mode
Show answer
Answer: It avoids name collisions between collections
FQCN like ansible.builtin.apt makes it explicit which collection provides the module, avoiding ambiguity when multiple collections define a module with the same short name.