ansible 常用模块

时间:2024-01-27 10:34:51

目录

1.ping模块

 2.command模块

3. shell模块

4.copy模块

5.file模块

 6.fetch模块

7.cron模块

8.yum模块

9.service模块

10.user模块

11.group模块

12.script 模块

 13.setup模块

14. get_url模块

15.stat模块

16.unarchive模块


1.ping模块

使用ansible db1 -m ping 命令进行主机连通性测试

 2.command模块

这个模块可以直接在远程主机上执行命令,并将结果返回本主机。

命令模块接受命令名称,后面是空格分隔的列表参数。给定的命令将在所有选定的节点上执行。它不会通过shell进行处理,比如$HOME和操作如"<",">","|",";","&" 工作(需要使用(shell)模块实现这些功能)。注意,该命令不支持| 管道命令。

chdir  # 在执行命令之前,先切换到该目录

executable # 切换shell来执行命令,需要使用命令的绝对路径

free_form   # 要执行的Linux指令,一般使用Ansible的-a参数代替。

creates   # 一个文件名,当这个文件存在,则该命令不执行,可以用来做判断

removes # 一个文件名,这个文件不存在,则该命令不执行

列举几种,如下:

[root@server ~]# ansible web -m command -a 'chdir=/data/ ls'  #先切换到/data/ 目录,再执行“ls”命令
[root@server ~]# ansible web -m command -a 'creates=/data/aaa.jpg ls'  #如果/data/aaa.jpg存在,则不执行“ls”命令
[root@server ~]# ansible web -m command -a 'removes=/data/aaa.jpg cat /data/a' #如果/data/aaa.jpg存在,则执行“cat /data/a”命令

3. shell模块

shell模块可以在远程主机上调用shell解释器运行命令,支持shell的各种功能,例如管道等

[root@localhost ansible]# ansible web -m shell -a 'cat /etc/passwd |grep "root"'
web1 | CHANGED | rc=0 >>
root:x:0:0:root:/root:/bin/bash
operator:x:11:0:operator:/root:/sbin/nologin
web2 | CHANGED | rc=0 >>
root:x:0:0:root:/root:/bin/bash
operator:x:11:0:operator:/root:/sbin/nologin
apache:x:48:48:Apache:/opt/rh/httpd24/root/usr/share/httpd:/sbin/nologin

4.copy模块

这个模块用于将文件复制到远程主机,同时支持给定内容生成文件和修改权限等。 其相关选项如下:

src #被复制到远程主机的本地文件。可以是绝对路径,也可以是相对路径。如果路径是一个目录,则会递归复制,用法类似于"rsync"

content#用于替换"src",可以直接指定文件的值

dest  #必选项,将源文件复制到的远程主机的绝对路径

backup #当文件内容发生改变后,在覆盖之前把源文件备份,备份文件包含时间信息

directory_mode#递归设定目录的权限,默认为系统默认权限

force#当目标主机包含该文件,但内容不同时,设为"yes",表示强制覆盖;设为"no",表示目标主机的目标位置不存在该文件才复制。默认为"yes"

others #所有的 file 模块中的选项可以在这里使用

 例如:

[root@localhost ansible]# ansible db1 -m copy -a 'src=/etc/passwd dest=/opt'
db1 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "checksum": "f8bfb8bffc9b65bcdb742b0382d602dc53182fa5", 
    "dest": "/opt/passwd", 
    "gid": 0, 
    "group": "root", 
    "md5sum": "4022cc06f1f2fa60d0eecb807417c1c4", 
    "mode": "0644", 
    "owner": "root", 
    "size": 846, 
    "src": "/root/.ansible/tmp/ansible-tmp-1705926026.42-3868-157297171862873/source", 
    "state": "file", 
    "uid": 0
}
[root@localhost ansible]# 

5.file模块

该模块主要用于设置文件的属性,比如创建文件、创建链接文件、删除文件等。 下面是一些常见的命令:

force#需要在两种情况下强制创建软链接,一种是源文件不存在,但之后会建立的情况下;另一种是目标软链接已存在,需要先取消之前的软链,然后创建新的软链,有两个选项:yes|no

group#定义文件/目录的属组。后面可以加上

mode:定义文件/目录的权限

owner#定义文件/目录的属主。后面必须跟上

path:定义文件/目录的路径

recurse#递归设置文件的属性,只对目录有效,后面跟上

src:被链接的源文件路径,只应用于state=link的情况

dest#被链接到的路径,只应用于state=link的情况

state#状态,有以下选项:

directory:如果目录不存在,就创建目录 link:创建软链接 hard:创建硬链接 touch:如果文件不存在,则会创建一个新的文件,如果文件或目录已存在,则更新其最后修改时间 absent:删除目录、文件或者取消链接文件

例如:在db2上的opt目录下创建test.txt文件

[root@localhost ~]# ansible db2 -m file -a 'path=/opt/test.txt state=touch'
db2 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "dest": "/opt/test.txt", 
    "gid": 0, 
    "group": "root", 
    "mode": "0644", 
    "owner": "root", 
    "size": 0, 
    "state": "file", 
    "uid": 0
}
[root@localhost ~]# 

 6.fetch模块

该模块用于从远程某主机获取(复制)文件到本地。 有两个选项:

dest:用来存放文件的目录

src:在远程拉取的文件,并且必须是一个file,不能是目录

例如:从db2服务器复制/etc/passwd到本地的/opt下

[root@localhost ~]# ansible db2 -m fetch -a 'src=/etc/passwd dest=/opt'
db2 | CHANGED => {
    "changed": true, 
    "checksum": "2f4dee438fc22b5c9f4c8ceff8703df5442a9c6e", 
    "dest": "/opt/db2/etc/passwd", 
    "md5sum": "acba6b845a59bdd39e1e6be6c64b408d", 
    "remote_checksum": "2f4dee438fc22b5c9f4c8ceff8703df5442a9c6e", 
    "remote_md5sum": null
}
[root@localhost ~]# ll /opt/db2/etc/
总用量 4
-rw-r--r-- 1 root root 1118 1月  24 16:19 passwd
[root@localhost ~]# 

7.cron模块

该模块适用于管理cron计划任务的。 其使用的语法跟我们的crontab文件中的语法一致,同时,可以指定以下选项:

day= #日应该运行的工作( 1-31, , /2, )

hour= # 小时 ( 0-23, , /2, )

minute= #分钟( 0-59, , /2, )

month= # 月( 1-12, *, /2, )

weekday= # 周 ( 0-6 for Sunday-Saturday,, )

job= #指明运行的命令是什么

name= #定时任务描述

reboot # 任务在重启时运行,不建议使用,建议使用special_time

special_time #特殊的时间范围,参数:reboot(重启时),annually(每年),monthly(每月),weekly(每周),daily(每天),hourly(每小时)

state #指定状态,present表示添加定时任务,也是默认设置,absent表示删除定时任务

user # 以哪个用户的身份执行

例如: 添加一个计划任务

[root@localhost ~]# ansible db2 -m cron -a 'name="同步时间" minute=*/1 job="ntpdate baidu.com" state=present'
db2 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "envs": [], 
    "jobs": [
        "同步时间"
    ]
}
[root@localhost ~]#

删除一个计划任务

[root@localhost ~]# ansible db2 -m cron -a 'name="同步时间" minute=*/1 job="ntpdate baidu.com" state=absent'
db2 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "envs": [], 
    "jobs": []
}
[root@localhost ~]# 

8.yum模块

顾名思义,该模块主要用于软件的安装。 其选项如下:

name= #所安装的包的名称

state=#present--->安装, latest--->安装最新的, absent---> 卸载软件。

update_cache#强制更新yum的缓存

conf_file#指定远程yum安装时所依赖的配置文件(安装本地已有的包)。

disable_gpg_check#是否禁止GPG checking,只用于presentor latest

disablerepo#临时禁止使用yum库。 只用于安装或更新时。

enablerepo #临时使用的yum库。只用于安装或更新时。

下面我们就来安装一个包试试看:

[root@localhost ~]# ansible db2 -m yum -a 'name=net-tools state=present'
db2 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "changes": {
        "installed": [
            "net-tools"
        ]
    }, 
    "msg": "Repository mysql-connectors-community is listed more than once in the configuration\nRepository mysql-tools-community is listed more than once in the configuration\n", 
    "rc": 0, 
    "results": [
        "Loaded plugins: fastestmirror\nLoading mirror speeds from cached hostfile\nResolving Dependencies\n--> Running transaction check\n---> Package net-tools.x86_64 0:2.0-0.25.20131004git.el7 will be installed\n--> Finished Dependency Resolution\n\nDependencies Resolved\n\n================================================================================\n Package         Arch         Version                        Repository    Size\n================================================================================\nInstalling:\n net-tools       x86_64       2.0-0.25.20131004git.el7       mybase       306 k\n\nTransaction Summary\n================================================================================\nInstall  1 Package\n\nTotal download size: 306 k\nInstalled size: 917 k\nDownloading packages:\nRunning transaction check\nRunning transaction test\nTransaction test succeeded\nRunning transaction\n  Installing : net-tools-2.0-0.25.20131004git.el7.x86_64                    1/1 \n  Verifying  : net-tools-2.0-0.25.20131004git.el7.x86_64                    1/1 \n\nInstalled:\n  net-tools.x86_64 0:2.0-0.25.20131004git.el7                                   \n\nComplete!\n"
    ]
}
[root@localhost ~]# 

9.service模块

该模块用于服务程序的管理。

其主要选项如下:

arguments #命令行提供额外的参数 enabled #设置开机启动。 name= #服务名称 runlevel #开机启动的级别,一般不用指定。 sleep #在重启服务的过程中,是否等待。如在服务关闭以后等待2秒再启动。(定义在剧本中。) state #有四种状态,分别为:started--->启动服务, stopped--->停止服务, restarted--->重启服务, reloaded--->重载配置

例如:

① 开启服务并设置自启动

[root@localhost wordpress]# ansible db2 -m service -a 'name=nginx state=started enabled=true'
db2 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "enabled": true, 
    "name": "nginx", 
    "state": "started", 
    "status": {
        "ActiveEnterTimestampMonotonic": "0", 
        "ActiveExitTimestampMonotonic": "0", 
        "ActiveState": "inactive", 
        "After": "system.slice systemd-journald.socket nss-lookup.target basic.target remote-fs.target network-online.target", 
        "AllowIsolate": "no", 
        "AmbientCapabilities": "0", 
        "AssertResult": "no", 
        "AssertTimestampMonotonic": "0", 
        "Before": "shutdown.target", 
        "BlockIOAccounting": "no", 
        "BlockIOWeight": "18446744073709551615", 
        "CPUAccounting": "no", 
        "CPUQuotaPerSecUSec": "infinity", 
        "CPUSchedulingPolicy": "0", 
        "CPUSchedulingPriority": "0", 
        "CPUSchedulingResetOnFork": "no", 
        "CPUShares": "18446744073709551615", 
        "CanIsolate": "no", 
        "CanReload": "yes", 
        "CanStart": "yes", 
        "CanStop": "yes", 
        "CapabilityBoundingSet": "18446744073709551615", 
        "CollectMode": "inactive", 
        "ConditionResult": "no", 
        "ConditionTimestampMonotonic": "0", 
        "Conflicts": "shutdown.target", 
        "ControlPID": "0", 
        "DefaultDependencies": "yes", 
        "Delegate": "no", 
        "Description": "nginx - high performance web server", 
        "DevicePolicy": "auto", 
        "Documentation": "http://nginx.org/en/docs/", 
        "ExecMainCode": "0", 
        "ExecMainExitTimestampMonotonic": "0", 
        "ExecMainPID": "0", 
        "ExecMainStartTimestampMonotonic": "0", 
        "ExecMainStatus": "0", 
        "ExecReload": "{ path=/bin/sh ; argv[]=/bin/sh -c /bin/kill -s HUP $(/bin/cat /var/run/nginx.pid) ; ignore_errors=no ; start_time=[n/a] ; stop_time=[n/a] ; pid=0 ; code=(null) ; status=0/0 }", 
        "ExecStart": "{ path=/usr/sbin/nginx ; argv[]=/usr/sbin/nginx -c /etc/nginx/nginx.conf ; ignore_errors=no ; start_time=[n/a] ; stop_time=[n/a] ; pid=0 ; code=(null) ; status=0/0 }", 
        "ExecStop": "{ path=/bin/sh ; argv[]=/bin/sh -c /bin/kill -s TERM $(/bin/cat /var/run/nginx.pid) ; ignore_errors=no ; start_time=[n/a] ; stop_time=[n/a] ; pid=0 ; code=(null) ; status=0/0 }", 
        "FailureAction": "none", 
        "FileDescriptorStoreMax": "0", 
        "FragmentPath": "/usr/lib/systemd/system/nginx.service", 
        "GuessMainPID": "yes", 
        "IOScheduling": "0", 
        "Id": "nginx.service", 
        "IgnoreOnIsolate": "no", 
        "IgnoreOnSnapshot": "no", 
        "IgnoreSIGPIPE": "yes", 
        "InactiveEnterTimestampMonotonic": "0", 
        "InactiveExitTimestampMonotonic": "0", 
        "JobTimeoutAction": "none", 
        "JobTimeoutUSec": "0", 
        "KillMode": "control-group", 
        "KillSignal": "15", 
        "LimitAS": "18446744073709551615", 
        "LimitCORE": "18446744073709551615", 
        "LimitCPU": "18446744073709551615", 
        "LimitDATA": "18446744073709551615", 
        "LimitFSIZE": "18446744073709551615", 
        "LimitLOCKS": "18446744073709551615", 
        "LimitMEMLOCK": "65536", 
        "LimitMSGQUEUE": "819200", 
        "LimitNICE": "0", 
        "LimitNOFILE": "4096", 
        "LimitNPROC": "14989", 
        "LimitRSS": "18446744073709551615", 
        "LimitRTPRIO": "0", 
        "LimitRTTIME": "18446744073709551615", 
        "LimitSIGPENDING": "14989", 
        "LimitSTACK": "18446744073709551615", 
        "LoadState": "loaded", 
        "MainPID": "0", 
        "MemoryAccounting": "no", 
        "MemoryCurrent": "18446744073709551615", 
        "MemoryLimit": "18446744073709551615", 
        "MountFlags": "0", 
        "Names": "nginx.service", 
        "NeedDaemonReload": "no", 
        "Nice": "0", 
        "NoNewPrivileges": "no", 
        "NonBlocking": "no", 
        "NotifyAccess": "none", 
        "OOMScoreAdjust": "0", 
        "OnFailureJobMode": "replace", 
        "PIDFile": "/var/run/nginx.pid", 
        "PermissionsStartOnly": "no", 
        "PrivateDevices": "no", 
        "PrivateNetwork": "no", 
        "PrivateTmp": "no", 
        "ProtectHome": "no", 
        "ProtectSystem": "no", 
        "RefuseManualStart": "no", 
        "RefuseManualStop": "no", 
        "RemainAfterExit": "no", 
        "Requires": "basic.target system.slice", 
        "Restart": "no", 
        "RestartUSec": "100ms", 
        "Result": "success", 
        "RootDirectoryStartOnly": "no", 
        "RuntimeDirectoryMode": "0755", 
        "SameProcessGroup": "no", 
        "SecureBits": "0", 
        "SendSIGHUP": "no", 
        "SendSIGKILL": "yes", 
        "Slice": "system.slice", 
        "StandardError": "inherit", 
        "StandardInput": "null", 
        "StandardOutput": "journal", 
        "StartLimitAction": "none", 
        "StartLimitBurst": "5", 
        "StartLimitInterval": "10000000", 
        "StartupBlockIOWeight": "18446744073709551615", 
        "StartupCPUShares": "18446744073709551615", 
        "StatusErrno": "0", 
        "StopWhenUnneeded": "no", 
        "SubState": "dead", 
        "SyslogLevelPrefix": "yes", 
        "SyslogPriority": "30", 
        "SystemCallErrorNumber": "0", 
        "TTYReset": "no", 
        "TTYVHangup": "no", 
        "TTYVTDisallocate": "no", 
        "TasksAccounting": "no", 
        "TasksCurrent": "18446744073709551615", 
        "TasksMax": "18446744073709551615", 
        "TimeoutStartUSec": "1min 30s", 
        "TimeoutStopUSec": "1min 30s", 
        "TimerSlackNSec": "50000", 
        "Transient": "no", 
        "Type": "forking", 
        "UMask": "0022", 
        "UnitFilePreset": "disabled", 
        "UnitFileState": "disabled", 
        "Wants": "network-online.target", 
        "WatchdogTimestampMonotonic": "0", 
        "WatchdogUSec": "0"
    }
}
[root@localhost wordpress]# 

  ② 关闭服务

[root@localhost wordpress]# ansible db2 -m service -a 'name=nginx state=stopped'
db2 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "name": "nginx", 
    "state": "stopped", 
    "status": {
        "ActiveEnterTimestamp": "三 2024-01-24 16:48:18 CST", 
        "ActiveEnterTimestampMonotonic": "21799387264", 
        "ActiveExitTimestampMonotonic": "0", 
        "ActiveState": "active", 
        "After": "network-online.target system.slice remote-fs.target nss-lookup.target basic.target systemd-journald.socket", 
        "AllowIsolate": "no", 
        "AmbientCapabilities": "0", 
        "AssertResult": "yes", 
        "AssertTimestamp": "三 2024-01-24 16:48:18 CST", 
        "AssertTimestampMonotonic": "21799357456", 
        "Before": "shutdown.target multi-user.target", 
        "BlockIOAccounting": "no", 
        "BlockIOWeight": "18446744073709551615", 
        "CPUAccounting": "no", 
        "CPUQuotaPerSecUSec": "infinity", 
        "CPUSchedulingPolicy": "0", 
        "CPUSchedulingPriority": "0", 
        "CPUSchedulingResetOnFork": "no", 
        "CPUShares": "18446744073709551615", 
        "CanIsolate": "no", 
        "CanReload": "yes", 
        "CanStart": "yes", 
        "CanStop": "yes", 
        "CapabilityBoundingSet": "18446744073709551615", 
        "CollectMode": "inactive", 
        "ConditionResult": "yes", 
        "ConditionTimestamp": "三 2024-01-24 16:48:18 CST", 
        "ConditionTimestampMonotonic": "21799357455", 
        "Conflicts": "shutdown.target", 
        "ControlGroup": "/system.slice/nginx.service", 
        "ControlPID": "0", 
        "DefaultDependencies": "yes", 
        "Delegate": "no", 
        "Description": "nginx - high performance web server", 
        "DevicePolicy": "auto", 
        "Documentation": "http://nginx.org/en/docs/", 
        "ExecMainCode": "0", 
        "ExecMainExitTimestampMonotonic": "0", 
        "ExecMainPID": "26571", 
        "ExecMainStartTimestamp": "三 2024-01-24 16:48:18 CST", 
        "ExecMainStartTimestampMonotonic": "21799387072", 
        "ExecMainStatus": "0", 
        "ExecReload": "{ path=/bin/sh ; argv[]=/bin/sh -c /bin/kill -s HUP $(/bin/cat /var/run/nginx.pid) ; ignore_errors=no ; start_time=[n/a] ; stop_time=[n/a] ; pid=0 ; code=(null) ; status=0/0 }", 
        "ExecStart": "{ path=/usr/sbin/nginx ; argv[]=/usr/sbin/nginx -c /etc/nginx/nginx.conf ; ignore_errors=no ; start_time=[三 2024-01-24 16:48:18 CST] ; stop_time=[三 2024-01-24 16:48:18 CST] ; pid=26570 ; code=exited ; status=0 }", 
        "ExecStop": "{ path=/bin/sh ; argv[]=/bin/sh -c /bin/kill -s TERM $(/bin/cat /var/run/nginx.pid) ; ignore_errors=no ; start_time=[n/a] ; stop_time=[n/a] ; pid=0 ; code=(null) ; status=0/0 }", 
        "FailureAction": "none", 
        "FileDescriptorStoreMax": "0", 
        "FragmentPath": "/usr/lib/systemd/system/nginx.service", 
        "GuessMainPID": "yes", 
        "IOScheduling": "0", 
        "Id": "nginx.service", 
        "IgnoreOnIsolate": "no", 
        "IgnoreOnSnapshot": "no", 
        "IgnoreSIGPIPE": "yes", 
        "InactiveEnterTimestampMonotonic": "0", 
        "InactiveExitTimestamp": "三 2024-01-24 16:48:18 CST", 
        "InactiveExitTimestampMonotonic": "21799358988", 
        "JobTimeoutAction": "none", 
        "JobTimeoutUSec": "0", 
        "KillMode": "control-group", 
        "KillSignal": "15", 
        "LimitAS": "18446744073709551615", 
        "LimitCORE": "18446744073709551615", 
        "LimitCPU": "18446744073709551615", 
        "LimitDATA": "18446744073709551615", 
        "LimitFSIZE": "18446744073709551615", 
        "LimitLOCKS": "18446744073709551615", 
        "LimitMEMLOCK": "65536", 
        "LimitMSGQUEUE": "819200", 
        "LimitNICE": "0", 
        "LimitNOFILE": "4096", 
        "LimitNPROC": "14989", 
        "LimitRSS": "18446744073709551615", 
        "LimitRTPRIO": "0", 
        "LimitRTTIME": "18446744073709551615", 
        "LimitSIGPENDING": "14989", 
        "LimitSTACK": "18446744073709551615", 
        "LoadState": "loaded", 
        "MainPID": "26571", 
        "MemoryAccounting": "no", 
        "MemoryCurrent": "18446744073709551615", 
        "MemoryLimit": "18446744073709551615", 
        "MountFlags": "0", 
        "Names": "nginx.service", 
        "NeedDaemonReload": "no", 
        "Nice": "0", 
        "NoNewPrivileges": "no", 
        "NonBlocking": "no", 
        "NotifyAccess": "none", 
        "OOMScoreAdjust": "0", 
        "OnFailureJobMode": "replace", 
        "PIDFile": "/var/run/nginx.pid", 
        "PermissionsStartOnly": "no", 
        "PrivateDevices": "no", 
        "PrivateNetwork": "no", 
        "PrivateTmp": "no", 
        "ProtectHome": "no", 
        "ProtectSystem": "no", 
        "RefuseManualStart": "no", 
        "RefuseManualStop": "no", 
        "RemainAfterExit": "no", 
        "Requires": "basic.target system.slice", 
        "Restart": "no", 
        "RestartUSec": "100ms", 
        "Result": "success", 
        "RootDirectoryStartOnly": "no", 
        "RuntimeDirectoryMode": "0755", 
        "SameProcessGroup": "no", 
        "SecureBits": "0", 
        "SendSIGHUP": "no", 
        "SendSIGKILL": "yes", 
        "Slice": "system.slice", 
        "StandardError": "inherit", 
        "StandardInput": "null", 
        "StandardOutput": "journal", 
        "StartLimitAction": "none", 
        "StartLimitBurst": "5", 
        "StartLimitInterval": "10000000", 
        "StartupBlockIOWeight": "18446744073709551615", 
        "StartupCPUShares": "18446744073709551615", 
        "StatusErrno": "0", 
        "StopWhenUnneeded": "no", 
        "SubState": "running", 
        "SyslogLevelPrefix": "yes", 
        "SyslogPriority": "30", 
        "SystemCallErrorNumber": "0", 
        "TTYReset": "no", 
        "TTYVHangup": "no", 
        "TTYVTDisallocate": "no", 
        "TasksAccounting": "no", 
        "TasksCurrent": "18446744073709551615", 
        "TasksMax": "18446744073709551615", 
        "TimeoutStartUSec": "1min 30s", 
        "TimeoutStopUSec": "1min 30s", 
        "TimerSlackNSec": "50000", 
        "Transient": "no", 
        "Type": "forking", 
        "UMask": "0022", 
        "UnitFilePreset": "disabled", 
        "UnitFileState": "enabled", 
        "WantedBy": "multi-user.target", 
        "Wants": "network-online.target", 
        "WatchdogTimestamp": "三 2024-01-24 16:48:18 CST", 
        "WatchdogTimestampMonotonic": "21799387178", 
        "WatchdogUSec": "0"
    }
}
[root@localhost wordpress]# 

10.user模块

该模块主要是用来管理用户账号。 其主要选项如下:

comment# 用户的描述信息

createhome# 是否创建家目录

force# 在使用state=absent时, 行为与userdel –force一致.

group# 指定基本组

groups# 指定附加组,如果指定为(groups=)表示删除所有组

home # 指定用户家目录

move_home# 如果设置为home=时, 试图将用户主目录移动到指定的目录

name# 指定用户名

non_unique# 该选项允许改变非唯一的用户ID值

password# 指定用户密码,对密码加密可以使用python的crypt和passlib

remove# 在使用state=absent时, 行为是与userdel –remove一致

shell# 指定默认shell

state# 设置帐号状态,不指定为创建,指定值为absent表示删除

system# 当创建一个用户,设置这个用户是系统用户。这个设置不能更改现有用户

uid# 指定用户的uid

 ① 添加一个用户并指定其 uid

[root@localhost ~]# ansible db2 -m user -a 'name=keer uid=11111'
db2 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "comment": "", 
    "create_home": true, 
    "group": 11111, 
    "home": "/home/keer", 
    "name": "keer", 
    "shell": "/bin/bash", 
    "state": "present", 
    "system": false, 
    "uid": 11111
}
[root@localhost ~]# 

② 删除用户

注意:这样删除用户,用户的家目录与邮件目录并未删除

[root@localhost ~]# ansible db2 -m user -a 'name=keer uid=11111 state=absent'
db2 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "force": false, 
    "name": "keer", 
    "remove": false, 
    "state": "absent"
}
[root@localhost ~]# 

11.group模块

该模块主要用于添加或删除组。 常用的选项如下:

gid=#设置组的GID号 name=#指定组的名称 state=#指定组的状态,默认为创建,设置值为absent为删除

system=#设置值为yes,表示创建为系统组

例如:

① 创建组

[root@localhost ~]# ansible db2 -m group -a 'name=sanguo gid=12222'
db2 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "gid": 12222, 
    "name": "sanguo", 
    "state": "present", 
    "system": false
}
[root@localhost ~]# 

② 删除组

[root@localhost ~]# ansible db2 -m group -a 'name=sanguo state=absent'
db2 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "name": "sanguo", 
    "state": "absent"
}
[root@localhost ~]# 

12.script 模块

该模块用于将本机的脚本在被管理端的机器上运行。 该模块直接指定脚本的路径即可,我们通过例子来看一看到底如何使用的:

 首先,我们写一个脚本,并给其加上执行权限:

[root@server ~]# vim /tmp/df.sh
    #!/bin/bash
    date >> /tmp/disk_total.log 
    df -lh >> /tmp/disk_total.log 
[root@server ~]# chmod +x /tmp/df.sh 

然后,我们直接运行命令来实现在被管理端执行该脚本:

[root@server ~]# ansible web -m script -a '/tmp/df.sh'
192.168.37.122 | SUCCESS => {
    "changed": true, 
    "rc": 0, 
    "stderr": "Shared connection to 192.168.37.122 closed.\r\n", 
    "stdout": "", 
    "stdout_lines": []
}
192.168.37.133 | SUCCESS => {
    "changed": true, 
    "rc": 0, 
    "stderr": "Shared connection to 192.168.37.133 closed.\r\n", 
    "stdout": "", 
    "stdout_lines": []
}

 13.setup模块

该模块主要用于收集信息,是通过调用facts组件来实现的。 facts组件是Ansible用于采集被管机器设备信息的一个功能,我们可以使用setup模块查机器的所有facts信息,可以使用filter来查看指定信息。整个facts信息被包装在一个JSON格式的数据结构中,ansible_facts是最上层的值。 facts就是变量,内建变量 。每个主机的各种信息,cpu颗数、内存大小等。会存在facts中的某个变量中。调用后返回很多对应主机的信息,在后面的操作中可以根据不同的信息来做不同的操作。如redhat系列用yum安装,而debian系列用apt来安装软件。

① 查看信息

我们可以直接用命令获取到变量的值,具体我们来看看例子:  

[root@server ~]# ansible web -m setup -a 'filter="*mem*"'   #查看内存
192.168.37.122 | SUCCESS => {
    "ansible_facts": {
        "ansible_memfree_mb": 1116, 
        "ansible_memory_mb": {
            "nocache": {
                "free": 1397, 
                "used": 587
            }, 
            "real": {
                "free": 1116, 
                "total": 1984, 
                "used": 868
            }, 
            "swap": {
                "cached": 0, 
                "free": 3813, 
                "total": 3813, 
                "used": 0
            }
        }, 
        "ansible_memtotal_mb": 1984
    }, 
    "changed": false
}
192.168.37.133 | SUCCESS => {
    "ansible_facts": {
        "ansible_memfree_mb": 1203, 
        "ansible_memory_mb": {
            "nocache": {
                "free": 1470, 
                "used": 353
            }, 
            "real": {
                "free": 1203, 
                "total": 1823, 
                "used": 620
            }, 
            "swap": {
                "cached": 0, 
                "free": 3813, 
                "total": 3813, 
                "used": 0
            }
        }, 
        "ansible_memtotal_mb": 1823
    }, 
    "changed": false
}

我们可以通过命令查看一下内存的大小以确认一下是否一致:

[root@server ~]# ansible web -m shell -a 'free -m'
192.168.37.122 | SUCCESS | rc=0 >>
              total        used        free      shared  buff/cache   available
Mem:           1984         404        1122           9         457        1346
Swap:          3813           0        3813

192.168.37.133 | SUCCESS | rc=0 >>
              total        used        free      shared  buff/cache   available
Mem:           1823         292        1207           9         323        1351
Swap:          3813           0        3813

可以看出信息是一致的。

② 保存信息

我们的setup模块还有一个很好用的功能就是可以保存我们所筛选的信息至我们的主机上,同时,文件名为我们被管制的主机的IP,这样方便我们知道是哪台机器出的问题。

我们可以看一看例子:

[root@server tmp]# ansible web -m setup -a 'filter="*mem*"' --tree /tmp/facts
192.168.37.122 | SUCCESS => {
    "ansible_facts": {
        "ansible_memfree_mb": 1115, 
        "ansible_memory_mb": {
            "nocache": {
                "free": 1396, 
                "used": 588
            }, 
            "real": {
                "free": 1115, 
                "total": 1984, 
                "used": 869
            }, 
            "swap": {
                "cached": 0, 
                "free": 3813, 
                "total": 3813, 
                "used": 0
            }
        }, 
        "ansible_memtotal_mb": 1984
    }, 
    "changed": false
}
192.168.37.133 | SUCCESS => {
    "ansible_facts": {
        "ansible_memfree_mb": 1199, 
        "ansible_memory_mb": {
            "nocache": {
                "free": 1467, 
                "used": 356
            }, 
            "real": {
                "free": 1199, 
                "total": 1823, 
                "used": 624
            }, 
            "swap": {
                "cached": 0, 
                "free": 3813, 
                "total": 3813, 
                "used": 0
            }
        }, 
        "ansible_memtotal_mb": 1823
    }, 
    "changed": false
}

然后我们可以去查看一下:

[root@server ~]# cd /tmp/facts/
[root@server facts]# ls
192.168.37.122  192.168.37.133
[root@server facts]# cat 192.168.37.122 
{"ansible_facts": {"ansible_memfree_mb": 1115, "ansible_memory_mb": {"nocache": {"free": 1396, "used": 588}, "real": {"free": 1115, "total": 1984, "used": 869}, "swap": {"cached": 0, "free": 3813, "total": 3813, "used": 0}}, "ansible_memtotal_mb": 1984}, "changed": false}

14. get_url模块

get_url模块
用途: 用于将文件或软件从http、https或ftp下载到本地节点上

常用参数:

dest: 指定将文件下载的绝对路径---必须
url: 文件的下载地址(网址)---必须
url_username: 用于http基本认证的用户名
url_password: 用于http基本认证的密码
validate_certs: 如果否,SSL证书将不会验证。这只应在使用自签名证书的个人控制站点上使用
owner: 指定属主
group: 指定属组
mode: 指定权限

ansible -i /etc/ansible/hosts  zabbix -m get_url -a "url=ftp://10.3.131.50/soft/wechat.py dest=/tmp"

15.stat模块

 用途:检查文件或文件系统的状态
注意:
对于Windows目标,请改用win_stat模块

选项:
path:文件/对象的完整路径(必须)

案例:

name: install_apcu | Check if apcu local file is already configured.
stat: path={{ php_apcu_file_path }}
connection: local
register: php_apcu_file_result
常用的返回值判断:
exists: 判断是否存在
isuid: 调用用户的ID与所有者ID是否匹配

16.unarchive模块

用途:从本地机器上复制存档后,将其解包。
说明:
该unarchive模块将解压缩一个存档。
默认情况下,它将在解包之前将源文件从本地系统复制到目标。
设置remote_src=yes为解包目标上已经存在的档案。
对于Windows目标,请改用win_unzip模块。

常用选项:

dest:远程绝对路径,档案应该被解压缩
exec:列出需要排除的目录和文件
src:指定源
creates:一个文件名,当它已经存在时,这个步骤将不会被运行

 例如:将本机的/root/easy-springmvc-maven.zip解压到web服务器的/tmp目录下

ansible -i /etc/ansible/hosts web -m unarchive -a 'src=/root/easy-springmvc-maven.zip dest=/tmp'

- name: Extract foo.tgz into /var/lib/foo
 unarchive:
   src: foo.tgz
   dest: /var/lib/foo

- name: Unarchive a file that is already on the remote machine
 unarchive:
   src: /tmp/foo.zip
   dest: /usr/local/bin
   remote_src: yes

- name: Unarchive a file that needs to be downloaded (added in 2.0)
 unarchive:
   src: https://example.com/example.zip
   dest: /usr/local/bin
   remote_src: yes