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"