Ansible Best Practices for Network Automation

After implementing Ansible-based automation at multiple Fortune 500 companies, I’ve developed a set of best practices that can help teams avoid common pitfalls and maximize their automation success.

Directory Structure Matters

A well-organized Ansible project is crucial for maintainability. Here’s the structure I recommend:

├── ansible.cfg
├── inventories/
│   ├── production/
│   │   ├── group_vars/
│   │   ├── host_vars/
│   │   └── hosts
│   └── staging/
│       ├── group_vars/
│       ├── host_vars/
│       └── hosts
├── playbooks/
│   ├── deploy.yml
│   └── validate.yml
├── roles/
│   ├── common/
│   └── network/
└── library/

Variable Precedence

Understanding Ansible’s variable precedence is essential. From lowest to highest priority:

  1. Role defaults
  2. Inventory variables (group_vars, host_vars)
  3. Playbook group_vars and host_vars
  4. Command line variables (-e flag)

For network automation, I recommend keeping device-specific variables in host_vars and shared configurations in group_vars.

Testing

Implement testing at multiple levels:

  • Syntax checking: ansible-playbook --syntax-check playbook.yml
  • Linting: Use ansible-lint to ensure code quality
  • Dry runs: Utilize --check mode before applying changes
  • Molecule: For comprehensive role testing

Idempotency

Ensure your playbooks are idempotent - running them multiple times should result in the same state. For network devices, this often means:

  1. Using state modules rather than commands when possible
  2. Implementing proper checks before making changes
  3. Designing playbooks to be convergent rather than procedural

Error Handling

Robust error handling is critical for network automation:

- name: Configure interface
  ios_config:
    lines:
      - description WAN Connection
      - ip address 192.168.1.1 255.255.255.0
    parents: interface GigabitEthernet0/1
  register: result
  failed_when: 
    - result.failed
    - "'timeout' not in result.msg"
  retry: 3
  delay: 10

Managing Secrets

Securely manage credentials using:

  • Ansible Vault for encryption
  • Environment variables for temporary credentials
  • Integration with external secret management systems

Next Steps

In future posts, I’ll dive deeper into specific aspects of network automation with Ansible, including multi-vendor environments, CI/CD integration, and advanced testing strategies.