Ansible condition judgment and loop

In ansible, only when can realize conditional judgment

tasks:

  - name: config the yum repo for centos 7

    yum_repository:

       name: epel

       description: epel

       baseurl: http://mirrors.aliyun.com/epel/7/$basearch/

       gpgcheck: no

    when: ansible_distribution_major_version == "7"

Pay attention to two points:

The object judged by when is task , so it is at the same list level as task . The result of its judgment determines whether the task it is in is executed, not whether the task below it is executed.

There is no need to add {{ }} symbols when referencing variables in when .


(1) When no conditions are set, two servers execute commands at the same time, how to set only 192.168.20.42 to execute operation commands

image


(2) Configure playbook

[root@k8s-master2 install]# more when.yaml

---

- hosts: webservers

  remote_user: root

  gather_facts: true

  tasks:

  -name:  Only the 192.168.20.42 host is allowed to execute

    debug: msg="{{ansible_default_ipv4.address}}"

when: ansible_default_ipv4.address == '192.168.20.42'


(3) Perform operation:

[root@k8s-master2 install]# ansible-playbook when.yaml 

image

The result skipped 43 servers and executed directly on 42 servers


2. Cycle: Create users in batches


[root@k8s-master2 install]# more user.yaml

---

- hosts: webservers

  remote_user: root

  gather_facts: true

  tasks:

  -name:  all hosts execute


    user: name={{ item }} state=present

    with_items:

      - user1

      - user2

      - hahashen

[root@k8s-master2 install]# ansible-playbook -C user.yaml

[root@k8s-master2 install]# ansible-playbook  user.yaml

image

verification:

192.168.20.41

[root@k8s-node1 ~]# tail -n 3 /etc/passwd

user1:x:1001:1001::/home/user1:/bin/bash

user2:x:1002:1002::/home/user2:/bin/bash

hahashen:x:1003:1003::/home/hahashen:/bin/bash

 

192.168.20.42

[root@k8s-node2 ~]# tail -n 3 /etc/passwd

user1:x:1001:1001::/home/user1:/bin/bash

user2:x:1002:1002::/home/user2:/bin/bash

hahashen:x:1003:1003::/home/hahashen:/bin/bash


↓↓ Click "Read the original text" [Join the DevOps operation and maintenance team ]

Related Reading:

1. Playbook distributes Nginx configuration files

2. Alibaba Cloud-Ansible batch update remote host user passwords in actual combat

3. Dry goods-ansible configuration and server batch distribution (1)

4. Dry goods-ansible configuration and server batch distribution (2)

5. Installation and configuration of Ansible


image


Guess you like

Origin blog.51cto.com/15127516/2657693