Files
ansible/best-practices.md

1.5 KiB

Best Practices

1. Idempotency

Use modules that ensure idempotency (e.g., service, package, file):

- name: Ensure Apache is running
  service:
    name: apache2
    state: started
    enabled: yes

2. Playbook Structure

  • Separate tasks into logical sections using block/rescue
  • Use handlers for services/configuration management:
    - name: Restart Apache
      service:
        name: apache2
        state: restarted
      handlers:
        - name: Restart Apache
          service:
            name: apache2
            state: restarted
    

3. Inventory Management

  • Use ansible-inventory --list to validate inventory structure
  • Leverage dynamic inventory for cloud environments (e.g., AWS, OpenStack)

4. Security

  • Store secrets in Ansible Vault:
    ansible-vault encrypt_string --vault-id myvault@prompt 'secret_value'
    
  • Use become: yes for privileged tasks and restrict SSH access

5. Testing

  • Always use --check to simulate changes:
    ansible-playbook site.yml --check
    
  • Use --diff to review changes:
    ansible-playbook site.yml --diff
    

6. Troubleshooting

  • Use --verbosity=2 for detailed output
  • Debug variables with debug module:
    - name: Show variable value
      debug:
        msg: "{{ some_variable }}"
    

7. Automation

  • Use ansible-pull for agentless orchestration
  • Combine with CI/CD pipelines for automated deployments