实施处理程序、处理任务失败和文件管理
1. 实施处理程序
1.1 Ansible处理程序
Ansible模块设计为具有幂等性。这表示,在正确编写的playbook中,playbook及其任务可以运行多次而不会改变受管主机,除非需要进行更改使受管主机进入所需的状态。
但在时候,在任务确实更改系统时,可能需要运行进一步的任务。例如,更改服务配置文件时可能要求重新加载该服务以便使其更改的配置生效。
处理程序是响应由其他任务触发的通知的任务。仅当任务在受管主机上更改了某些内容时,任务才通知其处理程序。每个处理程序具有全局唯一的名称,在playbook中任务块的末尾触发。如果没有任务通过名称通知处理程序,处理程序就不会运行。如果一个或多个任务通知处理程序,处理程序就会在play中的所有其他任务完成后运行一次。因为处理程序就是任务,所以可以在处理程序中使用他们将用于任何其他任务的模块。通常而言,处理程序被用于重新引导主机和重启服务。
处理程序可视为非活动任务,只有在使用notify语句显式调用时才会被触发。在下列代码片段中,只有配置文件更新并且通知了该任务,restart apache处理程序才会重启Apache服务器:
tasks:
- name: copy demo.example.conf configuratioon template # 通知处理程序的任务
template:
src: /var/lib/templates/demo.example.conf.template
dest: /etc/httpd/conf.d/demo.example.conf
notify: # notify语句指出该任务需要触发一个处理程序
- restart apache # 要运行的处理程序的名称
handlers: # handlers关键字表示处理程序任务列表的开头
- name: restart apache # 被任务调用的处理程序的名称
service: # 用于该处理程序的模块
name: httpd
state: restarted
在上面的例子中,restart apache处理程序只有在template任务通知已发生更改时才会触发。一个任务可以在其notify部分中调用多个处理程序。Ansible将notify语句视为数组,并且迭代处理程序名称:
tasks:
- name: copy demo.example.conf configuration template
template:
src: /var/lib/templates/demo.exammple.conf.template
dest: /etc/httpd/conf.d/demo.example.conf
notify:
- restart mysql
- restart apache
handlers:
- name: restart mysql
service:
name: mariadb
state: restarted
- name: restart apache
service:
name: httpd
state: restarted
1.2 使用处理程序的好处
使用处理程序时需要牢记几个重要事项:
处理程序始终按照play的handlers部分指定的顺序运行。它们不按在任务中由notify语句列出的顺序运行,或按任务通知它们的顺序运行。
处理程序通常在相关play中的所有其他任务完成后运行。playbook的tasks部分中某一任务调用的处理程序,将等到tasks下的所有任务都已处理后才会运行。
处理程序名称存在于各play命名空间中。如果两个处理程序被错误地给予相同的名称,则仅会运行一个。
即使有多个任务通知处理程序,该处理程序依然仅运行一次。如果没有任务通知处理程序,它就不会运行。
如果包含notify语句的任务没有报告changed结果(例如,软件包已安装并且任务报告ok),则处理程序不会获得通知。处理程序将被跳过,直到有其他任务通知它。只有相关任务报告了changed状态,Ansible才会通知处理程序。
处理程序用于在任务对受管主机进行更改时执行额外操作。它们不应用作正常任务的替代。
2. 处理任务失败
2.1 管理play中的任务错误
Ansible评估任务的返回代码,从而确定任务是成功还是失败。通常而言,当任务失败时,Ansible将立即在该主机上中止play的其余部分并且跳过所有后续任务。
但有些时候,可能希望即使在任务失败时也继续执行play。例如,或许预期待定任务有可能会失败,并且希望通过有条件地运行某项其他任务来修复。
Ansible有多种功能可用于管理任务错误。
2.2 忽略任务失败
默认情况下,任务失败时play会中止。不过,可以通过忽略失败的任务来覆盖此行为。可以在任务中使用ignore_errors关键字来实现此目的。
下列代码片段演示了如何在任务中使用ignore_errors,以便在任务失败时也继续在主机上执行playbook。例如,如果notapkg软件包不存在,则yum模块将失败,但若将ignore_errors设为yes,则执行将继续。
[root@ansible playbook]# cat test.yml
---
- hosts: 192.168.200.154
tasks:
- name: install httpd
yum:
name: http123
state: present
ignore_errors: yes
- name: start service
service:
name: httpd
state: started
enabled: yes
[root@ansible ansible]# ansible-playbook /opt/playbook/test.yml
PLAY [192.168.200.154] *********************************************************
TASK [Gathering Facts] *********************************************************
ok: [192.168.200.154]
TASK [install httpd] ***********************************************************
fatal: [192.168.200.154]: FAILED! => {"changed": false, "failures": ["No package http123 available."], "msg": "Failed to install some of the specified packages", "rc": 1, "results": []}
...ignoring
TASK [start service] ***********************************************************
ok: [192.168.200.154]
PLAY RECAP *********************************************************************
192.168.200.154 : ok=3 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=1
2.3 任务失败后强制执行处理程序
通常而言,如果任务失败并且play在该主机上中止,则收到play中早前任务通知的处理程序将不会运行。如果在play中设置force_handlers: yes关键字,则即使play因为后续任务失败而中止也会调用被通知的处理程序。
下列代码片段演示了如何在play中使用force_handlers关键字,以便在任务失败时也强制执行相应的处理程序:
---
- hosts: 192.168.72.137
force_handlers: yes
tasks:
- name:
command: echo "yyds"
notify: restart
- name:
yum:
name: aaa
srate: present
handlers:
- name: restart
service:
name: httpd
state: restarted
[root@master xm]# ansible-playbook test.yml
PLAY [192.168.200.154] ******************************************************************************************************************
TASK [Gathering Facts] *****************************************************************************************************************
Enter passphrase for key '/root/.ssh/id_rsa':
ok: [192.168.200.154]
TASK [command] *************************************************************************************************************************
changed: [192.168.200.154]
TASK [yum] *****************************************************************************************************************************
fatal: [192.168.200.154]: FAILED! => {"changed": false, "msg": "Unsupported parameters for (dnf) module: srate Supported parameters include: allow_downgrade, autoremove, bugfix, conf_file, disable_excludes, disable_gpg_check, disable_plugin, disablerepo, download_dir, download_only, enable_plugin, enablerepo, exclude, install_repoquery, install_weak_deps, installroot, list, lock_timeout, name, releasever, security, skip_broken, state, update_cache, update_only, validate_certs"}
RUNNING HANDLER [restart] **************************************************************************************************************
changed: [192.168.200.154]
PLAY RECAP *****************************************************************************************************************************
192.168.200.154
请记住,处理程序会在任务报告changed结果时获得通知,而在任务报告ok或failed结果时不会获得通知。
2.4 指定任务失败条件
可以在任务中使用failed_when关键字来指定表示任务已失败的条件。这通常与命令模块搭配使用,这些模块可能成功执行了某一命令,但命令的输出可能指示了失败。
例如,可以运行输出错误消息的脚本,并使用该消息定义任务的失败状态。下列代码片段演示了如何在任务中使用failed_when关键字:
tasks:
- name: Run user creation script
shell: /usr/local/bin/create_users.sh
register: command_result
failed_when: "'Password missing' in command_result.stdout"
fail模块也可用于强制任务失败。上面的场景也可以编写为两个任务:
tasks:
- name: Run user creation script
shell: /usr/local/bin/create_users.sh
register: command_result
ignore_errors: yes
- name: Report script failure
fail:
msg: "The password is missing in the output"
when: "'Password missing' in command_result.stdout"
我们可以使用fail模块为任务提供明确的失败消息。此方法还支持延迟失败,允许在运行中间任务以完成或回滚其他更改。
2.5 指定何时任务报告“Changed”结果
当任务对托管主机进行了更改时,会报告 changed 状态并通知处理程序。如果任务不需要进行更改,则会报告ok并且不通知处理程序。
changed_when关键字可用于控制任务在何时报告它已进行了更改。例如,下一示例中的shell模块将用于获取供后续任务使用的Kerberos凭据。它通常会在运行时始终报告changed。为抵制这种更改,应设置changed_when: false,以便它仅报告ok或failed。
- name: get Kerberos credentials as "admin"
shell: echo "{{ krb_admin_pass }}" | kinit -f admin
changed_when: false
以下示例使用shell模块,根据通过已注册变量收集的模块的输出来报告changed
---
- hosts: 192.168.200.154
tasks:
- name: abc
shell: echo "runtime" | passwd --stdin abc
register: xiong
notify:
- print info
handlers:
- name: print info
debug:
msg: "密码已经创建了!!!"
[root@master xm]# ansible-playbook test.yml
PLAY [192.168.200.154] ******************************************************************************************************************
TASK [Gathering Facts] *****************************************************************************************************************
ok: [192.168.200.154]
TASK [abc] ******************************************************************************************************************************
changed: [192.168.200.154]
RUNNING HANDLER [print info] ***********************************************************************************************************
ok: [192.168.200.154] => {
"msg": "密码已经创建了!!!"
}
PLAY RECAP *****************************************************************************************************************************
192.168.200.154 : ok=3 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
2.6 Ansible块和错误处理
在playbook中,块是对任务进行逻辑分组的子句,可用于控制任务的执行方式。例如,任务块可以含有when关键字,以将某一条件应用到多个任务:
- name: block example
hosts: 192.168.200.154
tasks:
- name: installing and configuring Yum versionlock plugin
block:
- name: package needed by yum
yum:
name: yum-plugin-versionlock
state: present
- name: lock version of tadata
lineinfile:
dest: /etc/yum/pluginconf.d/versionlock.list
line: tzdata-2020j-1
state: present
when: ansible_distribution == "Redhat"
通过块,也可结合rescue和always语句来处理错误。如果块中的任何任务失败,则执行其rescue块中的任务来进行恢复。在block子句中的任务以及rescue子句中的任务(如果出现故障)运行之后,always子句中的任务运行。总结:
block:定义要运行的主要任务
rescue:定义要在block子句中定义的任务失败时运行的任务
always:定义始终都独立运行的任务,不论block和rescue子句中定义的任务是成功还是失败
以下示例演示了如何在playbook中实施块。即使block子句中定义的任务失败,rescue和always子句中定义的任务也会执行。
tasks:
- name: Upgrade DB
block:
- name: upgrade the database
shell:
cmd: /usr/local/lib/upgrade-database
rescue:
- name: revert the database upgrade
shell:
cmd: /usr/local/lib/revert-database
always:
- name: always restart the database
service:
name: mariadb
state: restarted
3. 文件管理
3.1 修改文件并将其复制到主机
3.1.1 描述文件模块
Files模块库包含的模块允许用户完成与Linux文件管理相关的大多数任务,如创建、复制、编辑和修改文件的权限和其他属性。下表提供了常用文件管理模块的列表:
常用文件模块
模块名称 | 模块说明 |
---|---|
blockinfile | 插入、更新或删除由可自定义标记线包围的多行文本块 |
copy | 将文件从本地或远程计算机复制到受管主机上的某个位置。类似于file模块,copy模块还可以设置文件属性,包括SELinux上下文件。 |
fetch | 此模块的作用和copy模块类似,但以相反方式工作。 此模块用于从远程计算机获取文件到控制节点,并将它们存储在按主机名组织的文件树中。 |
file | 设置权限、所有权、SELinux上下文以及常规文件、符号链接、硬链接和目录的时间戳等属性。此模块还可以创建或删除常规文件、符号链接、硬链接和目录。其他多个与文件相关的模块支持与file模块相同的属性设置选项,包括copy模块。 |
lineinfile | 确保特定行位于某文件中,或使用反向引用正则表达式来替换现有行。此模块主要在用户想要更改文件的某一行时使用。 |
stat | 检索文件的状态信息,类似于Linux中的stat命令。 |
synchronize | 围绕rsync命令的一个打包程序,可加快和简化常见任务。synchronize模块无法提供对rsync命令的完整功能的访问权限,但确实最常见的调用更容易实施。用户可能仍需通过run command模块直接调用rsync命令。 |
3.2 file模块的自动化示例
在受管主机上创建、复制、编辑和删除文件是用户可以使用Files模块库中的模块实施的常见任务。
以下示例显示了可以使用这些模块自动执行常见文件管理任务的方式。
3.2.1 确保受管主机存在文件
使用file模块处理受管主机上的文件。其工作方式与touch命令类似,如果不存在则创建一个空文件,如果存在,则更新其修改时间。在本例中,除了处理文件之外,Ansible还确保将文件的所有者、组和权限设置为特定值。
//新建一个yml文件
[root@ansible test]# vim test.yml
---
- hosts: 192.168.200.154
tasks:
- name: touch file
file:
path: /root/test
state: touch
//执行
[root@ansible ansible]# ansible-playbook /opt/playbook/test/test.yml
PLAY [192.168.200.154] *********************************************************
TASK [Gathering Facts] *********************************************************
ok: [192.168.200.154]
TASK [touch file] **************************************************************
changed: [192.168.200.154]
PLAY RECAP *********************************************************************
192.168.200.154 : ok=2 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
//查看结果
[root@localhost ~]# ls
anaconda-ks.cfg test
3.2.2 修改文件属性
使用file模块还可以确保新的或现有的文件具有正确的权限和SELinux类型。
例如,以下文件保留了相对于用户主目录的默认SELinux上下文,这不是所需的上下文。
//查看原来的文件属性
[root@localhost ~]# ls -Z test
unconfined_u:object_r:admin_home_t:s0 test
//编写一个yml文件
[root@ansible test]# vim test.yml
---
- hosts: 192.168.200.154
tasks:
- name: SElinux type is set to samba_share_t
file:
path: /root/test
setype: samba_share_t
//执行
[root@ansible ansible]# ansible-playbook /opt/playbook/test/test.yml
PLAY [192.168.200.154] *********************************************************
TASK [Gathering Facts] *********************************************************
ok: [192.168.200.154]
TASK [SElinux type is set to samba_share_t] ************************************
changed: [192.168.200.154]
PLAY RECAP *********************************************************************
192.168.200.154 : ok=2 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
//查看效果
[root@localhost ~]# ls -Z test
unconfined_u:object_r:samba_share_t:s0 test
文件属性参数在多个文件管理模块中可用。运行ansible-doc file和ansible-doc copy命令以获取其他信息。
3.2.3 使SElinux文件上下文更改具有持久性
设置文件上下文时,file模块的行为与chcon类似。通过运行restorecon,可能会意外地撤消使用该模块所做的更改。使用file设置上下文后,用户可以使用system模块集合中的sefcontext来更新SELinux策略,如semanage fcontext。
[root@ansible test]# vim test.yml
[root@ansible test]# cat test.yml
---
- hosts: 192.168.200.154
tasks:
- name: SElinux type is persistently set to samba_share_t
sefcontext:
target: /root/test
setype: samba_share_t
state: present
注意:sefcontext模块更新SELinux策略中目标的默认上下文,但不更改现有文件的上下文。
3.2.1 在受管主机上复制和编辑文件
在此示例中,copy模块用于将位于控制节点上的Ansible工作目录中的文件复制到选定的受管主机。
默认情况下,此模块假定设置了force: yes。这会强制该模块覆盖远程文件(如果存在但包含与正在复制的文件不同的内容)。如果设置force: no,则它仅会将该文件复制到受管主机(如果该文件尚不存在)。
//编写一个yml文件
[root@ansible test]# vim test.yml
---
- hosts: 192.168.200.154
tasks:
- name: Copy a test1 to managed hosts
copy:
src: /root/test1 //源地址
dest: /root/ //目标地址
//执行
[root@ansible ansible]# ansible-playbook /opt/playbook/test/test.yml
PLAY [192.168.200.154] *********************************************************
TASK [Gathering Facts] *********************************************************
ok: [192.168.200.154]
TASK [Copy a test1 to managed hosts] *******************************************
changed: [192.168.200.154]
PLAY RECAP *********************************************************************
192.168.200.154 : ok=2 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
//结果
[root@localhost ~]# ls
anaconda-ks.cfg test test1
要从受管主机检索文件,请使用fetch模块。这可用于在将参考系统分发给其他受管主机之前从参考系统中检查诸如SSH公钥之类的文件。
[root@ansible test]# vim test.yml
---
- name: copy
hosts: 192.168.200.154
tasks:
- name: test
fetch:
src: /root/test.sh //注意它和copy不一样,这里是受管主机的路径
dest: /root/ //这里才是控制机的路径,他和copy是反的
[root@ansible ansible]#
[root@ansible ansible]# ansible-playbook node/test.yml
PLAY [copy] *************************************************************
TASK [Gathering Facts] *********************************************************
ok: [192.168.200.154]
TASK [test] ********************************************************************
changed: [192.168.200.154]
PLAY RECAP *********************************************************************
192.168.200.154 : ok=2 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
[root@ansible ansible]# ls /root
192.168.200.154 test.sh //可以看见受管主机文件已经到控制机上了
anaconda-ks.cfg
要确保现有文件中存在特定的单行文本,请使用lineinfile模块:
- name: Add a line of text to a file
lineinfile:
path: /path/to/file
line: 'Add this line to the file'
state: present
要将文本块添加到现有文件,请使用blockinfile模块:
[root@ansible test]# cat test.yml
---
- hosts: 192.168.200.154
tasks:
- name: test
blockinfile:
path: /opt/syb // 给受管主机opt下添加文本
block: |
syb
bys
hello world
state: present
create: yes //如果没有文件,自动创建
//执行
[root@ansible ansible]# ansible-playbook /opt/playbook/test/test.yml
PLAY [192.168.200.154] *********************************************************
TASK [Gathering Facts] *********************************************************
ok: [192.168.200.154]
TASK [test] ********************************************************************
changed: [192.168.200.154]
PLAY RECAP *********************************************************************
192.168.200.154 : ok=2 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
//查看结果
[root@localhost ~]# cd /opt/
[root@localhost opt]# ls
syb
[root@localhost opt]# cat syb
# BEGIN ANSIBLE MANAGED BLOCK
syb
bys
hello world
# END ANSIBLE MANAGED BLOCK
注意:使用blockinfile模块时,注释块标记插入到块的开头和结尾,以确保幂等性
# BEGIN ANSIBLE MANAGED BLOCK
syb
bys
hello world
# END ANSIBLE MANAGED BLOCK
用户可以使用该模块的marker参数,帮助确保将正确的注释字符或文本用于相关文件。
3.2.5 从受管主机中删除文件
从受管主机中删除文件的基本示例是使用file模块和state: absent参数。state参数对于许多模块是可选的。一些模块也支持其他选项。
[root@ansible test]# vim test.yml //删除上面创建的syb
---
- name: delelt file
hosts: 192.168.200.154
tasks:
- name: test
file:
dest: /opt/syb
state: absent
[root@ansible ansible]# ansible-playbook /opt/playbook/test/test.yml //执行成功
PLAY [delele file] *************************************************************
TASK [Gathering Facts] *********************************************************
ok: [192.168.200.154]
TASK [test] ********************************************************************
changed: [192.168.200.154]
PLAY RECAP *********************************************************************
192.168.200.154 : ok=2 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
[root@localhost opt]# ls //查看此时已经没有,已经被删除
3.2.6 检索受管主机上的文件状态
stat模块检索文件的事实,类似于Linux中的stat命令。参数提供检索文件属性、确定文件检验和等功能。
stat模块返回一个包含文件状态数据的值的散列字典,允许用户使用单独的变量引用各条信息。
以下示例注册stat模块的结果,然后显示它检查的文件的MD5检验和。
- name: Verify the checksum of a file
stat:
path: /path/to/file
checksum_algorithm: md5
register: result
- debug
msg: "The checksum of the file is {{ result.stat.checksum }}"
有关stat模块返回的值的信息由ansible-doc记录,或者可以注册一个变量并显示其内容以查看可用内容:
- name: Examine all stat output of /etc/passwd
hosts: 192.168.200.154
tasks:
- name: stat /etc/passwd
stat:
path: /etc/passwd
register: results
- name: Display stat results
debug:
var: results
3.2.7 同步控制节点和受管主机之间的文件
synchronize模块是一个围绕rsync工具的打包程序,它简化了playbook中的常见文件管理任务。rsync工具必须同时安装在本机和远程主机上。默认情况下,在使用synchronize模块时,“本地主机”是同步任务所源自的主机(通常是控制节点),而“目标主机”是synchronize连接到的主机。
以下示例将位于Ansible工作目录中的文件同步到受管主机:
- name: synchronize local file to remote files
synchronize:
src: file
dest: /path/to/file
有很多种方法可以使用synchronize模块及其许多参数,包括同步目录。运行ansible-doc synchronize命令查看其他参数和playbook示例。