command模块 ansible默认模块用于在远程主机上执行任意命令
command模块不支持shell特性 如 管道| 重定向>
ansible all -a "mkdir /tmp/demo" 在所有被管理主机上创建目录/tmp/demo
ansible web1 -a "ip a s " 查看web1的ip地址
ansible web1 -a "ip a s | head" !报错!
shell模块 与command类似 但是支持shell特性 如管道 重定向
ansible web1 -m shell -a "ip a s | head" 查看web1的ip地址 只显示前10行
script模块 用于在远程主机上执行脚本
vim /root/ansible/test.sh 在控制段工作目录创建脚本即可
ansible webservers -m script -a "test.sh" 在webservers组的主机上执行脚本
file模块 可以创建文件 目录 链接等 还可修改权限 属性
常用选项 path:指定文件路径 owner:指定文件所有者 group:指定文件所属组
state:状态 touch:表示创建文件 directory:表示创建目录 link:表示创软链接 absent:表示删除
mode:设置权限 src:source的简写指源 dest:destination的简写指目标
ansible webservers -m file -a "path=/tmp/file.txt state=touch" 在webservers组的主机上创建/tmp/file.txt
ansible webservers -m file -a "path="/tmp/demo state=directory" 在web组的主机上创建/tmp/demo目录
ansible webservers -m file -a "path=/tmp/file.txt owner=sshd group=adm mode='0777'"将属主改为sshd 属组改为adm 权限0777
ansible webservers -m file -a "path=/tmp/file.txt state=absent" 删除webservers组的主机上的/tmp/file.txt文件
ansible webservers -m file -a "path=/tmp/demo state=absent" 删除webservers组的主机上的/tmp/demo目录
ansible webservers -m file -a "src=/etc/hosts dest=/tmp/hosts.txt state=link" 创建/etc/hosts的软链接 目标是/tmp/hosts.txt
copy模块 用于将文件从控制断拷贝到被控端 src:源 dest:目标 content:内容
ansible webservers -m copy -a "src=test.txt dest=/root/" 将test.txt拷贝到webservers主机的/root/
ansible webservers -m copy -a "content='hello world' dest=/tmp/mytest.txt" 在目标主机上创建/tmp/mytest.txt内容是helloworld
fetch模块 与copy相反 copy是上传 fetch是下载 src:源 dest:目标
ansible webservers -m fetch -a "src=/etc/hosts dest=~/" 将webservers组主机上的/etc/hosts下载到本地用户的家目录下
lineinfile模块 用于确保目标文件中有某一行内容 path:待修改的文件路径 line:写入文件的一行内容 regexp:正则表达式
ansible webservers -m lineinfile -a "path=/etc/issue line='Hello world'"主机/etc/issue中一定要有helloworld如果不存在则添到结
ansible webservers -m lineinfile -a "path=/etc/issue line='123' regexp='Hello'"主机把/etc/issue中有Hello的行 替换成123
replace模块 替换关键词 path:待修改文件路径 replace:查找之后替换的内容 regexp:正则表达式用于查找文件中的内容
ansible webservers -m replace -a "path=/etc/issue regexp='old' replace='new'"将主机上/etc/issue文件中old替换成new
user模块 实现linux用户管理 name:待创建的用户名 uid:用户id group:主组 groups:附加组 home:家目录 password:密码 state:状态 present表示创建 absent表示删除 remove:删除家目录,邮箱 指为yes或true都可
ansible webservers -m user -a "name=zhangsan" 在webservers组的主机上创建用户zhangsan
ansible webservers -m user -a "name=lisi uid=1010 group=adm groups=daemon,root home=/home/lisi"
ansible webservers -m user -a "name=zhangsan password={{'123456'|password_hash('sha512')}}" {{}}是固定格式 password_hash是函数 sha512是加密算法 则password_hash函数将会把123456通过sha512加密变成张三的密码
ansible webservers -m user -a "name=zhangsan state=absent" 删除用户zhangsan 不删除家目录
ansible webservers -m user -a "name=lisi state=absent remove=yes" 删除lisi用户 同时删除家目录
A创建删除组 name:待创建的组名 gid:组的id号 state:present表示创建他是默认选项 absent表示删除
ansible webservers -m group -a "name=devops" 在webservers组的主机上创建名为devops的组
ansible webservers -m group -a "name=devops state=absent" 在webservers组的主机上删除名为devops的组