English translation
12. Writing Playbooks: Loops and Conditional Statements in Ansible
AI Article Decision Snapshot
Turn the lesson into workflow, model, budget, and security checks before choosing tools.
Use this quick snapshot before leaving the article. It keeps the next search tied to practical AI software, model/API, cost, privacy, and implementation questions.
Workflow fit
Identify the real job behind the article: coding, research, document review, support, analytics, content, or internal automation.
Model or tool decision
Decide whether the next step is a software shortlist, an AI tool comparison, an API platform choice, or a model benchmark.
Budget and usage signal
Estimate seats, API calls, prompt volume, retries, review time, and fallback work before assuming the workflow is cheap.
Security and privacy review
Check whether source code, customer data, private documents, prompts, logs, or embeddings will enter the AI workflow.
In the previous article, we discussed how to define and manage tasks. In this article, we’ll delve deeper into using loops and conditional statements in Ansible Playbooks to enhance the flexibility and adaptability of your automation scripts.
Using Loops
Loops are a powerful mechanism for controlling task execution in Ansible—commonly used to process lists or dictionaries. Below, we’ll explore how to use loops in Playbooks.
Example: Using with_items
Suppose you need to install the same set of software packages across multiple servers. You can achieve this efficiently using the with_items loop. Here’s a Playbook example that installs common packages:
- name: Install common packages
hosts: all
tasks:
- name: Install packages
apt:
name: "{{ item }}"
state: present
with_items:
- vim
- git
- curl
In this Playbook, the apt module processes each package in the with_items list sequentially. This approach significantly simplifies task definition.
Example: Using with_dict
For dictionary-type data, Ansible provides the with_dict loop. The following example assigns a specific IP address to each host based on its hostname:
- name: Assign IP addresses to hosts
hosts: all
tasks:
- name: Set IP based on hostname
command: echo "The IP for {{ item.key }} is {{ item.value }}"
with_dict:
server1: 192.168.1.10
server2: 192.168.1.11
In this example, item.key and item.value correspond to the dictionary’s key (hostname) and value (IP address), respectively. Ansible automatically substitutes these placeholders during each iteration.
Using Conditional Statements
Conditional statements allow you to determine whether a task should execute based on specific criteria. Ansible uses the when keyword to implement conditional logic.
Example: Conditional Execution Based on Variable Values
The following example demonstrates how to conditionally install Nginx depending on the operating system family:
- name: Check package installation
hosts: all
tasks:
- name: Install nginx
apt:
name: nginx
state: present
when: ansible_os_family == "Debian" # Install nginx only on Debian-based systems
Here, the task executes only if the ansible_os_family variable equals "Debian". This ensures your Playbook behaves appropriately across diverse environments.
Example: Combining Loops and Conditions
Combining loops with conditionals is a common and powerful pattern. The following example shows how to install packages only if they are not already present on the target system:
- name: Install specific packages based on conditions
hosts: all
tasks:
- name: Install packages only if they are not already installed
apt:
name: "{{ item }}"
state: present
with_items:
- git
- vim
- curl
when: ansible_facts.packages[item] is not defined
In this case, the task runs only when the specified package is absent from the system—avoiding redundant installations.
Summary
In this article, we explored how to use loops and conditional statements in Ansible Playbooks to increase the flexibility and robustness of automation workflows. Through concrete examples, we demonstrated practical applications of these features—equipping you with valuable techniques for writing more sophisticated Playbooks.
In the next article, we’ll cover how to configure basic Inventory files—a foundational step for managing heterogeneous host environments. By combining well-structured Inventory definitions with the looping and conditional capabilities covered here, you can dramatically improve both the efficiency and maintainability of your automation infrastructure.
Apply This Lesson
Turn this article into AI software, model, API, and security decisions.
English Article FAQ
Use this article as evidence before choosing AI tools
How should I use this AI Tutorials article?
Use it as the implementation or learning layer, then connect the idea to AI software buyer guides, tool comparisons, benchmarks, API choices, and security checks before making a production decision.
Is this English article different from the Chinese original?
The English edition is localized for global AI readers while preserving the original diagrams, screenshots, prompts, code examples, and source context from the Chinese article.
What should I read after 12. Writing Playbooks: Loops and Conditional Statements in Ansible?
Continue with AI Software Buyer Guides, AI Tools Workbench, Best AI Coding Agents, AI Model Benchmarks, OpenAI vs Anthropic API, or LLM Security Tools depending on the decision you need to make.
Can this article alone choose an AI product or model?
No. Treat the article as evidence and context, then validate fit with pricing, privacy requirements, integration effort, benchmark results, workflow tests, and fallback planning.
Continue