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"
相关推荐
迷茫的大专生7 天前
服务器部署与 MySQL 运维学习笔记:从 Ansible 到高可用与性能优化
mysql·nginx·ansible·mysql优化·keepalive
杜子不疼.10 天前
Ansible 批量部署 Node Exporter:从单机安装流程到远程主机统一执行
ai·ansible
运维全栈笔记11 天前
Ansible 自动化 Nginx 集群部署实战:动态 Inventory、滚动发布与 Role 工程化
nginx·自动化·ansible
User_芊芊君子15 天前
让异构增量同步飞起来-KFS全链路并行同步方案
运维·自动化·ansible
あ-18 天前
ansible-playbook安装seaweedfs三节点集群
ansible
Tassel_YUE20 天前
非 ansible 主机批量执行命令方法:psssh 和 pscp(随手记)
linux·网络·ssh·scp·ansible
亿朝亿夕1 个月前
ansible安装
ansible
.柒宇.1 个月前
运维常见面试题_07_配置管理与监控(Ansible · Prometheus · Alertmanager)· 容器编排(Kubernetes)
运维·k8s·ansible·prometheus
相顾若初见1 个月前
Ansible部署k8s
容器·kubernetes·ansible
wzq11_6661 个月前
ansible部署项目——基于tidb数据库安装zabbix_server
ansible·zabbix·tidb