Ansible 常用模块 #

模块概述 #

Ansible 模块是执行具体任务的代码单元,每个模块负责特定的功能。

text
┌─────────────────────────────────────────────────────────────┐
│                      模块分类                                │
├─────────────────────────────────────────────────────────────┤
│                                                              │
│  系统模块          文件模块          包管理模块              │
│  ──────────        ──────────        ──────────             │
│  command           copy              apt                    │
│  shell             file              yum                    │
│  script            template          dnf                    │
│  raw               lineinfile        pip                    │
│                                                              │
│  服务模块          用户模块          网络模块                │
│  ──────────        ──────────        ──────────             │
│  service           user              get_url                │
│  systemd           group             uri                    │
│  supervisor        authorized_key    wait_for               │
│                                                              │
└─────────────────────────────────────────────────────────────┘

文件模块 #

copy 模块 #

复制文件到远程主机:

yaml
# 复制文件
- name: Copy configuration file
  copy:
    src: files/app.conf
    dest: /etc/app/app.conf
    owner: root
    group: root
    mode: '0644'

# 复制目录
- name: Copy directory
  copy:
    src: files/app/
    dest: /var/www/app/
    owner: www-data
    group: www-data
    mode: '0755'

# 直接写入内容
- name: Create file with content
  copy:
    content: |
      # Configuration file
      setting1=value1
      setting2=value2
    dest: /etc/app/config.conf
    owner: root
    group: root
    mode: '0644'

# 备份原文件
- name: Copy with backup
  copy:
    src: files/nginx.conf
    dest: /etc/nginx/nginx.conf
    backup: yes
    validate: nginx -t -c %s

# 验证文件
- name: Copy and validate
  copy:
    src: sudoers
    dest: /etc/sudoers.d/user
    validate: 'visudo -cf %s'

file 模块 #

管理文件和目录属性:

yaml
# 创建目录
- name: Create directory
  file:
    path: /var/www/app
    state: directory
    owner: www-data
    group: www-data
    mode: '0755'

# 创建多级目录
- name: Create nested directories
  file:
    path: /var/www/app/logs
    state: directory
    recurse: yes
    owner: www-data
    group: www-data

# 创建文件
- name: Create empty file
  file:
    path: /var/www/app/.env
    state: touch
    owner: www-data
    group: www-data
    mode: '0644'

# 删除文件
- name: Remove file
  file:
    path: /tmp/tempfile
    state: absent

# 删除目录
- name: Remove directory
  file:
    path: /tmp/tempdir
    state: absent

# 创建符号链接
- name: Create symlink
  file:
    src: /var/www/app/current
    dest: /var/www/app/latest
    state: link

# 创建硬链接
- name: Create hard link
  file:
    src: /var/www/app/file.txt
    dest: /var/www/app/link.txt
    state: hard

# 修改权限
- name: Change permissions
  file:
    path: /var/www/app
    owner: www-data
    group: www-data
    mode: '0755'
    recurse: yes

template 模块 #

部署 Jinja2 模板:

yaml
# 基本使用
- name: Deploy configuration
  template:
    src: templates/app.conf.j2
    dest: /etc/app/app.conf
    owner: root
    group: root
    mode: '0644'

# 带验证
- name: Deploy nginx config
  template:
    src: nginx.conf.j2
    dest: /etc/nginx/nginx.conf
    validate: nginx -t -c %s
  notify: Reload Nginx

# 带备份
- name: Deploy with backup
  template:
    src: app.yml.j2
    dest: /etc/app/app.yml
    backup: yes

lineinfile 模块 #

管理文件中的行:

yaml
# 确保行存在
- name: Ensure line exists
  lineinfile:
    path: /etc/hosts
    line: '192.168.1.100 webserver'
    state: present

# 确保行不存在
- name: Ensure line absent
  lineinfile:
    path: /etc/hosts
    line: '192.168.1.100 oldserver'
    state: absent

# 使用正则表达式替换
- name: Replace line using regex
  lineinfile:
    path: /etc/ssh/sshd_config
    regexp: '^PermitRootLogin'
    line: 'PermitRootLogin no'
    state: present

# 在匹配行后插入
- name: Insert after match
  lineinfile:
    path: /etc/app/config.conf
    insertafter: '^# Database settings'
    line: 'db_host=localhost'

# 在匹配行前插入
- name: Insert before match
  lineinfile:
    path: /etc/app/config.conf
    insertbefore: '^# End of config'
    line: 'cache_enabled=true'

# 创建文件(如果不存在)
- name: Create file if not exists
  lineinfile:
    path: /etc/app/config.conf
    line: '# Configuration file'
    create: yes

# 验证文件
- name: Modify sudoers with validation
  lineinfile:
    path: /etc/sudoers
    state: present
    regexp: '^%sudo'
    line: '%sudo ALL=(ALL) NOPASSWD: ALL'
    validate: 'visudo -cf %s'

replace 模块 #

替换文件中的文本:

yaml
# 替换所有匹配
- name: Replace all occurrences
  replace:
    path: /etc/app/config.conf
    regexp: 'localhost'
    replace: 'db.example.com'

# 使用正则表达式组
- name: Replace with groups
  replace:
    path: /etc/app/config.conf
    regexp: 'port=(\d+)'
    replace: 'port=8080'

# 带备份
- name: Replace with backup
  replace:
    path: /etc/nginx/nginx.conf
    regexp: 'listen 80'
    replace: 'listen 8080'
    backup: yes

synchronize 模块 #

使用 rsync 同步文件:

yaml
# 同步目录
- name: Sync directory
  synchronize:
    src: files/app/
    dest: /var/www/app/
    delete: yes

# 同步到远程
- name: Push files
  synchronize:
    src: files/app/
    dest: /var/www/app/
    mode: push

# 从远程拉取
- name: Pull files
  synchronize:
    src: /var/www/app/
    dest: backup/
    mode: pull

# 排除文件
- name: Sync with exclude
  synchronize:
    src: files/app/
    dest: /var/www/app/
    delete: yes
    rsync_opts:
      - "--exclude=.git"
      - "--exclude=node_modules"

包管理模块 #

apt 模块 #

Debian/Ubuntu 包管理:

yaml
# 更新缓存
- name: Update apt cache
  apt:
    update_cache: yes
    cache_valid_time: 3600

# 安装软件包
- name: Install package
  apt:
    name: nginx
    state: present

# 安装多个软件包
- name: Install multiple packages
  apt:
    name:
      - nginx
      - git
      - curl
    state: present

# 安装指定版本
- name: Install specific version
  apt:
    name: nginx=1.18.0-0ubuntu1
    state: present

# 确保最新版本
- name: Ensure latest version
  apt:
    name: nginx
    state: latest

# 卸载软件包
- name: Remove package
  apt:
    name: nginx
    state: absent

# 卸载软件包及配置
- name: Purge package
  apt:
    name: nginx
    state: absent
    purge: yes

# 升级所有软件包
- name: Upgrade all packages
  apt:
    upgrade: dist

# 安装 deb 包
- name: Install deb package
  apt:
    deb: /tmp/package.deb

# 检查软件包是否可升级
- name: Check for updates
  apt:
    update_cache: yes
    upgrade: no
  register: apt_result

yum 模块 #

RHEL/CentOS 包管理:

yaml
# 安装软件包
- name: Install package
  yum:
    name: nginx
    state: present

# 安装多个软件包
- name: Install multiple packages
  yum:
    name:
      - nginx
      - git
      - curl
    state: present

# 安装指定版本
- name: Install specific version
  yum:
    name: nginx-1.18.0
    state: present

# 确保最新版本
- name: Ensure latest version
  yum:
    name: nginx
    state: latest

# 卸载软件包
- name: Remove package
  yum:
    name: nginx
    state: absent

# 升级所有软件包
- name: Upgrade all packages
  yum:
    name: '*'
    state: latest

# 从 URL 安装
- name: Install from URL
  yum:
    name: https://example.com/package.rpm
    state: present

# 启用仓库
- name: Install from specific repo
  yum:
    name: nginx
    enablerepo: epel
    state: present

pip 模块 #

Python 包管理:

yaml
# 安装包
- name: Install pip package
  pip:
    name: requests

# 安装指定版本
- name: Install specific version
  pip:
    name: requests==2.28.0

# 安装多个包
- name: Install multiple packages
  pip:
    name:
      - requests
      - flask
      - gunicorn

# 从 requirements.txt 安装
- name: Install from requirements
  pip:
    requirements: /var/www/app/requirements.txt

# 卸载包
- name: Uninstall package
  pip:
    name: requests
    state: absent

# 使用特定 pip
- name: Install with specific pip
  pip:
    name: requests
    executable: pip3

# 在虚拟环境中安装
- name: Install in virtualenv
  pip:
    name: requests
    virtualenv: /var/www/app/venv

服务模块 #

service 模块 #

管理服务:

yaml
# 启动服务
- name: Start service
  service:
    name: nginx
    state: started

# 停止服务
- name: Stop service
  service:
    name: nginx
    state: stopped

# 重启服务
- name: Restart service
  service:
    name: nginx
    state: restarted

# 重载配置
- name: Reload service
  service:
    name: nginx
    state: reloaded

# 开机启动
- name: Enable service
  service:
    name: nginx
    enabled: yes

# 禁用开机启动
- name: Disable service
  service:
    name: nginx
    enabled: no

# 启动并设置开机启动
- name: Start and enable service
  service:
    name: nginx
    state: started
    enabled: yes

systemd 模块 #

管理 systemd 服务:

yaml
# 启动服务
- name: Start systemd service
  systemd:
    name: nginx
    state: started

# 重载 systemd 守护进程
- name: Reload systemd daemon
  systemd:
    daemon_reload: yes

# 启用服务
- name: Enable systemd service
  systemd:
    name: nginx
    enabled: yes
    masked: no

# 禁用服务
- name: Mask service
  systemd:
    name: nginx
    masked: yes

# 重置失败状态
- name: Reset failed service
  systemd:
    name: nginx
    state: reset-failed

用户管理模块 #

user 模块 #

管理用户:

yaml
# 创建用户
- name: Create user
  user:
    name: deploy
    shell: /bin/bash
    groups: sudo
    append: yes

# 创建用户并设置密码
- name: Create user with password
  user:
    name: deploy
    password: "{{ 'mypassword' | password_hash('sha512') }}"

# 创建用户并生成 SSH 密钥
- name: Create user with SSH key
  user:
    name: deploy
    generate_ssh_key: yes
    ssh_key_bits: 2048
    ssh_key_file: .ssh/id_rsa

# 创建系统用户
- name: Create system user
  user:
    name: appuser
    system: yes
    shell: /sbin/nologin
    create_home: no

# 删除用户
- name: Remove user
  user:
    name: deploy
    state: absent

# 删除用户及其 home 目录
- name: Remove user with home
  user:
    name: deploy
    state: absent
    remove: yes

# 修改用户属性
- name: Modify user
  user:
    name: deploy
    groups: docker
    append: yes
    shell: /bin/zsh

# 设置用户过期时间
- name: Set user expiry
  user:
    name: tempuser
    expires: 1735689600  # Unix timestamp

group 模块 #

管理组:

yaml
# 创建组
- name: Create group
  group:
    name: developers

# 创建组并指定 GID
- name: Create group with GID
  group:
    name: developers
    gid: 1001

# 创建系统组
- name: Create system group
  group:
    name: appgroup
    system: yes

# 删除组
- name: Remove group
  group:
    name: developers
    state: absent

authorized_key 模块 #

管理 SSH 授权密钥:

yaml
# 添加 SSH 公钥
- name: Add SSH key
  authorized_key:
    user: deploy
    key: "{{ lookup('file', '~/.ssh/id_rsa.pub') }}"

# 添加多个密钥
- name: Add multiple SSH keys
  authorized_key:
    user: deploy
    key: "{{ item }}"
  loop:
    - "ssh-rsa AAAA... user1@host1"
    - "ssh-rsa BBBB... user2@host2"

# 删除密钥
- name: Remove SSH key
  authorized_key:
    user: deploy
    key: "ssh-rsa AAAA... user@host"
    state: absent

# 独占模式(只保留指定的密钥)
- name: Set exclusive SSH key
  authorized_key:
    user: deploy
    key: "{{ lookup('file', '~/.ssh/id_rsa.pub') }}"
    exclusive: yes

命令模块 #

command 模块 #

执行命令(不支持管道等 shell 特性):

yaml
# 执行命令
- name: Run command
  command: ls -la /tmp

# 指定工作目录
- name: Run in directory
  command: npm install
  args:
    chdir: /var/www/app

# 创建文件前检查
- name: Run if file not exists
  command: touch /tmp/newfile
  args:
    creates: /tmp/newfile

# 移除文件前检查
- name: Run if file exists
  command: rm /tmp/oldfile
  args:
    removes: /tmp/oldfile

shell 模块 #

执行 shell 命令:

yaml
# 执行 shell 命令
- name: Run shell command
  shell: cat /etc/passwd | grep root

# 使用管道
- name: Use pipe
  shell: ps aux | grep nginx | grep -v grep

# 使用重定向
- name: Use redirect
  shell: echo "hello" > /tmp/hello.txt

# 使用环境变量
- name: Use environment
  shell: echo $HOME
  environment:
    MY_VAR: "value"

# 使用脚本
- name: Run script
  shell: /usr/local/bin/myscript.sh

script 模块 #

在远程主机执行本地脚本:

yaml
# 执行本地脚本
- name: Run local script
  script: /local/path/script.sh

# 带参数执行
- name: Run script with args
  script: /local/path/script.sh arg1 arg2

# 创建文件前检查
- name: Run if file not exists
  script: /local/path/setup.sh
  args:
    creates: /etc/app/configured

网络模块 #

get_url 模块 #

下载文件:

yaml
# 下载文件
- name: Download file
  get_url:
    url: https://example.com/file.tar.gz
    dest: /tmp/file.tar.gz

# 下载并验证校验和
- name: Download with checksum
  get_url:
    url: https://example.com/file.tar.gz
    dest: /tmp/file.tar.gz
    checksum: sha256:abc123...

# 下载并设置权限
- name: Download with permissions
  get_url:
    url: https://example.com/script.sh
    dest: /usr/local/bin/script.sh
    mode: '0755'

# 使用认证
- name: Download with auth
  get_url:
    url: https://example.com/file
    dest: /tmp/file
    url_username: user
    url_password: pass

uri 模块 #

发送 HTTP 请求:

yaml
# GET 请求
- name: GET request
  uri:
    url: http://localhost:8080/api/health
    return_content: yes
  register: result

# POST 请求
- name: POST request
  uri:
    url: http://localhost:8080/api/users
    method: POST
    body_format: json
    body:
      name: John
      email: john@example.com
    headers:
      Content-Type: application/json

# 检查状态码
- name: Check status
  uri:
    url: http://localhost:8080/health
    status_code: 200

# 等待服务就绪
- name: Wait for service
  uri:
    url: http://localhost:8080/health
    status_code: 200
  register: result
  until: result.status == 200
  retries: 10
  delay: 5

wait_for 模块 #

等待条件:

yaml
# 等待端口
- name: Wait for port
  wait_for:
    port: 8080
    timeout: 60

# 等待文件存在
- name: Wait for file
  wait_for:
    path: /var/www/app/ready
    timeout: 300

# 等待文件包含内容
- name: Wait for file content
  wait_for:
    path: /var/log/app.log
    search_regex: "Application started"

# 等待服务响应
- name: Wait for service
  wait_for:
    host: localhost
    port: 8080
    delay: 5
    timeout: 60

其他常用模块 #

debug 模块 #

调试输出:

yaml
# 输出消息
- name: Debug message
  debug:
    msg: "Current host is {{ inventory_hostname }}"

# 输出变量
- name: Debug variable
  debug:
    var: ansible_facts

# 条件调试
- name: Conditional debug
  debug:
    msg: "This is production"
  when: environment == 'production'

stat 模块 #

检查文件状态:

yaml
# 检查文件
- name: Check file
  stat:
    path: /etc/nginx/nginx.conf
  register: file_stat

# 使用结果
- name: Use stat result
  debug:
    msg: "File exists"
  when: file_stat.stat.exists

# 检查是否是目录
- name: Check if directory
  stat:
    path: /var/www/app
  register: dir_stat

- name: Create if not exists
  file:
    path: /var/www/app
    state: directory
  when: not dir_stat.stat.exists

cron 模块 #

管理定时任务:

yaml
# 创建定时任务
- name: Create cron job
  cron:
    name: "backup job"
    minute: "0"
    hour: "2"
    job: "/usr/local/bin/backup.sh"

# 创建每天执行的任务
- name: Daily cron job
  cron:
    name: "daily cleanup"
    special_time: daily
    job: "/usr/local/bin/cleanup.sh"

# 创建每周执行的任务
- name: Weekly cron job
  cron:
    name: "weekly report"
    weekday: "0"
    hour: "8"
    job: "/usr/local/bin/report.sh"

# 删除定时任务
- name: Remove cron job
  cron:
    name: "backup job"
    state: absent

# 禁用定时任务
- name: Disable cron job
  cron:
    name: "backup job"
    job: "/usr/local/bin/backup.sh"
    disabled: yes

mount 模块 #

管理挂载点:

yaml
# 挂载文件系统
- name: Mount filesystem
  mount:
    path: /mnt/data
    src: /dev/sdb1
    fstype: ext4
    state: mounted

# 卸载文件系统
- name: Unmount filesystem
  mount:
    path: /mnt/data
    state: unmounted

# 添加到 fstab
- name: Add to fstab
  mount:
    path: /mnt/data
    src: /dev/sdb1
    fstype: ext4
    opts: defaults
    state: present

# 挂载 NFS
- name: Mount NFS
  mount:
    path: /mnt/nfs
    src: 192.168.1.100:/export/data
    fstype: nfs
    state: mounted

下一步 #

现在你已经掌握了常用模块,接下来学习 Handlers 处理器 了解如何处理配置变更后的操作!

最后更新:2026-03-29