changed_when关键词的作用是在条件成立时,将任务状态改为changed。
---
- hosts: control
tasks:
- name: create folder
file:
path: "{{ item }}"
state: directory
recurse: yes
with_items:
- /etc/123/1qdf
- /root/123/qww
changed_when: false ##将之前的changed状态改为ok,但是tasks已经执行
输出结果如下:
[root@ansible129 ansible]# ansible-playbook -i hosts debug.yml
PLAY [control] ***********************
TASK [Gathering Facts] *****
Thursday 09 April 2020 11:22:05 +0800 (0:00:00.043) 0:00:00.043 ********
ok: [192.168.124.129]
TASK [create folder] **********************************************
Thursday 09 April 2020 11:22:12 +0800 (0:00:06.800) 0:00:06.844 ****
ok: [192.168.124.129] => (item=/etc/123/1qdf)
ok: [192.168.124.129] => (item=/root/123/qww)
TASK [test bool] ******************************************************
192.168.124.129 :ok=3 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
Thursday 09 April 2020 11:22:13 +0800 (0:00:00.320) 0:00:08.079 *****
=====================================================================
Gathering Facts ----------------------------------------- 6.80s
create folder ------------------------------------------------- 0.91s
test bool -----------------------------------------------
bool值:
bool参数可以把字符串转换为函数值
如下:
- name: test ipv4 network connection
shell: |
ping -c 3 "{{ item }}"
with_items: "{{ ansible_all_ipv4_addresses }}"
changed_when: false
delegate_to: "{{ groups.control.0 }}"
when: enable_network_check | bool
#bool过滤器可以根据字符串的内容返回bool值true或者false
#字符串的内容为yes、1、True、true则返回布尔值true,字符串内容为其他内容则返回false
- name: enable alerts for web servers
hosts: webservers ###使用这种方式可以代替delegate_to
tasks:
- name: enable alerts
nagios: action=enable_alerts service=web host="{{ inventory_hostname }}"
delegate_to: nagios.example.com
become: true
普通切换root
- name: Setting sysctl values
sysctl: name={{ item.name }} value={{ item.value }} sysctl_set=yes
become: true
become_user: tom ##需要切换的用户
with_items:
- { name: "net.ipv4.ip_nonlocal_bind", value: 1}
- { name: "net.ipv6.ip_nonlocal_bind", value: 1}
- { name: "net.unix.max_dgram_qlen", value: 128}
when:
- set_sysctl | bool
failed_when:
当条件成立时该tasks失败
- name: check exist vm ofter migrate
debug: msg="ofter migrate exist vm"
failed_when: ensure_vm_exist.stdout | bool != 0
以下方式也可以
- name: failed when can not find kolla-ansible
fail:
msg: "Can not found kolla-ansible in {{ package_path }} folder"
when:
- find_kolla_ansible.stdout_lines|length == 0