Ansible best practices

Recommended patterns for playbook structure, role organization, variable management, and idempotent tasks.

Ansible best practices

Recommended patterns for playbook structure, role organization, variable management, and idempotent tasks.

Use Roles to Organize Ansible Playbooks

Ansible roles group related tasks, handlers, templates, files, and variables into a standard directory structure. Use ansible-galaxy init role_name to create the skeleton. Roles make playbooks reusable across projects and environments.

Keep Ansible Playbooks Idempotent

Every task in an Ansible playbook should produce the same result when run multiple times. Avoid the command and shell modules for tasks that have dedicated modules (use apt instead of shell: apt install). When command or shell is unavoidable, add creates, removes, or when conditions to prevent repeated execution.

Separate Ansible Variables by Environment

Store environment-specific variables in group_vars/{environment}/ directories. Keep secrets in vault.yml files encrypted with Ansible Vault. Use all.yml for variables shared across all environments and {group}.yml for group-specific overrides.

Use ansible-playbook --check Before Applying Changes

Ansible's check mode ( --check --diff) simulates playbook execution and shows what would change without modifying the target systems. Run check mode before every production deployment to verify the expected changes.

Pin Package Versions in Ansible Playbooks

Specify exact package versions with the apt and dnf modules to prevent unexpected upgrades:

- name: Install specific Nginx version
  apt:
    name: nginx=1.24.0-1ubuntu1
    state: present

Use Handlers for Service Restarts in Ansible

Ansible handlers run only once at the end of a play, even if notified by multiple tasks. Use handlers for service restarts to avoid restarting a service multiple times when multiple configuration files change in the same play.