Ansible常用模块及使用

📦 包管理模块

apt (Debian/Ubuntu)

 ---
 - name: 安装Nginx
   hosts: group1                    # 目标主机组,修改为你要操作的主机组
   become: yes                      # 使用sudo权限,改为no则不用root权限
   tasks:
     - name: 安装Nginx
       apt:
         name: nginx                # 包名,改这个可以安装不同软件
         state: present             # 状态选项:
                                    # - present: 安装(不更新已存在的包)
                                    # - latest: 安装并更新到最新版
                                    # - absent: 卸载

 ---
 - name: 安装多个软件包
   hosts: group1
   become: yes
   tasks:
     - name: 安装基础工具
       apt:
         name:                      # 包列表,添加或删除包名即可
           - git
           - wget
           - curl
           - vim
         state: present
         update_cache: yes          # yes: 先执行 apt update 更新索引
                                    # no: 不更新索引(更快但可能找不到新包)

yum (CentOS/RHEL)

 ---
 - name: 安装Nginx
   hosts: group1
   become: yes
   tasks:
     - name: 安装Nginx
       yum:
         name: nginx                # 包名,修改可安装其他软件
         state: present             # present: 安装 | latest: 更新 | absent: 卸载

package (通用模块,推荐跨平台)

 ---
 - name: 安装Nginx(跨平台)
   hosts: group1
   become: yes
   tasks:
     - name: 安装Nginx
       package:
         name: nginx                # 包名,自动适配系统的包管理器
         state: present             # Ubuntu用apt,CentOS用yum自动转换

📂 文件与目录管理模块

copy - 从控制节点复制文件到远程

 ---
 - name: 分发配置文件
   hosts: group1
   become: yes
   tasks:
     - name: 复制Nginx配置
       copy:
         src: /root/nginx.conf      # 源文件路径(在Ansible控制机上)
                                    # 修改为你要复制的文件路径
         dest: /etc/nginx/nginx.conf # 目标路径(在远程主机上)
                                    # 修改为你要放置的位置
         owner: root                # 文件所有者,改这个可以改变权限归属
         group: root                # 文件所属组
         mode: '0644'               # 文件权限:
                                    # 0644: rw-r--r-- (644)
                                    # 0755: rwxr-xr-x (755)
                                    # 0600: 只有所有者可读写
         backup: yes                # yes: 覆盖前备份原文件
                                    # no: 直接覆盖不备份

 ---
 - name: 分发配置文件并重启服务
   hosts: group1
   become: yes
   tasks:
     - name: 复制配置文件
       copy:
         src: /root/app.conf
         dest: /etc/app/app.conf
         mode: '0644'
       notify: 重启应用             # 文件变化时触发handler
 ​
   handlers:                        # 只在文件变化时执行
     - name: 重启应用
       service:
         name: app                  # 服务名,改为你要重启的服务
         state: restarted

file - 管理远程主机上的文件和目录

 ---
 - name: 创建应用目录结构
   hosts: group1
   become: yes
   tasks:
     - name: 创建应用目录
       file:
         path: /opt/myapp           # 目录路径,修改为你要创建的路径
         state: directory           # directory: 创建目录
                                    # touch: 创建空文件
                                    # link: 创建软链接
                                    # absent: 删除
         mode: '0755'               # 目录权限
         owner: www-data            # 所有者,改为你的用户
         group: www-data            # 所属组

 ---
 - name: 创建日志目录和软链接
   hosts: group1
   become: yes
   tasks:
     - name: 创建日志目录
       file:
         path: /var/log/myapp
         state: directory
         mode: '0755'
 ​
     - name: 创建软链接
       file:
         src: /etc/nginx/sites-available/default  # 源文件
         dest: /etc/nginx/sites-enabled/default   # 链接路径
         state: link                # 创建软链接

 ---
 - name: 清理旧文件
   hosts: group1
   become: yes
   tasks:
     - name: 删除临时文件
       file:
         path: /tmp/old_file.txt    # 文件路径,改为你要删除的
         state: absent              # 确保文件不存在(删除)
 ​
     - name: 创建空配置文件
       file:
         path: /etc/app/config.ini
         state: touch               # 如果文件不存在则创建
         mode: '0644'

template - 使用Jinja2模板生成配置文件

 ---
 - name: 使用模板生成配置
   hosts: group1
   become: yes
   tasks:
     - name: 生成Nginx配置
       template:
         src: nginx.conf.j2         # 模板文件(可包含变量如 {{ port }})
                                    # 修改模板内容可动态生成不同配置
         dest: /etc/nginx/nginx.conf
         owner: root
         group: root
         mode: '0644'

🚀 命令执行模块

command - 执行简单命令(安全)

 ---
 - name: 执行系统命令
   hosts: group1
   tasks:
     - name: 查看系统版本
       command:
         cmd: cat /etc/os-release   # 要执行的命令
                                    # 修改为你想执行的任何系统命令
       register: os_info            # 将命令输出保存到变量
 ​
     - name: 显示系统信息
       debug:
         msg: "{{ os_info.stdout }}" # 显示命令输出

 ---
 - name: 重启服务
   hosts: group1
   become: yes
   tasks:
     - name: 重启网络
       command:
         cmd: /usr/bin/systemctl restart network  # 改为你要重启的服务

shell - 执行复杂的Shell命令

 ---
 - name: 执行Shell命令
   hosts: group1
   tasks:
     - name: 清理30天前的日志
       shell:
         cmd: "find /var/log -name '*.log' -mtime +30 -delete"  # 删除30天前的日志
                                    # 修改 +30 可改变保留天数
                                    # 修改 /var/log 可改变清理目录
       become: yes

 ---
 - name: 检查并重启服务
   hosts: group1
   become: yes
   tasks:
     - name: 检查Nginx状态
       shell:
         cmd: "systemctl status nginx || systemctl restart nginx"
         # || 表示:如果前面失败则执行后面
         # 修改 nginx 可改为其他服务
       ignore_errors: yes           # yes: 即使失败也继续执行
                                    # no: 失败则停止

 ---
 - name: 执行复杂Shell操作
   hosts: group1
   tasks:
     - name: 获取系统信息并保存
       shell:
         cmd: "df -h > /tmp/disk_usage.txt && hostname >> /tmp/disk_usage.txt"
         # > 覆盖写入,>> 追加写入
         # 修改命令可执行任何Shell操作
         chdir: /tmp                # 先切换到该目录再执行

🔧 系统状态管理模块

service - 管理服务

 ---
 - name: 管理Nginx服务
   hosts: group1
   become: yes
   tasks:
     - name: 启动Nginx并设置开机自启
       service:
         name: nginx                # 服务名,改为你要管理的服务
         state: started             # started: 启动
                                    # stopped: 停止
                                    # restarted: 重启
                                    # reloaded: 重载配置
         enabled: yes               # yes: 开机自启 | no: 关闭开机自启

systemd - 专门管理systemd服务

 ---
 - name: 管理服务
   hosts: group1
   become: yes
   tasks:
     - name: 启动并设置开机自启
       systemd:
         name: myapp                # 服务名
         state: started
         enabled: yes
         daemon_reload: yes         # yes: 重新加载systemd配置
                                    # 修改配置文件后需要设为yes

👤 用户管理模块

user - 管理用户账户

 ---
 - name: 创建部署用户
   hosts: group1
   become: yes
   tasks:
     - name: 创建用户deploy
       user:
         name: deploy               # 用户名,修改可创建不同用户
         uid: 1001                  # 用户ID,修改可指定不同UID
         group: www-data            # 主组
         groups: sudo,admin         # 附加组列表
         shell: /bin/bash           # 登录shell,改为 /bin/false 可禁止登录
         create_home: yes           # yes: 创建家目录 | no: 不创建
         password: "{{ 'mypassword' | password_hash('sha512') }}"
                                    # 修改密码字符串可改变用户密码

 ---
 - name: 删除用户
   hosts: group1
   become: yes
   tasks:
     - name: 删除旧用户
       user:
         name: olduser              # 改为要删除的用户名
         state: absent              # 删除用户
         remove: yes                # yes: 同时删除家目录和邮箱

📊 信息收集与调试模块

ping - 测试连通性

 ---
 - name: 测试主机连通性
   hosts: group1
   tasks:
     - name: Ping所有主机
       ping:                        # 成功返回 "pong"

setup - 收集主机信息

 ---
 - name: 收集主机信息
   hosts: group1
   tasks:
     - name: 收集系统信息
       setup:
         filter: ansible_os_family  # 只收集操作系统类型
                                    # 改为 ansible_* 可收集其他信息
                                    # 不写filter则收集所有信息
       register: facts
 ​
     - name: 显示操作系统
       debug:
         msg: "系统类型: {{ facts.ansible_facts.ansible_os_family }}"

debug - 输出调试信息

 ---
 - name: 调试输出
   hosts: group1
   tasks:
     - name: 输出主机信息
       debug:
         msg: "当前主机: {{ inventory_hostname }},IP: {{ ansible_default_ipv4.address }}"
         # 修改msg内容可输出不同变量
 ​
     - name: 输出变量值
       debug:
         var: ansible_os_family      # 显示指定变量的值

📦 软件管理扩展模块

git - 管理代码仓库

 ---
 - name: 部署应用代码
   hosts: group1
   tasks:
     - name: 从Git克隆代码
       git:
         repo: 'https://github.com/your/awesome-app.git'
                                    # 仓库地址,改为你的Git仓库
         dest: /opt/awesome-app     # 克隆到的目录
         version: main              # 分支/标签:
                                    # - main: 主分支
                                    # - v1.0.0: 指定标签
                                    # - develop: 开发分支
         force: yes                 # yes: 强制覆盖本地修改
                                    # no: 如果本地有修改则失败
         depth: 1                   # 浅克隆深度,改为1只克隆最新提交

get_url - 下载文件

 ---
 - name: 下载文件
   hosts: group1
   become: yes
   tasks:
     - name: 下载安装包
       get_url:
         url: https://example.com/file.tar.gz  # 下载地址
         dest: /tmp/file.tar.gz    # 保存路径
         mode: '0755'              # 文件权限
         timeout: 30               # 超时时间(秒)
         checksum: sha256:abcdef123456...  # 校验和,确保文件完整性
                                    # 修改URL可下载不同文件

🔐 配置管理模块

lineinfile - 管理配置文件中的行

 ---
 - name: 配置SSH安全
   hosts: group1
   become: yes
   tasks:
     - name: 禁止root登录
       lineinfile:
         path: /etc/ssh/sshd_config  # 要修改的配置文件
         regexp: '^PermitRootLogin'  # 匹配已有行(正则表达式)
         line: 'PermitRootLogin no'  # 替换成这行内容
         backup: yes                 # 修改前备份
         state: present              # present: 确保存在 | absent: 删除
         # 修改 line 的值可改变配置,如改为 yes 则允许root登录
 ​
     - name: 修改SSH默认端口
       lineinfile:
         path: /etc/ssh/sshd_config
         regexp: '^#?Port '         # ^#? 匹配行首有#或没有#的情况
         line: 'Port 2222'          # 改为你要的端口号
         # 修改 Port 后面的数字可改变SSH端口

🏗️ 综合应用示例

 ---
 - name: 完整部署Web服务器
   hosts: group1                    # 修改为你的主机组
   become: yes
   vars:                            # 变量区域,统一修改
     app_name: myapp                # 应用名,改这个所有引用都变
     app_port: 8080                 # 端口号,改这个改变服务端口
     admin_email: admin@example.com # 管理员邮箱
   tasks:
     # === 系统更新 ===
     - name: 更新包缓存
       apt:
         update_cache: yes
       when: ansible_os_family == "Debian"  # 只在Debian系执行
       # 改为 RedHat 则只在CentOS执行
 ​
     # === 安装软件 ===
     - name: 安装Nginx和工具
       package:
         name:                      # 修改列表可增减软件
           - nginx
           - curl
           - git
         state: present
 ​
     # === 创建目录 ===
     - name: 创建应用目录
       file:
         path: /opt/{{ app_name }}  # 使用变量,改 app_name 即可
         state: directory
         mode: '0755'
 ​
     # === 复制配置 ===
     - name: 复制配置文件
       copy:
         src: /root/nginx.conf
         dest: /etc/nginx/nginx.conf
         mode: '0644'
         backup: yes
       notify: 重启Nginx
 ​
     # === 启动服务 ===
     - name: 启动Nginx
       service:
         name: nginx
         state: started
         enabled: yes
 ​
   handlers:
     - name: 重启Nginx
       service:
         name: nginx
         state: restarted

💡 常见修改场景速查

你想要的效果

修改哪里

安装不同的软件包

修改 name: nginx 改为其他包名

更改目标机器

修改 hosts: group1 为其他主机组

不用sudo权限

删除 become: yes 或改为 become: no

改变文件权限

修改 mode: '0644' 的数字

改变服务状态

修改 state: started 为 stopped / restarted

让服务开机不自启

修改 enabled: yes 为 no

删除文件/目录

修改 state: directory 为 absent

传递不同变量

使用 -e "key=value" 命令行参数

只对特定主机执行

使用 --limit hostname 参数