Ansible命令

1 命令组成

ansible 命令四大部分组成

(1)ansible头部使用命令

(2)-all 代表操作所有机器,可以指定某个IP/组

(3)-m 代表使用模块,你所要进行的操作

(4)-a 代表你使用模块的详细参数,模块下的某一个具体功能

复制代码
ansible -all -m 模块 -a "参数"

2 模块

(1)高频核心使用模块

复制代码
command模块:执行普通Linux命令
shell模块:执行命令,支持管道、重定向
copy模块:本地文件批量推送到远程服务器
file模块:创建/删除文件、目录、修改权限
user模块:批量创建、删除系统用户
yum/dnf 模块:批量安装、卸载软件

(2)示例

command

复制代码
# 1. 查看远程主机主机名
ansible all -m command -a "hostname"

# 2. 切换到/tmp目录执行ls
ansible all -m command -a "ls chdir=/tmp"

# 3. /etc/hosts存在就不执行touch
ansible all -m command -a "touch test.txt creates=/etc/hosts"

shell

复制代码
# 1. 磁盘过滤根分区(管道生效)
ansible all -m shell -a "df -h | grep /dev/vda1"

# 2. 输出内容重定向写入文件
ansible all -m shell -a "echo 'test content' > /tmp/demo.txt"

# 3. 多命令串联
ansible all -m shell -a "mkdir -p /data && touch /data/flag.txt"

copy

复制代码
# 1. 推送本地/etc/hosts到远程/tmp/,权限644
ansible all -m copy -a "src=/etc/hosts dest=/tmp/hosts.bak mode=644"

# 2. 推送前备份远程已有同名文件
ansible all -m copy -a "src=/root/my.conf dest=/etc/my.conf backup=yes"

# 3. 直接写入单行内容到远程文件(不用本地文件)
ansible all -m copy -a "content='hello ansible\nline2' dest=/tmp/hello.txt"

file

复制代码
# 1. 递归创建多级目录
ansible all -m file -a "path=/data/ansible state=directory mode=755 owner=root"

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

# 3. 删除文件
ansible all -m file -a "path=/tmp/test.file state=absent"

# 4. 创建软链接:/link -> /data/ansible
ansible all -m file -a "path=/link src=/data/ansible state=link"

user

复制代码
# 1. 创建可登录普通用户test
ansible all -m user -a "name=test shell=/bin/bash"

# 2. 创建不可登录系统账号nginx
ansible all -m user -a "name=nginx shell=/sbin/nologin"

# 3. 删除用户+一并删除家目录
ansible all -m user -a "name=test state=absent remove=yes"

# 4. 给用户追加附加组
ansible all -m user -a "name=test groups=wheel append=yes"

yum/dnf

复制代码
# 1. 批量安装tree、net-tools
ansible all -m yum -a "name=tree,net-tools state=installed"

# 2. 卸载软件
ansible all -m yum -a "name=tree state=absent"

# 3. 升级nginx到最新版本
ansible all -m yum -a "name=nginx state=latest"

# 4. 安装本地rpm包
ansible all -m yum -a "name=/root/nginx.rpm state=installed"
相关推荐
垚垚学技术_聚焦云原生3 天前
Ansible Vault 安全实践:敏感密码、密钥加密存储方案
安全·elasticsearch·ansible
广目软件5 天前
HA分布式架构采集节点变更操作手册20261029
运维·服务器·ansible·zabbix·prometheus
Moshow郑锴6 天前
Ansible 批量部署 Node.js 服务:ZIP 直解与共享目录分发两种方案对比
node.js·ansible
垚垚学技术_聚焦云原生6 天前
Ansible Playbook 进阶:when 条件、loop 循环、handlers 触发器落地
linux·ansible·自动化运维·devops
Moshow郑锴6 天前
GCP MIG 重建后 Ansible 初始化实战:PowerShell + NSSM 挂载 Windows 服务
windows·ansible
承渊政道8 天前
新增一台服务器时还要重新装Nginx?Ansible只改hosts目标列表,同一份Playbook继续执行
运维·nginx·ansible·内网穿透·cpolar
Helix25010 天前
Ansible混合环境自动化:Windows与Linux统一配置管理实战
windows·自动化·ansible·playbook·配置管理·winrm·混合环境
垚垚学技术_聚焦云原生11 天前
Ansible 变量体系详解:主机变量、组变量、全局变量优先级实战
ansible·自动化运维·devops·变量优先级
I'mChloe20 天前
不再逐台装Docker:我用Ansible Playbook批量统一服务器环境
服务器·docker·ansible
筑梦之路20 天前
Alibaba Cloud Linux 4 制作 Ansible RPM包实践(离线可复用)——筑梦之路
linux·运维·ansible