Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Aprende Loops and Conditional Statements | Automating Configurations
Introduction to Ansible

bookLoops and Conditional Statements

Ansible allows you to automate IT tasks efficiently, but real-world scenarios rarely involve simple, one-time actions. Often, you need to repeat the same operation on multiple items or make decisions based on the current state of your systems. This is where loops and conditional statements become essential in Ansible.

With loops, you can perform the same task—such as installing a list of packages or creating multiple users—without writing repetitive code. Conditional statements let you control when a task should run, depending on facts or results from previous steps. Using these tools, you create playbooks that are flexible, reusable, and intelligent enough to handle a variety of environments and requirements.

Understanding how to use loops and conditionals will help you automate more complex workflows, reduce errors, and save time in your configuration management tasks.

Loops in Ansible

Loops in Ansible allow you to repeat a task for each item in a list. This is useful when you need to perform the same action, such as installing packages or creating users, multiple times with different values.

Using with_items and loop

You can use either the with_items directive or the more modern loop keyword to iterate over a list. Both achieve similar results, but loop is preferred in new playbooks for consistency and flexibility.

Installing Multiple Packages

Suppose you want to install several packages on your servers. You can use a loop to avoid repeating the task for each package name:

- name: Install multiple packages
  apt:
    name: "{{ item }}"
    state: present
  loop:
    - git
    - curl
    - htop

This task runs the apt module three times, once for each package in the list.

Creating Multiple Users

You can also create several users with a single task:

- name: Create multiple users
  user:
    name: "{{ item }}"
    state: present
  with_items:
    - alice
    - bob
    - charlie

This task uses with_items to loop through the list of usernames and ensure each user exists on the system.

Choosing Between with_items and loop

  • Use loop for new playbooks; it is the recommended and more flexible approach.
  • Use with_items only when maintaining older playbooks.

Loops help you write concise, maintainable automation scripts by avoiding code repetition and making your tasks scalable.

Conditional Statements in Ansible

Conditional statements allow you to control whether a task runs based on the state of your systems. In Ansible, you use the when keyword to specify these conditions.

Using when to Control Task Execution

The when keyword lets you run a task only if a certain condition is true. This makes your playbooks more flexible and efficient.

Example: Install a Package Only If It Is Missing

Suppose you want to install the git package, but only if it is not already installed. You can use the when statement with a fact that checks if git is present:

- name: Install git if not present
  apt:
    name: git
    state: present
  when: ansible_facts.packages['git'] is not defined

Explanation:

  • The task checks if git is missing by evaluating if ansible_facts.packages['git'] is not defined;
  • If the condition is true (the package is missing), the task runs and installs git;
  • If the condition is false (the package is already installed), the task is skipped.

Common Use Cases for when

  • Run a task only if a file exists or does not exist;
  • Execute a handler only on specific operating systems;
  • Apply configuration changes based on variable values.

Syntax Tips

  • Always use valid Jinja2 expressions inside the when statement;
  • You can combine multiple conditions using and or or operators;
  • Place the when keyword at the same indentation level as the task.

Conditional statements make your automation smarter and more adaptable, ensuring tasks run only when needed.

question mark

Which Ansible keyword is commonly used to loop over a list of items in a task

Select the correct answer

¿Todo estuvo claro?

¿Cómo podemos mejorarlo?

¡Gracias por tus comentarios!

Sección 3. Capítulo 1

Pregunte a AI

expand

Pregunte a AI

ChatGPT

Pregunte lo que quiera o pruebe una de las preguntas sugeridas para comenzar nuestra charla

Suggested prompts:

Can you show more examples of using loops in Ansible?

How do I combine loops and conditionals in a single task?

What are some best practices for using loops and conditionals in playbooks?

Awesome!

Completion rate improved to 8.33

bookLoops and Conditional Statements

Desliza para mostrar el menú

Ansible allows you to automate IT tasks efficiently, but real-world scenarios rarely involve simple, one-time actions. Often, you need to repeat the same operation on multiple items or make decisions based on the current state of your systems. This is where loops and conditional statements become essential in Ansible.

With loops, you can perform the same task—such as installing a list of packages or creating multiple users—without writing repetitive code. Conditional statements let you control when a task should run, depending on facts or results from previous steps. Using these tools, you create playbooks that are flexible, reusable, and intelligent enough to handle a variety of environments and requirements.

Understanding how to use loops and conditionals will help you automate more complex workflows, reduce errors, and save time in your configuration management tasks.

Loops in Ansible

Loops in Ansible allow you to repeat a task for each item in a list. This is useful when you need to perform the same action, such as installing packages or creating users, multiple times with different values.

Using with_items and loop

You can use either the with_items directive or the more modern loop keyword to iterate over a list. Both achieve similar results, but loop is preferred in new playbooks for consistency and flexibility.

Installing Multiple Packages

Suppose you want to install several packages on your servers. You can use a loop to avoid repeating the task for each package name:

- name: Install multiple packages
  apt:
    name: "{{ item }}"
    state: present
  loop:
    - git
    - curl
    - htop

This task runs the apt module three times, once for each package in the list.

Creating Multiple Users

You can also create several users with a single task:

- name: Create multiple users
  user:
    name: "{{ item }}"
    state: present
  with_items:
    - alice
    - bob
    - charlie

This task uses with_items to loop through the list of usernames and ensure each user exists on the system.

Choosing Between with_items and loop

  • Use loop for new playbooks; it is the recommended and more flexible approach.
  • Use with_items only when maintaining older playbooks.

Loops help you write concise, maintainable automation scripts by avoiding code repetition and making your tasks scalable.

Conditional Statements in Ansible

Conditional statements allow you to control whether a task runs based on the state of your systems. In Ansible, you use the when keyword to specify these conditions.

Using when to Control Task Execution

The when keyword lets you run a task only if a certain condition is true. This makes your playbooks more flexible and efficient.

Example: Install a Package Only If It Is Missing

Suppose you want to install the git package, but only if it is not already installed. You can use the when statement with a fact that checks if git is present:

- name: Install git if not present
  apt:
    name: git
    state: present
  when: ansible_facts.packages['git'] is not defined

Explanation:

  • The task checks if git is missing by evaluating if ansible_facts.packages['git'] is not defined;
  • If the condition is true (the package is missing), the task runs and installs git;
  • If the condition is false (the package is already installed), the task is skipped.

Common Use Cases for when

  • Run a task only if a file exists or does not exist;
  • Execute a handler only on specific operating systems;
  • Apply configuration changes based on variable values.

Syntax Tips

  • Always use valid Jinja2 expressions inside the when statement;
  • You can combine multiple conditions using and or or operators;
  • Place the when keyword at the same indentation level as the task.

Conditional statements make your automation smarter and more adaptable, ensuring tasks run only when needed.

question mark

Which Ansible keyword is commonly used to loop over a list of items in a task

Select the correct answer

¿Todo estuvo claro?

¿Cómo podemos mejorarlo?

¡Gracias por tus comentarios!

Sección 3. Capítulo 1
some-alt