第二章 ansible自动化运维工具 模块


[root@ansible ~]# yum install -y ansible
[root@ansible ~]# ansible --version	#查看版本
ansible 2.9.27
  config file = /etc/ansible/ansible.cfg
  configured module search path = [u'/root/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
  ansible python module location = /usr/lib/python2.7/site-packages/ansible
  executable location = /usr/bin/ansible
  python version = 2.7.5 (default, Oct 30 2018, 23:45:53) [GCC 4.8.5 20150623 (Red Hat 4.8.5-36)]
[root@ansible ~]# vim /etc/ansible/hosts 
...
[websrvs]
192.168.37.6
192.168.37.18

[appsrvs]
192.168.37.[1:2]8
[root@ansible ~]# ansible all --list-hosts		#列出所有已经被我管理的主机
  hosts (3):
    192.168.37.18
    192.168.37.28
    192.168.37.6
[root@ansible ~]# ansible websrvs --list-hosts		#列出websrvs组中被我管理的主机
  hosts (2):
    192.168.37.6
    192.168.37.18
[root@ansible ~]# ansible websrvs -m ping #权限被拒绝、红的
[root@ansible ~]# vim /etc/ansible/ansible.cfg
...
host_key_checking = False		#把注释取消(登录就不用再yes)
...
[root@ansible ~]# cd .ssh
[root@ansible .ssh]# cat known_hosts 	#37.637.18的key已经保存了
192.168.37.6 ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAvPMo7BWfNOOFXbntNAmxPDPcWHdZOGwbgyrLgW30fX1ALnO7GshGzHE25x0TCbslbm5lvQI0xWGRSPqssXXAWgIxr/6+wyb3GOko8UqXXNC6UGsv94YU3Z9mvImDEbqmpsP3LwQtbnOVC/iwPHeksY4d1T6nNioDjWk4OZOF2sHGpcCzyvdy+wNrLoG6F4ZTGjrjtqRosXMWGA/gUrX8nSJXonrj8jsbbunqKbYoAnXEZ/aTUKPuUFgm7zSqf7dtOOl3nFtPhd8FKAY9qDdIoB/pO0bJVyvYgw+w8kwo5A+5UxRXlojWlASEQaoJsCIxwrOGDVLliWikHaqkBTzp4w==
192.168.37.18 ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBMd0DORXlksp76WhLhFL3OyE+E0VGs4LQT+7Dr+Eahyam33SJlVlzLAf3biPtYVOA+mTnkXxt6HhBA0VEIGVVko=
[root@ansible .ssh]# ansible 192.168.37.28 -m ping
192.168.37.28 | UNREACHABLE! => {
    "changed": false, 
    "msg": "Failed to connect to the host via ssh: Warning: Permanently added '192.168.37.28' (ECDSA) to the list of known hosts.\r\nPermission denied (publickey,gssapi-keyex,gssapi-with-mic,password).", 
    "unreachable": true
}
[root@ansible .ssh]# cat known_hosts 	#上面步骤失败、但是'192.168.37.28'也已经保存进去了
192.168.37.6 ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAvPMo7BWfNOOFXbntNAmxPDPcWHdZOGwbgyrLgW30fX1ALnO7GshGzHE25x0TCbslbm5lvQI0xWGRSPqssXXAWgIxr/6+wyb3GOko8UqXXNC6UGsv94YU3Z9mvImDEbqmpsP3LwQtbnOVC/iwPHeksY4d1T6nNioDjWk4OZOF2sHGpcCzyvdy+wNrLoG6F4ZTGjrjtqRosXMWGA/gUrX8nSJXonrj8jsbbunqKbYoAnXEZ/aTUKPuUFgm7zSqf7dtOOl3nFtPhd8FKAY9qDdIoB/pO0bJVyvYgw+w8kwo5A+5UxRXlojWlASEQaoJsCIxwrOGDVLliWikHaqkBTzp4w==
192.168.37.18 ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBMd0DORXlksp76WhLhFL3OyE+E0VGs4LQT+7Dr+Eahyam33SJlVlzLAf3biPtYVOA+mTnkXxt6HhBA0VEIGVVko=
192.168.37.28 ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBMd0DORXlksp76WhLhFL3OyE+E0VGs4LQT+7Dr+Eahyam33SJlVlzLAf3biPtYVOA+mTnkXxt6HhBA0VEIGVVko=
[root@ansible .ssh]# ansible 192.168.37.28 -m ping -k		#-k代表密码需要手工输、输入对方root密码、就变成绿色代表成功
SSH password: 
192.168.37.28 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false, 
    "ping": "pong"
}
[root@ansible .ssh]# vim /etc/ansible/ansible.cfg 		#可以改颜色 搜colors即可
...
[colors]
#highlight = white
#verbose = blue
#warn = bright purple
#error = red
#debug = dark gray
#deprecate = purple
#skip = cyan
#unreachable = red
#ok = green
#changed = yellow
#diff_add = green
#diff_remove = red
#diff_lines = cyan
...

ansible基于key验证

[root@ansible .ssh]# ssh-keygen 	#基于key验证
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa): 
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /root/.ssh/id_rsa.
Your public key has been saved in /root/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:olIwG7v7jfsk9oBE6ZX6hP/f88o405Xrq/sVEoI0KcU root@ansible
The key's randomart image is:
+---[RSA 2048]----+
|       o+.       |
|   . ...Eo       |
|  * o  .. . .    |
| o X       . .   |
|  B o . S   ...  |
| . B . .    o. . |
|  + B .  . . ..  |
|   + O  o+o ..   |
|  ..+o=.oo*O=.   |
+----[SHA256]-----+
[root@ansible .ssh]# ssh-copy-id 192.168.37.6		#key验证、单项的
[root@ansible .ssh]# ssh-copy-id 192.168.37.18
[root@ansible .ssh]# ssh-copy-id 192.168.37.28

ping:探测对方主机是否活跃

[root@ansible .ssh]# ansible all -m ping	#都成功了 ping是探测对方主机是否活跃
192.168.37.28 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false, 
    "ping": "pong"
}
192.168.37.18 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false, 
    "ping": "pong"
}
192.168.37.6 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false, 
    "ping": "pong"
}
[root@ansible .ssh]# cat /etc/ansible/hosts 	#ansible主机清单中有两个分组
...
[websrvs]
192.168.37.6
192.168.37.18

[appsrvs]
192.168.37.[1:2]8
逻辑与
	ansible “websrvs:&dbsrvs” –m ping 
	在websrvs组并且在dbsrvs组中的主机
逻辑非
	ansible ‘websrvs:!dbsrvs’ –m ping 
	在websrvs组,但不在dbsrvs组中的主机
	注意:此处为单引号
综合逻辑
 	ansible ‘websrvs:dbsrvs:&appsrvs:!ftpsrvs’ –m ping
正则表达式
	ansible “websrvs:&dbsrvs” –m ping 
	ansible “~(web|db).*\.magedu\.com” –m ping

逻辑与、有交集的只有18

[root@ansible .ssh]# ansible "websrvs:&appsrvs" -m ping -C
192.168.37.18 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false, 
    "ping": "pong"
}

逻辑非、属于weebsrvs但是不属于appsrvs 只有6

[root@ansible .ssh]# ansible 'websrvs:!appsrvs' -m ping -C
192.168.37.6 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false, 
    "ping": "pong"
}
vim /etc/ansible/ansible.cfg
...
#log_path = /var/log/ansible.log		#日志文件、建议开启、后续可以查看此文件‘/var/log/ansible.log’、看执行了哪些操作
...

Command:在远程主机执行命令,默认模块,可忽略-m选项

[root@ansible .ssh]# ansible-doc -s command	#查看command模块的帮助说明、-s简单说明
- name: Execute commands on targets
  command:
      argv:                  # Passes the command as a list rather than a string. Use `argv' to avoid
                               quoting values that would otherwise be
                               interpreted incorrectly (for example "user
                               name"). Only the string or the list form
                               can be provided, not both.  One or the
                               other must be provided.
      chdir:                 # Change into this directory before running the command.
      cmd:                   # The command to run.
      creates:               # A filename or (since 2.0) glob pattern. If it already exists, this step
                               *won't* be run.
      free_form:             # The command module takes a free form command to run. There is no actual
                               parameter named 'free form'.
[root@ansible ~]# ansible all -m command -a "ls /data"	##command是默认模块  查看/data/下内数据
192.168.37.18 | CHANGED | rc=0 >>

192.168.37.28 | CHANGED | rc=0 >>

192.168.37.6 | CHANGED | rc=0 >>
lost+found

[root@ansible ~]# ansible all -m command -a "chdir=/data ls"
192.168.37.18 | CHANGED | rc=0 >>

192.168.37.28 | CHANGED | rc=0 >>

192.168.37.6 | CHANGED | rc=0 >>
lost+found
[root@ansible ~]# ansible all -m command -a "creates=/etc/fstab ls /data"		#/etc/fstab存在将不执行ls /data命令
192.168.37.6 | SUCCESS | rc=0 >>
skipped, since /etc/fstab exists
192.168.37.18 | SUCCESS | rc=0 >>
skipped, since /etc/fstab exists
192.168.37.28 | SUCCESS | rc=0 >>
skipped, since /etc/fstab exists

[root@ansible ~]# ansible all -m command -a "creates=/etc/xxx ls /data"		#/etc/xxx不存在将执行ls /data命令
192.168.37.6 | CHANGED | rc=0 >>
lost+found
192.168.37.28 | CHANGED | rc=0 >>

192.168.37.18 | CHANGED | rc=0 >>
[root@ansible ~]# ansible all -a 'getent passwd wang'		#看看其他主机有没有wang的账户
192.168.37.6 | CHANGED | rc=0 >>
wang:x:500:500::/home/wang:/bin/bash
192.168.37.28 | CHANGED | rc=0 >>
wang:x:1000:1000:wang:/home/wang:/bin/bash
192.168.37.18 | CHANGED | rc=0 >>
wang:x:1000:1000:wang:/home/wang:/bin/bash

Shell:和command相似,用shell执行命令

#需要用shell模块改密码、成功了!
[root@ansible ~]# ansible all -m shell -a 'echo magedu|passwd --stdin wang'
192.168.37.6 | CHANGED | rc=0 >>
Changing password for user wang.
passwd: all authentication tokens updated successfully.
192.168.37.28 | CHANGED | rc=0 >>
Changing password for user wang.
passwd: all authentication tokens updated successfully.
192.168.37.18 | CHANGED | rc=0 >>
Changing password for user wang.
passwd: all authentication tokens updated successfully.

主机192.168.37.6

[root@centos6 ~]$ ll /etc/shadow
----------. 1 root root 1039 Apr  5 01:14 /etc/shadow
[root@centos6 ~]$ date
Sat Jun 18 17:01:01 CST 2022
[root@centos6 ~]$ ll /etc/shadow	#时间发生变化、说明密码已经改了
---------- 1 root root 1031 Jun 18 17:02 /etc/shadow

主机ansible

[root@ansible ~]# ansible all -m command -a 'echo $HOSTNAME'
192.168.37.6 | CHANGED | rc=0 >>
$HOSTNAME		<--显示有问题
192.168.37.28 | CHANGED | rc=0 >>
$HOSTNAME
192.168.37.18 | CHANGED | rc=0 >>
$HOSTNAME

#看看用户名也显示正常了、之前的command模块是看不了的
[root@ansible ~]# ansible all -m shell -a 'echo $HOSTNAME'
192.168.37.6 | CHANGED | rc=0 >>
centos6			<--显示正常
192.168.37.28 | CHANGED | rc=0 >>
node28
192.168.37.18 | CHANGED | rc=0 >>
node18
[root@ansible ~]# vim /etc/ansible/ansible.cfg
...
module_name = shell		#把module_name = command改成module_name = shell
...
[root@ansible ~]# ansible all -a 'echo $HOSTNAME'		#在查看一下、看看默认模块是否改成了shell
192.168.37.6 | CHANGED | rc=0 >>
centos6			<--发现可以看到正确主机名、成功了
192.168.37.18 | CHANGED | rc=0 >>
node18
192.168.37.28 | CHANGED | rc=0 >>
node28
[root@ansible ~]# ansible all -a 'getenforce'		#查看selinux策略
192.168.37.6 | CHANGED | rc=0 >>
Disabled
192.168.37.28 | CHANGED | rc=0 >>
Disabled
192.168.37.18 | CHANGED | rc=0 >>
Disabled
#更改selinux策略
[root@ansible ~]# ansible all -a "sed -i 's@SELINUX=disabled@SELINUX=enforcing@' /etc/selinux/config"
[WARNING]: Consider using the replace, lineinfile or template module rather than running 'sed'.  If you
need to use command because replace, lineinfile or template is insufficient you can add 'warn: false' to
this command task or set 'command_warnings=False' in ansible.cfg to get rid of this message.
192.168.37.6 | CHANGED | rc=0 >>

192.168.37.28 | CHANGED | rc=0 >>

192.168.37.18 | CHANGED | rc=0 >>

#查看是否改变
[root@ansible ~]# ansible all -a "cat /etc/selinux/config"
192.168.37.6 | CHANGED | rc=0 >>

# This file controls the state of SELinux on the system.
# SELINUX= can take one of these three values:
#     enforcing - SELinux security policy is enforced.
#     permissive - SELinux prints warnings instead of enforcing.
#     disabled - No SELinux policy is loaded.
SELINUX=enforcing			 <---发生变化
# SELINUXTYPE= can take one of these two values:
#     targeted - Targeted processes are protected,
#     mls - Multi Level Security protection.
SELINUXTYPE=targeted 
...

[root@ansible ~]# ansible all -a "sed -i 's@SELINUX=enforcing@SELINUX=disabled@' /etc/selinux/config"
[WARNING]: Consider using the replace, lineinfile or template module rather than running 'sed'.  If you
need to use command because replace, lineinfile or template is insufficient you can add 'warn: false' to
this command task or set 'command_warnings=False' in ansible.cfg to get rid of this message.
192.168.37.6 | CHANGED | rc=0 >>

192.168.37.18 | CHANGED | rc=0 >>

192.168.37.28 | CHANGED | rc=0 >>

script:在远程主机上运行ansible服务器上的脚本

#创建测试脚本、后续在远程的ansible机器上执行
[root@ansible ~]# vim test.sh

echo "hello world"

[root@ansible ~]# chmod +x test.sh 		#加执行权限
[root@ansible ~]# ./test.sh 		#本机测试一下
hello world
[root@ansible ~]# ansible all -m script -a '/root/test.sh'
192.168.37.6 | CHANGED => {
    "changed": true, 
    "rc": 0, 
    "stderr": "Shared connection to 192.168.37.6 closed.\r\n", 
    "stderr_lines": [
        "Shared connection to 192.168.37.6 closed."
    ], 
    "stdout": "hello world\r\n", 
    "stdout_lines": [
        "hello world"			<---运行脚本、显示的结果
    ]
}
192.168.37.18 | CHANGED => {
    "changed": true, 
    "rc": 0, 
    "stderr": "Shared connection to 192.168.37.18 closed.\r\n", 
    "stderr_lines": [
        "Shared connection to 192.168.37.18 closed."
    ], 
    "stdout": "hello world\r\n", 
    "stdout_lines": [
        "hello world"
    ]
}
192.168.37.28 | CHANGED => {
    "changed": true, 
    "rc": 0, 
    "stderr": "Shared connection to 192.168.37.28 closed.\r\n", 
    "stderr_lines": [
        "Shared connection to 192.168.37.28 closed."
    ], 
    "stdout": "hello world\r\n", 
    "stdout_lines": [
        "hello world"
    ]
}

Copy:从主控端复制文件到远程主机

[root@ansible ~]# ansible websrvs -m copy -a 'src=/etc/fstab dest=/data'
192.168.37.6 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "checksum": "2ebeb21c40f38509d8460e06894c5f253e46806b", 
    "dest": "/data/fstab", 
    "gid": 0, 
    "group": "root", 
    "md5sum": "c05fb40b2982ffaadcb09e7bf6c2c598", 
    "mode": "0644", 
    "owner": "root", 
    "size": 633, 
    "src": "/root/.ansible/tmp/ansible-tmp-1655565183.43-9209-12932793576617/source", 
    "state": "file", 
    "uid": 0
}
192.168.37.18 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "checksum": "2ebeb21c40f38509d8460e06894c5f253e46806b", 
    "dest": "/data/fstab", 
    "gid": 0, 
    "group": "root", 
    "md5sum": "c05fb40b2982ffaadcb09e7bf6c2c598", 
    "mode": "0644", 
    "owner": "root", 
    "size": 633, 
    "src": "/root/.ansible/tmp/ansible-tmp-1655565183.48-9211-39976474454465/source", 
    "state": "file", 
    "uid": 0
}
[root@ansible ~]# ansible websrvs -a 'ls -l /data'
192.168.37.6 | CHANGED | rc=0 >>
total 20
-rw-r--r--  1 root root   633 Jun 18 23:13 fstab		<--可以看到刚刚拷贝的文件夹
drwx------. 2 root root 16384 Apr  5 01:04 lost+found
192.168.37.18 | CHANGED | rc=0 >>
total 4
-rw-r--r-- 1 root root 633 Jun 18 23:13 fstab			<--可以看到刚刚拷贝的文件夹
#权限600、所有者wang、所有组bin
[root@ansible ~]# ansible websrvs -m copy -a 'src=/etc/passwd dest=/data/passwd2 mode=600 owner=wang group=bin'
192.168.37.6 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "checksum": "c63c8db71c2ceca7fa2db6a5bd1440bf44191ffe", 
    "dest": "/data/passwd2", 
    "gid": 1, 
    "group": "bin", 	<---
    "md5sum": "2f624743cae43f8dfefcaca3ee936736", 
    "mode": "0600",  	<---
    "owner": "wang",  	<---
    "size": 2401, 
    "src": "/root/.ansible/tmp/ansible-tmp-1655565598.15-9372-225542328123495/source", 
    "state": "file", 
    "uid": 500
}
192.168.37.18 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "checksum": "c63c8db71c2ceca7fa2db6a5bd1440bf44191ffe", 
    "dest": "/data/passwd2", 
    "gid": 1, 
    "group": "bin", 
    "md5sum": "2f624743cae43f8dfefcaca3ee936736", 
    "mode": "0600", 
    "owner": "wang", 
    "size": 2401, 
    "src": "/root/.ansible/tmp/ansible-tmp-1655565598.23-9374-213488217102367/source", 
    "state": "file", 
    "uid": 1000
}

#可以看到我们刚刚设置的权限、属主属组等信息
[root@ansible ~]# ansible websrvs -a 'ls -l /data'
192.168.37.6 | CHANGED | rc=0 >>
total 24
-rw-r--r--  1 root root   633 Jun 18 23:13 fstab
drwx------. 2 root root 16384 Apr  5 01:04 lost+found
-rw-------  1 wang bin   2401 Jun 18 23:19 passwd2	#权限600、所有者wang、所有组bin
192.168.37.18 | CHANGED | rc=0 >>
total 8
-rw-r--r-- 1 root root  633 Jun 18 23:13 fstab
-rw------- 1 wang bin  2401 Jun 18 23:19 passwd2	#权限600、所有者wang、所有组bin

#如果担心现有的文件被覆盖、可用‘backup=yes’提前备份
[root@ansible ~]# ansible websrvs -m copy -a 'src=/etc/motd dest=/data/passwd2 mode=600 owner=wang group=bin backup=yes'
192.168.37.18 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "backup_file": "/data/passwd2.73959.2022-06-19@00:08:25~", 
    "changed": true, 
    "checksum": "da39a3ee5e6b4b0d3255bfef95601890afd80709", 
    "dest": "/data/passwd2", 
    "gid": 1, 
    "group": "bin", 
    "md5sum": "d41d8cd98f00b204e9800998ecf8427e", 
    "mode": "0600", 
    "owner": "wang", 
    "size": 0, 
    "src": "/root/.ansible/tmp/ansible-tmp-1655568501.93-10231-15497784621014/source", 
    "state": "file", 
    "uid": 1000
}
192.168.37.6 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "backup_file": "/data/passwd2.4670.2022-06-19@00:01:35~", 
    "changed": true, 
    "checksum": "da39a3ee5e6b4b0d3255bfef95601890afd80709", 
    "dest": "/data/passwd2", 
    "gid": 1, 
    "group": "bin", 
    "md5sum": "d41d8cd98f00b204e9800998ecf8427e", 
    "mode": "0600", 
    "owner": "wang", 
    "size": 0, 
    "src": "/root/.ansible/tmp/ansible-tmp-1655568501.88-10229-173038415319041/source", 
    "state": "file", 
    "uid": 500
}

#可以看到备份
[root@ansible ~]# ansible websrvs -a 'ls -l /data'
192.168.37.6 | CHANGED | rc=0 >>
total 24
-rw-r--r--  1 root root   633 Jun 18 23:13 fstab
drwx------. 2 root root 16384 Apr  5 01:04 lost+found
-rw-------  1 wang bin      0 Jun 19 00:01 passwd2
-rw-------  1 wang bin   2401 Jun 18 23:19 passwd2.4670.2022-06-19@00:01:35~		<---备份
192.168.37.18 | CHANGED | rc=0 >>
total 8
-rw-r--r-- 1 root root  633 Jun 18 23:13 fstab
-rw------- 1 wang bin     0 Jun 19 00:08 passwd2
-rw------- 1 wang bin  2401 Jun 18 23:19 passwd2.73959.2022-06-19@00:08:25~		<---备份
#生成的3行内容‘line1\nline2\nline3’放到‘/data/test.txt’文件
[root@ansible ~]# ansible websrvs -m copy -a 'content="line1\nline2\nline3" dest=/data/test.txt mode=600 owner=wang group=bin backup=yes'
192.168.37.18 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "backup_file": "/data/test.txt.74665.2022-06-19@00:17:41~", 
    "changed": true, 
    "checksum": "0ab7283988e8f49022d126054947f222cbdf0a52", 
    "dest": "/data/test.txt", 
    "gid": 1, 
    "group": "bin", 
    "md5sum": "81facad50c8e6244de64a98cf4f56f77", 
    "mode": "0600", 
    "owner": "wang", 
    "size": 17, 
    "src": "/root/.ansible/tmp/ansible-tmp-1655569061.03-10598-58298513846034/source", 
    "state": "file", 
    "uid": 1000
}
192.168.37.6 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "backup_file": "/data/test.txt.5322.2022-06-19@00:10:51~", 
    "changed": true, 
    "checksum": "0ab7283988e8f49022d126054947f222cbdf0a52", 
    "dest": "/data/test.txt", 
    "gid": 1, 
    "group": "bin", 
    "md5sum": "81facad50c8e6244de64a98cf4f56f77", 
    "mode": "0600", 
    "owner": "wang", 
    "size": 17, 
    "src": "/root/.ansible/tmp/ansible-tmp-1655569061.0-10596-52387362134666/source", 
    "state": "file", 
    "uid": 500
}

#看看是否和我们想的一样、三行内容
[root@ansible ~]# ansible websrvs -a 'cat /data/test.txt'
192.168.37.6 | CHANGED | rc=0 >>
line1
line2
line3
192.168.37.18 | CHANGED | rc=0 >>
line1
line2
line3

Fetch:从远程主机提取文件至主控端,copy相反,【目前只能抓文件、不能抓文件夹】

[root@ansible ~]# ansible websrvs -m fetch -a 'src=/var/log/messages dest=/data'
192.168.37.18 | CHANGED => {
    "changed": true, 
    "checksum": "3ea90cca298aa0dd8eb8dbe10488712dcf3b4758", 
    "dest": "/data/192.168.37.18/var/log/messages", 
    "md5sum": "e159f6cb704797bf58ab9e3b5f37421f", 
    "remote_checksum": "3ea90cca298aa0dd8eb8dbe10488712dcf3b4758", 
    "remote_md5sum": null
}
192.168.37.6 | CHANGED => {
    "changed": true, 
    "checksum": "e6ddea3e1e47326a5e0771590c996cffc76889a0", 
    "dest": "/data/192.168.37.6/var/log/messages", 
    "md5sum": "e409e985d8adeb20f369f8f6aafb8c0a", 
    "remote_checksum": "e6ddea3e1e47326a5e0771590c996cffc76889a0", 
    "remote_md5sum": null
}

#发现已经把远程的文件抓取过来了
[root@ansible ~]# ll /data/
total 0
drwxr-xr-x 3 root root 17 Jun 19 00:22 192.168.37.18
drwxr-xr-x 3 root root 17 Jun 19 00:22 192.168.37.6

[root@ansible ~]# tree /data/
/data/
├── 192.168.37.18
│   └── var
│       └── log
│           └── messages
└── 192.168.37.6
    └── var
        └── log
            └── messages

6 directories, 2 files

File:设置文件属性

#查看一下文件属性
[root@ansible ~]# ansible websrvs -a 'ls -l /data'
192.168.37.6 | CHANGED | rc=0 >>
total 32
-rw-r--r--  1 root root   633 Jun 18 23:13 fstab
drwx------. 2 root root 16384 Apr  5 01:04 lost+found
-rw-------  1 wang bin      0 Jun 19 00:01 passwd2
-rw-------  1 wang bin   2401 Jun 18 23:19 passwd2.4670.2022-06-19@00:01:35~
-rw-------  1 wang bin     17 Jun 19 00:10 test.txt
-rw-------  1 wang bin     19 Jun 19 00:05 test.txt.5322.2022-06-19@00:10:51~
192.168.37.18 | CHANGED | rc=0 >>
total 16
-rw-r--r-- 1 root root  633 Jun 18 23:13 fstab
-rw------- 1 wang bin     0 Jun 19 00:08 passwd2
-rw------- 1 wang bin  2401 Jun 18 23:19 passwd2.73959.2022-06-19@00:08:25~
-rw------- 1 wang bin    17 Jun 19 00:17 test.txt
-rw------- 1 wang bin    19 Jun 19 00:12 test.txt.74665.2022-06-19@00:17:41~

#管理的文件用path指定、把所有者改成wang 权限700 
[root@ansible ~]# ansible websrvs -m file -a 'path=/data/fstab owner=wang mode=700'
192.168.37.6 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "gid": 0, 
    "group": "root", 
    "mode": "0700", 
    "owner": "wang", 
    "path": "/data/fstab", 
    "size": 633, 
    "state": "file", 
    "uid": 500
}
192.168.37.18 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "gid": 0, 
    "group": "root", 
    "mode": "0700", 
    "owner": "wang", 
    "path": "/data/fstab", 
    "size": 633, 
    "state": "file", 
    "uid": 1000
}

#查看一下是否改了
[root@ansible ~]# ansible websrvs -a 'ls -l /data'
192.168.37.6 | CHANGED | rc=0 >>
total 32
-rwx------  1 wang root   633 Jun 18 23:13 fstab	<---属性发生变化
drwx------. 2 root root 16384 Apr  5 01:04 lost+found
-rw-------  1 wang bin      0 Jun 19 00:01 passwd2
-rw-------  1 wang bin   2401 Jun 18 23:19 passwd2.4670.2022-06-19@00:01:35~
-rw-------  1 wang bin     17 Jun 19 00:10 test.txt
-rw-------  1 wang bin     19 Jun 19 00:05 test.txt.5322.2022-06-19@00:10:51~
192.168.37.18 | CHANGED | rc=0 >>
total 16
-rwx------ 1 wang root  633 Jun 18 23:13 fstab	<---属性发生变化
-rw------- 1 wang bin     0 Jun 19 00:08 passwd2
-rw------- 1 wang bin  2401 Jun 18 23:19 passwd2.73959.2022-06-19@00:08:25~
-rw------- 1 wang bin    17 Jun 19 00:17 test.txt
-rw------- 1 wang bin    19 Jun 19 00:12 test.txt.74665.2022-06-19@00:17:41~
  1. 创建软连接\由state=link后面参数指定
[root@ansible ~]# ansible websrvs -m file -a 'src=/data/fstab path=/data/fstab.link state=link'
192.168.37.6 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "dest": "/data/fstab.link", 
    "gid": 0, 
    "group": "root", 
    "mode": "0777", 
    "owner": "root", 
    "size": 11, 
    "src": "/data/fstab", 
    "state": "link", 
    "uid": 0
}
192.168.37.18 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "dest": "/data/fstab.link", 
    "gid": 0, 
    "group": "root", 
    "mode": "0777", 
    "owner": "root", 
    "size": 11, 
    "src": "/data/fstab", 
    "state": "link", 
    "uid": 0
}

[root@ansible ~]# ansible websrvs -a 'ls -l /data'
192.168.37.6 | CHANGED | rc=0 >>
total 32
-rwx------  1 wang root   633 Jun 18 23:13 fstab
lrwxrwxrwx  1 root root    11 Jun 19 00:36 fstab.link -> /data/fstab	<---软连接
drwx------. 2 root root 16384 Apr  5 01:04 lost+found
-rw-------  1 wang bin      0 Jun 19 00:01 passwd2
-rw-------  1 wang bin   2401 Jun 18 23:19 passwd2.4670.2022-06-19@00:01:35~
-rw-------  1 wang bin     17 Jun 19 00:10 test.txt
-rw-------  1 wang bin     19 Jun 19 00:05 test.txt.5322.2022-06-19@00:10:51~
192.168.37.18 | CHANGED | rc=0 >>
total 16
-rwx------ 1 wang root  633 Jun 18 23:13 fstab
lrwxrwxrwx 1 root root   11 Jun 19 00:42 fstab.link -> /data/fstab	<---软连接
-rw------- 1 wang bin     0 Jun 19 00:08 passwd2
-rw------- 1 wang bin  2401 Jun 18 23:19 passwd2.73959.2022-06-19@00:08:25~
-rw------- 1 wang bin    17 Jun 19 00:17 test.txt
-rw------- 1 wang bin    19 Jun 19 00:12 test.txt.74665.2022-06-19@00:17:41~
  1. 创建硬连接\由state=hard后面参数指定
[root@ansible ~]# ansible websrvs -m file -a 'src=/data/fstab path=/data/fstab.link2 state=hard'
192.168.37.6 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "dest": "/data/fstab.link2", 
    "gid": 0, 
    "group": "root", 
    "mode": "0700", 
    "owner": "wang", 
    "size": 633, 
    "src": "/data/fstab", 
    "state": "hard", 
    "uid": 500
}
192.168.37.18 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "dest": "/data/fstab.link2", 
    "gid": 0, 
    "group": "root", 
    "mode": "0700", 
    "owner": "wang", 
    "size": 633, 
    "src": "/data/fstab", 
    "state": "hard", 
    "uid": 1000
}

[root@ansible ~]# ansible websrvs -a 'ls -l /data'
192.168.37.6 | CHANGED | rc=0 >>
total 36
-rwx------  2 wang root   633 Jun 18 23:13 fstab
lrwxrwxrwx  1 root root    11 Jun 19 00:36 fstab.link -> /data/fstab
-rwx------  2 wang root   633 Jun 18 23:13 fstab.link2	<---硬连接
drwx------. 2 root root 16384 Apr  5 01:04 lost+found
-rw-------  1 wang bin      0 Jun 19 00:01 passwd2
-rw-------  1 wang bin   2401 Jun 18 23:19 passwd2.4670.2022-06-19@00:01:35~
-rw-------  1 wang bin     17 Jun 19 00:10 test.txt
-rw-------  1 wang bin     19 Jun 19 00:05 test.txt.5322.2022-06-19@00:10:51~
192.168.37.18 | CHANGED | rc=0 >>
total 20
-rwx------ 2 wang root  633 Jun 18 23:13 fstab
lrwxrwxrwx 1 root root   11 Jun 19 00:42 fstab.link -> /data/fstab
-rwx------ 2 wang root  633 Jun 18 23:13 fstab.link2	<---硬连接
-rw------- 1 wang bin     0 Jun 19 00:08 passwd2
-rw------- 1 wang bin  2401 Jun 18 23:19 passwd2.73959.2022-06-19@00:08:25~
-rw------- 1 wang bin    17 Jun 19 00:17 test.txt
-rw------- 1 wang bin    19 Jun 19 00:12 test.txt.74665.2022-06-19@00:17:41~
  1. 还可以创建空文件\由state=touch后面参数指定
[root@ansible ~]# ansible websrvs -m file -a 'path=/data/f1.txt state=touch'
192.168.37.6 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "dest": "/data/f1.txt", 
    "gid": 0, 
    "group": "root", 
    "mode": "0644", 
    "owner": "root", 
    "size": 0, 
    "state": "file", 
    "uid": 0
}
192.168.37.18 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "dest": "/data/f1.txt", 
    "gid": 0, 
    "group": "root", 
    "mode": "0644", 
    "owner": "root", 
    "size": 0, 
    "state": "file", 
    "uid": 0
}
[root@ansible ~]# ansible websrvs -a 'ls -l /data'
192.168.37.6 | CHANGED | rc=0 >>
total 36
-rw-r--r--  1 root root     0 Jun 19 00:41 f1.txt	<--创建了f1.txt文件
-rwx------  2 wang root   633 Jun 18 23:13 fstab
lrwxrwxrwx  1 root root    11 Jun 19 00:36 fstab.link -> /data/fstab
-rwx------  2 wang root   633 Jun 18 23:13 fstab.link2
drwx------. 2 root root 16384 Apr  5 01:04 lost+found
-rw-------  1 wang bin      0 Jun 19 00:01 passwd2
-rw-------  1 wang bin   2401 Jun 18 23:19 passwd2.4670.2022-06-19@00:01:35~
-rw-------  1 wang bin     17 Jun 19 00:10 test.txt
-rw-------  1 wang bin     19 Jun 19 00:05 test.txt.5322.2022-06-19@00:10:51~
192.168.37.18 | CHANGED | rc=0 >>
total 20
-rw-r--r-- 1 root root    0 Jun 19 00:48 f1.txt	<--创建了f1.txt文件
-rwx------ 2 wang root  633 Jun 18 23:13 fstab
lrwxrwxrwx 1 root root   11 Jun 19 00:42 fstab.link -> /data/fstab
-rwx------ 2 wang root  633 Jun 18 23:13 fstab.link2
-rw------- 1 wang bin     0 Jun 19 00:08 passwd2
-rw------- 1 wang bin  2401 Jun 18 23:19 passwd2.73959.2022-06-19@00:08:25~
-rw------- 1 wang bin    17 Jun 19 00:17 test.txt
-rw------- 1 wang bin    19 Jun 19 00:12 test.txt.74665.2022-06-19@00:17:41~
  1. 还可以删除文件\由state=absent后面参数指定
#删除f1.txt文件
[root@ansible ~]# ansible websrvs -m file -a 'path=/data/f1.txt state=absent'
192.168.37.6 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "path": "/data/f1.txt", 
    "state": "absent"
}
192.168.37.18 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "path": "/data/f1.txt", 
    "state": "absent"
}

[root@ansible ~]# ansible websrvs -a 'ls -l /data'
192.168.37.6 | CHANGED | rc=0 >>
total 36
-rwx------  2 wang root   633 Jun 18 23:13 fstab
lrwxrwxrwx  1 root root    11 Jun 19 00:36 fstab.link -> /data/fstab
-rwx------  2 wang root   633 Jun 18 23:13 fstab.link2
drwx------. 2 root root 16384 Apr  5 01:04 lost+found
-rw-------  1 wang bin      0 Jun 19 00:01 passwd2
-rw-------  1 wang bin   2401 Jun 18 23:19 passwd2.4670.2022-06-19@00:01:35~
-rw-------  1 wang bin     17 Jun 19 00:10 test.txt
-rw-------  1 wang bin     19 Jun 19 00:05 test.txt.5322.2022-06-19@00:10:51~
192.168.37.18 | CHANGED | rc=0 >>
total 20
-rwx------ 2 wang root  633 Jun 18 23:13 fstab
lrwxrwxrwx 1 root root   11 Jun 19 00:42 fstab.link -> /data/fstab
-rwx------ 2 wang root  633 Jun 18 23:13 fstab.link2
-rw------- 1 wang bin     0 Jun 19 00:08 passwd2
-rw------- 1 wang bin  2401 Jun 18 23:19 passwd2.73959.2022-06-19@00:08:25~
-rw------- 1 wang bin    17 Jun 19 00:17 test.txt
-rw------- 1 wang bin    19 Jun 19 00:12 test.txt.74665.2022-06-19@00:17:41~
  1. 如果想把目录清空、会显示报错、目录忙、虽然失败了、但是我们可以查看一下是否真的删了
    注意:此命令很危险
[root@ansible ~]# ansible websrvs -m file -a 'path=/data/ state=absent'
192.168.37.6 | FAILED! => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false, 
    "msg": "rmtree failed: [Errno 16] Device or resource busy: '/data/'"
}
192.168.37.18 | FAILED! => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false, 
    "msg": "rmtree failed: [Errno 16] Device or resource busy: '/data/'"

[root@ansible ~]# ansible websrvs -a 'ls -l /data'
192.168.37.6 | CHANGED | rc=0 >>
total 0
192.168.37.18 | CHANGED | rc=0 >>
total 0

Hostname:管理主机名

#更改'37.28'主机名
[root@ansible ~]# ansible 192.168.37.28 -m hostname -a 'name=centos7-2'
192.168.37.28 | CHANGED => {
    "ansible_facts": {
        "ansible_domain": "", 
        "ansible_fqdn": "centos7-2", 
        "ansible_hostname": "centos7-2", 
        "ansible_nodename": "centos7-2", 
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "name": "centos7-2"
}

[root@ansible ~]# ansible all -a 'hostname'
192.168.37.6 | CHANGED | rc=0 >>
centos6
192.168.37.28 | CHANGED | rc=0 >>
centos7-2		<--#可以看到37.28已经改名
192.168.37.18 | CHANGED | rc=0 >>
node18

Cron:计划任务

支持时间:minute(分钟),hour(小时),day(天),month(月),weekday(星期)

  1. 创建计划任务
#创建计划任务
[root@ansible ~]# ansible websrvs -m cron -a "minute=*/5 job='/usr/sbin/ntpdate 172.16.0.1 &>/dev/null' name=Synctime"
192.168.37.18 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "envs": [], 
    "jobs": [
        "Synctime"
    ]
}
192.168.37.6 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "envs": [], 
    "jobs": [
        "Synctime"
    ]
}

37.6主机:查看创建计划任务

[root@centos6 ~]$ crontab -l
#Ansible: Synctime
*/5 * * * * /usr/sbin/ntpdate 172.16.0.1 &>/dev/null
  1. 禁用某个计划任务
#禁用某个计划任务、如'Synctime'
[root@ansible ~]# ansible websrvs -m cron -a "minute=*/5 job='/usr/sbin/ntpdate 172.16.0.1 &>/dev/null' name=Synctime disabled=yes"
192.168.37.18 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "envs": [], 
    "jobs": [
        "Synctime"
    ]
}
192.168.37.6 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "envs": [], 
    "jobs": [
        "Synctime"
    ]
}

37.6主机:查看创建计划任务是否禁用

#发现已经禁用、计划任务已经被'#'注释掉
[root@centos6 ~]$ crontab -l
#Ansible: Synctime
#*/5 * * * * /usr/sbin/ntpdate 172.16.0.1 &>/dev/null
  1. 启用某个计划任务
[root@ansible ~]# ansible websrvs -m cron -a "minute=*/5 job='/usr/sbin/ntpdate 172.16.0.1 &>/dev/null' name=Synctime disabled=no"
192.168.37.18 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "envs": [], 
    "jobs": [
        "Synctime"
    ]
}
192.168.37.6 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "envs": [], 
    "jobs": [
        "Synctime"
    ]
}

37.6主机:查看创建计划任务是否启用

[root@centos6 ~]$ crontab -l
#Ansible: Synctime
*/5 * * * * /usr/sbin/ntpdate 172.16.0.1 &>/dev/null
  1. 删除某个计划任务
[root@ansible ~]# ansible websrvs -m cron -a "minute=*/5 job='/usr/sbin/ntpdate 172.16.0.1 &>/dev/null' name=Synctime state=absent"
192.168.37.6 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "envs": [], 
    "jobs": []
}
192.168.37.18 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "envs": [], 
    "jobs": []
}

37.6主机:查看创建计划任务是否启用

[root@centos6 ~]$ crontab -l

unarchive:解包解压缩

unarchive:解包解压缩,有两种用法:
1、将ansible主机上的压缩包在本地解压缩后传到远程主机上,设置copy=yes.
2、将远程主机上的某个压缩包解压缩到指定路径下,设置copy=no

[root@ansible ~]# tar zcvf /data/sysconfig.tar.gz /etc/sysconfig

[root@ansible ~]# ll /data/
total 60
drwxr-xr-x 3 root root    17 Jun 19 00:22 192.168.37.18
drwxr-xr-x 3 root root    17 Jun 19 00:22 192.168.37.6
-rw-r--r-- 1 root root 58380 Jun 19 01:43 sysconfig.tar.gz	#刚刚压缩的文件

[root@ansible ~]# ansible websrvs -a'ls -l /data'
192.168.37.6 | CHANGED | rc=0 >>
total 0
192.168.37.18 | CHANGED | rc=0 >>
total 0

[root@ansible ~]# ansible websrvs -m unarchive -a 'src=/data/sysconfig.tar.gz dest=/data/ owner=wang mode=700'
192.168.37.18 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "dest": "/data/", 
    "extract_results": {
        "cmd": [
            "/usr/bin/gtar", 
            "--extract", 
            "-C", 
            "/data/", 
            "-z", 
            "--owner=wang", 
            "-f", 
            "/root/.ansible/tmp/ansible-tmp-1655574407.14-12972-189737982101537/source"
        ], 
        "err": "", 
        "out": "", 
        "rc": 0
    }, 
    "gid": 0, 
    "group": "root", 
    "handler": "TgzArchive", 
    "mode": "0755", 
    "owner": "root", 
    "size": 17, 
    "src": "/root/.ansible/tmp/ansible-tmp-1655574407.14-12972-189737982101537/source", 
    "state": "directory", 
    "uid": 0
}
192.168.37.6 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "dest": "/data/", 
    "extract_results": {
        "cmd": [
            "/bin/gtar", 
            "--extract", 
            "-C", 
            "/data/", 
            "-z", 
            "--owner=wang", 
            "-f", 
            "/root/.ansible/tmp/ansible-tmp-1655574407.07-12970-132555838968091/source"
        ], 
        "err": "", 
        "out": "", 
        "rc": 0
    }, 
    "gid": 0, 
    "group": "root", 
    "handler": "TgzArchive", 
    "mode": "0755", 
    "owner": "root", 
    "size": 4096, 
    "src": "/root/.ansible/tmp/ansible-tmp-1655574407.07-12970-132555838968091/source", 
    "state": "directory", 
    "uid": 0
}

#确认一下是否成功、发现属性没有改变、实际已经改了、看下图
[root@ansible ~]# ansible websrvs -a'ls -l /data'
192.168.37.6 | CHANGED | rc=0 >>
total 4
drwxr-xr-x 3 root root 4096 Jun 19 01:39 etc
192.168.37.18 | CHANGED | rc=0 >>
total 0
drwxr-xr-x 3 root root 23 Jun 19 01:46 etc

#发现已经改了、只是没有改上级文件夹的、但是把文件夹中的文件属性已经改了
[root@ansible ~]# ansible websrvs -a'ls -l /data/etc/sysconfig'
192.168.37.6 | CHANGED | rc=0 >>
total 204
-rwx------ 1 wang root  351 Jan 12 11:10 anaconda
-rwx------ 1 wang root  403 Oct 31  2018 atd
-rwx------ 1 wang root  484 Jan 12 11:10 authconfig
...
-rwx------ 1 wang root   55 Oct 31  2018 virtlockd
-rwx------ 1 wang root   53 Oct 31  2018 virtlogd
-rwx------ 1 wang root  610 Oct 31  2018 wpa_supplicant

[root@ansible ~]# ansible websrvs -a'ls -ld /data/etc/sysconfig'
192.168.37.6 | CHANGED | rc=0 >>
drwx------ 6 wang root 4096 Apr 22 10:31 /data/etc/sysconfig
192.168.37.18 | CHANGED | rc=0 >>
drwx------ 6 wang root 4096 Apr 22 10:31 /data/etc/sysconfig

把本机压缩包、拷贝到目标主机、进行解压缩

#把本机压缩包、拷贝到目标主机
[root@ansible ~]# ansible websrvs -m copy -a 'src=/data/sysconfig.tar.gz dest=/data/'
192.168.37.6 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "checksum": "9508528554d8e3bc69ca529f513dd486ba0b7211", 
    "dest": "/data/sysconfig.tar.gz", 
    "gid": 0, 
    "group": "root", 
    "md5sum": "cd8f27ff5f96f91bb97e64d9449adf15", 
    "mode": "0644", 
    "owner": "root", 
    "size": 58380, 
    "src": "/root/.ansible/tmp/ansible-tmp-1655575074.54-13272-242585730443756/source", 
    "state": "file", 
    "uid": 0
}
192.168.37.18 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "checksum": "9508528554d8e3bc69ca529f513dd486ba0b7211", 
    "dest": "/data/sysconfig.tar.gz", 
    "gid": 0, 
    "group": "root", 
    "md5sum": "cd8f27ff5f96f91bb97e64d9449adf15", 
    "mode": "0644", 
    "owner": "root", 
    "size": 58380, 
    "src": "/root/.ansible/tmp/ansible-tmp-1655575074.57-13274-155585373594034/source", 
    "state": "file", 
    "uid": 0
}

[root@ansible ~]# ansible websrvs -a'ls -l /data'
192.168.37.6 | CHANGED | rc=0 >>
total 64
drwxr-xr-x 3 root root  4096 Jun 19 01:39 etc
-rw-r--r-- 1 root root 58380 Jun 19 01:51 sysconfig.tar.gz
192.168.37.18 | CHANGED | rc=0 >>
total 60
drwxr-xr-x 3 root root    23 Jun 19 01:46 etc
-rw-r--r-- 1 root root 58380 Jun 19 01:57 sysconfig.tar.gz
#将远程主机上的某个压缩包解压缩到指定路径下,因为包已经在远程主机上了、不是从本机拷贝过去的、所以设置copy=no
[root@ansible ~]# ansible websrvs -m unarchive -a 'src=/data/sysconfig.tar.gz dest=/data/ copy=no'
192.168.37.18 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "dest": "/data/", 
    "extract_results": {
        "cmd": [
            "/usr/bin/gtar", 
            "--extract", 
            "-C", 
            "/data/", 
            "-z", 
            "-f", 
            "/data/sysconfig.tar.gz"
        ], 
        "err": "", 
        "out": "", 
        "rc": 0
    }, 
    "gid": 0, 
    "group": "root", 
    "handler": "TgzArchive", 
    "mode": "0755", 
    "owner": "root", 
    "size": 41, 
    "src": "/data/sysconfig.tar.gz", 
    "state": "directory", 
    "uid": 0
}
192.168.37.6 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "dest": "/data/", 
    "extract_results": {
        "cmd": [
            "/bin/gtar", 
            "--extract", 
            "-C", 
            "/data/", 
            "-z", 
            "-f", 
            "/data/sysconfig.tar.gz"
        ], 
        "err": "", 
        "out": "", 
        "rc": 0
    }, 
    "gid": 0, 
    "group": "root", 
    "handler": "TgzArchive", 
    "mode": "0755", 
    "owner": "root", 
    "size": 4096, 
    "src": "/data/sysconfig.tar.gz", 
    "state": "directory", 
    "uid": 0
}

Yum:管理包

[root@ansible ~]# ansible websrvs -m yum -a "name=httpd"	#安装httpd、默认state=present
[root@ansible ~]# ansible websrvs -m yum -a "name=httpd state=absent"		#删除httpd

Service:管理服务

[root@ansible ~]# ansible websrvs -m yum -a "name=httpd state=present"	#前提 安装httpd、测试
  1. 启动httpd服务、并设置开机启动
#启动httpd服务、并设置开机启动
[root@ansible ~]# ansible websrvs -m service -a "name=httpd state=started enabled=yes"

37.6主机:查看是否有httpd端口号80

[root@centos6 ~]$ ss -tnl
State       Recv-Q Send-Q               Local Address:Port                 Peer Address:Port 
...
LISTEN      0      128                             :::80                             :::*    
...
  1. 停止httpd服务
[root@ansible ~]# ansible websrvs -m service -a 'name=httpd state=stopped'
  1. 把httpd服务端口号改为8080上监听、并且生效
[root@ansible ~]# ansible websrvs -a 'sed -i "s#^Listen.*#Listen 8080#" /etc/httpd/conf/httpd.conf'

37.6主机:httpd配置文件端口号改为8080

[root@centos6 ~]$ vim /etc/httpd/conf/httpd.conf
...
Listen 8080			#发现远程主机配置文件端口号改成8080
...
#重启服务、并设置开机启动
[root@ansible ~]# ansible websrvs -m service -a 'name=httpd state=restarted enabled=yes'

#重启服务后端口号变成8080
[root@ansible ~]# ansible websrvs -a 'ss -ntl'
192.168.37.6 | CHANGED | rc=0 >>
State      Recv-Q Send-Q        Local Address:Port          Peer Address:Port 
...   
LISTEN     0      128                      :::8080                    :::*     
... 
192.168.37.18 | CHANGED | rc=0 >>
State      Recv-Q Send-Q Local Address:Port               Peer Address:Port              
...
LISTEN     0      128         :::8080                    :::*                   
...

User:管理用户

  1. 创建mysql用户
#创建mysql用户、系统账号、指定家目录、shell类型
[root@ansible ~]# ansible websrvs -m user -a 'name=mysql system=yes home=/data/mysql shell=/bin/false'

#查看一下是否创建成功
[root@ansible ~]# ansible websrvs -a 'getent passwd mysql'
192.168.37.6 | CHANGED | rc=0 >>
mysql:x:496:493::/data/mysql:/bin/false
192.168.37.18 | CHANGED | rc=0 >>
mysql:x:987:981::/data/mysql:/bin/false

查看/data/下mysql目录隐藏文件有没有、发现有、这不是好事

#查看/data/下mysql目录生成没有
[root@ansible ~]# ansible websrvs -a 'ls -l /data'
192.168.37.6 | CHANGED | rc=0 >>
total 20
drwx------. 2 root  root  16384 Apr  5 01:04 lost+found
drwx------  4 mysql mysql  4096 Jun 20 02:28 mysql
192.168.37.18 | CHANGED | rc=0 >>
total 0
drwx------ 3 mysql mysql 78 Jun 20 02:28 mysql

#查看/data/下mysql目录隐藏文件有没有、发现有、这不是好事
[root@ansible ~]# ansible websrvs -a 'ls -la /data/mysql'
192.168.37.18 | CHANGED | rc=0 >>
total 12
drwx------ 3 mysql mysql  78 Jun 20 02:28 .
drwxr-xr-x 3 root  root   19 Jun 20 02:28 ..
-rw-r--r-- 1 mysql mysql  18 Oct 31  2018 .bash_logout
-rw-r--r-- 1 mysql mysql 193 Oct 31  2018 .bash_profile
-rw-r--r-- 1 mysql mysql 231 Oct 31  2018 .bashrc
drwxr-xr-x 4 mysql mysql  39 Apr 26 10:08 .mozilla
192.168.37.6 | CHANGED | rc=0 >>
total 28
drwx------  4 mysql mysql 4096 Jun 20 02:28 .
drwxr-xr-x. 4 root  root  4096 Jun 20 02:28 ..
-rw-r--r--  1 mysql mysql   18 Mar 23  2017 .bash_logout
-rw-r--r--  1 mysql mysql  176 Mar 23  2017 .bash_profile
-rw-r--r--  1 mysql mysql  124 Mar 23  2017 .bashrc
drwxr-xr-x  2 mysql mysql 4096 Nov 12  2010 .gnome2
drwxr-xr-x  4 mysql mysql 4096 Apr  5 01:05 .mozilla
  1. 我们希望创建mysql的时候、不要把家目录的目录创建出来
[root@ansible ~]# ansible websrvs -m user -a 'name=mysql2 system=yes home=/data/mysql2 shell=/bin/false create_home=no'

#查看/data/下mysql2目录不存在
[root@ansible ~]# ansible websrvs -a 'ls -la /data/mysql2'
192.168.37.6 | FAILED | rc=2 >>
ls: cannot access /data/mysql2: No such file or directorynon-zero return code
192.168.37.18 | FAILED | rc=2 >>
ls: cannot access /data/mysql2: No such file or directorynon-zero return code

#没有mysql2目录
[root@ansible ~]# ansible websrvs -a 'ls -l /data'

#但是这个mysql2用户确实生成了
[root@ansible ~]# ansible websrvs -a 'getent passwd mysql2'
192.168.37.6 | CHANGED | rc=0 >>
mysql2:x:495:492::/data/mysql2:/bin/false
192.168.37.18 | CHANGED | rc=0 >>
mysql2:x:986:980::/data/mysql2:/bin/false
  1. 删除用户mysql2
#删除mysql2用户
 [root@ansible ~]# ansible websrvs -m user -a 'name=mysql2 state=absent'

#确认mysql2用户是否删除、已经删了
[root@ansible ~]# ansible websrvs -a 'getent passwd mysql2'
192.168.37.6 | FAILED | rc=2 >>
non-zero return code
192.168.37.18 | FAILED | rc=2 >>
non-zero return code
  1. 删除用户mysql、并包括家目录’remove=yes’
[root@ansible ~]# ansible websrvs -m user -a 'name=mysql state=absent remove=yes'

#发现mysql的家目录被删除了
[root@ansible ~]# ansible websrvs -a 'ls -l /data'
192.168.37.6 | CHANGED | rc=0 >>
total 16
drwx------. 2 root root 16384 Apr  5 01:04 lost+found
192.168.37.18 | CHANGED | rc=0 >>
total 0

Group:管理组

#创建组、系统账号
[root@ansible ~]# ansible websrvs -m group-a 'name=testgroup system=yes'
#删除组
[root@ansible ~]# ansible websrvs -m group-a 'name=testgroup system=absent'

ansible-galaxy :通过互联网下载相应的包、安装、删除

[root@ansible ~]# ansible-galaxy install geerlingguy.ntp
- downloading role 'ntp', owned by geerlingguy
- downloading role from https://github.com/geerlingguy/ansible-role-ntp/archive/master.tar.gz	#也可wget下载
- extracting geerlingguy.ntp to /root/.ansible/roles/geerlingguy.ntp		#下载后所放位置
- geerlingguy.ntp (master) was installed successfully	#下载完成

看看刚刚下载的文件、简单了解一下

[root@ansible ~]# cd .ansible/roles/
[root@ansible roles]# ls
geerlingguy.ntp
[root@ansible roles]# cd geerlingguy.ntp/
[root@ansible geerlingguy.ntp]# ls
defaults  handlers  LICENSE  meta  molecule  README.md  tasks  templates  vars

#查看一下刚刚下载文件的目录结构
[root@ansible geerlingguy.ntp]# tree
.
├── defaults
│   └── main.yml
├── handlers
│   └── main.yml
├── LICENSE
├── meta
│   └── main.yml
├── molecule
│   └── default
│       ├── converge.yml
│       └── molecule.yml
├── README.md
├── tasks
│   └── main.yml
├── templates
│   ├── chrony.conf.j2
│   ├── clock.j2
│   └── ntp.conf.j2
└── vars
    ├── Archlinux.yml
    ├── Debian.yml
    ├── FreeBSD.yml
    ├── RedHat.yml
    └── Suse.yml

8 directories, 16 files

列出所有已安装的galaxy

#列出所有已安装的galaxy
[root@ansible geerlingguy.ntp]# ansible-galaxy list
# /root/.ansible/roles
- geerlingguy.ntp, master		<---
# /usr/share/ansible/roles
# /etc/ansible/roles

安装galaxy
ansible-galaxy install geerlingguy.redis
删除galaxy
ansible-galaxy remove geerlingguy.redis

ansible-vault 功能:管理加密解密yml文件

[root@ansible ~]# mkdir /data/playbook	#创建一个文件夹专门放playbook
[root@ansible ~]# cd /data/playbook
[root@ansible playbook]#  vim hello.yml

- hosts: websrvs
  tesks:
    - name: flrst yml
      command: /bin/echo "hello world"
  1. 加密
[root@ansible playbook]# ansible-vault encrypt hello.yml
New Vault password: 	#输入密码、如123.com
Confirm New Vault password: 	#再次输入密码
Encryption successful
[root@ansible playbook]# ll
total 4
-rw------- 1 root root 679 Jun 21 15:48 hello.yml
[root@ansible playbook]# cat hello.yml 
$ANSIBLE_VAULT;1.1;AES256		<--发现使用AES对称密钥的256位算法进行加密
34353839666534356533363266303930343239333839373232386662363361323837343562653931
6439653166313330366234626634303430333539643539610a383561366462346135653462386532
36396330326562393134653636386665633538353334653437643963613531626234666139396565
3531643033393431630a336164643232383062656665636236633462663330323230373135653338
38666639326663356261316464373337373439666365663036616162353637333339353730316433
37393434666631633836653464333131373136343461613534333336323735333431336135303130
36666532643666383939383133316563306534313363386366656638353733346463613661363539
64666130353162373038393361363831383330626139633734396434333463373534616138373865
6261

#加密后需要解密
[root@ansible playbook]# ansible-playbook hello.yml
ERROR! Attempting to decrypt but no vault secrets found
  1. 解密
[root@ansible playbook]# ansible-vault decrypt hello.yml
Vault password:  	#输入密码、如123.com
Decryption successful

#解密后之前的文件、可以正常查看
[root@ansible playbook]# cat hello.yml 
- hosts: websrvs
  tesks:
    - name: flrst yml
      command: /bin/echo "hello world"
  1. 查看加密文件、编辑加密文件
[root@ansible playbook]# ansible-vault encrypt hello.yml
New Vault password: 
Confirm New Vault password: 
Encryption successful

[root@ansible playbook]# cat hello.yml 
$ANSIBLE_VAULT;1.1;AES256
64643262353939383831633464653132613463386230366231666434633865366365616637316231
3936303735646263623838353333373263336130663763610a656364366633363364316635323234
34386563623263626232353237373937366336353935383166666133653065323263646130636330
6335326132636162330a623962346638353361306134616632376565613366386530303238313130
66333561393661626131653736396334653330323665386665326431323138393437363166353437
32643131386534633437666232373731633732323531326233376161633731303662633938663931
36343334666362643439623439313964323265636361393165383161626534353631656635653331
33336666616433396434346233373366316235623263623033376561623763313261656537613437
6437

#查看加密文件
[root@ansible playbook]# ansible-vault view hello.yml
Vault password: 	#输对密码、即可查看
- hosts: websrvs
  tesks:
    - name: flrst yml
      command: /bin/echo "hello world"

#编辑加密文件
[root@ansible playbook]# ansible-vault edit hello.yml
Vault password: 	#输入正确密码、即可编辑加密文件

- hosts: websrvs
  tesks:
    - name: flrst yml2		<--添加一个'2'、做修改测试
      command: /bin/echo "hello world"

#查看加密文件、看看内容是否变化
[root@ansible playbook]# ansible-vault view hello.yml
Vault password: 
- hosts: websrvs
  tesks:
    - name: flrst yml2		<--刚刚添加一个'2'确实生效
      command: /bin/echo "hello world"
  1. 修改口令
[root@ansible playbook]# ansible-vault rekey hello.yml
Vault password: 	#输入旧口令
New Vault password: 	#输入新口令
Confirm New Vault password: 	#再次输入新口令
Rekey successful		#成功
  1. 创建新文件【空的】
[root@ansible playbook]# ansible-vault create hello2.yml 
New Vault password: 
Confirm New Vault password: 
...
内容自己写
...

Ansible-console:工作台、2.0+新增,可交互执行命令,支持tab

[root@ansible playbook]# ansible-console
Welcome to the ansible console.
Type help or ? to list commands.

#执行用户@当前操作的主机组 (当前组的主机数量)[f:并发数]$
root@all (3)[f:5]$ 
#查看帮助、用'help''?'
root@all (3)[f:5]$ help
Documented commands (type help <topic>):
========================================
...
zpool_facts
zypper
zypper_repository
#列出当前组主机列表
root@all (3)[f:5]$ list
192.168.37.18
192.168.37.28
192.168.37.6
#设置并发数: forks n 例如: forks 10
root@all (3)[f:5]$ forks 10
root@all (3)[f:10]$ 
#切换组: cd 主机组 例如: cd websrvs
root@all (3)[f:10]$ cd websrvs
root@websrvs (2)[f:10]$ 		#切换后就针对'websrvs'里的主机进行操作

#如在'websrvs'里的主机、安装httpd服务
root@websrvs (2)[f:10]$ yum name=httpd

#如在'websrvs'里的主机、卸载httpd服务
root@websrvs (2)[f:10]$ yum name=httpd state=absent

#Ansible-console:工作台
root@websrvs (2)[f:10]$ exit

ansible-playbook

  • playbook是由一个或多个“play”组成的列表
  • play的主要功能在于将预定义的一组主机,装扮成事先通过ansible中的task定义好的角色。Task实际是调用ansible的一个module,将多个play组织在一个playbook中,即可以让它们联合起来,按事先编排的机制执行预定义的动作
  • Playbook采用YAML语言编写

前提
ansible主机

[root@ansible ~]# yum install httpd -y
[root@ansible ~]# cp /etc/httpd/conf/httpd.conf /data/playbook/
[root@ansible ~]# cd /data/playbook/
[root@ansible playbook]# vim httpd.conf 
...
Listen 8080			<---端口号改为8080
...
[root@ansible playbook]# vim httpd.yml

---
- hosts: appsrvs		#针对appsrvs的主机
  remote_user: root		#以root身份执行

  tasks:
    - name: install		#安装httpd服务
      yum: name=httpd           
    - name: config     #从本机/data/playbook/httpd.conf拷贝到目标主机/ect/httpd/conf/copy: src=/data/playbook/httpd.conf dest=/etc/httpd/conf/ 
    - name: service		#服务名httpd、启动、设置开机启动
      service: name=httpd state=started enabled=yes

主机37.18

##发现没有80端口
~]# ss -ntl

ansible主机

#检查一下脚本语法是否正确
[root@ansible playbook]# ansible-playbook -C httpd.yml

#执行脚本
[root@ansible playbook]# ansible-playbook httpd.yml

37.18主机

#查看是否有httpd服务的、8080端口
[root@CentOS7 conf]# ss -ntl
State      Recv-Q Send-Q        Local Address:Port                       Peer Address:Port              
...           
LISTEN     0      128                       *:8080                                  *:*   
...

#可以看到httpd服务已经安装
~]# rpm -q httpd
httpd-2.4.6-88.el7.centos.x86_64
#列出运行任务的主机
[root@ansible playbook]# ansible-playbook --list-hosts httpd.yml

playbook: httpd.yml

  play #1 (appsrvs): appsrvs	TAGS: []
    pattern: [u'appsrvs']
    hosts (2):
      192.168.37.28
      192.168.37.18

#列出task
[root@ansible playbook]# ansible-playbook --list-tasks httpd.yml

playbook: httpd.yml

  play #1 (appsrvs): appsrvs	TAGS: []
    tasks:
      install	TAGS: []
      config	TAGS: []
      service	TAGS: []

#列出tag
[root@ansible playbook]# ansible-playbook --list-tags httpd.yml

playbook: httpd.yml

  play #1 (appsrvs): appsrvs	TAGS: []
      TASK TAGS: []

实验:ansible playbook实现二进制安装mariadb

上传 mariadb-10.2.25-linux-x86_64.tar.gz到/data/playbook下

[root@ansible playbook]# ls
httpd.conf  httpd.yml  mariadb-10.2.25-linux-x86_64.tar.gz

#解压缩
[root@ansible playbook]# tar xvf mariadb-10.2.25-linux-x86_64.tar.gz

[root@ansible playbook] cd mariadb-10.2.25-linux-x86_64/

[root@ansible mariadb-10.2.25-linux-x86_64]# cp support-files/my-huge.cnf /data/playbook/

[root@ansible mariadb-10.2.25-linux-x86_64]# vim /data/playbook/my-huge.cnf 
...
[mysqld]
datadir=/data/mysql		#添加一行
port            = 3306
...

创建playbook脚本

#创建playbook脚本
[root@ansible mariadb-10.2.25-linux-x86_64]# vim /data/playbook/install_mariadb.yml

---
- hosts: appsrvs		#可定义指定'组'或指定主机'192.168.37.6'
  remote_user: root

  tasks:
    - name: user		#建账号
      user: name=mysql system=yes home=/data/mysql create_home=no shell=/sbin/nologin
    - name: unarchive	#解压缩、copy=yes可忽略、因为默认就是
      unarchive: src=/data/playbook/mariadb-10.2.25-linux-x86_64.tar.gz dest=/usr/local/ owner=root group=root
    - name: mysql link	#创建软连接
      file: src=/usr/local/mariadb-10.2.25-linux-x86_64 dest=/usr/local/mysql state=link
    - name: mysql datadir	#创建文件夹
      file: path=/data/mysql state=directory
    - name: mysql datadir owner group	#更改属性
      file: path=/data/mysql owner=mysql group=mysql
    - name: mysql database	#创建数据库
      shell: chdir=/usr/local/mysql/ scripts/mysql_install_db --datadir=/data/mysql --user=mysql
    - name: path var	#path变量
      copy: content='PATH=/usr/local/mysql/bin:$PATH' dest=/etc/profile.d/mysql.sh
    - name: config	#配置文件
      copy: src=/data/playbook/my-huge.cnf dest=/etc/my.cnf
    - name: service file	#服务脚本文件
      shell: cp /usr/local/mysql/support-files/mysql.server /etc/init.d/mysqld
    - name: start service	#启动服务
      shell: /etc/init.d/mysqld start
[root@ansible mariadb-10.2.25-linux-x86_64]# cd /data/playbook/
[root@ansible playbook]# ansible-playbook install_mariadb.yml

37.18主机

~]# du -sh .ansible/
328M	.ansible/
~]# du -sh .ansible/
438M	.ansible/


~]# du -sh /usr/local/mariadb-10.2.25-linux-x86_64/
1.5G	/usr/local/mariadb-10.2.25-linux-x86_64/

#看看端口是否打开
[root@CentOS7 ~]# ss -ntl
State      Recv-Q Send-Q        Local Address:Port                       Peer Address:Port              
...               
LISTEN     0      128                       *:8080                                  *:*                  
...

~]# mysql
bash: mysql: command not found...
~]# . /etc/profile.d/mysql.sh	#运行完此步骤、使变量生效或退出此主机(37.18)远程窗口重新登录、即可进入mysql
~]# mysql
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 10
Server version: 10.2.25-MariaDB-log MariaDB Server

Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

MariaDB [(none)]> 

测试脚本、能否在CentOS6上用
37.6主机、系统CentOS6

6 ~]# rpm -q mysql-server
6 ~]# yum remove mysql-server -y

ansible主机

[root@ansible playbook]# cat install_mariadb.yml 
---
- hosts: 192.168.37.6	<--此处改成CentOS6主机的IP地址
  remote_user: root
...


[root@ansible playbook]# ansible-playbook install_mariadb.yml

37.6主机、有3306端口即可

6 ~]$ ss -ntl
State       Recv-Q Send-Q               Local Address:Port                 Peer Address:Port 
...
LISTEN      0      80                              :::3306                           :::*     
...

实验:ansible playbook 实现httpd服务部署

handlers和notify结合使用触发条件

  • Handlers
    是task列表,这些task与前述的task并没有本质上的不同,用于当关注的资源发生变化时,才会采取一定的操作
  • Notify此action可用于在每个play的最后被触发,这样可避免多次有改变发生时每次都执行指定的操作,仅在所有的变化发生完成后一次性地执行指定操作。在notify中列出的操作称为handler,也即notify中调用handler中定义的操作

如httpd服务已启动、需要将端口号更改为’9527’

[root@ansible ~]# vim /data/playbook/httpd.yml 	#【此脚本、后续可反复修改使用】

---
- hosts: appsrvs
  remote_user: root

  tasks:
    - name: install
      yum: name=httpd
    - name: config
      copy: src=/data/playbook/httpd.conf dest=/etc/httpd/conf/
      notify: restart httpd		#触发器 'notify':通知
    - name: service
      service: name=httpd state=started enabled=yes

  handlers:
    - name: restart httpd		#触发器名称要和上面一致
      service: name=httpd state=restarted		#触发器:执行的命令是重启httpd服务
[root@ansible ~]# vim /data/playbook/httpd.conf 
...
Listen 9527		#将httpd端口号改为'9527'
...

37.18主机
现在端口号:8080

7 ~]# ss -ntl
State      Recv-Q Send-Q        Local Address:Port                       Peer Address:Port              
...           
LISTEN     0      128                       *:8080                                  *:*     
...
[root@ansible ~]# cd /data/playbook/

#执行脚本后、远程主机端口号会发生变化
[root@ansible playbook]# ansible-playbook httpd.yml

37.18主机
端口号变成:9527

7 ~]# ss -ntl
State      Recv-Q Send-Q        Local Address:Port                       Peer Address:Port              
...          
LISTEN     0      128                       *:9527                                  *:*     
...
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值