Ansible模块

ansible模块

ansible测试

ansible docker -m ping
ansible all -m ping
# 第二段为主机组,all代表主机组里所有机器。-m:指定模块

模块帮助

ansible-doc #查看ansible帮助
ansible-doc -l #查看系统自带的模块
ansible-doc -l |grep user #查看user相关的模块
ansible-doc user #查看user模块的帮助,其中=是必选项,-是可选项

使用模块

ansible docker -m user -a 'name=admin'
#-a代表该模块的参数,后面用单引号引起来

ansible docker -m user -a 'name=admin state=present'
ansible docker -m user -a 'name=admin state=absent'
#state等于present代表添加用户,state等于absent代表删除用户,默认为添加

常用模块

  • command模块
ansible docker -m command -a 'useradd admin'
  • shell模块
ansible docker -m shell -a 'mkdir -p /tmp/test'
  • service
- name start httpd service
  service:
  name: httpd
  state: started
  enabled: yes
  • script模块
#执行被控端的脚本
ansible docker -m script -a '/data/install.sh'

#直接在被控端执行主控端的如下脚本,不用拷贝到被控端
#/bin/bash
ifconfig
df –hT

chmod u+x scripts.sh
ansible all -m script -a “scripts.sh”
  • yum_repository模块
ansible all -m yum_repository -a 'name=dev description="CentOS7 repo" file=dvd baseurl=http://192.168.10.130/pub/BaseOS gpgcheck=no enabled=yes'
#name是yum配置文件里的[]里的名字。description是yum配置文件里的name。file是yum配置文件的名字,后面不用加repo。

command模块和shell模块

区别

  • command模块命令将不会使用shell执行,因此,像$HOME这样的变量是不可用的,还有像<,>,,|,;,&都将不可用。

  • shell模块通过shell程序执行,默认是/bin/sh,像<,>,|,;,&可用,但这样有潜在的shell注入风险

总结:command模块更安全,因为它不受用户环境的影响。也很大的避免了潜在的shell注入风险

如何选择

两个模块都要避免使用,应该优先考虑更具体的ansible模块。比如用command或者shell执行yum命令前,应该先了解yum模块的使用方法。
使用具体模块比执行命令要优雅很多,因为这些模块设计都是具有幂等性的,并满足其他标准,如异常处理等。
Ansible包含众多的模块,大部分模块都能够保证操作的幂等性,即相关操作的多次执行能够达到相同结果这一特性。

如果没有更具体的模块,或者就是想单纯的执行某个命令,相对来说command更安全。

如果需要用户环境和流式操作,则只能使用shell模块。

WilliamZheng©版权所有 转载请注明出处! 运维架构师群:833329925
原文地址:https://www.cnblogs.com/williamzheng/p/14760249.html