Brc's blog
首页
前端
后端
运维
  • 工作笔记
  • 分类
  • 标签
  • 归档
关于

Brc

努力中
首页
前端
后端
运维
  • 工作笔记
  • 分类
  • 标签
  • 归档
关于
  • Linux基础

  • Linux进阶

    • shell

    • nginx

    • keepalived

    • LVS

    • ansible

      • Ansible基础快速入门
      • Ansible Playbook
      • Ansible Variables
      • Ansible Facts Variables
      • Ansible Task Control
        • when条件语句
          • 案例1-根据不同操作系统安装相同的软件
          • 案例2-为特定的主机添加Nginx仓库
        • Handlers与Notify
          • 案例-变更服务配置触发重启
          • Handlers注意事项与说明
        • tags 任务标签
          • 案例1-指定执行某个tags
          • 案例2-指定排除某个tags
        • include任务复用
          • 案例1-多个项目调用相同task
          • 案例2-Inlcude结合tags应用
        • Playbook异常处理
          • 案例1-Playbook错误忽略
          • 案例2-task执行失败强制调用handlers
          • 案例3-控制Tasks报告状态为OK
      • Ansible Advanced
      • python调用ansible模块
    • docker

    • mysql

  • 其他

  • 运维
  • Linux进阶
  • ansible
Brc
2022-01-03
目录

Ansible Task Control

# when条件语句

when判断在Ansible中的使用频率非常高;比如yum模块可以自动检测软件包是否已被安装,而无需人为干涉,但对于有些任务则是需要进行判断才可以实现的。

  • 比如:web节点都需要配置nginx仓库,但其他节点并不需要,此时就会用到when判断。
  • 比如:Centos与Ubuntu都需要安装Apache,而Centos系统软件包为httpd,而Ubuntu系统软件包为httpd2,那么此时就需要判断主机系统,然后为不同的主机系统安装不同的软件包。

# 案例1-根据不同操作系统安装相同的软件

  1. 为所有主机安装Apache软件

    • 系统为CentOS:安装httpd
    • 系统为Ubuntu:安装httpd2
    [root@manager control]# cat when_system.yml
    - hosts: webservers
      tasks:
        #通过fact变量判断系统为centos才会安装httpd
        - name: Centos Install httpd
          yum: name=httpd state=present
          when: (ansible_distribution == "CentOS")
    
        #通过fact变量判断系统为ubuntu才会安装httpd2
        - name: Ubuntu Install httpd
          yum: name=httpd2 state=present
          when: (ansible_distribution == "Ubuntu")
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
  2. 执行playbook

    [root@manager control]# ansible-playbook when_system.yml
    
    PLAY [webservers] ********************************************************************
    
    TASK [Centos Install httpd] **********************************************************
    ok: [10.0.0.13]
    ok: [10.0.0.12]
    
    TASK [Ubuntu Install httpd] **********************************************************
    skipping: [10.0.0.12]
    skipping: [10.0.0.13]
    
    PLAY RECAP ***************************************************************************
    10.0.0.12                  : ok=1    changed=0    unreachable=0    failed=0    skipped=1    rescued=0    ignored=0
    10.0.0.13                  : ok=1    changed=0    unreachable=0    failed=0    skipped=1    rescued=0    ignored=0
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15

# 案例2-为特定的主机添加Nginx仓库

  1. 为所有主机添加Nginx仓库

    • 主机名为web:添加Nginx仓库
    • 主机名不为web:不做任何处理
    [root@manager control]# cat when_yum.yml
    - hosts: all
      tasks:
        - name: Add Nginx Yum Repository
          yum_repository:
            name: nginx
            description: Nginx Repository
            baseurl: http://nginx.org/packages/centos/7/$basearch/
            gpgcheck: no
          when: (ansible_hostname is match("web"))
    
    # 当然when也可以使用and与or方式
    # when: (ansible_hostname is match("web*")) or (ansible_hostname is match("lb*"))
    
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
  2. 执行playbook

    [root@manager control]# ansible-playbook when_yum.yml
    
    1



### 案例3-判断服务是否正常运行

- 判断`httpd`服务是否处于运行状态
    - 已运行:则重启服务
    - 未运行:则不做处理

1. 通过`register`将命令执行结果保存至变量,然后通过`when`语句进行判断

    ```sh
    [root@manager control]# cat when_service.yml
    - hosts: webservers
      tasks:
        - name: Check Httpd Server
          command: systemctl is-active httpd
          ignore_errors: yes
          register: check_httpd

        - name: debug outprint #通过debug的var输出该变量的所有内容
          debug: var=check_httpd

        - name: Httpd Restart #如果check_httpd执行命令结果等于0,则执行重启httpd,否则跳过
          service: name=httpd state=restarted
          when: check_httpd.rc == 0

    ```

2. 执行`playbook`

    ```sh
    [root@manager control]# ansible-playbook when_service.yml
    PLAY [webservers] ********************************************************************
    TASK [Check Httpd Server] ************************************************************
        changed: [10.0.0.13]
        changed: [10.0.0.12]

    TASK [debug outprint] ****************************************************************
        ok: [10.0.0.12] => {
            "check_httpd": {
                "changed": true,
                "cmd": [
                    "systemctl",
                    "is-active",
                    "httpd"
                ],
                "delta": "0:00:00.005817",
            "end": "2022-03-28 07:18:35.245988",
                "failed": false,
                "rc": 0,
                "start": "2022-03-28 07:18:35.240171",
            "stderr": "",
                "stderr_lines": [],
                "stdout": "active",
                "stdout_lines": [
                    "active"
                ]
            }
        }
        ok: [10.0.0.13] => {
            "check_httpd": {
                "changed": true,
                "cmd": [
                    "systemctl",
                    "is-active",
                    "httpd"
                ],
                "delta": "0:00:00.005770",
                "end": "2022-03-28 07:18:29.502212",
                "failed": false,
                "rc": 0,
                "start": "2022-03-28 07:18:29.496442",
                "stderr": "",
                "stderr_lines": [],
                "stdout": "active",
                "stdout_lines": [
                    "active"
                ]
            }
        }
    TASK [Httpd Restart] *****************************************************************
    changed: [10.0.0.12]
    changed: [10.0.0.13]

    PLAY RECAP ***************************************************************************
    10.0.0.12                  : ok=3    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
    10.0.0.13                  : ok=3    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

    ```



## loop 循环语句

在写`playbook`的时候发现了很多`task`都要重复引用某个相同的模块,比如一次启动10个服务,或者一次拷贝10个文件,如果按照传统的写法最少要写10次,这样会显得`playbook`很臃肿。如果使用循环的方式来编写`playbook`,这样可以减少重复编写`task`带来的臃肿;

### 案例1-使用循环批量启动服务

1. 在没有使用循环的场景下,启动多个服务需要写多条`task`任务。

    ```sh
    [root@manager control]# cat loop_service.yml
    - hosts: webservers
      tasks:
        - name: Installed Httpd Mariadb Package
          yum: name=httpd,mariadb state=latest

        - name: Start Httpd Server
          service: name=httpd state=started enabled=yes

        - name: Start Mariadb Server
          service: name=mariadb state=started enabled=yes
    ```

2. 我们将如上的`playbook`修改为循环的方式,减少重复编写多条`task`任务。

    ```sh
    [root@manager control]# cat loop_service.yml
    - hosts: webservers
      tasks:
        - name: Installed Httpd Mariadb Package
          yum: name=httpd,mariadb-server state=latest

        - name: Start Httpd Mariadb Server
          service: name={{ item }} state=started enabled=yes
          loop:
          - httpd
          - mariadb
    ```

3. 执行`playbook`

    ```sh
    [root@manager control]# ansible-playbook loop_service.yml
    PLAY [webservers] ********************************************************************

    TASK [Installed Httpd Mariadb Package] ***********************************************
        changed: [10.0.0.12]
        changed: [10.0.0.13]

    TASK [Start Httpd Mariadb Server] ****************************************************
        ok: [10.0.0.13] => (item=httpd)
        ok: [10.0.0.12] => (item=httpd)
        changed: [10.0.0.13] => (item=mariadb)
    changed: [10.0.0.12] => (item=mariadb)

    PLAY RECAP ***************************************************************************
    10.0.0.12                  : ok=2    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
    10.0.0.13                  : ok=2    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
    ```



### 案例2-使用循环批量安装软件

1. 批量安装软件

    ```sh
    [root@manager control]# cat loop_service_v2.yml
    - hosts: webservers
      tasks:
        - name: Installed Httpd Mariadb Package
          yum: name={{ pack }} state=latest
          vars:
            pack:
            - httpd
            - mariadb-server
    ```

2. 执行`playbook`

    ```sh
    [root@manager control]# ansible-playbook loop_service_v2.yml
    PLAY [webservers] ********************************************************************

    TASK [Installed Httpd Mariadb Package] ***********************************************
        ok: [10.0.0.12]
        ok: [10.0.0.13]

    PLAY RECAP ***************************************************************************
        10.0.0.12                  : ok=1    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
        10.0.0.13                  : ok=1    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
    ```



### 案例3-使用循环批量创建用户

1. 批量创建用户,使用`key values`字典的方式

    ```sh
    [root@manager control]# cat loop_user.yml
    - hosts: webservers
      tasks:
        - name: Add Users
          user: name={{ item.name }} groups={{ item.groups }} state=present
          with_items:
            - { name: "testuser1", groups: "bin" }
            - { name: "testuser2", groups: "root" }
    ```

2. 执行`playbook`

    ```sh
    [root@manager control]# ansible-playbook loop_user.yml
    PLAY [webservers] ********************************************************************

    TASK [Add Users] *********************************************************************
            changed: [10.0.0.13] => (item={u'name': u'testuser1', u'groups': u'bin'})
            changed: [10.0.0.12] => (item={u'name': u'testuser1', u'groups': u'bin'})
            changed: [10.0.0.12] => (item={u'name': u'testuser2', u'groups': u'root'})
        changed: [10.0.0.13] => (item={u'name': u'testuser2', u'groups': u'root'})

    PLAY RECAP ***************************************************************************
        10.0.0.12                  : ok=1    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
        10.0.0.13                  : ok=1    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

    ```



### 案例4-使用循环批量拷贝文件

```sh
[root@manager control]# cat loop_file.yml
- hosts: all
  tasks:
    - name: Configure Rsync Server
      copy: src={{ item.src }} dest=/etc/{{ item.dest }} mode={{item.mode }}

      with_items:
        - {src: "rsyncd.conf", dest: "rsyncd.conf", mode: "0644"}
        - {src: "rsync.passwd", dest: "rsync.passwd", mode: "0600"}
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234

# Handlers与Notify

Handlers是一个触发器,同时是一个特殊的tasks,它无法直接运行,它需要被tasks通知后才会运行。比如:httpd服务配置文件发生变更,我们则可通过Notify通知给指定的handlers触发器,然后执行相应重启服务的操作,如果配置文件不发生变更操作,则不会触发Handlers任务的执行;

# 案例-变更服务配置触发重启

  1. 使用Ansible的playbook部署httpd服务

    [root@manager control]# cat webserver.yml
    - hosts: webservers
      remote_user: root
      #1.定义变量,在配置文件中调用
      vars:
        http_port: 8881
    
      tasks:
        #2.安装httpd服务
        - name: Install Httpd Server
          yum: name=httpd state=present
    
        #3.使用template模板,引用上面vars定义的变量至配置文件中
        - name: Configure Httpd Server
          template: src=./httpd.conf.j2 dest=/etc/httpd/conf/httpd.conf
          notify: #调用名称为Restart Httpd Server的handlers(可以写多个)
            - Restart Httpd Server
    
        #4.启动Httpd服务
        - name: Start Httpd Server
          service: name=httpd state=started enabled=yes
    
      #5.如果配置文件发生变化会调用该handlers下面的对应名称的task
      handlers:
        - name: Restart Httpd Server
          service: name=httpd state=restarted
    
    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
  2. 只有当我们修改配置文件才会触发handlers

    [root@manager control]# ansible-playbook webserver.yml
    PLAY [webservers] ********************************************************************
    
    TASK [Install Httpd Server] **********************************************************
            ok: [10.0.0.12]
            ok: [10.0.0.13]
    
    TASK [Configure Httpd Server] ********************************************************
            changed: [10.0.0.12]
            changed: [10.0.0.13]
    
    TASK [Start Httpd Server] ************************************************************
            ok: [10.0.0.12]
            ok: [10.0.0.13]
    
    RUNNING HANDLER [Restart Httpd Server] ***********************************************
            changed: [10.0.0.13]
            changed: [10.0.0.12]
    
    PLAY RECAP ***************************************************************************
            10.0.0.12                  : ok=4    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
            10.0.0.13                  : ok=4    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22

# Handlers注意事项与说明

  • handlers注意事项
    • 无论多少个task通知了相同的handlers,handlers仅会在所有tasks结束后运行一次。
    • 只有task发生改变了才会通知handlers,没有改变则不会触发handlers。
    • 不能使用handlers替代tasks、因为handlers是一个特殊的tasks。

# tags 任务标签

默认情况下,Ansible在执行一个playbook时,会执行playbook中所有的任务。而标签功能是用来指定要运行playbook中的某个特定的任务;

  • 为playbook添加标签的方式有如下几种:
    • 对一个task打一个标签
    • 对一个task打多个标签
    • 对多个task打一个标签
  • task打完标签使用的几种方式
    • -t执行指定tag标签对应的任务
    • --skip-tags执行除--skip-tags标签之外的所有任务

# 案例1-指定执行某个tags

  1. 使用-t执行指定的tags标签对应的任务

    [root@manager control]# cat nfs.yml
    - hosts: nfs
      remote_user: root
      tasks:
        - name: Install Nfs Server
          yum: name=nfs-utils state=present
          tags:
            - install_nfs
            - install_nfs-server
    
        - name: Service Nfs Server
          service: name=nfs-server state=started enabled=yes
          tags: start_nfs-server
    
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
  2. 执行playbook

    [root@manager control]# ansible-playbook nfs.yml
    PLAY [nfs] ***************************************************************************
    
    TASK [Install Nfs Server] ************************************************************
            ok: [10.0.0.12]
    
    TASK [Service Nfs Server] ************************************************************
            changed: [10.0.0.12]
    
    PLAY RECAP ***************************************************************************
            10.0.0.12                  : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
    
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
  3. 使用-t指定tags标签对应的任务, 多个tags使用逗号隔开即可

    [root@manager control]# ansible-playbook -t install_nfs-server nfs.yml
    PLAY [nfs] ***************************************************************************
    
    TASK [Install Nfs Server] ************************************************************
            ok: [10.0.0.12]
    
    PLAY RECAP ***************************************************************************
            10.0.0.12                  : ok=1    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
    
    
    1
    2
    3
    4
    5
    6
    7
    8
    9

# 案例2-指定排除某个tags

  • 使用--skip-tags排除不执行的tags

    [root@manager control]# ansible-playbook --skip-tags install_nfs-server nfs.yml
    PLAY [nfs] ***************************************************************************
    
    TASK [Service Nfs Server] ************************************************************
        ok: [10.0.0.12]
    
    PLAY RECAP ***************************************************************************
    10.0.0.12                  : ok=1    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
    
    
    1
    2
    3
    4
    5
    6
    7
    8
    9

# include任务复用

有时,我们发现大量的Playbook内容需要重复编写,各Tasks之间功能需相互调用才能完成各自功能,Playbook庞大到维护困难,这时我们需要使用include。比如:A项目需要用到重启httpd,B项目也需要用到重启httpd,那么我们可以使用Include来减少重复编写。

# 案例1-多个项目调用相同task

  1. 编写restart_httpd.yml文件

    #注意这是一个tasks所以没有play的任何信息
    [root@manager control]# cat restart_httpd.yml
    - name: Restart Httpd Server
      service: name=httpd state=restarted
    
    1
    2
    3
    4
  2. A Project的playbook如下

    [root@manager control]# cat a_project.yml
    - hosts: webservers
      tasks:
        - name: A Project command
          command: echo "A"
    
        - name: Restart httpd
          include: restart_httpd.yml
    
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
  3. B Project的playbook如下

    [root@manager control]# cat b_project.yml
    - hosts: webservers
      tasks:
        - name: B Project command
          command: echo "B"
    
        - name: Restart httpd
          include: restart_httpd.yml
    
    1
    2
    3
    4
    5
    6
    7
    8
  4. A Project和B Project执行后的测试结果如下

    [root@manager control]# ansible-playbook a_project.yml
    PLAY [webservers] ********************************************************************
    
    TASK [A Project command] *************************************************************
            changed: [10.0.0.12]
            changed: [10.0.0.13]
    
    TASK [Restart Httpd Server] **********************************************************
            changed: [10.0.0.12]
            changed: [10.0.0.13]
    
    PLAY RECAP ***************************************************************************
            10.0.0.12                  : ok=2    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
            10.0.0.13                  : ok=2    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
    
    [root@manager control]# ansible-playbook b_project.yml
    
    PLAY [webservers] ********************************************************************
    
    TASK [B Project command] *************************************************************
        changed: [10.0.0.12]
        changed: [10.0.0.13]
    
    TASK [Restart Httpd Server] **********************************************************
        changed: [10.0.0.13]
        changed: [10.0.0.12]
    
    PLAY RECAP ***************************************************************************
        10.0.0.12                  : ok=2    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
        10.0.0.13                  : ok=2    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
    
    
    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

# 案例2-Inlcude结合tags应用

  • 通过指定标签tags,来说明是安装tomcat8还是tomcat9
    • 准备入口main.yml文件,然后包含install_tomcat8.yml以及install_tomcat9.yml
    • 在执行main.yml时,需要通过--tags指明要安装的版本
  1. 编写main.yml入口文件

    [root@manager control]# cat main.yml
    - hosts: localhost
      tasks:
        - name: Installed Tomcat8 Version
          include: install_tomcat8.yml
          tags: tomcat8
    
        - name: Installed Tomcat9 Version
          include: install_tomcat9.yml
          tags: tomcat9
    
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
  2. 编写install_tomcat8.yml

    [root@manager control]# cat install_tomcat8.yml
    - hosts: webservers
      vars:
        - tomcat_version: 8.5.63
        - tomcat_install_dir: /usr/local
      tasks:
        - name: Install jdk1.8
          yum:
            name: java-1.8.0-openjdk
            state: present
    
        - name: Download tomcat
          get_url:
            url: http://mirrors.hust.edu.cn/apache/tomcat/tomcat-8/v{{ tomcat_version }}/bin/apache-tomcat-{{ tomcat_version}}.tar.gz
            dest: /tmp
    
        - name: Unarchive tomcat-{{ tomcat_version }}.tar.gz
          unarchive:
            src: /tmp/apache-tomcat-{{ tomcat_version }}.tar.gz
            dest: "{{ tomcat_install_dir }}"
            copy: no
    
        - name: Start tomcat
          shell: cd {{ tomcat_install_dir }} &&
                mv apache-tomcat-{{ tomcat_version }} tomcat8 &&
                cd tomcat8/bin && nohup ./startup.sh &
    
    
    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
  3. 编写install_tomcat9.yml

    [root@manager control]# cat install_tomcat9.yml
    - hosts: webservers
      vars:
        - tomcat_version: 9.0.43
        - tomcat_install_dir: /usr/local
      tasks:
        - name: Install jdk1.8
          yum:
            name: java-1.8.0-openjdk
            state: present
    
        - name: Download tomcat
          get_url:
            url: http://mirrors.hust.edu.cn/apache/tomcat/tomcat-9/v{{ tomcat_version }}/bin/apache-tomcat-{{ tomcat_version}}.tar.gz
            dest: /tmp
    
        - name: Unarchive tomcat-{{ tomcat_version }}.tar.gz
          unarchive:
            src: /tmp/apache-tomcat-{{ tomcat_version }}.tar.gz
            dest: "{{ tomcat_install_dir }}"
            copy: no
    
        - name: Start tomcat
          shell: cd {{ tomcat_install_dir }} &&
                mv apache-tomcat-{{ tomcat_version }} tomcat8 &&
                cd tomcat8/bin && nohup ./startup.sh &
    
    
    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
  4. 执行main.yml文件,然后通过--tags执行对应的版本

    [root@manager control]# ansible-playbook main.yml --tags tomcat8
    [root@manager control]# ansible-playbook main.yml --tags tomcat9
    
    1
    2

# Playbook异常处理

# 案例1-Playbook错误忽略

在playbook执行的过程中,难免会遇到一些错误。由于playbook遇到错误后,不会执行之后的任务,不便于调试,此时,可以使用ignore_errors来暂时忽略错误,使得playbook继续执行。

  1. 编写playbook,当有task执行失败则会立即终止后续task运行

    [root@manager control]# cat ignore.yml
    - hosts: all
      remote_user: root
      tasks:
        - name: Ignore False
          command: /bin/false
    
        - name: touch new file
          file: path=/tmp/bi_ignore state=touch
    
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
  2. 执行playbook,会报错,后续的任务也没有执行。

    [root@manager control]# ansible-playbook ignore.yml
    PLAY [all] ***************************************************************************
    
    TASK [Ignore False] ******************************************************************
            fatal: [10.0.0.12]: FAILED! => {"changed": true, "cmd": ["/bin/false"], "delta": "0:00:00.003536", "end": "2022-03-28 08:53:15.630142", "msg": "non-zero return code", "rc": 1, "start": "2022-03-28 08:53:15.626606", "stderr": "", "stderr_lines": [], "stdout": "", "stdout_lines": []}
            fatal: [10.0.0.13]: FAILED! => {"changed": true, "cmd": ["/bin/false"], "delta": "0:00:00.003847", "end": "2022-03-28 08:53:09.886954", "msg": "non-zero return code", "rc": 1, "start": "2022-03-28 08:53:09.883107", "stderr": "", "stderr_lines": [], "stdout": "", "stdout_lines": []}
    
    PLAY RECAP ***************************************************************************
            10.0.0.12                  : ok=0    changed=0    unreachable=0    failed=1    skipped=0    rescued=0    ignored=0
            10.0.0.13                  : ok=0    changed=0    unreachable=0    failed=1    skipped=0    rescued=0    ignored=0
    
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
  3. 此时我们给对应的task任务添加忽略错误

    [root@manager control]# cat ignore.yml
    - hosts: all
      remote_user: root
      tasks:
        - name: Ignore False
          command: /bin/false
          ignore_errors: yes
    
        - name: touch new file
          file: path=/tmp/bi_ignore state=touch
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
  4. 再次执行playbook如果碰到指定的tasks错误,会自动忽略,继续执行剩下的tasks

    [root@manager control]# ansible-playbook ignore.yml
    PLAY [all] ***************************************************************************
    TASK [Ignore False] ******************************************************************
        fatal: [10.0.0.12]: FAILED! => {"changed": true, "cmd": ["/bin/false"], "delta": "0:00:00.003070", "end": "2022-03-28 08:53:51.214443", "msg": "non-zero return code", "rc": 1, "start": "2022-03-28 08:53:51.211373", "stderr": "", "stderr_lines": [], "stdout": "", "stdout_lines": []}
        ...ignoring
        fatal: [10.0.0.13]: FAILED! => {"changed": true, "cmd": ["/bin/false"], "delta": "0:00:00.003109", "end": "2022-03-28 08:53:45.470045", "msg": "non-zero return code", "rc": 1, "start": "2022-03-28 08:53:45.466936", "stderr": "", "stderr_lines": [], "stdout": "", "stdout_lines": []}
            ...ignoring
    
    TASK [touch new file] ****************************************************************
        changed: [10.0.0.12]
        changed: [10.0.0.13]
    
    PLAY RECAP ***************************************************************************
        10.0.0.12                  : ok=2    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=1
        10.0.0.13                  : ok=2    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=1
    
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16

# 案例2-task执行失败强制调用handlers

通常情况下,当task失败后,play将会终止,任何在前面已经被tasks notify的handlers都不会被执行。如果你在play中设置了force_handlers: yes参数,被通知的handlers就会被强制执行。(有些特殊场景可能会使用到)

  1. 编写playbook

    [root@manager control]# cat igno_handlers.yml
    - hosts: webservers
      force_handlers: yes #强制调用handlers
      tasks:
        - name: Touch File
          file: path=/tmp/bgx_handlers state=touch
          notify: Restart Httpd Server
    
        - name: Installed Packages
          yum: name=sb state=latest
    
      handlers:
      - name: Restart Httpd Server
        service: name=httpd state=restarted
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
  2. 执行playbook

    [root@manager control]# ansible-playbook igno_handlers.yml
    PLAY [webservers] ********************************************************************
    
    TASK [Touch File] ********************************************************************
            changed: [10.0.0.12]
            changed: [10.0.0.13]
    
    TASK [Installed Packages] ************************************************************
            fatal: [10.0.0.13]: FAILED! => {"changed": false, "msg": "No package matching 'sb' found available, installed or updated", "rc": 126, "results": ["No package matching 'sb' found available, installed or updated"]}
            fatal: [10.0.0.12]: FAILED! => {"changed": false, "msg": "No package matching 'sb' found available, installed or updated", "rc": 126, "results": ["No package matching 'sb' found available, installed or updated"]}
    
    RUNNING HANDLER [Restart Httpd Server] ***********************************************
            changed: [10.0.0.12]
            changed: [10.0.0.13]
    
    PLAY RECAP ***************************************************************************
        10.0.0.12                  : ok=2    changed=2    unreachable=0    failed=1    skipped=0    rescued=0    ignored=0
        10.0.0.13                  : ok=2    changed=2    unreachable=0    failed=1    skipped=0    rescued=0    ignored=0
    
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19

# 案例3-控制Tasks报告状态为OK

  1. 编辑playbook

    [root@manager control]# cat change.yml
    - hosts: webservers
      tasks:
        #获取系统httpd服务启动状态,将其结果写入Httpd_Port变量中
        - name: Get Httpd Server Port
          shell: netstat -lntp|grep httpd
          register: Httpd_Port
    
        #输出Httpd_Port变量中的内容
        - name: Out Httpd Server Status
          debug: msg={{ Httpd_Port.stdout_lines }}
          ignore_errors: yes
    
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
  2. 执行playbook会发现第一个task运行shell模块报告的改变,即使它没有真正的在远端系统做出改变,如果你一直运行,它会一直处在改变状态。

    [root@manager control]# ansible-playbook change.yml
    PLAY [webservers] ********************************************************************
    
    TASK [Get Httpd Server Port] *********************************************************
            changed: [10.0.0.13]
            changed: [10.0.0.12]
    
    TASK [Out Httpd Server Status] *******************************************************
            ok: [10.0.0.12] => {
                "msg": [
                    "tcp6       0      0 :::8882                 :::*                    LISTEN      27796/httpd         "
            ]
            }
            ok: [10.0.0.13] => {
                "msg": [
                    "tcp6       0      0 :::8882                 :::*                    LISTEN      53135/httpd         "
                ]
            }
    
    PLAY RECAP ***************************************************************************
        10.0.0.12                  : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
        10.0.0.13                  : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
    
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
  3. shell任务不应该每次都报告changed状态,因为它没有在被管理主机执行后发生变化。添changed_when: false来抑制这个改变

    [root@manager control]# cat change.yml
    - hosts: webservers
      tasks:
        #获取系统httpd服务启动状态,将其结果写入Httpd_Port变量中
        - name: Get Httpd Server Port
          shell: netstat -lntp|grep httpd
          register: Httpd_Port
          changed_when: false #该task不发生changed提示
    
        #输出Httpd_Port变量中的内容
        - name: Out Httpd Server Status
          debug: msg={{ Httpd_Port.stdout_lines }}
          ignore_errors: yes
    
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
  4. 再次执行playbook

    [root@manager control]# ansible-playbook change.yml
    PLAY [webservers] ********************************************************************
    
    TASK [Get Httpd Server Port] *********************************************************
        ok: [10.0.0.13]
        ok: [10.0.0.12]
    
    TASK [Out Httpd Server Status] *******************************************************
        ok: [10.0.0.12] => {
            "msg": [
                "tcp6       0      0 :::8882                 :::*                    LISTEN      27796/httpd         "
        ]
        }
        ok: [10.0.0.13] => {
            "msg": [
                "tcp6       0      0 :::8882                 :::*                    LISTEN      53135/httpd         "
            ]
        }
    
    PLAY RECAP ***************************************************************************
    10.0.0.12                  : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
    10.0.0.13                  : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
    
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
#ansible#playbook
Last Updated: 2024/03/29, 17:39:25
Ansible Facts Variables
Ansible Advanced

← Ansible Facts Variables Ansible Advanced→

最近更新
01
谷歌云创建GKE集群
07-26
02
ElastiCacheForRedis启用密码
07-26
03
upload-to-gcs
06-29
更多文章>
Theme by Vdoing | Copyright © 2021-2024 Brc | MIT License | 浙ICP备19031881号-4
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式