Ansible 自动化运维速查表

Ansible 是无 Agent 的自动化运维工具,用 YAML 编写 Playbook 管理服务器。整理常用命令和模块,快速上手自动化。

系统与运维·共 18 条命令·最后更新 2026-07-19
返回 系统与运维

ad-hoc 命令 5

ansible all -m ping
测试所有主机连通性
ansible webservers -m shell -a "uptime"
在 webservers 组执行 shell 命令
ansible all -m setup -a "filter=ansible_os_family"
收集主机 facts 信息
ansible all -m copy -a "src=file.txt dest=/tmp/"
复制文件到远程主机
ansible all -m service -a "name=nginx state=started"
启动服务

Playbook 基础 5

ansible-playbook site.yml
执行 Playbook
ansible-playbook site.yml --check
dry-run 模式,不实际执行
ansible-playbook site.yml --limit web
只对 web 组执行
ansible-playbook site.yml -e "var=value"
传入额外变量
ansible-playbook site.yml --tags deploy
只执行 tagged 任务

常用模块 5

- name: Install nginx\n apt:\n name: nginx\n state: present
apt 包管理模块
- name: Copy config\n template:\n src: nginx.conf.j2\n dest: /etc/nginx/nginx.conf
template 模板渲染模块
- name: Start service\n service:\n name: nginx\n state: started\n enabled: yes
service 服务管理模块
- name: Create user\n user:\n name: deploy\n shell: /bin/bash
user 用户管理模块
- name: Run command\n shell: npm run build\n args:\n chdir: /app
shell 命令执行模块

Inventory 管理 3

[webservers]\nweb1 ansible_host=10.0.1.1\nweb2 ansible_host=10.0.1.2
INI 格式 Inventory
ansible all -i hosts.yml
指定 Inventory 文件
ansible all --list-hosts
列出所有匹配主机

💡 提示

  • Ansible 默认使用 SSH 连接,无需在目标机器安装 Agent。
  • template 模块用 Jinja2 语法渲染配置文件,比 copy 更灵活。
  • --check 模式(dry-run)可以预览 Playbook 执行效果而不实际修改系统。
  • roles 目录结构:tasks/main.yml、handlers/main.yml、templates/、files/、defaults/main.yml。