ansible條件判斷和循環

在ansible中,只有when能夠實現條件判斷
node

tasks:web

  - name: config the yum repo for centos 7centos

    yum_repository:bash

       name: epel服務器

       description: epel運維

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

       gpgcheck: no阿里雲

    when: ansible_distribution_major_version == "7"url

注意兩點:spa

when判斷的對象是task,因此和task在同一列表層次。它的判斷結果決定它所在task是否執行,而不是它下面的task是否執行。

when中引用變量的時候不須要加{{ }}符號。


(1)不設置條件時,兩臺服務器同時執行命令,如何設置只容許192.168.20.42執行操做命令

圖片


(2)配置playbook

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

---

- 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'


(3)執行操做:

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

圖片

結果跳過43服務器,直接在42服務器上執行


2、循環:批量建立用戶


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

---

- hosts: webservers

  remote_user: root

  gather_facts: true

  tasks:

  - name: 全部主機執行


    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

圖片

驗證:

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


↓↓ 點擊"閱讀原文" 【加入DevOps運維團

相關閱讀:

一、Playbook分發Nginx配置文件

二、阿里雲--實戰Ansible批量更新遠程主機用戶密碼

三、乾貨--ansible配置和服務器批量分發(一)

四、乾貨--ansible配置和服務器批量分發(二)

五、Ansible的安裝、配置


圖片

相關文章
相關標籤/搜索