在ansible中,只有when可以实现条件判断
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"
注意两点:
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服务器上执行
二、循环:批量创建用户
[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运维团】
相关阅读: