Ansible: Automate Everything from First Playbook to Production · Playbooks: Tasks, Handlers and Conditionals
Your First Playbook: Install and Start Nginx
Write a YAML playbook that installs Nginx, deploys a default page and starts the service, then run it twice to see idempotency in action.
What you'll build
A playbook that installs Nginx on a server, copies a custom index page, ensures the service is running, and proves that a second run changes nothing.
The idea
A playbook is a YAML file containing one or more plays. Each play targets a group of hosts and runs an ordered list of tasks. Each task calls one Ansible module.
---
- name: Descriptive play name
hosts: webservers
become: true # all tasks in this play run as root
tasks:
- name: Install nginx
ansible.builtin.apt:
name: nginx
state: present
- name: Start nginx
ansible.builtin.service:
name: nginx
state: started
enabled: true
Idempotency is the core principle: running a playbook twice produces the same end state. The apt module checks whether the package is already installed before doing anything; the service module checks whether the service is already started. On the second run, every task reports ok instead of changed.
Key flags for ansible-playbook:
| Flag | Purpose |
|---|---|
--check / -C |
Dry run — show what would change without changing it |
--diff / -D |
Show file diffs when templates or copies change content |
-v / -vv / -vvv |
Increase verbosity (connection details, module args, SSH debug) |
--limit <pattern> |
Run against a subset of the target hosts |
--tags <t> |
Run only tasks tagged with the given name |
-e "var=value" |
Pass extra variables on the command line |
The code
mkdir -p ansible-lab && cd ansible-lab
cat > ansible.cfg << 'EOF'
[defaults]
inventory = inventory.ini
host_key_checking = False
stdout_callback = yaml
EOF
cat > inventory.ini << 'EOF'
[webservers]
localhost ansible_connection=local
EOF
cat > site.yml << 'EOF'
---
- name: Install and configure Nginx
hosts: webservers
become: true
tasks:
- name: Install nginx
ansible.builtin.apt:
name: nginx
state: present
update_cache: true
cache_valid_time: 3600
- name: Deploy custom index page
ansible.builtin.copy:
dest: /var/www/html/index.html
content: |
<!doctype html>
<html>
<head><title>Managed by Ansible</title></head>
<body><h1>Hello from Ansible</h1></body>
</html>
owner: www-data
group: www-data
mode: "0644"
- name: Ensure nginx is started and enabled
ansible.builtin.service:
name: nginx
state: started
enabled: true
EOF
cat site.yml
echo "---"
ansible-playbook site.yml 2>&1 | tail -15
Output
---
- name: Install and configure Nginx
hosts: webservers
become: true
tasks:
- name: Install nginx
ansible.builtin.apt:
name: nginx
state: present
update_cache: true
cache_valid_time: 3600
- name: Deploy custom index page
ansible.builtin.copy:
dest: /var/www/html/index.html
content: |
<!doctype html>
<html>
<head><title>Managed by Ansible</title></head>
<body><h1>Hello from Ansible</h1></body>
</html>
owner: www-data
group: www-data
mode: "0644"
- name: Ensure nginx is started and enabled
ansible.builtin.service:
name: nginx
state: started
enabled: true
---
/tmp/tmp4swg3ik0/script.sh: line 51: ansible-playbook: command not foundRun this on your computer — see “Get Started” for setup.
Run the same playbook again — idempotency means nothing changes:
cd ansible-lab
ansible-playbook site.yml 2>&1 | tail -10
Output
/tmp/tmpve1s1oaf/script.sh: line 2: ansible-playbook: command not found
Run this on your computer — see “Get Started” for setup.
changed=0 on the second run. Every task checked the current state and found it already matched the desired state.
Check mode (--check) performs a dry run:
ansible-playbook site.yml --check --diff
This shows what would change without actually applying. Use it in CI or before deploying to production.
Common mistakes
- Running without
become: true. Package installation and service management need root. Without it, tasks fail with permission errors that look like module bugs. - Missing
update_cache: trueon apt. On a fresh server, the package index may be empty.aptwill fail with "package not found" unless you update the cache first.cache_valid_time: 3600avoids updating on every run. - Using
state: latesteverywhere.state: latestupgrades the package on every run, turning your playbook into a rolling-upgrade tool. Usestate: presentto install only if missing; upgrade deliberately. - Naming tasks "Task 1", "Task 2". Descriptive names appear in the output and in
--checkmode. "Install nginx" tells you what a task does; "Task 1" tells you nothing. - Not using fully qualified collection names (FQCNs).
apt:works, butansible.builtin.apt:is unambiguous — it won't collide with a custom module namedaptfrom a third-party collection.
Key points
- A playbook is YAML: a list of plays, each with
hosts,become, andtasks. - Each task calls one module; modules are idempotent — running twice produces the same state.
--checkdoes a dry run;--diffshows what would change;-v/-vv/-vvvadds verbosity.- Use
state: present(notlatest) unless you want automatic upgrades. - Name every task descriptively; use FQCNs for modules.
Further reading: Playbook intro · ansible-playbook CLI
Practice questions
What does idempotency mean in the context of Ansible playbooks?
Answer
Running the same playbook multiple times produces the same end state. If a package is already installed or a service is already started, the task reports 'ok' instead of 'changed' and makes no modifications. This makes playbooks safe to re-run.
Why should you prefer state: present over state: latest for packages?
Answer
state: present installs the package only if it is missing and leaves existing installations untouched. state: latest upgrades the package on every run, which can introduce unexpected version changes. Upgrades should be a deliberate action, not a side effect of configuration management.
What is the purpose of cache_valid_time in the apt module?
Answer
It tells Ansible to skip running apt-get update if the cache was refreshed within the given number of seconds. This avoids a slow network call on every playbook run while still ensuring the cache is reasonably fresh for package installation.
Open in the app to mark lessons complete, take notes and track your progress.