ansible学习笔记一:模块
需求:
公司内随着机器使用的越来越多,按照之前的方式已经使用不便了,需要使用ansible批量管理了,这里用测试实例验证一次,做为学习笔记。
环境:
因为自己笔记本性能问题,这里只用两台虚拟机做测试:
服务器名 | IP |
---|---|
ansible-server | 192.168.31.53 |
ansible-client | 192.168.31.167 |
安装的话,这里就不详细的说明了,因为太简单了。。因为我用的是centos7,直接yum安装就好了。。配置的话,其实我只是在/etc/ansible/hosts末尾加上了我的client主机,就开始做了测试了。下面从常用模块开始吧。
常用模块:
1. cron模块
- 这个模块是添加/删除定时任务的。
- 例如:
- 每周1,3,5做定时报警
ansible all -m cron -a ‘minute=* week=1,3,5 job="/usr/bin/wall FBI warnging" name=warngingcron’
2. script模块
- 本地写好脚本,加上执行权限之后,可以不需要分发到各服务器上,直接能看到执行结果,这样就省了copy模块的一次操作
- 例如:
ansible all -m script -a ‘/root/f1.sh’
3. yum模块
- 这里的操作其实很简单,直接就是安装
ansible all -m yum -a ‘name=httpd’
ansible all -m yum -a ‘name=nginx’
- 清理缓存,并安装
ansible all -m yum -a ‘name=dstat update_cache=yes’
4. service模块
- 这个模块是对服务的状态进程操作的
- 例如:
- 启动httpd服务并添加开启自启
ansible all -m service -a ‘name=httpd state=started enabled=yes’
5. user模块
- 这个模块是对用户的操作的
- 例如:
- 可以用name指定用户名,system指定是否系统用户,home指定家目录,groups指定属组,comment指定说明
ansible all -m user -a ‘name=nginx shell=/sbin/nologin system=yes home=/var/nginx groups=root,bin comment=“nginx service”’
- 查询
[root@ansible ~]# ansible all -a ‘getent passwd nginx’
192.168.31.167 | CHANGED | rc=0 >>
nginx❌988:982:nginx service:/var/nginx:/sbin/nologin
- 删除用户
ansible all -m user -a ‘name=ngixn state=absent remove=yes’
6. group模块
- 这个模块是对用户组进程操作的
- 例如:
- 添加用户组
ansible all -m group -a ‘name=nginx system=yes gid=999’
- 删除用户组
ansible all -m group -a ‘name=nginx state=absent’
- 查询组信息
ansible all -a ‘getent group nginx’
7. copy模块
- 这个模块是对文件进行复制操作的
- 例如
ansible all -m copy -a ‘src=/root/file dest=/root/ mode=755’
8. shell模块
- 这个模块其实是实际使用中用到最多的模块,这个模块基本快成万能模块了。。当然,你需要提前熟悉linux命令。当然这里需要注意下单引号和双引号的问题。
- 例如:
- 过滤/root/file文件内容
ansible all -m shell -a ‘grep 123 /root/file’
- 复制文件到其他地方
ansible all -m shell -a ‘cp /root/file /opt’
- 删除用户及家目录
ansible all -m shell -a ’ userdel -r test1’