«
ansible(一)

时间:2022-8-24     作者:李泽信     分类: ansible


一、ansible自动化工具

二、ansible实现原理

1.Ansible core核心引擎:
2.Host inventory主机清单:用来定义Ansible所管理的主机,默认是在Ansible的hosts配置文件中定义被管理主机,同时也支持自定义动态主机清单和指定其他配置文件的位置;
3.Connection plugins连接插件:负责和被管理主机实现通信。除支持使用SSH连接被管理主机外,Ansible还支持其他的连接方式,所以需要有连接插件将各个主机用连接插件连接到Ansible;
4.Playbooks(yam1,yam2)剧本:用来集中定义Ansible任务的配置文件,即将多个任务定义在一个剧本中由Ansible自动执行,可以由控制主机针对多台被管理主机同时运行多个任务;
5.Core modules核心模块:是Ansible自带的模块,使用这些模块将资源分发到被管理主机,使其执行特定任务或匹配特定的状态;
6.Custom modules自定义模块:用于完成模块功能的补充,可借助相关插件完成记录日志、发送邮件等功能;

三、安装ansible

系统环境 IP地址 主机名 所需软件
centos7.8 192.168.100.101 ansible ansible
centos7.8 192.168.100.102 slave1
centos7.8 192.168.100.103 slave2
[root@ansible ~]# wget -O /etc/yum.repos.d/epel.repo https://mirrors.aliyun.com/repo/epel-7.repo
[root@ansible ~]# yum -y install ansible
[root@ansible ~]# rpm -qa ansible
ansible-2.9.27-1.el7.noarch
[root@ansible ~]# rpm -qc ansible
/etc/ansible/ansible.cfg
/etc/ansible/hosts
[root@ansible ~]# ls /etc/ansible/
ansible.cfg                     ##主配置文件
hosts                       ##定义被管理主机IP或主机名
roles                           ##角色或者插件路径,默认该目录为空

[root@ansible ~]# vi /etc/ansible/hosts     #配置被管理主机列表,本机也可以是被管理主机
[webservers]
192.168.100.102
192.168.100.103

#主配置文件
inventory = /etc/ansible/hosts      #这个参数表示资源清单inventory文件的位置
library = /usr/share/ansible        #指向存放Ansible模块的目录,支持多个目录方式,只要用冒号(:)隔开就可以
forks = 5       #并发连接数,默认为5
sudo_user = root        #设置默认执行命令的用户
remote_port = 22        #指定连接被管节点的管理端口,默认为22端口,建议修改,能够更加安全
host_key_checking = False       #设置是否检查SSH主机的密钥,值为True/False。关闭后第一次连接不会提示配置实例
timeout = 60        #设置SSH连接的超时时间,单位为秒
log_path = /var/log/ansible.log     #指定一个存储ansible日志的文件(默认不记录日志)
ansible <host-pattern>  [-m module_name] [-a args] [options]

<host-pattern> :指定主机组或IP
[-m module_name] : 指定调用模块
[-a args] [options] : 传递给模块的参数

-a MODULE_ARGS   #模块的参数,如果执行默认COMMAND的模块,即是命令参数,如: “date”,“pwd”等等
-k,--ask-pass #ask for SSH password。登录密码,提示输入SSH密码而不是假设基于密钥的验证
--ask-su-pass #ask for su password。su切换密码
-K,--ask-sudo-pass #ask for sudo password。提示密码使用sudo,sudo表示提权操作
--ask-vault-pass #ask for vault password。假设我们设定了加密的密码,则用该选项进行访问
-B SECONDS #后台运行超时时间
-C #模拟运行环境并进行预运行,可以进行查错测试
-c CONNECTION #连接类型使用
-f FORKS #并行任务数,默认为5
-i INVENTORY #指定主机清单的路径,默认为/etc/ansible/hosts
--list-hosts #查看有哪些主机组
-m MODULE_NAME #执行模块的名字,默认使用 command 模块,所以如果是只执行单一命令可以不用 -m参数
-o #压缩输出,尝试将所有结果在一行输出,一般针对收集工具使用
-S #用 su 命令
-R SU_USER #指定 su 的用户,默认为 root 用户
-s #用 sudo 命令
-U SUDO_USER #指定 sudo 到哪个用户,默认为 root 用户
-T TIMEOUT #指定 ssh 默认超时时间,默认为10s,也可在配置文件中修改
-u REMOTE_USER #远程用户,默认为 root 用户
-v #查看详细信息,同时支持-vvv,-vvvv可查看更详细信息

常用命令

ansible test --list-hosts # 列出执行主机列表
ansible-doc -l  # 查看所有模块   (键入q退出)
ansible-doc command # 查看command模块详细信息
ansible-doc -s command  # 查看command模块详细用法
ansible test -m command -a 'df -h'  # 对所有被控服务器使用df -h 命令
ansible web -m command -a 'useradd Tom' # 批量添加用户
[root@ansible ~]# ssh-keygen -t rsa
[root@ansible ~]# ssh-copy-id root@192.168.100.102
[root@ansible ~]# ssh-copy-id root@192.168.100.103
[root@ansible ~]# ansible -k all -m ping
SSH password: 123123
192.168.100.102 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false, 
    "ping": "pong"
}
192.168.100.103 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false, 
    "ping": "pong"
}
chdir       ##执行命令前,切换到该目录
creates     ##当该文件存在时,则不执行该步骤
executable  ##换用其他shell环境执行命令
free_form   ##需要执行的脚本
removes     ##当该文件不存在时,则不执行该步骤

例如

[root@ansible ~]# ansible webservers -a 'chdir=/root/ ls'       ##切换到该路径,执行ls命令
192.168.100.103 | CHANGED | rc=0 >>
anaconda-ks.cfg
apache-tomcat-9.0.10.tar.gz
jdk-8u171-linux-x64.tar.gz
192.168.100.102 | CHANGED | rc=0 >>
anaconda-ks.cfg
apache-tomcat-9.0.10.tar.gz
jdk-8u171-linux-x64.tar.gz

[root@ansible ~]# ansible webservers -a 'creates=/etc/fstab ls /root'       ##如果该文件存在,则不执行ls /root命令
192.168.100.103 | SUCCESS | rc=0 >>
skipped, since /etc/fstab exists
192.168.100.102 | SUCCESS | rc=0 >>
skipped, since /etc/fstab exists

[root@ansible ~]# ansible webservers -a 'removes=/etc/fstab ls /root'       ##如果该文件存在,则执行ls /root
192.168.100.102 | CHANGED | rc=0 >>
anaconda-ks.cfg
apache-tomcat-9.0.10.tar.gz
jdk-8u171-linux-x64.tar.gz
192.168.100.103 | CHANGED | rc=0 >>
anaconda-ks.cfg
apache-tomcat-9.0.10.tar.gz
jdk-8u171-linux-x64.tar.gz
src         ##源文件位置
content     ##手动编写源文件内容
dest        ##目标主机上的目标文件位置
mode        ##设置文件权限
owner       ##设置文件属性
group       ##设置文件属组
force       ##强制覆盖文件
backup      ##当文件内容发生改变后,再覆盖前备份源文件,备份文件包含时间信息
directory_mode      ##递归设定目录的权限,默认为系统默认权限
others      ##所有的file模块中的选项可以在这里使用
1.复制文件
[root@ansible ~]# ansible webservers -m copy -a 'src=/root/1.sh dest=/root/hello'
192.168.100.103 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false, 
    "checksum": "2c7123d6102ba1c47057f51fa46ebad71bbfb3a5", 
    "dest": "/root/hello", 
    "gid": 0, 
    "group": "root", 
    "mode": "0644", 
    "owner": "root", 
    "path": "/root/hello", 
    "size": 19, 
    "state": "file", 
    "uid": 0
}
192.168.100.102 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false, 
    "checksum": "2c7123d6102ba1c47057f51fa46ebad71bbfb3a5", 
    "dest": "/root/hello", 
    "gid": 0, 
    "group": "root", 
    "mode": "0644", 
    "owner": "root", 
    "path": "/root/hello", 
    "size": 19, 
    "state": "file", 
    "uid": 0
}

2.给定内容生成文件,并制定权限
[root@ansible ~]# ansible webservers -m copy -a 'content="I am keer\n" dest=/root/name mode=666'
192.168.100.103 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false, 
    "checksum": "0421570938940ea784f9d8598dab87f07685b968", 
    "dest": "/root/name", 
    "gid": 0, 
    "group": "root", 
    "mode": "0666", 
    "owner": "root", 
    "path": "/root/name", 
    "size": 10, 
    "state": "file", 
    "uid": 0
}
192.168.100.102 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false, 
    "checksum": "0421570938940ea784f9d8598dab87f07685b968", 
    "dest": "/root/name", 
    "gid": 0, 
    "group": "root", 
    "mode": "0666", 
    "owner": "root", 
    "path": "/root/name", 
    "size": 10, 
    "state": "file", 
    "uid": 0
}
查看生成文件的权限
[root@ansible ~]# ansible webservers -m shell -a 'ls -l /root'
192.168.100.102 | CHANGED | rc=0 >>
总用量 196060
-rw-------. 1 root root      1262 1月  23 2019 anaconda-ks.cfg
-rw-r--r--  1 root root   9858504 10月 30 2021 apache-tomcat-9.0.10.tar.gz
-rw-r--r--  1 root root        19 8月  24 15:48 hello
-rw-r--r--  1 root root 190890122 10月 30 2021 jdk-8u171-linux-x64.tar.gz
-rw-rw-rw-  1 root root        10 8月  24 15:58 name
192.168.100.103 | CHANGED | rc=0 >>
总用量 196060
-rw-------. 1 root root      1262 1月  23 2019 anaconda-ks.cfg
-rw-r--r--  1 root root   9858504 10月 30 2021 apache-tomcat-9.0.10.tar.gz
-rw-r--r--  1 root root        19 8月  24 15:48 hello
-rw-r--r--  1 root root 190890122 10月 30 2021 jdk-8u171-linux-x64.tar.gz
-rw-rw-rw-  1 root root        10 8月  24 15:58 name

3.覆盖
[root@ansible ~]# ansible webservers -m copy -a 'content="hello world\n" backup=yes dest=/root/name mode=666'
192.168.100.102 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "backup_file": "/root/name.4722.2022-08-24@16:01:49~", 
    "changed": true, 
    "checksum": "22596363b3de40b06f981fb85d82312e8c0ed511", 
    "dest": "/root/name", 
    "gid": 0, 
    "group": "root", 
    "md5sum": "6f5902ac237024bdd0c176cb93063dc4", 
    "mode": "0666", 
    "owner": "root", 
    "size": 12, 
    "src": "/root/.ansible/tmp/ansible-tmp-1661328108.07-16905-102450375068468/source", 
    "state": "file", 
    "uid": 0
}
192.168.100.103 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "backup_file": "/root/name.18438.2022-08-24@16:01:49~", 
    "changed": true, 
    "checksum": "22596363b3de40b06f981fb85d82312e8c0ed511", 
    "dest": "/root/name", 
    "gid": 0, 
    "group": "root", 
    "md5sum": "6f5902ac237024bdd0c176cb93063dc4", 
    "mode": "0666", 
    "owner": "root", 
    "size": 12, 
    "src": "/root/.ansible/tmp/ansible-tmp-1661328108.08-16906-87257431749426/source", 
    "state": "file", 
    "uid": 0
}
查看文件及备份情况
[root@ansible ~]# ansible webservers -m shell -a 'ls -l /root'
192.168.100.103 | CHANGED | rc=0 >>
总用量 196064
-rw-------. 1 root root      1262 1月  23 2019 anaconda-ks.cfg
-rw-r--r--  1 root root   9858504 10月 30 2021 apache-tomcat-9.0.10.tar.gz
-rw-r--r--  1 root root        19 8月  24 15:48 hello
-rw-r--r--  1 root root 190890122 10月 30 2021 jdk-8u171-linux-x64.tar.gz
-rw-rw-rw-  1 root root        12 8月  24 16:01 name
-rw-rw-rw-  1 root root        10 8月  24 15:58 name.18438.2022-08-24@16:01:49~
192.168.100.102 | CHANGED | rc=0 >>
总用量 196064
-rw-------. 1 root root      1262 1月  23 2019 anaconda-ks.cfg
-rw-r--r--  1 root root   9858504 10月 30 2021 apache-tomcat-9.0.10.tar.gz
-rw-r--r--  1 root root        19 8月  24 15:48 hello
-rw-r--r--  1 root root 190890122 10月 30 2021 jdk-8u171-linux-x64.tar.gz
-rw-rw-rw-  1 root root        12 8月  24 16:01 name
-rw-rw-rw-  1 root root        10 8月  24 15:58 name.4722.2022-08-24@16:01:49~
[root@ansible ~]# ansible webservers -m shell -a 'cat /root/name'
192.168.100.103 | CHANGED | rc=0 >>
hello world
192.168.100.102 | CHANGED | rc=0 >>
hello world
name        ##软件包名称
state       ##软件包状态,present表示安装,absent表示卸载,latest安装最新
update_cache        ##安装软件前更新缓存
enablerepo      ##指定yum源名称
conf_file       ##指定yum安装时所加载的yum配置文件
disable_pgp_check       ##是否禁止GPG checking,只用于present or latest
disablerepo     ##临时禁止使用yum库,只用于安装或更新
enablerepo      ##临时使用的yum库,只用于安装或更新

例如

安装httpd
[root@ansible ~]# ansible webservers -m yum -a 'name=httpd state=present'
192.168.100.102 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "changes": {
        "installed": [
            "httpd"
        ]
    }, 
    "msg": "", 
    "rc": 0, 
    "results": [
        "Loaded plugins: fastestmirror\nLoading mirror speeds from cached hostfile\nResolving Dependencies\n--> Running transaction check\n---> Package httpd.x86_64 0:2.4.6-67.el7.centos will be installed\n--> Finished Dependency Resolution\n\nDependencies Resolved\n\n================================================================================\n Package       Arch           Version                       Repository     Size\n================================================================================\nInstalling:\n httpd         x86_64         2.4.6-67.el7.centos           local         2.7 M\n\nTransaction Summary\n================================================================================\nInstall  1 Package\n\nTotal download size: 2.7 M\nInstalled size: 9.4 M\nDownloading packages:\nRunning transaction check\nRunning transaction test\nTransaction test succeeded\nRunning transaction\n  Installing : httpd-2.4.6-67.el7.centos.x86_64                             1/1 \n  Verifying  : httpd-2.4.6-67.el7.centos.x86_64                             1/1 \n\nInstalled:\n  httpd.x86_64 0:2.4.6-67.el7.centos                                            \n\nComplete!\n"
    ]
}
192.168.100.103 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "changes": {
        "installed": [
            "httpd"
        ]
    }, 
    "msg": "", 
    "rc": 0, 
    "results": [
        "Loaded plugins: fastestmirror\nLoading mirror speeds from cached hostfile\nResolving Dependencies\n--> Running transaction check\n---> Package httpd.x86_64 0:2.4.6-67.el7.centos will be installed\n--> Finished Dependency Resolution\n\nDependencies Resolved\n\n================================================================================\n Package       Arch           Version                       Repository     Size\n================================================================================\nInstalling:\n httpd         x86_64         2.4.6-67.el7.centos           local         2.7 M\n\nTransaction Summary\n================================================================================\nInstall  1 Package\n\nTotal download size: 2.7 M\nInstalled size: 9.4 M\nDownloading packages:\nRunning transaction check\nRunning transaction test\nTransaction test succeeded\nRunning transaction\n  Installing : httpd-2.4.6-67.el7.centos.x86_64                             1/1 \n  Verifying  : httpd-2.4.6-67.el7.centos.x86_64                             1/1 \n\nInstalled:\n  httpd.x86_64 0:2.4.6-67.el7.centos                                            \n\nComplete!\n"
    ]
}

启动验证
[root@ansible ~]# ansible webservers   -a 'systemctl start httpd'
[root@ansible ~]# ansible webservers   -a 'netstat -utpln |grep 80'
192.168.100.103 | CHANGED | rc=0 >>
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name    
tcp        0      0 0.0.0.0:80              0.0.0.0:*               LISTEN      19935/httpd         
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      856/sshd            
tcp        0      0 127.0.0.1:25            0.0.0.0:*               LISTEN      1009/master         
udp        0      0 127.0.0.1:323           0.0.0.0:*                           637/chronyd         
192.168.100.102 | CHANGED | rc=0 >>
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name    
tcp        0      0 0.0.0.0:80              0.0.0.0:*               LISTEN      6218/httpd          
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      855/sshd            
tcp        0      0 127.0.0.1:25            0.0.0.0:*               LISTEN      1008/master         
udp        0      0 127.0.0.1:323           0.0.0.0:*                           636/chronyd 

卸载httpd

[root@ansible ~]# ansible webservers -m yum -a 'name=httpd state=absent'
192.168.100.103 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "changes": {
        "removed": [
            "httpd"
        ]
    }, 
    "msg": "", 
    "rc": 0, 
    "results": [
        "已加载插件:fastestmirror\n正在解决依赖关系\n--> 正在检查事务\n---> 软件包 httpd.x86_64.0.2.4.6-67.el7.centos 将被 删除\n--> 解决依赖关系完成\n\n依赖关系解决\n\n================================================================================\n Package       架构           版本                         源              大小\n================================================================================\n正在删除:\n httpd         x86_64         2.4.6-67.el7.centos          @local         9.4 M\n\n事务概要\n================================================================================\n移除  1 软件包\n\n安装大小:9.4 M\nDownloading packages:\nRunning transaction check\nRunning transaction test\nTransaction test succeeded\nRunning transaction\n  正在删除    : httpd-2.4.6-67.el7.centos.x86_64                            1/1 \n  验证中      : httpd-2.4.6-67.el7.centos.x86_64                            1/1 \n\n删除:\n  httpd.x86_64 0:2.4.6-67.el7.centos                                            \n\n完毕!\n"
    ]
}
192.168.100.102 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "changes": {
        "removed": [
            "httpd"
        ]
    }, 
    "msg": "", 
    "rc": 0, 
    "results": [
        "已加载插件:fastestmirror\n正在解决依赖关系\n--> 正在检查事务\n---> 软件包 httpd.x86_64.0.2.4.6-67.el7.centos 将被 删除\n--> 解决依赖关系完成\n\n依赖关系解决\n\n================================================================================\n Package       架构           版本                         源              大小\n================================================================================\n正在删除:\n httpd         x86_64         2.4.6-67.el7.centos          @local         9.4 M\n\n事务概要\n================================================================================\n移除  1 软件包\n\n安装大小:9.4 M\nDownloading packages:\nRunning transaction check\nRunning transaction test\nTransaction test succeeded\nRunning transaction\n  正在删除    : httpd-2.4.6-67.el7.centos.x86_64                            1/1 \n  验证中      : httpd-2.4.6-67.el7.centos.x86_64                            1/1 \n\n删除:\n  httpd.x86_64 0:2.4.6-67.el7.centos                                            \n\n完毕!\n"
    ]
}

state       ##状态:
                    directory为目录,不存在则创建
                    touch为文件,不存在则创建,存在则更新其为最后修改时间
                    file即使文件不存在也不创建
                    link创建软链接
                    hard创建硬链接
                    absent删除目录、文件或者取消链接文件
owner       ##属主,后面必须跟上     path        ##目标位置
group       ##属组,后面可以加上      mode   ##文件/目录权限
dest        ##被链接的路径,只应用于state=link的情况

例如

1.创建目录
[root@ansible ~]# ansible webservers -m file -a 'path=/root/app state=directory'
192.168.100.102 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "gid": 0, 
    "group": "root", 
    "mode": "0755", 
    "owner": "root", 
    "path": "/root/app", 
    "size": 6, 
    "state": "directory", 
    "uid": 0
}
192.168.100.103 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "gid": 0, 
    "group": "root", 
    "mode": "0755", 
    "owner": "root", 
    "path": "/root/app", 
    "size": 6, 
    "state": "directory", 
    "uid": 0
}

查看验证
[root@ansible ~]# ansible webservers -m shell -a 'ls -l /root'
192.168.100.102 | CHANGED | rc=0 >>
总用量 196064
-rw-------. 1 root root      1262 1月  23 2019 anaconda-ks.cfg
-rw-r--r--  1 root root   9858504 10月 30 2021 apache-tomcat-9.0.10.tar.gz
drwxr-xr-x  2 root root         6 8月  24 16:42 app
-rw-r--r--  1 root root        19 8月  24 15:48 hello
-rw-r--r--  1 root root 190890122 10月 30 2021 jdk-8u171-linux-x64.tar.gz
-rw-rw-rw-  1 root root        12 8月  24 16:01 name
-rw-rw-rw-  1 root root        10 8月  24 15:58 name.4722.2022-08-24@16:01:49~
192.168.100.103 | CHANGED | rc=0 >>
总用量 196064
-rw-------. 1 root root      1262 1月  23 2019 anaconda-ks.cfg
-rw-r--r--  1 root root   9858504 10月 30 2021 apache-tomcat-9.0.10.tar.gz
drwxr-xr-x  2 root root         6 8月  24 16:42 app
-rw-r--r--  1 root root        19 8月  24 15:48 hello
-rw-r--r--  1 root root 190890122 10月 30 2021 jdk-8u171-linux-x64.tar.gz
-rw-rw-rw-  1 root root        12 8月  24 16:01 name
-rw-rw-rw-  1 root root        10 8月  24 15:58 name.18438.2022-08-24@16:01:49~

2.创建链接文件
[root@ansible ~]# ansible webservers -m file -a 'path=/root/bbb.jpg src=aaa.jpg state=link'
192.168.100.102 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "dest": "/root/bbb.jpg", 
    "gid": 0, 
    "group": "root", 
    "mode": "0777", 
    "owner": "root", 
    "size": 7, 
    "src": "aaa.jpg", 
    "state": "link", 
    "uid": 0
}
192.168.100.103 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "dest": "/root/bbb.jpg", 
    "gid": 0, 
    "group": "root", 
    "mode": "0777", 
    "owner": "root", 
    "size": 7, 
    "src": "aaa.jpg", 
    "state": "link", 
    "uid": 0
}
验证查看
[root@ansible ~]# ansible webservers -m shell -a 'ls -l /root'
192.168.100.102 | CHANGED | rc=0 >>
总用量 196064
-rw-r--r--  1 root root         0 8月  24 16:57 aaa.jpg
lrwxrwxrwx  1 root root         7 8月  24 16:58 bbb.jpg -> aaa.jpg
192.168.100.103 | CHANGED | rc=0 >>
总用量 196064
-rw-r--r--  1 root root         0 8月  24 16:57 aaa.jpg
lrwxrwxrwx  1 root root         7 8月  24 16:58 bbb.jpg -> aaa.jpg

3.删除文件
[root@ansible ~]# ansible webservers -m file -a 'path=/root/name state=absent'
192.168.100.103 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "path": "/root/name", 
    "state": "absent"
}
192.168.100.102 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "path": "/root/name", 
    "state": "absent"
}
查看验证
[root@ansible ~]# ansible webservers -m shell -a 'ls /root/name'
192.168.100.102 | FAILED | rc=2 >>
ls: 无法访问/root/name: 没有那个文件或目录non-zero return code
192.168.100.103 | FAILED | rc=2 >>
ls: 无法访问/root/name: 没有那个文件或目录non-zero return code
name            ##用户名
home            ##家目录位置
shell           ##指定登录shell
uid             ##指定用户uid
state           ##状态,不指定为新建,absent为删除
force           ##强制删除
comment         ##用户的描述信息
createhome      ##是否创建家目录
group           ##指定基本组
groups          ##指定附加组,如果指定为(groups=)表示删除所有组
move_home       ##如果设置为home=时,试图将用户主目录移动到指定的目录
non_unique      ##该选项允许改变非唯一的用户ID值
password        ##指定用户密码
remove          ##在使用state=absent时,行为是userdel -remove一致
system          ##当创建一个用户,设置这个用户是系统用户。这个设置不能跟更改现有用户

例如

1.添加用户
[root@ansible ~]# ansible webservers -m user -a 'name=zhangsan uid=111111'
192.168.100.103 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "comment": "", 
    "create_home": true, 
    "group": 1000, 
    "home": "/home/zhangsan", 
    "name": "zhangsan", 
    "shell": "/bin/bash", 
    "state": "present", 
    "system": false, 
    "uid": 111111
}
192.168.100.102 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "comment": "", 
    "create_home": true, 
    "group": 1000, 
    "home": "/home/zhangsan", 
    "name": "zhangsan", 
    "shell": "/bin/bash", 
    "state": "present", 
    "system": false, 
    "uid": 111111
}

查看验证
[root@ansible ~]# ansible webservers -m shell -a 'cat /etc/passwd |grep zhangsan'
192.168.100.103 | CHANGED | rc=0 >>
zhangsan:x:111111:1000::/home/zhangsan:/bin/bash
192.168.100.102 | CHANGED | rc=0 >>
zhangsan:x:111111:1000::/home/zhangsan:/bin/bash

2.删除用户
[root@ansible ~]# ansible webservers -m user -a 'name=zhangsan state=absent'
192.168.100.103 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "force": false, 
    "name": "zhangsan", 
    "remove": false, 
    "state": "absent"
}
192.168.100.102 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "force": false, 
    "name": "zhangsan", 
    "remove": false, 
    "state": "absent"
}

查看验证
[root@ansible ~]# ansible webservers -m shell -a 'cat /etc/passwd |grep zhangsan'
192.168.100.103 | FAILED | rc=1 >>
non-zero return code
192.168.100.102 | FAILED | rc=1 >>
non-zero return code
name            ##计划任务名称
minute          ##分钟
hour            ##小时
day             ##日
month           ##月
weekday         ##周
job             ##指定运行的命令是什么
reboot          ##任务在重启时运行,不建议使用,建议使用special_time
special_time        ##特殊的时间范围,参数:reboot(重启时),annually(每年),monthly(每月),weekly(每周),daily(每天),hourly(每小时)
state           ##指定状态,present表示添加定时任务,也是默认设置,absent表示删除定时任务
user            ##以哪个用户的身份执行

例如

1.添加计划任务
[root@ansible ~]# ansible webservers -m cron -a 'name="ntp update every 5 min"  minute=*/5 job="/sbin/ntpdate 192.168.100.101 &> /dev/null"'
192.168.100.102 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "envs": [], 
    "jobs": [
        "ntp update every 5 min"
    ]
}
192.168.100.103 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "envs": [], 
    "jobs": [
        "ntp update every 5 min"
    ]
}

验证查看
[root@ansible ~]# ansible webservers -m shell -a 'crontab -l'
192.168.100.103 | CHANGED | rc=0 >>
#Ansible: ntp update every 5 min
*/5 * * * * /sbin/ntpdate 192.168.100.101 &> /dev/null
192.168.100.102 | CHANGED | rc=0 >>
#Ansible: ntp update every 5 min
*/5 * * * * /sbin/ntpdate 192.168.100.101 &> /dev/null

2.删除计划任务
[root@ansible ~]# ansible webservers -m cron -a 'name="ntp update every 5 min" minute=*/5 job="/sbin/ntpdate 192.168.100.101 &> /dev/null" state=absent'
192.168.100.102 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "envs": [], 
    "jobs": []
}
192.168.100.103 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "envs": [], 
    "jobs": []
}

查看验证
[root@ansible ~]# ansible webservers -m shell -a 'crontab -l'
192.168.100.103 | CHANGED | rc=0 >>

192.168.100.102 | CHANGED | rc=0 >>
[root@ansible ~]# ansible webservers -m shell -a 'cat /etc/passwd |grep root'
192.168.100.102 | CHANGED | rc=0 >>
root:x:0:0:root:/root:/bin/bash
operator:x:11:0:operator:/root:/sbin/nologin
192.168.100.103 | CHANGED | rc=0 >>
root:x:0:0:root:/root:/bin/bash
operator:x:11:0:operator:/root:/sbin/nologin
[root@ansible ~]# ansible 192.168.100.102 -m setup
192.168.100.102 | SUCCESS => {
    "ansible_facts": {
        "ansible_all_ipv4_addresses": [
            "192.168.100.102"
        ], 
        "ansible_all_ipv6_addresses": [], 
        "ansible_apparmor": {
            "status": "disabled"
        }, 
        "ansible_architecture": "x86_64", 
        "ansible_bios_date": "07/02/2015", 
        "ansible_bios_version": "6.00", 
        "ansible_cmdline": {
            "BOOT_IMAGE": "/vmlinuz-3.10.0-693.el7.x86_64", 
            "ipv6.disable": "1", 
            "net.ifnames": "0", 
            "quiet": true, 
            "rd.lvm.lv": "centos/swap", 
            "rhgb": true, 
            "ro": true, 
            "root": "/dev/mapper/centos-root"
        }, 
arguments           ##命令行提供额外的参数
enabled             ##设置开机启动
name=               ##服务名称
runlevel            ##开机启动的级别,一般不指定
sleep               ##再重启服务的过程中,是否等待。如在服务关闭以后等待2秒在启动。(定义在剧本中)
state               ##有四种状态,分别为:started--->启动服务,stopped--->停止服务,restarted--->重启服务,reloaded--->重载配置

例如:

1.启动httpd服务
[root@ansible ~]# ansible webservers -m service -a 'name=httpd state=started enabled=true'
192.168.100.102 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "enabled": true, 
    "name": "httpd", 
    "state": "started",
    ...
192.168.100.103 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "enabled": true, 
    "name": "httpd", 
    "state": "started",
    ...

验证查看
[root@ansible ~]# ansible webservers -m shell -a 'ss -ntl'
192.168.100.102 | CHANGED | rc=0 >>
State      Recv-Q Send-Q Local Address:Port               Peer Address:Port              
LISTEN     0      128          *:80                       *:*  
192.168.100.103 | CHANGED | rc=0 >>
State      Recv-Q Send-Q Local Address:Port               Peer Address:Port              
LISTEN     0      128          *:80                       *:*

2.关闭httpd服务
[root@ansible ~]# ansible webservers -m service -a 'name=httpd state=stopped'
192.168.100.102 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "name": "httpd", 
    "state": "stopped",
    ...
192.168.100.103 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "name": "httpd", 
    "state": "stopped", 
    ...

验证查看
[root@ansible ~]# ansible webservers -m shell -a 'ss -ntl|grep 80'
192.168.100.103 | FAILED | rc=1 >>
non-zero return code
192.168.100.102 | FAILED | rc=1 >>
non-zero return code
gid         ##设置组的GID
name=       ##指定组的名称
state=      ##指定组的状态,默认为创建,设置值为absent删除
system=     ##设置为yes,表示创建为系统组

例如:

1.创建组
[root@ansible ~]# ansible web -m group -a 'name=happy gid=12222'
192.168.100.102 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "gid": 12222, 
    "name": "happy", 
    "state": "present", 
    "system": false
}
192.168.100.103 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "gid": 12222, 
    "name": "happy", 
    "state": "present", 
    "system": false
}

验证查看
[root@ansible ~]# ansible web -m shell -a 'cat /etc/group |grep 12222'
192.168.100.102 | CHANGED | rc=0 >>
happy:x:12222:
192.168.100.103 | CHANGED | rc=0 >>
happy:x:12222:

2.删除组
[root@ansible ~]# ansible web -m group -a 'name=happy state=absent'
192.168.100.103 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "name": "happy", 
    "state": "absent"
}
192.168.100.102 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "name": "happy", 
    "state": "absent"
}

验证查看
[root@ansible ~]# ansible web -m shell -a 'cat /etc/group|grep 12222'
192.168.100.102 | FAILED | rc=1 >>
non-zero return code
192.168.100.103 | FAILED | rc=1 >>
non-zero return code
1.编辑脚本
[root@ansible ~]# vi free.sh
#!/bin/bash

date >>/root/free_total.log
free -g >>/root/free_total.log

[root@ansible ~]# chmod +x free.sh
直接运行命令实现在被管理端执行该脚本
[root@ansible ~]# ansible web -m script -a '/root/free.sh'
192.168.100.102 | CHANGED => {
    "changed": true, 
    "rc": 0, 
    "stderr": "Shared connection to 192.168.100.102 closed.\r\n", 
    "stderr_lines": [
        "Shared connection to 192.168.100.102 closed."
    ], 
    "stdout": "", 
    "stdout_lines": []
}
192.168.100.103 | CHANGED => {
    "changed": true, 
    "rc": 0, 
    "stderr": "Shared connection to 192.168.100.103 closed.\r\n", 
    "stderr_lines": [
        "Shared connection to 192.168.100.103 closed."
    ], 
    "stdout": "", 
    "stdout_lines": []
}

验证查看
[root@ansible ~]# ansible web -m shell -a 'cat /root/free_total.log'
192.168.100.102 | CHANGED | rc=0 >>
2022年 08月 25日 星期四 17:19:20 CST
              total        used        free      shared  buff/cache   available
Mem:              0           0           0           0           0           0
Swap:             1           0           1
192.168.100.103 | CHANGED | rc=0 >>
2022年 08月 25日 星期四 17:19:20 CST
              total        used        free      shared  buff/cache   available
Mem:              0           0           0           0           0           0
Swap:             1           0           1
dest            ##用来存放文件的目录
src             ##在远程获取的文件,必须是文件,不能是目录

例如

[root@ansible ~]# ansible web -m fetch -a 'src=/root/202208.file dest=/root'
192.168.100.103 | CHANGED => {
    "changed": true, 
    "checksum": "da39a3ee5e6b4b0d3255bfef95601890afd80709", 
    "dest": "/root/192.168.100.103/root/202208.file", 
    "md5sum": "d41d8cd98f00b204e9800998ecf8427e", 
    "remote_checksum": "da39a3ee5e6b4b0d3255bfef95601890afd80709", 
    "remote_md5sum": null
}
192.168.100.102 | CHANGED => {
    "changed": true, 
    "checksum": "da39a3ee5e6b4b0d3255bfef95601890afd80709", 
    "dest": "/root/192.168.100.102/root/202208.file", 
    "md5sum": "d41d8cd98f00b204e9800998ecf8427e", 
    "remote_checksum": "da39a3ee5e6b4b0d3255bfef95601890afd80709", 
    "remote_md5sum": null
}
可以查看到文件复制成功,要注意,文件保存的路径是我们设置的接收目录下的被管制的主机IP目录下
[root@ansible ~]# ls
192.168.100.102  192.168.100.103