Ansible Tutorial · Advanced Topics · Lesson 20 of 20

Ansible Best Practices

Conventions and patterns for maintainable automation.

Members can save this page, take notes and track progress. See membership · Sign in

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-file in 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.md for each role explaining what it does, its variables and dependencies.
  • Use ansible-doc and docstrings in custom modules.
  • Keep a CHANGELOG.md for the project.

Security

  • Run as a non-root user with become only where needed.
  • Use SSH key authentication, never passwords.
  • Restrict become: true to tasks that need it, not entire plays.
  • Apply any_errors_fatal: true to critical deploys.
  • Disable host_key_checking only in labs, never in production.
Using tags to run specific tasks
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=0

Run this on your computer — see “Get Started” for setup.

Test yourself

Why should you use fully qualified collection names (FQCN) for modules?

  1. It makes playbooks run faster
  2. It avoids name collisions between collections
  3. It is required by ansible-lint
  4. It 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.

Last reviewed · By the ByteCamel team · How we write content

Was this page helpful?

Report a mistake