Validate an Ansible Playbook
Ansible playbooks are YAML files that define automation tasks across servers. Indentation errors and missing required fields cause playbook runs to fail partway through, potentially leaving servers in inconsistent states. This example shows a playbook that installs and configures a web server. Validate the YAML syntax before running ansible-playbook to catch structural errors before they reach your infrastructure.
Example
---
- name: Configure web server
hosts: webservers
become: true
vars:
app_port: 8080
app_user: deploy
tasks:
- name: Install nginx
apt:
name: nginx
state: present
update_cache: true
- name: Copy nginx config
template:
src: nginx.conf.j2
dest: /etc/nginx/nginx.conf
notify: Restart nginx
handlers:
- name: Restart nginx
service:
name: nginx
state: restartedFAQ
- What is the become directive in Ansible?
- become: true tells Ansible to run tasks with elevated privileges (sudo by default), required for tasks that install packages or modify system files.
- What are handlers in Ansible?
- Handlers are tasks that only run when notified by another task. They are commonly used to restart services after configuration changes, and run once at the end of a play even if notified multiple times.
- What is the difference between a play and a task?
- A playbook contains one or more plays. Each play targets a group of hosts and contains a list of tasks. Tasks are the individual units of work executed by Ansible modules.
Related Examples
Validate a GitHub Actions Workflow
GitHub Actions workflows are YAML files where formatting errors prevent pipeline...
Validate a CloudFormation TemplateAWS CloudFormation templates define cloud infrastructure as code and must be val...
Validate a docker-compose.yml FileDocker Compose files are notoriously sensitive to indentation because YAML uses ...