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"
相关推荐
小义_17 小时前
【Ansible】(三)基础配置与连接设置
云原生·ansible
炸炸鱼.5 天前
Ansible 企业级实战:Playbook 与 Roles 完全指南
网络·ansible
风曦Kisaki6 天前
# 自动化运维Day03:Ansible模块进阶(setup,debug),四种常用变量,进阶语法;Ansible Roles(角色)
运维·自动化·ansible
炸炸鱼.8 天前
Ansible 部署应用:从入门到精通
ansible
Peace8 天前
【Ansible】
linux·运维·ansible
Plastic garden9 天前
K8s(1)前置ansible准备环境
容器·kubernetes·ansible
遇见火星11 天前
从0到1掌握Ansible:让自动化运维不再是梦想
运维·自动化·ansible
遇见火星11 天前
Jenkins + Ansible 集成实战:把配置管理焊进流水线里
运维·ansible·jenkins
江华森13 天前
Ansible 自动化运维:从入门到实战
运维·自动化·ansible