很多ansible模块都具有幂等性的特征。
幂等性:任意次执行所产生的影响均与一次执行的影响相同
command,shell,script默认不带幂等性
-
[root@control ansible]# ansible-doc -l | wc -l 查看ansible有多少个模块
-
2834
file模块 --创建文件、目录、连接、权限、属性-------------
ansible all -m file -a "path=/tmp/file.txt state=touch" 所有虚拟机创建文件
常见报错
1、node1 | FAILED! => {
… …
"changed": false,
"msg": "value of state must be one of: absent, directory, file, hard, link, touch, got: touc"
}
参数打错 "msg"报错value of 等号后面参数打错
2、node1 | FAILED! => {
… …
"msg": "Unsupported parameters for (file) module: nmae Supported parameters include: _diff_peek, _original_basename, access_time,
access_time_format, attributes, backup, content, delimiter, directory_mode,
follow, force, group, mode, modification_time, modification_time_format, owner,
path, recurse, regexp, remote_src, selevel, serole, setype, seuser, src, state,
unsafe_writes"
} state或path打错,"msg"报错Unsupported parameters 等号前面参数打错
ansible test -m file \
-a "path=/tmp/mydir state=directory" 创建目录
touch 没有文件创建文件 如果有就修改文件时间
SUID 、s=4
SGID 、s =2
Sticky Bit 、t=1
ansible test -m file \
> -a "path=/tmp/file.txt owner=sshd group=adm mode=0777"修改权限
到node1主机查看权限是否修改
absent 缺少、卸载、删除
present 出现、安装、创建
ansible all -m file -a "path=/tmp/file.txt state=absent"删除所有虚拟机/tmp/file.txt
[root@control ansible]# ansible test -m file \
> -a "src=/etc/hosts path=/tmp/host.txt state=link" 创建软连接
到node1上查看
ls -l /tmp/host.txt
lrwxrwxrwx. 1 root root 10 May 25 11:48 /tmp/host.txt -> /etc/hosts
copy模块--------
将本机文件拷贝到对方电脑
echo AAA > ~/a.txt
[root@control ansible]# ansible test -m copy -a "src=~/a.txt dest=/root"
到node1上查看
ls /root/a.txt
/root/a.txt
fetch模块
与copy模块类似,作用相反 将其他主机文件拷贝到本地
ansible test -m fetch -a "src=/etc/hostname dest=~/" 将node1hostname拷贝到本机
ansible-doc 模块名称 查看帮助文档
lineinfile单行修改|replace模块 修改文件内容
ansible test -m lineinfile \
> -a "path=/etc/issue line='hello world'" 在源文件最后一行追加一行
到node1上查看
cat /etc/issue
\S
Kernel \r on an \mhello world
ansible test -m replace \
> -a "path=/etc/issue.net regexp=Kernel replace=Ocean" 将Kernel替换成Ocean regexp后面是旧内容 replace后面是新内容
到node1查看结果
cat /etc/issue.net
\S
Ocean \r on an \m
user模块
ansible test -m user -a "name=tuser1 state=present" 创建用户
到node1查看此用户
id tuser1
uid=1000(tuser1) gid=1000(tuser1) groups=1000(tuser1)
ansible test -m user -a \
> "name=tuser2 uid=1010 group=adm groups=daemon,root home=/home/tuser2" 创建用户指定参数
到node1查看此用户
id tuser2
uid=1010(tuser2) gid=4(adm) groups=4(adm),2(daemon),0(root)
添加密码
[root@control ansible]# ansible test -m user \
> -a "name=tuser1 password={{'abc'| password_hash('sha512')}}" 给tuser1添加密码
到node1查看
cat /etc/shadow
tuser1:$6$pFisl4525069stkX$570vO9HbWe95EzQZCeSxTk6QOdak2t2B52jn2/h.pVhALKnf71JIIR1s..1nvBeFVUEggiEg.KTKPrfFFzl0X.:18772:0:99999:7:::
删除用户
ansible test -m user \
> -a "name=tuser1 state=absent" 仅删除用户 不删除家目录
到node1查看
[root@node1 ~]# id tuser1
id: ‘tuser1’: no such user
[root@control ansible]# ansible test -m user -a "name=tuser2 state=absent remove=true" 删除用户、连同家目录邮箱一起删除
到node1查看
ls /home
tuser1 家目录没有tuser2