Ansible入门三:【模块】

模块帮助官方文档

一、概述

Ansible 模块是自动化运维的核心执行单元,每一个模块封装了一类标准化运维操作,执行时模块代码会被推送到远程主机运行,完成后自动清理临时文件,无需在远端部署额外客户端。

二.模块分类

模块插件官方文档:

1. 模块官方分类体系

Ansible 官方按照功能维度将模块划分为多个大类,核心类别包括:

  • 系统管理类:主机名、用户组、服务、定时任务、内核参数、磁盘挂载等

  • 文件操作类:文件传输、目录管理、压缩解压、内容编辑等

  • 命令执行类:远程命令、脚本分发执行等

  • 包管理类:yum、apt、dnf 等各发行版软件包与仓库管理

  • 网络设备类:交换机、路由器等网络设备配置管控

  • 云平台类:公有云资源创建与管理

  • 数据库类:各类数据库实例、库表、权限管理

完整模块索引与参数说明可查阅 Ansible 官方文档站点。

2. 幂等性:核心设计原则

幂等性指多次执行同一操作,最终结果与执行一次完全一致,不会因重复执行产生异常或副作用。这是 Ansible 区别于原生 Shell 脚本的核心优势。

  • 具备天然幂等性:copy、file、yum、service、user、cron 等绝大多数业务模块,会先判断当前系统状态,仅在状态不匹配时执行变更。

  • 无天然幂等性:command、shell、script 等命令执行类模块,直接执行命令逻辑,需通过 creates 等参数或业务逻辑自行保证幂等。


三、核心模块

(一)命令执行类模块

1. command 模块

  • 功能定位:Ansible 默认模块(-m 可省略),在目标主机执行简单命令。

  • 核心特性:不通过 Shell 环境执行,不支持管道 |、重定向 >、多命令分隔符 ;、变量解析等 Shell 语法,安全性更高。

  • 幂等性:不具备。但可通过 creates / removes 参数模拟条件判断。

  • 参数

    • cmd:待执行的命令

    • chdir:执行命令前切换到指定工作目录(cd)

    • creates:若指定文件/目录已存在,则跳过命令执行,用于实现幂等(if)

    • removes:若指定文件/目录不存在,则跳过命令执行

  • 示例

    # 查看远程主机名
    ansible 主机组 -m command -a 'hostname'
    
    # creates相当于if语句,用于判断文件或目录是否存在,若不存在才会执行后面的命令
    [root@Ans-prometheus /etc/ansible]# ansible consul1 -m command -a 'creates=/root/consul mkdir consul'
    10.0.0.71 | CHANGED | rc=0 >>
    
    [root@Ans-prometheus /etc/ansible]# ansible consul1 -m command -a 'creates=/root/consul mkdir agent'
    10.0.0.71 | SUCCESS | rc=0 >>
    skipped, since /root/consul existsDid not run command since '/root/consul' exists
    
    # 切换目录并创建文件(带幂等判断)
    ansible 主机组 -m command -a 'chdir=/opt creates=/opt/test.txt touch test.txt'
    
    # 不支持重定向
    ansible 10.0.0.71 -m command -a 'echo https://www.cnblogs.com/ > blog.txt'
    10.0.0.71 | CHANGED | rc=0 >>
    https://www.cnblogs.com > blog.txt
    
    
    
    # 不支持管道符号
    ansible 10.0.0.71 -m command -a 'echo 10+20|bc'
    10.0.0.71 | CHANGED | rc=0 >>
    10+20|bc 
    
    # 不支持同时执行多条命令
    ansible 10.0.0.71 -m command -a 'date;id'
    10.0.0.71 | FAILED | rc=2 >>
    [Errno 2] No such file or directory: b'date;id'
    

2. shell 模块

  • 功能定位:通过系统 shell 执行命令,支持管道、重定向等复杂语法。

  • 核心特性:功能强于 command,但缺乏幂等性,多次执行可能报错(如 mkdir 重复执行)。

  • 最佳实践:对于非常复杂的多行指令,建议先编写脚本,再通过 scriptcopy + shell 执行,提高可维护性。

  • 核心参数:与 command 模块一致,同样支持 chdircreatesremoves 等幂等控制参数。

  • 示例

    # 管道运算
    ansible 主机组 -m shell -a 'echo 10+20 | bc'
    
    # 多条命令连续执行
    ansible 主机组 -m shell -a 'date && id && hostname'
    
    # 内容重定向写入文件
    ansible 主机组 -m shell -a "cat /var/log/messages | grep ERROR > /tmp/error.log"
    
    # 还原ansible原理【在ansible执行过程中,去对应的/tmp目录下查看数据】
    	- 运行命令
    [root@Ans-prometheus /etc/ansible]# ansible 10.0.0.71 -m shell -a 'sleep 60; echo successfully'
    10.0.0.71 | CHANGED | rc=0 >>
    successfully
    
    	- 远端主机查看
    [root@Ans-prometheus /etc/ansible]# cat /tmp/ansible-tmp-1736267242.7051392-44872-55740912527729/AnsiballZ_command.py 
    ...
        ANSIBALLZ_PARAMS = '{"ANSIBLE_MODULE_ARGS": {"_raw_params": "sleep 60; echo successfully", "...
    
    	- 可以保留远端主机的Python脚本,默认是删除,可以调整为保留
    [root@Ans-prometheus /etc/ansible]# vim /etc/ansible/ansible.cfg 
    ...
    keep_remote_files=True
    

3. script 模块

  • 功能定位:将管控端本地的脚本传输到远程主机并执行,支持 Shell、Python 等所有远端可运行的脚本类型。

  • 核心特性:脚本仅需存放在 Ansible 控制端,无需提前分发;脚本本身无需赋予执行权限。

  • 典型用法

    # 执行本地 Shell 脚本
    ansible 主机组 -m script -a '/data/scripts/health_check.sh'
    
    # 执行本地 Python 脚本
    ansible 主机组 -m script -a '/data/scripts/monitor_collect.py' # 远程主机需有 python3
    

(二)文件管理类模块

4. copy 模块

  • 功能定位:将控制端的文件/目录复制到远程主机,支持权限、属主配置。

  • 核心特性:天然幂等,通过校验文件 checksum 判断是否需要覆盖,内容无变化则不执行传输。

  • 核心参数

    • src:控制端源文件/目录路径

    • dest:远端目标绝对路径

    • owner / group:目标文件属主、属组

    • mode:文件权限,推荐写 4 位八进制(如 0644

    • content:直接指定文件内容,替代 src 生成文件

    • backup:覆盖前备份原文件

  • 典型用法

    # 复制本地文件到远端
    ansible 主机组 -m copy -a 'src=/etc/hosts dest=/tmp/hosts.bak mode=0644'
    
    # 直接生成脚本文件
    ansible 主机组 -m copy -a 'content="#!/bin/bash\necho hello" dest=/tmp/start.sh mode=0755'
    

5. fetch 模块

  • 功能定位:与 copy 反向,将远程主机的单个文件拉取到 Ansible 控制端。

  • 核心特性:仅支持拉取文件,不支持直接拉取目录;自动按主机名创建子目录,避免多主机文件重名覆盖。

  • 核心参数

    • src:目的端文件

    • dest:控制端路径

  • 典型用法

    [root@Ans-prometheus /etc/ansible]# ansible consul -m fetch -a "src=/etc/hostname dest=/data/ansible"
    10.0.0.73 | CHANGED => {
        "changed": true,
        "checksum": "27a04745ee10530b058518a9b477b6a0e6927e9f",
        "dest": "/data/ansible/10.0.0.73/etc/hostname",
        "md5sum": "c0788e5f4350591c1e387697a3086f62",
        "remote_checksum": "27a04745ee10530b058518a9b477b6a0e6927e9f",
        "remote_md5sum": null
    }
    10.0.0.72 | CHANGED => {
        "changed": true,
        "checksum": "954ef1e82606877121f7288533d5bd915005b76b",
        "dest": "/data/ansible/10.0.0.72/etc/hostname",
        "md5sum": "3bae593db65aec07ac8f0cd44bf18e6c",
        "remote_checksum": "954ef1e82606877121f7288533d5bd915005b76b",
        "remote_md5sum": null
    }
    10.0.0.71 | CHANGED => {
        "changed": true,
        "checksum": "f9af23c5a5b8293ae2a55a46bb7a5834fde576a6",
        "dest": "/data/ansible/10.0.0.71/etc/hostname",
        "md5sum": "5d46db18826bf5e5751085da7b27c93c",
        "remote_checksum": "f9af23c5a5b8293ae2a55a46bb7a5834fde576a6",
        "remote_md5sum": null
    }
    [root@Ans-prometheus /etc/ansible]# tree /data/ansible/
    /data/ansible/
    ├── 10.0.0.71
    │   └── etc
    │       └── hostname
    ├── 10.0.0.72
    │   └── etc
    │       └── hostname
    └── 10.0.0.73
        └── etc
            └── hostname
    
    6 directories, 3 files
    [root@Ans-prometheus /etc/ansible]# cat /data/ansible/10.0.0.71/etc/hostname
    consul1
    [root@Ans-prometheus /etc/ansible]# cat /data/ansible/10.0.0.72/etc/hostname
    consul2
    [root@Ans-prometheus /etc/ansible]# cat /data/ansible/10.0.0.73/etc/hostname
    consul3
    [root@Ans-prometheus /etc/ansible]#
    

6. get_url 模块

  • 功能定位:在远程主机直接下载网络资源,支持 HTTP/HTTPS/FTP 协议。

  • 核心特性:支持校验和验证;文件已存在且校验和匹配时自动跳过,实现幂等。

  • 核心参数

    • url:资源下载地址

    • dest:远端保存路径

    • checksum:文件校验和,格式如 md5:xxxsha256:xxx

    • validate_certs:是否校验 SSL 证书

  • 典型用法

    # 基础下载
    ansible 主机组 -m get_url -a 'url=https://example.com/pkg.tar.gz dest=/tmp/'
    
    # 带 MD5 校验下载
    ansible 主机组 -m get_url -a 'url=https://example.com/pkg.tar.gz dest=/tmp/ checksum=md5:314b16...'
    

7. file 模块

  • 功能定位:管理远程主机的文件、目录、软链接,支持创建、删除、属性修改。

  • 核心特性:完全幂等,通过 state 参数定义目标状态。

  • 核心参数

    • path:目标文件/目录路径

    • state:目标状态

      • directory:创建目录(支持递归)

      • touch:创建空文件

      • link / hard:创建软/硬链接

      • absent:递归删除文件/目录

    • owner / group / mode:属主、属组、权限

    • recurse:递归设置目录内所有文件属性

  • 典型用法

    # 递归创建目录并设置属主
    ansible 主机组 -m file -a 'path=/data/app state=directory owner=app group=app mode=0755 recurse=yes'
    
    # 创建软链接
    ansible 主机组 -m file -a 'src=/data/app/logs dest=/var/log/app state=link'
    
    # 删除目录
    ansible 主机组 -m file -a 'path=/tmp/old_cache state=absent'
    

8. stat 模块

  • 功能定位:获取远程文件的详细状态信息,等价于 Linux stat 命令。

  • 核心特性:仅采集信息,不做任何变更,常用于 Playbook 条件判断。

  • 典型用法

    [root@Ans-prometheus /etc/ansible]# ansible consul1 -m stat -a "path=/etc/passwd"
    10.0.0.71 | SUCCESS => {
        "changed": false,
        "stat": {
            "atime": 1785847588.5319998,
            "attr_flags": "e",
            "attributes": [
                "extents"
            ],
            "block_size": 4096,
            "blocks": 8,
            "charset": "us-ascii",
            "checksum": "730fbbfad07876867dbe57c8cb53b517a2603cb7",
            "ctime": 1782641767.8743956,
            "dev": 2050,
            "device_type": 0,
            "executable": false,
            "exists": true,
            "gid": 0,
            "gr_name": "root",
            "inode": 393810,
            "isblk": false,
            "ischr": false,
            "isdir": false,
            "isfifo": false,
            "isgid": false,
            "islnk": false,
            "isreg": true,
            "issock": false,
            "isuid": false,
            "mimetype": "text/plain",
            "mode": "0644",
            "mtime": 1782641767.8743956,
            "nlink": 1,
            "path": "/etc/passwd",
            "pw_name": "root",
            "readable": true,
            "rgrp": true,
            "roth": true,
            "rusr": true,
            "size": 1963,
            "uid": 0,
            "version": "1019670601",
            "wgrp": false,
            "woth": false,
            "writeable": true,
            "wusr": true,
            "xgrp": false,
            "xoth": false,
            "xusr": false
        }
    }
    
    
  • 返回信息包含:文件是否存在、大小、权限、属主、inode、修改时间、是否为软链接等。

9. archive 模块

  • 功能定位:在远程主机上对文件/目录进行打包压缩,支持 zip、tar、bz2 等格式。

  • 说明:属于社区模块,ansible-core 版本默认不包含,需安装 community.general 集合。

  • 安装命令ansible-galaxy collection install community.general

  • 典型用法

      # 打包为 zip 格式
      [root@Ans-prometheus /etc/ansible]# ansible consul1 -m archive -a "path=/etc/hosts dest=/data/hosts.zip format=zip"
    10.0.0.71 | CHANGED => {
        "archived": [
            "/etc/hosts"
        ],
        "arcroot": "/etc/",
        "changed": true,
        "dest": "/data/hosts.zip",
        "dest_state": "archive",
        "expanded_exclude_paths": [],
        "expanded_paths": [
            "/etc/hosts"
        ],
        "gid": 0,
        "group": "root",
        "missing": [],
        "mode": "0644",
        "owner": "root",
        "size": 253,
        "state": "file",
        "uid": 0
    }
    
    ---
    [root@consul1 /data]# ll
    total 40
    drwxr-xr-x  6 root   root    4096 Aug  4 23:10 ./
    drwxr-xr-x 21 root   root    4096 Jun  9 23:02 ../
    drwxr-xr-x  2 root   root    4096 Jun 28 18:15 ans/
    drwxr-xr-x  3 consul consul  4096 Jun 10 22:30 consul/
    -rw-r--r--  1 root   root     253 Aug  4 23:10 hosts.zip
    
    

10. unarchive 模块

  • 功能定位:将压缩包解压到远程主机指定目录,要求远程主机有相应解压工具(如 unzip)

  • 核心特性:支持两种模式:将控制端压缩包传到远端再解压;直接解压远端本地/远程 URL 的压缩包。

  • 核心参数

    • src:压缩包路径(本地、远端、URL 均可)

    • dest:远端解压目标目录(必须已存在)

    • remote_src:设为 yes 表示 src 是远端路径/URL

      [root@Ans-prometheus /etc/ansible]# ansible consul1 -m unarchive -a "src=/data/hosts.zip dest=/tmp/ remote_src=yes"
      10.0.0.71 | FAILED! => {
          "changed": false,
          "msg": "Failed to find handler for \"/data/hosts.zip\". Make sure the required command to extract the file is installed.\nUnable to find required 'unzip' or 'unzip' binary in the path.\nCommand \"/usr/bin/tar\" could not handle archive: Unable to list files in the archive: tar (child): bzip2: Cannot exec: No such file or directory\ntar (child): Error is not recoverable: exiting now\n/usr/bin/tar: Child returned status 2\n/usr/bin/tar: Error is not recoverable: exiting now\n\nCommand \"/usr/bin/tar\" could not handle archive: Unable to list files in the archive: xz: (stdin): File format not recognized\n/usr/bin/tar: Child returned status 1\n/usr/bin/tar: Error is not recoverable: exiting now\n\nCommand \"/usr/bin/tar\" could not handle archive: Unable to list files in the archive: zstd: /*stdin*\\: unsupported format \n/usr/bin/tar: Child returned status 1\n/usr/bin/tar: Error is not recoverable: exiting now\n\nCommand \"/usr/bin/tar\" could not handle archive: Unable to list files in the archive: /usr/bin/tar: This does not look like a tar archive\n/usr/bin/tar: Exiting with failure status due to previous errors\n\nCommand \"/usr/bin/tar\" found no files in archive. Empty archive files are not supported.\nUnable to find required 'unzip' or 'zipinfo' binary in the path."
      }
      
  • 典型用法

     # 解压远程压缩包到远端
    [root@Ans-prometheus /etc/ansible]# ansible consul1 -m unarchive -a "src=/data/hosts.zip dest=/opt/ remote_src=yes"
    10.0.0.71 | CHANGED => {
       "changed": true,
       "dest": "/opt/",
       "extract_results": {
           "cmd": [
               "/usr/bin/unzip",
               "-o",
               "/data/hosts.zip",
               "-d",
               "/opt"
           ],
           "err": "",
           "out": "Archive:  /data/hosts.zip\n  inflating: /opt/hosts              \n",
           "rc": 0
       },
       "gid": 0,
       "group": "root",
       "handler": "ZipArchive",
       "mode": "0755",
       "owner": "root",
       "size": 4096,
       "src": "/data/hosts.zip",
       "state": "directory",
       "uid": 0
    }
    
    ---
    
    [root@consul1 /data]# ll /opt/
    total 12
    drwxr-xr-x  2 root root 4096 Aug  4 23:13 ./
    drwxr-xr-x 21 root root 4096 Jun  9 23:02 ../
    -rw-r--r--  1 root root  222 Jun  9 23:09 hosts
    [root@consul1 /data]# cat /opt/hosts
    127.0.0.1 localhost
    127.0.1.1 consul1
    
    # The following lines are desirable for IPv6 capable hosts
    ::1     ip6-localhost ip6-loopback
    fe00::0 ip6-localnet
    ff00::0 ip6-mcastprefix
    ff02::1 ip6-allnodes
    ff02::2 ip6-allrouters
    
    ---
    
    # 解压本地压缩包到远端
    [root@Ans-prometheus /etc/ansible]# ansible consul1 -m unarchive -a "src=/data/hostname.tar.gz  dest=/opt/"
    10.0.0.71 | CHANGED => {
       "changed": true,
       "dest": "/opt/",
       "extract_results": {
           "cmd": [
               "/usr/bin/tar",
               "--extract",
               "-C",
               "/opt",
               "-z",
               "-f",
               "/root/.ansible/tmp/ansible-tmp-1785857052.8750021-2599-46205835028719/source"
           ],
           "err": "",
           "out": "",
           "rc": 0
       },
       "gid": 0,
       "group": "root",
       "handler": "TgzArchive",
       "mode": "0755",
       "owner": "root",
       "size": 4096,
       "src": "/root/.ansible/tmp/ansible-tmp-1785857052.8750021-2599-46205835028719/source",
       "state": "directory",
       "uid": 0
    }
    ---
    
    [root@consul1 /opt]# ll
    total 16
    drwxr-xr-x  3 root root 4096 Aug  4 23:24 ./
    drwxr-xr-x 21 root root 4096 Jun  9 23:02 ../
    drwxr-xr-x  2 root root 4096 Aug  4 23:24 etc/
    -rw-r--r--  1 root root  222 Jun  9 23:09 hosts
    [root@consul1 /opt]# cat etc/hostname
    Ans-prometheus
    
     # 直接下载并解压远程压缩包
     ansible 主机组 -m unarchive -a 'src=https://example.com/nginx.zip dest=/opt/ remote_src=yes'
    

(三)系统管理类模块

11. hostname 模块

  • 功能定位:修改远程主机名,永久生效(会写入 /etc/hostname 或调用 hostnamectl)。

  • 典型用法

    ansible 10.0.0.1 -m hostname -a 'name=web-node01'
    

12. cron 模块

  • 功能定位:管理 crontab 定时任务,支持增删改、环境变量配置。

  • 核心特性:幂等,通过 name 唯一标识任务,重复执行不会重复添加。

  • 核心参数

    • name:任务名称(必填,用于唯一标识)

    • job:待执行的命令

    • minute / hour / day / month / weekday:时间字段,默认 *

    • user:指定任务所属用户

    • statepresent(创建/修改)、absent(删除)

    • disabled:设为 yes 注释掉而不删除。

    • env:设为 yes 表示配置环境变量而非定时任务

  • 典型用法

    # 创建每分钟执行的任务
    ansible 主机组 -m cron -a 'name="时间同步" job="/usr/sbin/ntpdate ntp.aliyun.com"'
    
    # 工作日凌晨2点执行日志清理
    ansible 主机组 -m cron -a 'name="日志清理" job="/scripts/clean_log.sh" minute=0 hour=2 weekday=1-5'
    
    # 删除指定任务
    ansible 主机组 -m cron -a 'name="日志清理" state=absent'
    

13. service 模块

  • 功能定位:管理系统服务,支持启动、停止、重启、重载与开机自启配置。

  • 核心特性:幂等,自动适配 systemd、sysvinit 等不同服务管理体系。

  • 核心参数

    • name:服务名称

    • state:服务状态:started / stopped / restarted / reloaded

    • enabled:是否开机自启,yes / no

  • 典型用法

    # 启动服务并设为开机自启
    ansible 主机组 -m service -a 'name=nginx state=started enabled=yes'
    
    # 重启服务
    ansible 主机组 -m service -a 'name=nginx state=restarted'
    

14. user 模块

  • 功能定位:管理系统用户,支持创建、删除、属性修改、密码配置、密钥生成。

  • 核心参数

    • name:用户名

    • uid:指定 UID

    • group:主组

    • groups:附加组

    • home:家目录路径

    • shell:登录 Shell

    • system:设为 yes 创建系统用户

    • password:加密后的密码(需通过 openssl passwd -6 生成)

    • generate_ssh_key:设为 yes 自动生成 SSH 密钥对

    • statepresent / absent

  • 典型用法

    # 创建普通业务用户
    ansible 主机组 -m user -a 'name=deploy uid=1001 home=/home/deploy shell=/bin/bash'
    
    # 创建无登录权限的系统用户
    ansible 主机组 -m user -a 'name=www system=yes create_home=no shell=/sbin/nologin'
    

15. group 模块

  • 功能定位:管理系统用户组。

  • 典型用法

    ansible 主机组 -m group -a 'name=devops gid=2000'
    

16. reboot 模块

  • 功能定位:重启远程主机,并等待主机重启恢复连接。

  • 核心参数

    • pre_reboot_delay:重启前等待秒数

    • msg:发送给终端用户的重启提示

    • reboot_timeout:等待重启超时时间

  • 典型用法

    ansible consul1 -m reboot -a 'pre_reboot_delay=60 msg="系统将在60秒后重启,请保存工作"'
    
    ---
    [root@consul1 /opt]#
    Broadcast message from root@consul1 on pts/1 (Tue 2026-08-04 23:37:41 CST):
    
    系统将在60秒后重启,请保存工作
    The system is going down for reboot at Tue 2026-08-04 23:38:41 CST!
    
    

17. mount 模块

  • 功能定位:管理磁盘挂载,支持临时挂载与永久写入 fstab。

  • 核心参数

    • src:挂载源设备

    • path:挂载点

    • fstype:文件系统类型(xfs、ext4 等)

    • state

      • mounted:永久挂载(写入 fstab 并立即生效)

      • unmounted:临时卸载(不修改 fstab)

      • absent:永久卸载(移除 fstab 并卸载)

  • 典型用法

    # 永久挂载数据盘
    ansible 主机组 -m mount -a 'src=/dev/data/lv_app path=/data/app fstype=xfs state=mounted'
    

18. selinux 模块

  • 功能定位:管理 RHEL/CentOS 系列系统的 SELinux 状态。

  • 说明:属于 ansible.posix 集合,ansible-core 需单独安装:ansible-galaxy collection install ansible.posix

  • 典型用法

    ansible 主机组 -m selinux -a 'state=disabled policy=targeted'
    

19. sysctl 模块

  • 功能定位:管理 Linux 内核参数,同时修改运行时状态与 /etc/sysctl.conf 配置。

  • 典型用法

    ansible 主机组 -m sysctl -a 'name=net.ipv4.ip_forward value=1'
    

20. pam_limits 模块

  • 功能定位:管理系统资源限制(/etc/security/limits.conf)。

  • 典型用法

    ansible 主机组 -m pam_limits -a 'domain=deploy limit_type=hard limit_item=nofile value=65535'
    

(四)软件包与仓库管理类

21. yum 模块

  • 功能定位:RHEL/CentOS/Rocky 等发行版的软件包管理。

  • 核心参数

    • name:软件包名,可指定版本

    • statepresent(安装)、absent(卸载)、latest(升级到最新)

    • enablerepo:临时启用指定仓库

    • disable_gpg_check:禁用 GPG 校验

  • 典型用法

    # 安装 Nginx
    ansible 主机组 -m yum -a 'name=nginx state=present'
    
    # 从指定源安装软件
    ansible 主机组 -m yum -a 'name=zabbix-agent enablerepo=zabbix state=present'
    

22. yum_repository 模块

  • 功能定位:管理 yum 软件仓库配置。

  • 典型用法

    ansible 主机组 -m yum_repository -a 'name=nginx description="Nginx Stable Repo" baseurl="http://nginx.org/packages/centos/$releasever/$basearch/" gpgcheck=1 enabled=1 gpgkey=https://nginx.org/keys/nginx_signing.key'
    

23. apt 模块

  • 功能定位:Debian/Ubuntu 系列的软件包管理。

  • 核心参数

    • update_cache:设为 yes 等价于 apt update

    • autoclean:清理本地缓存

  • 典型用法

    # 更新源并安装 Nginx
    ansible 主机组 -m apt -a 'name=nginx update_cache=yes state=present'
    

24. apt_repository 模块

  • 功能定位:管理 apt 软件源配置。

  • 典型用法

    ansible 主机组 -m apt_repository -a 'repo="deb [arch=amd64 signed-by=/etc/apt/keyrings/docker.gpg] https://mirrors.aliyun.com/docker-ce/linux/ubuntu jammy stable" filename=docker-ce'
    

25. apt_key 模块

  • 功能定位:管理 apt 软件源的 GPG 密钥。

  • 典型用法

    ansible 主机组 -m apt_key -a 'url=https://nginx.org/keys/nginx_signing.key state=present'
    

(五)文件内容编辑类

26. lineinfile 模块

  • 功能定位:按行编辑文件,支持替换、插入、删除指定行,是轻量配置修改的首选模块。

  • 核心特性:基于正则匹配行;替换时仅修改最后一行匹配项,删除时移除所有匹配行。

  • 核心参数

    • path:目标文件路径

    • regexp:匹配行的正则表达式

    • line:替换/插入的内容

    • insertafter / insertbefore:在匹配行之后/之前插入

    • backrefs:开启正则后向引用,支持 \1 分组引用

    • backup:修改前备份文件

    • create:文件不存在时自动创建

  • 典型用法

    # 禁用 root 远程登录
    ansible 主机组 -m lineinfile -a 'path=/etc/ssh/sshd_config regexp="^PermitRootLogin" line="PermitRootLogin no"'
    
    # 删除指定配置行
    ansible 主机组 -m lineinfile -a 'path=/etc/profile regexp="^export TEST" state=absent'
    
    	1.替换案例
    		1.1 远程主机准备数据
    [root@consul1 ]# cat /tmp/test.txt
    aaa
    bbb
    xixi-123
    haha-456
    hehe-789
    hehe-111
    
    		1.2 替换一行的内容
    [root@Ans-prometheus ]# ansible 10.0.0.71 -m lineinfile -a 'path=/tmp/test.txt regexp="^hehe" line="vovo"'
    
    		1.3 查看远程主机数据
    [root@consul1 ]# cat /tmp/test.txt
    aaa
    bbb
    xixi-123
    haha-456
    hehe-789
    vovo
    
    	2.新增案例
    		2.1 行位新增一行内容【注意,对于两次新增行的内容还不能一样】
    [root@Ans-prometheus ]# ansible 10.0.0.71 -m lineinfile -a 'path=/tmp/test.txt line="ccc-123"'
    
    		2.2 查看远程主机数据
    [root@consul1 ]# cat /tmp/test.txt
    aaa
    bbb
    xixi-123
    haha-456
    hehe-789
    vovo
    ccc-123
    
    	3.在锚定行的上一行添加数据
    		3.1 在锚定行的上方插入数据
    [root@Ans-prometheus ]# ansible 10.0.0.71 -m lineinfile -a 'path=/tmp/test.txt insertbefore="^hehe" line="AAAAA"'
    
    
    		3.2 查看远程主机数据
    [root@consul1 ]# cat /tmp/test.txt
    aaa
    bbb
    xixi-123
    haha-456
    AAAAA
    hehe-789
    vovo
    ccc-123
    
    	4.在锚定行的下一行添加数据
    		4.1 在锚定行的下方插入数据
    [root@Ans-prometheus ]# ansible 10.0.0.71 -m lineinfile -a 'path=/tmp/test.txt insertafter="^hehe" line="BBBBB"'
    
    		4.2 查看远程主机数据
    [root@consul1 ]# cat /tmp/test.txt
    aaa
    bbb
    xixi-123
    haha-456
    AAAAA
    hehe-789
    BBBBB
    vovo
    ccc-123
    
    	5.删除文件中的行
    		5.1 删除行会匹配所有的行,删除时可以进行备份
    [root@Ans-prometheus ]# ansible 10.0.0.71 -m lineinfile -a 'path=/tmp/test.txt regexp="123$" backup=yes state=absent'
    10.0.0.71 | CHANGED => {
        "ansible_facts": {
            "discovered_interpreter_python": "/usr/bin/python3"
        },
        "backup": "/tmp/test.txt.5809.2025-01-11@10:37:24~",
        "changed": true,
        "found": 2,
        "msg": "2 line(s) removed"
    }
    
    		5.2 查看远程主机数据
    [root@consul1 ]# cat /tmp/test.txt
    aaa
    bbb
    haha-456
    AAAAA
    hehe-789
    BBBBB
    vovo
    
    		5.3 查看备份的文件内容【备份文件参考删除时"backup"的输出内容】
    [root@consul1 ]# cat /tmp/test.txt.5809.2025-01-11@10:37:24~
    aaa
    bbb
    xixi-123
    haha-456
    AAAAA
    hehe-789
    BBBBB
    vovo
    ccc-123
    
    	6.新增行时文件不存在自动创建新文件
    		6.1 文件不存在,则创建新文件
    [root@Ans-prometheus ]# ansible 10.0.0.71 -m lineinfile -a 'path=/tmp/demo.log line="hello world" create=yes mode=600'
    
    		6.2 查看远程主机数据
    [root@consul1 ]# ll /tmp/demo.log 
    -rw------- 1 root root 16 Jan 11 10:40 /tmp/demo.log
    [root@consul1 ]# cat  /tmp/demo.log 
    hello world
    
    	7.正则匹配后向引用
    		7.1 查看修改前远程主机数据
    [root@consul1 ]# cat /tmp/test.txt
    aaa
    bbb
    haha-456
    AAAAA
    hehe-789
    BBBBB
    vovo
    ccc-123
            
            
            7.2 正则匹配后向引用
    [root@Ans-prometheus ]# ansible 10.0.0.71 -m lineinfile -a "path=/tmp/test.txt regexp='^haha(.*)$' backrefs=yes line='哈哈\1'"
    
    
    		7.3 再次查看远程主机数据
    [root@consul1 ]# cat /tmp/test.txt
    aaa
    bbb
    哈哈-456
    AAAAA
    hehe-789
    BBBBB
    vovo
    ccc-123
    

27. replace 模块

  • 功能定位:基于正则的全文内容替换,支持跨行匹配,批量替换所有匹配项,与 lineinfile 的区别:用于多行匹配并替换,

  • 核心参数

    • regexp:匹配正则

    • replace:替换后的内容

    • before / after:仅替换指定区间内的内容

  • 典型用法

    # 全文替换端口号
    ansible 主机组 -m replace -a 'path=/etc/nginx/nginx.conf regexp="80" replace="8080"'
    

(六)信息采集与调试类

28. setup 模块

  • 功能定位:采集远程主机的全量系统信息(Facts),包括硬件、操作系统、网络、环境变量等。

  • 核心参数filter 过滤指定字段,支持通配符。

  • 典型用法

    # 采集全部系统信息
    ansible 主机组 -m setup
    
    # 仅查看主机名与 IP 地址
    [root@Ans-prometheus /etc/ansible]# ansible consul -m setup -a 'filter=ansible_hostname,ansible_all_ipv4_addresses'
    10.0.0.71 | SUCCESS => {
        "ansible_facts": {
            "ansible_all_ipv4_addresses": [
                "10.0.0.71"
            ],
            "ansible_hostname": "consul1"
        },
        "changed": false
    }
    10.0.0.72 | SUCCESS => {
        "ansible_facts": {
            "ansible_all_ipv4_addresses": [
                "10.0.0.72"
            ],
            "ansible_hostname": "consul2"
        },
        "changed": false
    }
    10.0.0.73 | SUCCESS => {
        "ansible_facts": {
            "ansible_all_ipv4_addresses": [
                "10.0.0.73"
            ],
            "ansible_hostname": "consul3"
        },
        "changed": false
    }
    
    

29. debug 模块

  • 功能定位:输出调试信息,常用于 Playbook 中打印变量与提示。

  • 核心参数

    • msg:输出的消息内容
    • verbosity:输出级别,需对应执行时加 -v 参数才显示
  • 典型用法

    ansible 主机组 -m debug -a 'msg="部署流程执行完成"'
    

三、常见问题与排障指南

  1. unarchive 报错:dest '/xxx' must be an existing dir

    • 原因:指定的解压目标目录在远程主机不存在。

    • 解决:先用 file 模块创建目标目录,或修改为已存在的目录路径。

  2. 模块缺失警告:module xxx not found in

    • 原因:ansible-core 精简版未包含该社区模块。

    • 解决:确认模块所属 Collection,通过 ansible-galaxy collection install 安装。例如 selinux 属于 ansible.posix,archive 属于 community.general

  3. 通用排障技巧

    • 执行时加 -vvv 参数,可查看详细执行日志与参数传递过程;

    • 配置修改、删除类高危操作,可先加 --check 进行空跑验证,确认变更后再正式执行;

    • 复杂正则建议先在单台主机测试,验证匹配结果后再批量操作。


四、模块使用最佳实践

  1. 优先选用幂等模块
    能用专用业务模块实现的操作,绝不使用 shell/command。既保证幂等性,也更易维护和排错。

  2. 命令类模块选型原则
    简单命令优先用 command(无 Shell 注入风险);需要 Shell 语法时用 shell;超过 3 行的逻辑建议写成脚本,通过 script 模块执行,避免转义噩梦。

  3. 参数规范与安全

    • 文件路径统一使用绝对路径;

    • 权限使用 4 位八进制写法(如 0644),避免解析歧义;

    • 敏感信息(密码、密钥)使用 Ansible Vault 加密,禁止明文写入命令或脚本。

  4. 版本兼容性
    不同 Ansible 版本的模块参数可能存在差异,使用前可通过 ansible-doc 模块名 查看当前版本官方文档。生产环境建议固定 Ansible 大版本。

posted @ 2026-08-05 16:54  kyle_7Qc  阅读(14)  评论(0)    收藏  举报