Ansible 条件判断 循环 handlers 任务失败 文件管理的使用
1.条件判断
1.1 测试多个条件
一个when语句可用于评估多个条件。使用and和or关键字组合条件,并使用括号分组条件
如果任一条件为真时满足条件语句,则应当使用or语句。例如,如果计算机上运行的是红帽企业linux或Fedora,则下述条件得到满足:
when: ansible_distribution == "Redhat" or ansible_distribution == "Fedora"
使用and运算时,两个条件都必须为真,才能满足整个条件语句。例如,如果远程主机是红帽企业Linux7.5主机,并且安装的内核是指定版本,则将满足以下条件
when: ansible_distribution_version == "7.5" and ansible_kernel == "3.10.0-327.el7.x86_64"
when关键字还支持使用列表来描述条件列表。向when关键字提供列表时,将使用and运算组合所有条件。下面的示例演示了使用and运算符组合多个条件语句的另一方式:
when:
- ansible_distribution_version == "7.5"
- ansible_kernel == "3.10.0-327.el7.x86_64"
这种格式提高了可读性,而可读性是良好编写Ansible Playbook的关键目标。
通过使用括号分组条件,可以表达更复杂的条件语句。例如,如果计算机上运行的是红帽企业Linux7或Fedora28,则下述条件语句得到满足。此示例使用大于字符,这样长条件就可以在playbook中分成多行,以便于阅读。
when: >
( ansible_distribution == "Redhat" and
ansible_distribution_major_version == "7" )
or
( ansible_distribution == "Fedora" and
ansible_distribution_major_version == "28" )
1.2循环和有条件任务
//挂载到根目录 和 文件大小大于100000000 (没有就跳过)
---
- hosts: 192.168.72.137
vars:
- name: xxx
yum:
name: mariadb
state: install
loop: "{{ ansible_mounts }}"
when: item.mount == "/" and item.size.available > 10000000
[root@master xm]# ansible-playbook fact.yml
PLAY [192.168.72.137] *********************************************************
TASK [Gathering Facts] *********************************************************
ok: [192.168.72.137]
TASK [yum] *********************************************************************
changed: [192.168.72.137] => (item={'mount': '/', 'device': '/dev/mapper/rhel-root', 'fstype': 'xfs', 'options': 'rw,seclabel,relatime,attr2,inode64,noquota', 'size_total': 18238930944, 'size_available': 16646459392, 'block_size': 4096, 'block_total': 4452864, 'block_available': 4064077, 'block_used': 388787, 'inode_total': 8910848, 'inode_available': 8876476, 'inode_used': 34372, 'uuid': 'eb80880a-bf27-4cc7-8728-f8bc48b5834c'})
skipping: [192.168.72.137] => (item={'mount': '/boot', 'device': '/dev/nvme0n1p1', 'fstype': 'xfs', 'options': 'rw,seclabel,relatime,attr2,inode64,noquota', 'size_total': 1063256064, 'size_available': 876052480, 'block_size': 4096, 'block_total': 259584, 'block_available': 213880, 'block_used': 45704, 'inode_total': 524288, 'inode_available': 523987, 'inode_used': 301, 'uuid': '9d8f2355-8cc4-4c77-8fc8-592604911512'})
PLAY RECAP *********************************************************************
192.168.72.137 : ok=2 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
//当vsftpd运行时,重启httpd
---
- hosts: 192.168.72.137
tasks:
- name: xxx
shell: systemctl status vsftpd
ignore_errors: yes
register: result
- name: zzz
service:
name: httpd
state: restarted
when: result.rc == 0
[root@master xm]# ansible-playbook sb.yml
PLAY [192.168.72.137] ******************************************************************************************************************
TASK [Gathering Facts] *****************************************************************************************************************
Enter passphrase for key '/root/.ssh/id_rsa':
ok: [192.168.72.137]
TASK [xxx] *****************************************************************************************************************************
fatal: [192.168.72.137]: FAILED! => {"changed": true, "cmd": "systemctl status vsftpd", "delta": "0:00:00.009055", "end": "2021-07-26 11:37:21.215442", "msg": "non-zero return code", "rc": 4, "start": "2021-07-26 11:37:21.206387", "stderr": "Unit vsftpd.service could not be found.", "stderr_lines": ["Unit vsftpd.service could not be found."], "stdout": "", "stdout_lines": []}
...ignoring
TASK [zzz] *****************************************************************************************************************************
skipping: [192.168.72.137]
PLAY RECAP *****************************************************************************************************************************
192.168.72.137 : ok=2 changed=1 unreachable=0 failed=0 skipped=1 rescued=0 ignored=1
[root@master xm]#
2.handlers
Ansible模块设计为具有幂等性。这表示,在正确编写的playbook中,playbook及其任务可以运行多次而不会改变受管主机,除非需要进行更改使受管主机进入所需的状态
但在时候,在任务确实更改系统时,可能需要运行进一步的任务。例如,更改服务配置文件时可能要求重新加载该服务以便使其更改的配置生效。
处理程序是响应由其他任务触发的通知的任务。仅当任务在受管主机上更改了某些内容时,任务才通知其处理程序。每个处理程序具有全局唯一的名称,在playbook中任务块的末尾触发。如果没有任务通过名称通知处理程序,处理程序就不会运行。如果一个或多个任务通知处理程序,处理程序就会在play中的所有其他任务完成后运行一次。因为处理程序就是任务,所以可以在处理程序中使用他们将用于任何其他任务的模块。通常而言,处理程序被用于重新引导主机和重启服务。
- hosts: 192.168.72.137
tasks:
- name: xxx
lineinfile:
path: /etc/httpd/conf/httpd.conf
regexp: "Listen"
line: "Listen 8080"
- name:
service:
name: httpd
state: restarted
[root@master xm]# ansible-playbook sb.yml
PLAY [192.168.72.137] ******************************************************************************************************************
TASK [Gathering Facts] *****************************************************************************************************************
Enter passphrase for key '/root/.ssh/id_rsa':
ok: [192.168.72.137]
TASK [xxx] *****************************************************************************************************************************
changed: [192.168.72.137]
TASK [service] *************************************************************************************************************************
changed: [192.168.72.137]
PLAY RECAP *****************************************************************************************************************************
192.168.72.137 : ok=3 changed=2 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
//在执行一遍
[root@master xm]# ansible-playbook sb.yml
PLAY [192.168.72.137] ******************************************************************************************************************
TASK [Gathering Facts] *****************************************************************************************************************
ok: [192.168.72.137]
TASK [xxx] *****************************************************************************************************************************
ok: [192.168.72.137]
TASK [service] *************************************************************************************************************************
changed: [192.168.72.137]
PLAY RECAP *****************************************************************************************************************************
192.168.72.137 : ok=3 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
---
- hosts: 192.168.72.137
tasks:
- name: xxx
lineinfile:
path: /etc/httpd/conf/httpd.conf
regexp: "^Listen"
line: "Listen 8080"
notify:
restart httpd
handlers:
- name: restart httpd
service:
name: httpd
state: restarted
//运行可以发现没有发生任何变化 因为lineinfile没有改变所以不会重启httpd
[root@master xm]# ansible-playbook sb.yml
PLAY [192.168.72.137] ******************************************************************************************************************
TASK [Gathering Facts] *****************************************************************************************************************
Enter passphrase for key '/root/.ssh/id_rsa':
ok: [192.168.72.137]
TASK [xxx] *****************************************************************************************************************************
ok: [192.168.72.137]
PLAY RECAP *****************************************************************************************************************************
192.168.72.137 : ok=2 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
3.任务失败
Ansible评估任务的返回代码,从而确定任务是成功还是失败。通常而言,当任务失败时,Ansible将立即在该主机上中止play的其余部分并且跳过所有后续任务。
但有些时候,可能希望即使在任务失败时也继续执行play。例如,或许预期待定任务有可能会失败,并且希望通过有条件地运行某项其他任务来修复。
Ansible有多种功能可用于管理任务错误。
3.1忽略任务失败
默认情况下,任务失败时play会中止。不过,可以通过忽略失败的任务来覆盖此行为。可以在任务中使用ignore_errors关键字来实现此目的。
下列代码片段演示了如何在任务中使用ignore_errors,以便在任务失败时也继续在主机上执行playbook。例如,如果notapkg软件包不存在,则yum模块将失败,但若将ignore_errors设为yes,则执行将继续。
---
- hosts: 192.168.72.137
tasks:
- name: xxx
yum:
name: httpd22
state: present
- name: zzz
copy:
src: /opt/lamp.yml
dest: /opt/lamp/lamp.yml
- name: service httpd
service:
name: httpd
state: started
enabled: yes
//运行报错导致后面的任务也不能执行
[root@master xm]# ansible-playbook sb.yml
PLAY [192.168.72.137] ******************************************************************************************************************
TASK [Gathering Facts] *****************************************************************************************************************
Enter passphrase for key '/root/.ssh/id_rsa':
ok: [192.168.72.137]
TASK [xxx] *****************************************************************************************************************************
fatal: [192.168.72.137]: FAILED! => {"changed": false, "failures": ["No package httpd22 available."], "msg": "Failed to install some of the specified packages", "rc": 1, "results": []}
PLAY RECAP *****************************************************************************************************************************
192.168.72.137 : ok=1 changed=0 unreachable=0 failed=1 skipped=0 rescued=0 ignored=0
---
- hosts: 192.168.72.137
tasks:
- name: xxx
yum:
name: httpd22
state: present
ignore_errors: yes //我们使用这个以便任务失败也能继续执行
- name: config httpd
- name: zzz
copy:
src: /opt/lamp.yml
dest: /opt/lamp/lamp.yml
- name: service httpd
service:
name: httpd
state: started
enabled: yes
[root@master xm]# ansible-playbook sb.yml
PLAY [192.168.72.137] ******************************************************************************************************************
TASK [Gathering Facts] *****************************************************************************************************************
ok: [192.168.72.137]
TASK [xxx] *****************************************************************************************************************************
fatal: [192.168.72.137]: FAILED! => {"changed": false, "failures": ["No package httpd22 available."], "msg": "Failed to install some of the specified packages", "rc": 1, "results": []}
...ignoring
TASK [zzz] *****************************************************************************************************************************
changed: [192.168.72.137]
TASK [service httpd] *******************************************************************************************************************
ok: [192.168.72.137]
PLAY RECAP *****************************************************************************************************************************
192.168.72.137 : ok=4 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=1
3.2任务失败后强制执行处理程序
通常而言,如果任务失败并且play在该主机上中止,则收到play中早前任务通知的处理程序将不会运行。如果在play中设置force_handlers: yes关键字,则即使play因为后续任务失败而中止也会调用被通知的处理程序。
下列代码片段演示了如何在play中使用force_handlers关键字,以便在任务失败时也强制执行相应的处理程序:
---
- hosts: 192.168.72.137
force_handlers: yes
tasks:
- name:
command: echo "wsnd"
notify: restart
- name:
yum:
name: zzz
srate: present
handlers:
- name: restart
service:
name: httpd
state: restarted
[root@master xm]# ansible-playbook sb.yml
PLAY [192.168.72.137] ******************************************************************************************************************
TASK [Gathering Facts] *****************************************************************************************************************
Enter passphrase for key '/root/.ssh/id_rsa':
ok: [192.168.72.137]
TASK [command] *************************************************************************************************************************
changed: [192.168.72.137]
TASK [yum] *****************************************************************************************************************************
fatal: [192.168.72.137]: 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.72.137]
PLAY RECAP *****************************************************************************************************************************
192.168.72.137
3.3指定任务失败条件
可以在任务中使用failed_when关键字来指定表示任务已失败的条件。这通常与命令模块搭配使用,这些模块可能成功执行了某一命令,但命令的输出可能指示了失败。
例如,可以运行输出错误消息的脚本,并使用该消息定义任务的失败状态。下列代码片段演示了如何在任务中使用failed_when关键字:
#! /bin/bash
ls 777
[root@master xm]# cat sb.yml
---
- hosts: 192.168.72.137
tasks:
- name:
script: 1.sh
register: result
failed_when: "'没有那个文件或目录' in result.stdout"
- debug:
var: result
[root@master xm]# ansible-playbook sb.yml
PLAY [192.168.72.137] ******************************************************************************************************************
TASK [Gathering Facts] *****************************************************************************************************************
Enter passphrase for key '/root/.ssh/id_rsa':
ok: [192.168.72.137]
TASK [script] **************************************************************************************************************************
fatal: [192.168.72.137]: FAILED! => {"changed": true, "failed_when_result": true, "msg": "non-zero return code", "rc": 2, "stderr": "Shared connection to 192.168.72.137 closed.\r\n", "stderr_lines": ["Shared connection to 192.168.72.137 closed."], "stdout": "ls: 无法访问'777': 没有那个文件或目录\r\n", "stdout_lines": ["ls: 无法访问'777': 没有那个文件或目录"]}
PLAY RECAP *****************************************************************************************************************************
192.168.72.137 : ok=1 changed=0 unreachable=0 failed=1 skipped=0 rescued=0 ignored=0
//也可以使用fail模块来完成
[root@master xm]# ansible-playbook sb.yml
[root@master xm]# cat sb.yml
---
- hosts: 192.168.72.137
tasks:
- name:
script: 1.sh
register: result
ignore_errors: yes
- name:
fail:
msg: "傻逼熊用民"
when: "'没有那个文件或目录' in result.stdout"
PLAY [192.168.72.137] ******************************************************************************************************************
TASK [Gathering Facts] *****************************************************************************************************************
Enter passphrase for key '/root/.ssh/id_rsa':
ok: [192.168.72.137]
TASK [script] **************************************************************************************************************************
fatal: [192.168.72.137]: FAILED! => {"changed": true, "msg": "non-zero return code", "rc": 2, "stderr": "Shared connection to 192.168.72.137 closed.\r\n", "stderr_lines": ["Shared connection to 192.168.72.137 closed."], "stdout": "ls: 无法访问'777': 没有那个文件或目录\r\n", "stdout_lines": ["ls: 无法访问'777': 没有那个文件或目录"]}
...ignoring
TASK [fail] ****************************************************************************************************************************
fatal: [192.168.72.137]: FAILED! => {"changed": false, "msg": "傻逼熊用民"}
PLAY RECAP *****************************************************************************************************************************
192.168.72.137 : ok=2 changed=1 unreachable=0 failed=1 skipped=0 rescued=0 ignored=1
3.4指定何时任务报告“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.72.137
tasks:
- name: sb
shell: echo "runtime" | passwd --stdin shenlongfei
register: xiong
notify:
- print info
handlers:
- name: print info
debug:
msg: "傻逼申龙飞的密码已经创建了!!!"
~
[root@master xm]# ansible-playbook sb.yml
PLAY [192.168.72.137] ******************************************************************************************************************
TASK [Gathering Facts] *****************************************************************************************************************
ok: [192.168.72.137]
TASK [sb] ******************************************************************************************************************************
changed: [192.168.72.137]
RUNNING HANDLER [print info] ***********************************************************************************************************
ok: [192.168.72.137] => {
"msg": "傻逼申龙飞的密码已经创建了!!!"
}
PLAY RECAP *****************************************************************************************************************************
192.168.72.137 : ok=3 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
3.5 Ansible块和错误处理
在playbook中,块是对任务进行逻辑分组的子句,可用于控制任务的执行方式。例如,任务块可以含有when关键字,以将某一条件应用到多个任务:
- name: block example
hosts: 172.16.103.129
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: //如果我任务执行成功了 ,那么后面的任务就不执行,如果执行失败,就执行rescure里面的
- 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: //不管上面成功不成功。alway是一定会执行的
- name: always restart the database
service:
name: mariadb
state: restarted
4.文件管理
常用文件模块
模块名称 | 模块说明 |
---|---|
blockinfile | 插入、更新或删除由可自定义标记线包围的多行文本块 |
copy | 将文件从本地或远程计算机复制到受管主机上的某个位置。 类似于file模块,copy模块还可以设置文件属性,包括SELinux上下文件。 |
fetch | 此模块的作用和copy模块类似,但以相反方式工作。此模块用于从远程计算机获取文件到控制节点, 并将它们存储在按主机名组织的文件树中。 |
file | 设置权限、所有权、SELinux上下文以及常规文件、符号链接、硬链接和目录的时间戳等属性。 此模块还可以创建或删除常规文件、符号链接、硬链接和目录。其他多个与文件相关的 模块支持与file模块相同的属性设置选项,包括copy模块。 |
lineinfile | 确保特定行位于某文件中,或使用反向引用正则表达式来替换现有行。 此模块主要在用户想要更改文件的某一行时使用。 |
stat | 检索文件的状态信息,类似于Linux中的stat命令。 |
synchronize | 围绕rsync命令的一个打包程序,可加快和简化常见任务。 synchronize模块无法提供对rsync命令的完整功能的访问权限,但确实最常见的调用更容易实施。 用户可能仍需通过run command模块直接调用rsync命令 |
4.1file模块
在受管主机上创建、复制、编辑和删除文件是用户可以使用Files模块库中的模块实施的常见任务。
- name: Touch a file and set permissions
file:
path: /path/to/file //路径
owner: user1
group: group1 //组
mode: 0640 //权限
state: touch //这里的意思是创建一个空文件。
4.2修改文件属性
使用file模块还可以确保新的或现有的文件具有正确的权限和SELinux类型。
例如,以下文件保留了相对于用户主目录的默认SELinux上下文,这不是所需的上下文
[root@node1 ~]# ls -Z anaconda-ks.cfg //我们查看受管主机root下的一个文件
system_u:object_r:admin_home_t:s0 anaconda-ks.cfg //修改它的权限
[root@node1 ~]#
[root@node1 ~]# cat /etc/ansible/node/test.yml //play写法
---
- name: create user
hosts: 192.168.72.137
tasks:
- name: test
file:
path: /root/anaconda-ks.cfg
setype: xiong_niubi_shuaiqi_t //改为我们想要的
[root@node1 ~]#
[root@localhost ~]# ls -Z anaconda-ks.cfg //修改成功
system_u:object_r:xiong_niubi_shuaiqi_t:s0 anaconda-ks.cfg
[root@localhost ~]#
4.3使用SELINUX文件上下文更改具有持久性
设置文件上下文时,file模块的行为与chcon类似。通过运行restorecon,可能会意外地撤消使用该模块所做的更改。使用file设置上下文后,用户可以使用system模块集合中的sefcontext来更新SELinux策略,如semanage fcontext。
- name: Copy a file to managed hosts //这是我们常用的做法
copy:
src: file
dest: /path/to/file
要从受管主机检索文件,请使用fetch模块。这可用于在将参考系统分发给其他受管主机之前从参考系统中检查诸如SSH公钥之类的文件。
[root@localhost ~]# ls //受管主机上root下面有一个脚本, 我要把它弄到我控制机上
anaconda-ks.cfg test.sh
[root@localhost ~]#
[root@node1 ansible]# cat node/test.yml //play写法
---
- name: create user
hosts: 192.168.100.147
tasks:
- name: test
fetch:
src: /root/test.sh //注意它和copy不一样,这里是受管主机的路径
dest: /root/ //这里才是控制机的路径,他和copy是反的
[root@node1 ansible]#
[root@master ansible]# ansible-playbook node/test.yml
PLAY [create user] *************************************************************
TASK [Gathering Facts] *********************************************************
ok: [192.168.72.137]
TASK [test] ********************************************************************
changed: [192.168.72.137]
PLAY RECAP *********************************************************************
192.168.72.137 : ok=2 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
[root@master ansible]# ls /root
192.168.72.137 scripts test.sh //可以看见受管主机文件已经到控制机上了
anaconda-ks.cfg testdir
[root@master ansible]#
要确保现有文件中存在特定的单行文本,请使用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@master ansible]# cat node/test.yml
---
- name: create user
hosts: 192.168.72.137
tasks:
- name: test
blockinfile:
path: /tmp/xiong //给受管主机tmp下面添加文本
block: |
shabishenlongfei
hello shenlonggei
helle sbslf
hello SB
state: present
create: yes //没有文件的,自动创建
[root@master ansible]#
[root@master ansible]# ansible-playbook node/test.yml //执行成功
PLAY [create user] *************************************************************
TASK [Gathering Facts] *********************************************************
ok: [192.168.72.137]
TASK [test] ********************************************************************
changed: [192.168.72.137]
PLAY RECAP *********************************************************************
192.168.72.137 : ok=2 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
[root@localhost ~]# cd /tmp
[root@localhost tmp]# ls
xiong //创建成功
systemd-private-2126c22bfcc7458eac8d84abfdcb844c-chronyd.service-Vd9cpx
systemd-private-2126c22bfcc7458eac8d84abfdcb844c-httpd.service-xjP1M8
[root@localhost tmp]# cat shen //文本加入成功
# BEGIN ANSIBLE MANAGED BLOCK
shabishenlongfei
hello shenlonggei
helle sbslf
hello SB
# END ANSIBLE MANAGED BLOCK
[root@localhost tmp]#
注意:使用blockinfile模块时,注释块标记插入到块的开头和结尾,以确保幂等性
# BEGIN ANSIBLE MANAGED BLOCK
shabishenlongfei
hello shenlonggei
helle sbslf
hello SB
# END ANSIBLE MANAGED BLOCK
用户可以使用该模块的marker参数,帮助确保将正确的注释字符或文本用于相关文件。
4.4从受管主机中删除文件
从受管主机中删除文件的基本示例是使用file模块和state: absent参数。state参数对于许多模块是可选的。一些模块也支持其他选项
[root@master ansible]# cat node/test.yml //删除上面创建的xiong
---
- name: create user
hosts: 192.168.72.137
tasks:
- name: test
file:
dest: /tmp/xiong
state: absent
[root@master ansible]#
[root@master ansible]# ansible-playbook node/test.yml //执行成功
PLAY [create user] *************************************************************
TASK [Gathering Facts] *********************************************************
ok: [192.168.72.137]
TASK [test] ********************************************************************
changed: [192.168.72.137]
PLAY RECAP *********************************************************************
192.168.72.137 : ok=2 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
[root@localhost tmp]# ls //查看此时已经没有,已经被删除
systemd-private-2126c22bfcc7458eac8d84abfdcb844c-chronyd.service-Vd9cpx
systemd-private-2126c22bfcc7458eac8d84abfdcb844c-httpd.service-xjP1M8
[root@localhost tmp]
4.5检索受管主机上的文件状态
stat模块检索文件的事实,类似于Linux中的stat命令。参数提供检索文件属性、确定文件检验和等功能。
stat模块返回一个包含文件状态数据的值的散列字典,允许用户使用单独的变量引用各条信息。
以下示例注册stat模块的结果,然后显示它检查的文件的MD5检验和。
有关stat模块返回的值的信息由ansible-doc记录,或者可以注册一个变量并显示其内容以查看可用内容:
[root@master ansible]# cat node/test.yml
---
- name: create user
hosts: 192.168.72.137
tasks:
- name: test
stat:
path: /root/test.sh
register: xx
- debug:
var: xx
[root@master ansible]#
[root@master ansible]# ansible-playbook node/test.yml
PLAY [create user] *************************************************************
TASK [Gathering Facts] *********************************************************
ok: [192.168.72.137]
TASK [test] ********************************************************************
ok: [192.168.72.137]
TASK [debug] *******************************************************************
ok: [192.168.72.137] => {
"xx": {
"changed": false,
"failed": false,
"stat": {
"atime": 1627311982.0563967,
"attr_flags": "",
"attributes": [],
"block_size": 4096,
"blocks": 0,
"charset": "binary",
"checksum": "da39a3ee5e6b4b0d3255bfef95601890afd80709",
"ctime": 1627311840.0285206,
此处内容省略。。。。。。
}
}
}
PLAY RECAP *********************************************************************
192.168.72.137 : ok=3 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
4.6同步控制节点和受管主机之间的文件
synchronize模块是一个围绕rsync工具的打包程序,它简化了playbook中的常见文件管理任务。rsync工具必须同时安装在本机和远程主机上。默认情况下,在使用synchronize模块时,“本地主机”是同步任务所源自的主机(通常是控制节点),而“目标主机”是synchronize连接到的主机。
以下示例将位于Ansible工作目录中的文件同步到受管主机
[root@master node]# ls //我想把控制机中这个httpd同步到受管主机中
httpd test.yml
[root@master node]#
[root@master ansible]# cat node/test.yml
---
- name: create user
hosts: 192.168.72.137
tasks:
- name: test
yum:
name: rsync //必须下载rsync
state: present
- name:
synchronize: //用这个模块
src: httpd //原地址下的httpd
dest: /opt/httpd //同步到受管主机opt下面
[root@master ansible]#
[root@master ansible]# ansible-playbook node/test.yml //执行成功
PLAY [create user] *************************************************************
TASK [Gathering Facts] *********************************************************
ok: [192.168.72.137]
TASK [test] ********************************************************************
changed: [192.168.72.137]
TASK [synchronize] *************************************************************
changed: [192.168.72.137]
PLAY RECAP *********************************************************************
192.168.72.137 : ok=3 changed=2 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
[root@localhost opt]# ls //这边可以看到已经同步过来了
httpd xiong.sh
[root@localhost opt]#
有很多种方法可以使用synchronize模块及其许多参数,包括同步目录。运行ansible-doc synchronize命令查看其他参数和playbook示例。