今天研究了一个东西,就是如何在使用with_item的同时根据每一个item的情况,选择是否调用notify
我们很多时候都需要使用with_item这个循环,例如检测文件是否更新,或者其它什么时候,例如我们有4个文件
1 2 3 4 |
- a.file - b.file - c.file - d.file |
例如,当a 更新的时候,我们重启a服务,b更新的时候我们重启b服务,c更新的时候我们重启c服务,d更新的时候我们重启d服务
当然,我们可以写死:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
tasks: - name: copy the file a copy: src: /tmp/dev/a dest: /tmp/product/a notify: restart service a - name: copy the file b copy: src: /tmp/dev/b dest: /tmp/product/b notify: restart service b handlers: - name: restart service a service: name: a state: restarted - name: restart service b service: name: b state: restarted |
这样肯定没问题,当我们a文件更新的时候,会自动重启a服务,b文件更新的时候会自动重启b,但是我们能不能使用with_item来完成
1 2 3 4 5 6 7 8 9 10 |
- name: copy the file copy: src: /tmp/dev/{{ item }} dest: /tmp/product/{{ item }} notify: restart service {{ item }} with_items: - a - b - c - d |
答案是可以的,但是有一个问题,当a 文件更新的时候 不光a 服务重启了,b,c,d服务也重启了,这不是我们想看到的,解决办法如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
vars: files: - a - b - c - d - name: copy the file copy: src: /tmp/dev/{{ item }} dest: /tmp/product/{{ item }} with_items: {{ files }} register: result_copy - name: restart the service service: name: "{{ item.item }}" state: restarted with_items: result_copy.results when: item.changed == True |
就是我么不在使用notify模块功能,使用when来解决,其实虽然是个循环,但是我们的register仍然存储了每个item的相关信息,这样我们就可以在剩下的task中使用
另:完整测试用例
本地/tmp/dev/下会存放每次需要更新war包,当war有更新时,需要将新的war包拷贝到目的主机,并删除原来的war解压生成的文件夹
(后续重启服务没写)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
--- - hosts: test tasks: - name: get all the file under /tmp/dev/ shell: ls /tmp/dev register: files delegate_to: localhost - debug: var="{{ files.stdout_lines[1] }}" - debug: var="{{ item }}" with_items: "{{ files.stdout_lines }}" - name: copy the file copy: src: /tmp/dev/{{ item }} dest: /tmp/product/{{ item }} with_items: "{{ files.stdout_lines }}" register: result_copy - debug: msg="/tmp/product/{{ item.item|replace('.war','') }}" with_items: result_copy.results when: item.changed == True - name: delete the file file: path: /tmp/product/{{ item.item|replace(".war","") }} state: absent with_items: result_copy.results when: item.changed == True |
Latest posts by Zhiming Zhang (see all)
- aws eks node 自动化扩展工具 Karpenter - 8月 10, 2022
- ReplicationController and ReplicaSet in Kubernetes - 12月 20, 2021
- public key fingerprint - 5月 27, 2021