Ansible 模块速查表

ansible是一个强大的自动化运维工具,本文将介绍其常用模块的使用方法。

格式

基本文件结构

---
- hosts: production
  remote_user: root
  tasks:
  - ···

请将你的模块放在 tasks 下面。

任务格式

单行格式

- apt: pkg=vim state=present

映射格式

- apt:
    pkg: vim
    state: present

可折叠的标量格式

- apt: >
    pkg=vim
    state=present    

你可以使用以上任意一种格式来定义任务。对于简短的声明推荐使用单行格式,对于较长的声明推荐使用映射格式。

模块

Aptitude

包管理

- apt:
    pkg: nodejs
    state: present # absent | latest
    update_cache: yes
    force: no

Deb 包文件

- apt:
    deb: "https://packages.erlang-solutions.com/erlang-solutions_1.0_all.deb"

软件源管理

- apt_repository:
    repo: "deb https://··· raring main"
    state: present

软件源密钥

- apt_key:
    id: AC40B2F7
    url: "http://···"
    state: present

Git 相关

- git:
    repo: git://github.com/
    dest: /srv/checkout
    version: master
    depth: 10
    bare: yes

参考: git 模块

Git 配置

- git_config:
    name: user.email
    scope: global # local | system
    value: hi@example.com

参考: git_config 模块

用户管理

- user:
    state: present    # 状态:存在
    name: git        # 用户名
    system: yes      # 系统用户
    shell: /bin/sh   # 登录shell
    groups: admin    # 所属组
    comment: "Git Version Control"  # 注释

参考: user 模块

服务管理

- service:
    name: nginx      # 服务名称
    state: started   # 状态:启动
    enabled: yes     # 是否开机启动

参考: service 模块

Shell 相关

shell 命令

- shell: apt-get install nginx -y

额外选项

- shell: echo hello
  args:
    creates: /path/file  # 如果文件存在则跳过
    removes: /path/file  # 如果文件不存在则跳过
    chdir: /path        # 在执行前切换到此目录

多行命令示例

- shell: |
    echo "hello there"
    echo "multiple lines"    

参考: shell 模块

脚本执行

- script: /x/y/script.sh
  args:
    creates: /path/file  # 如果文件存在则跳过
    removes: /path/file  # 如果文件不存在则跳过  
    chdir: /path        # 在执行前切换到此目录

参考: script 模块

文件操作

文件管理

- file:
    path: /etc/dir
    state: directory # 类型:目录|文件|链接|硬链接|touch|删除

    # 可选参数:
    owner: bin      # 所有者
    group: wheel    # 所属组
    mode: 0644      # 权限
    recurse: yes    # 递归创建
    force: yes      # 强制创建软链接

参考: file 模块

文件复制

- copy:
    src: /app/config/nginx.conf   # 源文件
    dest: /etc/nginx/nginx.conf   # 目标位置

    # 可选参数:
    owner: user     # 所有者
    group: user     # 所属组
    mode: 0644      # 权限
    backup: yes     # 是否备份

参考: copy 模块

模板

- template:
    src: config/redis.j2       # 模板源文件
    dest: /etc/redis.conf      # 目标位置

    # 可选参数:
    owner: user     # 所有者
    group: user     # 所属组
    mode: 0644      # 权限
    backup: yes     # 是否备份

参考: template 模块

本地操作

本地执行

- name: 在本地执行操作
  local_action: shell echo hello

调试输出

- debug:
    msg: "Hello {{ var }}"

参考: debug 模块