loop循环
- 简单循环:
loop: ##赋值列表
- value1
- value2
- ...
- 实例:
vim test.yml
编辑playbook
--- - name: test loop hosts: 172.25.254.100 tasks: - name: touch file file: path: "/mnt/{{item.path}}" owner: "{{item.owner}}" state: touch loop: - path: westosfile owner: westos - path: rootfile owner: root
- 测试结果
条件(when)
= | value == “字符串”,value == 数字 |
---|---|
< | value < 数字 |
> | value > 数字 |
<= | value <= 数字 |
>= | value >= 数字 |
!= | value != 数字 |
is defined value | value is defined 变量存在 |
is not defined | value is not defined 变量不存在 |
bool变量 为true | value value的值为true |
bool变量 false | not value value的值为false |
|value in value2 value的值在value2列表中
格式:
when:
条件1 and 条件2 ## 一行显示 表示同时满足条件1和条件2才可以执行
- 条件1 ## 多行显示
- 条件2
when:
条件1 or 条件2 ## 一行显示
when: >
条件1
or
条件2
- 示例
-
vim test.yml
编辑playbook脚本--- - name: test when hosts: 172.25.254.100 vars: westos: path: westosfile owner: westos rc: 0 tasks: - name: touch file file: path: "/mnt/{{westos.path}}" owner: "{{westos.owner}}" state: touch when: westos.rc == 0 and westos.owner == "westos"
-
测试
-
表示 “或者” 的书写格式和测试结果
-
触发器(handlers)
格式:
notify: ##触发器当遇到更改时触发handlers
- 任务1
- 任务2
handlers: ##触发器触发后执行的动作
处理失败任务
ignore_errors
作用: 当play遇到任务失败时会终止
ignoer_errors: yes
将会忽略任务失败,继续执行下面的任务
示例:
-
要求: 给受控主机安装httpd,并且修改端口为8080(默认yum源仓库已经配置完成)
-
步骤:
-
vim test.yml
编辑playbook--- - name: test when hosts: all vars: http_port: 8080 tasks: - name: check apache shell: rpm -q httpd ignore_errors: yes ##忽略shell模块的执行后的错误进程 register: westos - name: dnf httpd dnf: name: httpd state: latest when: westos.rc == 1 - name: configure apache file lineinfile: path: /etc/httpd/conf/httpd.conf regexp: "^Listen" line: "Listen {{http_port}}" notify: - restart httpd handlers: - name: restart httpd service: name: httpd state: restarted
-
运行测试
-
force_handlers
作用:当任务失败后play被终止也会调用触发器进程
格式:
force_handlers: yes
示例:
---
- name: apache change port
hosts: 172.25.254.100
force_handlers: yes
vars:
http_port: 80
tasks:
- name: configure apache conf file
lineinfile:
path: /etc/httpd/conf/httpd.conf
regexp: "^Listen"
line: "Listen {{ http_port }}"
notify: restart apache
- name: install error
dnf:
name: westos
state: latest
handlers:
- name: restart apache
service:
name: httpd
state: restarted
enabled: yes
changed_when
作用:
控制任务在何时报告它已进行更改
格式:
changed_when:
示例:
---
- name: apache change port
hosts: 172.25.254.100
force_handlers: yes
vars:
http_port: 8080
tasks:
- name: configure apache conf file
lineinfile:
path: /etc/httpd/conf/httpd.conf
regexp: "^Listen"
line: "Listen {{ http_port }}"
changed_when: true
notify: restart apache
handlers:
- name: restart apache
service:
name: httpd
state: restarted
enabled: yes
failed_when
作用:当符合条件时强制任务失败
示例:
---
- name: test
hosts: 172.25.254.103
tasks:
- name: shell
shell: echo hello
register: westos
failed_when: "'hello' in westos.stdout"
block
block: ##定义要运行的任务
rescue: ##定义当block句子中出现失败任务后运行的任务
always: ##定义最终独立运行的任务