Operations 3 min read

Using Ansible 'when' Conditionals and Loops to Restrict Host Execution and Batch Create Users

This guide demonstrates how to use Ansible's when conditional to limit task execution to a specific host and how to employ loops with the user module to create multiple users across servers, including full playbook examples and verification steps.

Practical DevOps Architecture
Practical DevOps Architecture
Practical DevOps Architecture
Using Ansible 'when' Conditionals and Loops to Restrict Host Execution and Batch Create Users

In Ansible, the when keyword is the only built‑in way to perform conditional checks; it applies to the task itself, not to any sub‑tasks, and variables inside the condition are referenced without the {{ }} delimiters.

To allow only the host with IP 192.168.20.42 to run a command, the following when.yaml playbook is used:

---
- hosts: webservers
  remote_user: root
  gather_facts: true
  tasks:
    - name: 只允许 192.168.20.42 主机执行
      debug: msg="{{ansible_default_ipv4.address}}"
      when: ansible_default_ipv4.address == '192.168.20.42'

Running ansible-playbook when.yaml skips all other servers and executes the task only on the allowed host.

The article also shows how to use a loop to batch‑create users on all target machines. The user.yaml playbook defines a task that iterates over a list of usernames:

---
- hosts: webservers
  remote_user: root
  gather_facts: true
  tasks:
    - name: 所有主机执行
      user: name={{ item }} state=present
      with_items:
        - user1
        - user2
        - hahashen

The playbook can be run in check mode with ansible-playbook -C user.yaml and then applied normally with ansible-playbook user.yaml . Verification is performed by inspecting /etc/passwd on each host to confirm that the new users have been created.

automationDevOpsuser-managementAnsibleLoopconditionalwhen
Practical DevOps Architecture
Written by

Practical DevOps Architecture

Hands‑on DevOps operations using Docker, K8s, Jenkins, and Ansible—empowering ops professionals to grow together through sharing, discussion, knowledge consolidation, and continuous improvement.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.