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"
相关推荐
码上上班8 小时前
Ansible课程
ansible
至乐活着3 天前
Ansible自动化运维实战:从零部署高可用Nginx+静态网站集群
ansible·自动化运维·devops·playbook·配置管理
John Song6 天前
ansible-playbook常用的检查命令
windows·ansible
明航咨询_贾老师9 天前
RHCA Ansible高级自动化(DO374)认证信息整理
运维·自动化·ansible·rhca·红帽认证
有毒的教程13 天前
Ansible批量操作自动化完整教程:批量部署服务、配置同步、软件更新实战
运维·自动化·ansible
Hy行者勇哥18 天前
用Cursor智能编写Ansible/Terraform脚本,打通CI/CD链路
ci/cd·ansible·terraform
芷栀夏20 天前
飞牛NAS怎么部署Immich?家庭照片自动备份与远程访问教程
服务器·nginx·ansible
悠然南风1 个月前
Ansible常见模块总结及LDAP Role 编写与调试
ansible
祺风挽楠1 个月前
ansible编辑
网络·ansible
芳心粽伙饭1 个月前
Ansible课后作业
ansible