ansible-playbook changed_when使用

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
    

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值