Skip to main content
Documents
Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Back to homepage

Ansible Ad-Hoc

🧩 一、基础:Ansible Ad-Hoc 命令格式

ansible <hosts> -m <module> -a "<module arguments>"

示例:

ansible all -m ping
ansible web -m shell -a "ps aux | grep nginx"

🧩 二、常用模块大全(命令行版)

下面按功能分类,每个模块都给出 最常用的 ad-hoc 示例(可直接粘贴运行)。

2.1 系统探测 / 调试

ping

检查连通性

ansible all -m ping

setup

收集 facts

ansible all -m setup
ansible all -m setup -a "filter=ansible_mem*"

2.2 shell / command(务必区分)

command(默认,不解析 shell)

ansible all -a "ls -l /etc"

shell(允许管道、重定向)

ansible all -m shell -a "ps aux | grep nginx"
ansible web -m shell -a "echo 1 > /proc/sys/net/ipv4/ip_forward"

⚠️ 最佳实践:能用模块就不用 shell / command。

2.3 文件与目录操作

file

# 创建目录
ansible all -m file -a "path=/data/logs state=directory mode=0755"

# 创建软链接
ansible all -m file -a "src=/usr/bin/python3 dest=/usr/bin/python state=link"

copy

ansible all -m copy -a "src=./nginx.conf dest=/etc/nginx/nginx.conf"

fetch

从远端拉回文件

ansible all -m fetch -a "src=/var/log/messages dest=./logs/"

lineinfile

ansible all -m lineinfile -a 'path=/etc/sysctl.conf regexp="^net.ipv4.ip_forward" line="net.ipv4.ip_forward=1"'

blockinfile

ansible all -m blockinfile -a "path=/etc/profile block='export GOPROXY=https://proxy.golang.org'"

unarchive

ansible all -m unarchive -a "src=app.tar.gz dest=/opt/app remote_src=yes"

2.4 软件包管理(跨发行版)

package(推荐)

ansible all -m package -a "name=htop state=present"

apt

ansible debian -m apt -a "name=nginx update_cache=yes"

yum / dnf

ansible rhel -m yum -a "name=httpd state=present"

pip

ansible all -m pip -a "name=uvicorn"

2.5 服务管理(systemd)

service

ansible all -m service -a "name=nginx state=restarted enabled=yes"

systemd

ansible all -m systemd -a "name=docker daemon_reload=yes state=restarted"

2.6 用户 / 权限

user

ansible all -m user -a "name=martin shell=/bin/bash state=present"

group

ansible all -m group -a "name=devops state=present"

authorized_key

ansible all -m authorized_key -a "user=root key='{{ lookup(\"file\", \"id_rsa.pub\") }}'"

2.7 网络 / 系统内核

sysctl

ansible all -m sysctl -a "name=net.ipv4.ip_forward value=1 state=present reload=yes"

hostname

ansible web -m hostname -a "name=web01"

firewalld

ansible all -m firewalld -a "port=80/tcp permanent=yes state=enabled"

iptables

ansible all -m iptables -a "chain=INPUT protocol=tcp destination_port=22 jump=ACCEPT"

2.8 定时任务 & 系统操作

cron

ansible all -m cron -a "name=backup minute=0 hour=2 job='/usr/bin/backup.sh'"

mount

ansible all -m mount -a "path=/data src=/dev/vdb1 fstype=ext4 state=mounted"

reboot

ansible all -m reboot -a "reboot_timeout=600"

2.9 Git / 下载

git

ansible all -m git -a "repo=https://github.com/martin/app.git dest=/opt/app version=main"

get_url

ansible all -m get_url -a "url=https://example.com/app.tar.gz dest=/tmp/app.tar.gz"

uri

ansible all -m uri -a "url=https://httpbin.org/get method=GET return_content=yes"

2.10 Docker 模块(Ad-Hoc 超好用)

docker_image

ansible all -m docker_image -a "name=nginx source=pull"

docker_container

ansible all -m docker_container -a "name=nginx image=nginx:latest state=started ports=80:80"

docker_network

ansible all -m docker_network -a "name=mynet state=present"

2.11 Kubernetes 管理(无需 Playbook)

前提:配置 kubeconfig

k8s

创建 / 更新资源

ansible k8s -m k8s -a "state=present definition=@deployment.yaml"

k8s_info

ansible k8s -m k8s_info -a "kind=Pod namespace=default"

2.12 数据库管理

PostgreSQL

postgresql_db

ansible db -m postgresql_db -a "name=mydb state=present"

postgresql_user

ansible db -m postgresql_user -a "name=martin password=123 db=mydb"

MySQL

mysql_db

ansible db -m mysql_db -a "name=appdb state=present"

mysql_user

ansible db -m mysql_user -a "name=app password=123 priv=appdb.*:ALL"

🧰 2.13 文件同步 / 大文件处理

synchronize(使用 rsync,速度最快)

ansible all -m synchronize -a "src=./dist/ dest=/var/www/"

🧱 2.14 控制流(纯命令行技巧)

使用 register 等价物:-o 输出

ansible all -a "hostname" -o

使用 –limit

ansible all -m ping --limit web01

使用 –extra-vars

ansible all -m shell -a "echo {{ msg }}" --extra-vars "msg=hello"

实战最佳实践(非常重要)

1. 能不用 shell 就不用 shell

不安全、难维护、幂等性差。

2. 永远优先使用专用模块

例如安装软件使用 package,不要:

shell: yum install -y xxx

3. 使用 –check(Dry Run)排查变更

ansible all -m copy -a "src=a dest=b" --check

4. 使用 inventory 分组规范管理主机

例如:

[web]
web01
web02

[db]
db01

然后:

ansible web -m ping
ansible db -m service -a "name=mysql state=restarted"

5. 重要任务加 –forks 提速

ansible all -m ping --forks 50

6. 远程批量修改务必先 –check + –diff

ansible all -m lineinfile -a "path=/etc/sysctl.conf ..." --check --diff

7. 大规模变更建议先用 –limit 分批执行

ansible all --limit 'web01' -m copy -a ...
ansible all --limit 'web02' -m copy -a ...

Ansible Ad-Hoc 常用命令

🚀 Ansible Ad-Hoc 最常用 200 条命令(分类版大全)

💡 格式:

ansible <hosts> -m <module> -a "<args>"

常用附加参数:

-k 密码认证、-b sudo、-K sudo 密码、-u USER、-i inventory.ini

1. 🔍 Ping / 检查类

ansible all -m ping
ansible web -m ping
ansible all -m ping -u root
ansible all -m ping -k
ansible db -m ping -b
ansible all -m ping -f 10   # 控制并发
ansible all -m ping -e "ansible_port=2222"
ansible all -m ping -e "ansible_ssh_private_key_file=~/.ssh/id_rsa"
ansible all -m command -a "uptime"
ansible all -m shell -a "hostname"

2. 📁 文件/目录管理

file 模块

# 创建目录
ansible all -m file -a "path=/srv/www state=directory mode=0755"

# 删除目录
ansible all -m file -a "path=/tmp/test state=absent"

# 创建空文件
ansible all -m file -a "path=/tmp/x state=touch"

# 修改 owner
ansible all -m file -a "path=/var/www owner=nginx"

# 修改 group
ansible all -m file -a "path=/var/www group=nginx"

# 修改目录权限
ansible all -m file -a "path=/data mode=0777"

# 创建软连接
ansible all -m file -a "src=/etc/nginx/nginx.conf dest=/tmp/n.conf state=link"

# 创建硬链接
ansible all -m file -a "src=/bin/ls dest=/tmp/ls state=hard"

# 设置递归权限
ansible all -m file -a "path=/data state=directory recurse=yes mode=0755"

copy 模块

# 复制文件
ansible all -m copy -a "src=/etc/hosts dest=/tmp/hosts"

# 覆盖并指定权限
ansible all -m copy -a "src=a.conf dest=/etc/a.conf mode=0644"

# 复制文本内容
ansible all -m copy -a "content='hello' dest=/tmp/a.txt"

fetch 模块

# 拉取文件
ansible all -m fetch -a "src=/var/log/dmesg dest=./logs/ flat=yes"

# 拉取并保持目录结构
ansible all -m fetch -a "src=/etc/passwd dest=./result"

3. 📦 软件包(Linux Package)管理

apt

# 安装
ansible web -m apt -a "name=nginx state=present" -b

# 升级
ansible all -m apt -a "upgrade=dist" -b

# 安装多个包
ansible all -m apt -a "name='git wget curl' state=present" -b

# 删除
ansible all -m apt -a "name=nginx state=absent" -b

yum/dnf

# 安装
ansible all -m yum -a "name=httpd state=installed" -b

# 删除
ansible all -m yum -a "name=httpd state=removed" -b

# 安装多个
ansible all -m yum -a "name='git,tree' state=present" -b

# 列出更新
ansible all -m yum -a "list=updates"

4. 🧩 服务管理(systemd)

# 启动
ansible all -m service -a "name=nginx state=started" -b

# 停止
ansible all -m service -a "name=nginx state=stopped" -b

# 重启
ansible all -m service -a "name=nginx state=restarted" -b

# 重新加载
ansible all -m service -a "name=nginx state=reloaded" -b

# 开机启动
ansible all -m systemd -a "name=nginx enabled=yes" -b

# 禁用开机
ansible all -m systemd -a "name=nginx enabled=no" -b

# 检查状态
ansible all -m systemd -a "name=nginx state=started" -b

5. 🧹 命令/脚本执行(command/shell/script

command

# 执行 top
ansible all -m command -a "uptime"

# 执行 ls
ansible all -m command -a "ls -l /var/log"

shell

# 执行多条命令
ansible all -m shell -a "df -h && free -m"

# 执行管道命令
ansible all -m shell -a "ps aux | grep nginx"

script

# 执行本地脚本
ansible all -m script -a "./test.sh"

# 传参脚本
ansible all -m script -a "./deploy.sh param1 param2"

6. 🧩 用户与组管理

user 模块

# 创建用户
ansible all -m user -a "name=tom state=present"

# 删除用户
ansible all -m user -a "name=tom state=absent"

# 添加 sudo 权限
ansible all -m user -a "name=tom groups=sudo append=yes"

# 设置密码
ansible all -m user -a "name=tom password={{ '123456' | password_hash('sha512') }}"

# 锁定用户
ansible all -m user -a "name=tom state=present password_lock=yes"

group 模块

# 创建组
ansible all -m group -a "name=dev"

# 删除组
ansible all -m group -a "name=dev state=absent"

7. 🔐 SSH / 密钥 / 公钥管理

# 部署公钥
ansible all -m authorized_key -a "user=root key='{{ lookup('file','id_rsa.pub') }}'"

# 删除公钥
ansible all -m authorized_key -a "user=root key='ssh-rsa AAA...' state=absent"

8. 🌍 网络 / IP / 防火墙

# 查看 IP
ansible all -m command -a "ip addr"

# 设置内核参数
ansible all -m sysctl -a "name=net.ipv4.ip_forward value=1 reload=yes" -b

# firewalld 开端口
ansible all -m firewalld -a "port=80/tcp permanent=yes state=enabled" -b

# 关闭端口
ansible all -m firewalld -a "port=80/tcp state=disabled" -b

9. 📀 磁盘 / 文件系统

# 查看磁盘
ansible all -m shell -a "df -h"

# 挂载
ansible all -m mount -a "path=/data src=/dev/sdb1 fstype=ext4 state=mounted" -b

# 卸载
ansible all -m mount -a "path=/data state=unmounted" -b

10. 🐳 Docker 管理

# docker ps
ansible all -m shell -a "docker ps"

# 启动容器
ansible all -m docker_container -a "name=redis image=redis state=started"

# 停止容器
ansible all -m docker_container -a "name=redis state=stopped"

# 删除容器
ansible all -m docker_container -a "name=redis state=absent"

# 拉取镜像
ansible all -m docker_image -a "name=nginx source=pull"

11. 🌐 Git / SVN / 下载文件

# 克隆 Git
ansible all -m git -a "repo=https://github.com/a/b.git dest=/opt/b"

# 执行 wget
ansible all -m get_url -a "url=https://x.com/a.tar.gz dest=/tmp"

12. 🛠 系统信息收集(setup 模块)

ansible all -m setup

#  只获取网络信息
ansible all -m setup -a "filter=ansible_eth*"

# 获取 CPU 信息
ansible all -m setup -a "filter=ansible_processor*"

# 获取 IP
ansible all -m setup -a "filter=ansible_default_ipv4"

13. 📡 调试 / 输出(debug)

ansible all -m debug -a "msg='hello world'"

14. 📤 上传/下载(synchronize / rsync)

# pull
ansible all -m synchronize -a "src=/opt/file dest=/tmp/ mode=pull"

# push
ansible all -m synchronize -a "src=/opt/file dest=/tmp/ mode=push"

15. 🧰 高级模块(template、lineinfile 等)

lineinfile

# 添加配置行
ansible all -m lineinfile -a "path=/etc/sysctl.conf line='net.ipv4.ip_forward=1'" -b

# 修改配置行
ansible all -m lineinfile -a "path=/etc/ssh/sshd_config regexp='^#?PermitRootLogin' line='PermitRootLogin yes'" -b

replace

# 正则替换
ansible all -m replace -a "path=/etc/nginx/nginx.conf regexp='worker_processes .*' replace='worker_processes 4;' " -b

template

# 渲染模板
ansible all -m template -a "src=nginx.conf.j2 dest=/etc/nginx/nginx.conf"

16. 📚 其它常用模块

# hostname 管理
ansible all -m hostname -a "name=node-01"

# cron 任务
ansible all -m cron -a "name='backup' minute=0 hour=1 job='/usr/bin/backup'"

# 管理 SELinux
ansible all -m selinux -a "state=disabled" -b

# 管理 timezone
ansible all -m timezone -a "name=Asia/Shanghai"