Skill v1.0.0
currentAutomated scan100/100name: ansible description: Ansible automation, playbooks, and configuration management. Activate when working with Ansible YAML files or discussing Ansible patterns. metadata: version: "1.0.0"
The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in RFC 2119.
Ansible Workflow
Tool Grid
| Task | Tool | Command | |
|---|---|---|---|
| Lint | ansible-lint | ansible-lint | |
| YAML lint | yamllint | yamllint . | |
| Syntax check | ansible | ansible-playbook --syntax-check | |
| Dry run | ansible | ansible-playbook --check | |
| Run | ansible | ansible-playbook playbook.yml | |
| Test roles | molecule | molecule test | |
| Encrypt | sops | sops -e secrets.yml | |
| Decrypt | sops | sops -d secrets.yml |
Runtime Requirements
- Ansible Core 2.18+ with Python 3.12+
- ansible-lint and yamllint installed
- SOPS for secrets management (RECOMMENDED over ansible-vault for GitOps)
- Molecule + docker driver for role testing
Code Standards
FQCN Requirement
All module names MUST use Fully Qualified Collection Names (FQCN):
# CORRECT- name: Copy configuration fileansible.builtin.copy:src: app.confdest: /etc/app/app.conf# INCORRECT - DO NOT USE- name: Copy configuration filecopy:src: app.confdest: /etc/app/app.conf
Linting
All playbooks and roles MUST pass linting before commit:
# Run both lintersansible-lint && yamllint .
Sensitive Data
Tasks handling sensitive data MUST use no_log: true:
- name: Set database passwordansible.builtin.shell: |mysql -u root -p'{{ db_root_password }}' -e "SET PASSWORD..."no_log: true- name: Create API tokenansible.builtin.uri:url: "{{ api_endpoint }}/tokens"headers:Authorization: "Bearer {{ admin_token }}"no_log: trueregister: token_result
Secrets Management
SOPS (RECOMMENDED for GitOps)
SOPS is RECOMMENDED over ansible-vault for GitOps workflows:
# .sops.yamlcreation_rules:- path_regex: .*vars/secrets\.yml$age: age1xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
# Encryptsops -e vars/secrets.yml > vars/secrets.enc.yml# Decrypt inline during playbooksops -d vars/secrets.enc.yml | ansible-playbook -e @/dev/stdin playbook.yml
ansible-vault (Legacy)
When ansible-vault is required:
# Encrypt variable fileansible-vault encrypt group_vars/prod/vault.yml# Run with vaultansible-playbook --ask-vault-pass playbook.yml
Project Structure
Environment-Based Inventory
inventories/├── prod/│ ├── hosts.yml│ ├── group_vars/│ │ ├── all.yml│ │ ├── webservers.yml│ │ └── databases.yml│ └── host_vars/├── staging/│ ├── hosts.yml│ └── group_vars/└── dev/├── hosts.yml└── group_vars/
group_vars Organization
Organize group_vars by role name for clarity:
group_vars/├── all/│ ├── main.yml # Common variables│ └── secrets.enc.yml # SOPS-encrypted secrets├── webservers/│ ├── nginx.yml # Role: nginx│ └── ssl.yml # Role: ssl_certificates└── databases/├── postgresql.yml # Role: postgresql└── backup.yml # Role: db_backup
Role Structure
Roles SHOULD be single-purpose:
roles/├── nginx/ # Web server only├── ssl_certificates/ # SSL management only├── postgresql/ # Database only└── app_deploy/ # Application deployment only
Dynamic Inventories
AWS EC2
# inventories/aws/aws_ec2.ymlplugin: amazon.aws.aws_ec2regions:- us-east-1- us-west-2keyed_groups:- key: tags.Environmentprefix: env- key: tags.Roleprefix: rolefilters:instance-state-name: runninghostnames:- private-ip-addresscompose:ansible_host: private_ip_address
Azure RM
# inventories/azure/azure_rm.ymlplugin: azure.azcollection.azure_rmauth_source: autoinclude_vm_resource_groups:- production-rg- staging-rgkeyed_groups:- key: tags.Environmentprefix: envhostnames:- private_ipv4_addresses
GCP Compute
# inventories/gcp/gcp_compute.ymlplugin: google.cloud.gcp_computeprojects:- my-project-idzones:- us-central1-a- us-central1-bkeyed_groups:- key: labels.environmentprefix: envhostnames:- private_ip
Handler Patterns
Proper Handler Usage
# tasks/main.yml- name: Update nginx configurationansible.builtin.template:src: nginx.conf.j2dest: /etc/nginx/nginx.confnotify: Restart nginx- name: Update SSL certificateansible.builtin.copy:src: "{{ ssl_cert_file }}"dest: /etc/nginx/ssl/cert.pemnotify:- Validate nginx config- Reload nginx# handlers/main.yml- name: Validate nginx configansible.builtin.command: nginx -tchanged_when: false- name: Reload nginxansible.builtin.systemd:name: nginxstate: reloaded- name: Restart nginxansible.builtin.systemd:name: nginxstate: restarted
Handler Execution Order
Handlers execute in definition order, not notification order. Define handlers in logical sequence (validate -> reload -> restart).
Variable Precedence
Ansible variable precedence (highest to lowest):
- Extra vars (
-e "var=value") - Task vars (in task definition)
- Block vars
- Role and include vars
- Set facts / registered vars
- Play vars_files
- Play vars
- Host facts
- Playbook host_vars
- Inventory host_vars
- Playbook group_vars
- Inventory group_vars
- Role defaults
Best Practices
# Use role defaults for safe defaults# roles/nginx/defaults/main.ymlnginx_worker_processes: autonginx_worker_connections: 1024# Use group_vars for environment-specific overrides# group_vars/prod/nginx.ymlnginx_worker_connections: 4096# Use extra vars for one-time overrides onlyansible-playbook playbook.yml -e "nginx_worker_connections=8192"
Molecule Testing
Role Testing Setup
# roles/nginx/molecule/default/molecule.ymldependency:name: galaxydriver:name: dockerplatforms:- name: instanceimage: geerlingguy/docker-${MOLECULE_DISTRO:-rockylinux9}-ansiblepre_build_image: trueprivileged: truecommand: /usr/sbin/initprovisioner:name: ansibleverifier:name: ansible
Running Tests
molecule test # Full test cyclemolecule converge # Apply rolemolecule verify # Run verificationmolecule destroy # Cleanup
Performance Optimization
ansible.cfg Settings
forks = 20- Parallel executionpipelining = True- Reduce SSH operationsgathering = smart- Cache factsfact_caching = jsonfile- Persist facts
Task Optimization
# Use async for long-running tasks- name: Upgrade all packagesansible.builtin.dnf:name: "*"state: latestasync: 600poll: 10# Use free strategy for independent tasks- hosts: allstrategy: freetasks:- name: Independent task 1ansible.builtin.command: /opt/script1.sh- name: Independent task 2ansible.builtin.command: /opt/script2.sh
Pre-Commit Checklist
Before committing Ansible code:
- [ ]
ansible-lintpasses with no warnings - [ ]
yamllint .passes - [ ]
ansible-playbook --syntax-checkpasses - [ ] All modules use FQCN
- [ ] Sensitive tasks have
no_log: true - [ ] Secrets encrypted with SOPS (or vault)
- [ ] Molecule tests pass for modified roles
- [ ] Variables documented in role README