ansible的模块基本使用(三)

时间:2020-12-25 14:42:26

一、环境介绍

  1、前面我们了解了一下ansible的安装和基本使用,类似saltstack,Ansible也有很多自带的模块,为了方便使用我们下面来看看常用的模块基本用法。

[test239]
test239-linux ansible_ssh_host=172.16.5.239

[test241]
172.16.5.241

[test4:children]
test239
test241

二、常用模块

  1.1、command命令模块

  #ansible-doc -s command

 name: Executes a command on a remote node
  command:
      chdir:                 # 在执行命令之前,首先切换到该目录.
      creates:               # 一个文件名,当这个文件存在时候,则该命令不执行.
      removes:               # 一个文件名,当这个文件不存在时候,则该命令不执行.

  演示:

  ansible的模块基本使用(三)

  chdir:在执行命令之前,首先切换到该目录.

  ansible的模块基本使用(三)

  creates:一个文件名,当这个文件存在时候,则该命令不执行.

  ansible的模块基本使用(三)

  removes: # 一个文件名,当这个文件不存在时候,则该命令不执行.

   ansible的模块基本使用(三)

 

  1.2、copy模块

  常用参数如下:

  backup:在copy的过程中,在覆盖之前,将目标源文件备份,备份文件包含时间信息。有两个选项:yes|no,其实可以理解为,把目标文件覆盖掉,然后在把目标文件备份一份出来。

  ansible的模块基本使用(三)

  ansible的模块基本使用(三)

  content:用来替代src,用于将指定文件的内容,拷贝到远程文件内。其实这里content指定的文件内容,你可以直接写一句话,直接放到了目标文件中,是覆盖,不是追加,内容直接不能有空格。

  ansible的模块基本使用(三)

  dest:必选项。要将源文件复制到的远程主机的绝对路径,如果源文件是一个目录,那么该路径也必须是个目录

  directory_mode:递归设定目录的权限,默认为系统默认权限

  force:如果目标主机有该文件,但内容不同,如果设置为yes,则强制覆盖。默认没有force这参数时,默认就是yes。主要是参数是no的时候,如果目标确定没有这个文件的时候才复制,跟前面说的creates类似。

  group:应该拥有文件/目录的组的名称,将被馈送到`chown',属组权限

  mode:模式的文件或目录应该是,如0644将被馈送到`chmod'

  owner:应该拥有文件/目录的用户的名称,将被馈送到`chown'属主权限

  others:所有的file模块里的选项都可以在这里使用

   注意写法:

  如果src以/结束的话,代表你复制的是目录下的所有文件,如果结束时候没有/符号,代表你复制的事宜目录。

   ansible的模块基本使用(三)

   1.3、file模块

  #ansible-doc -s file

ansible的模块基本使用(三)ansible的模块基本使用(三)
 name: Sets attributes of files
  file:
      attributes:            # Attributes the file or directory should have. To get supported flags look at the man page for `chattr' on the target system. This string should
                               contain the attributes in the same order as the one displayed by `lsattr'.
      follow:                # This flag indicates that filesystem links, if they exist, should be followed.
      force:                 # force the creation of the symlinks in two cases: the source file does not exist (but will appear later); the destination exists and is a file
                               (so, we need to unlink the "path" file and create symlink to the "src" file in place of it).
      group:                 # Name of the group that should own the file/directory, as would be fed to `chown'.
      mode:                  # Mode the file or directory should be. For those used to `/usr/bin/chmod' remember that modes are actually octal numbers (like 0644). Leaving off
                               the leading zero will likely have unexpected results. As of version 1.8, the mode may be specified as a symbolic
                               mode (for example, `u+rwx' or `u=rw,g=r,o=r').
      owner:                 # Name of the user that should own the file/directory, as would be fed to `chown'.
      path:                  # (required) path to the file being managed.  Aliases: `dest', `name'
      recurse:               # recursively set the specified file attributes (applies only to state=directory)
      selevel:               # Level part of the SELinux file context. This is the MLS/MCS attribute, sometimes known as the `range'. `_default' feature works as for `seuser'.
      serole:                # Role part of SELinux file context, `_default' feature works as for `seuser'.
      setype:                # Type part of SELinux file context, `_default' feature works as for `seuser'.
      seuser:                # User part of SELinux file context. Will default to system policy, if applicable. If set to `_default', it will use the `user' portion of the
                               policy if available.
      src:                   # path of the file to link to (applies only to `state=link'). Will accept absolute, relative and nonexisting paths. Relative paths are not
                               expanded.
      state:                 # If `directory', all immediate subdirectories will be created if they do not exist, since 1.7 they will be created with the supplied permissions.
                               If `file', the file will NOT be created if it does not exist, see the [copy] or [template] module if you want
                               that behavior.  If `link', the symbolic link will be created or changed. Use `hard' for hardlinks. If `absent',
                               directories will be recursively deleted, and files or symlinks will be unlinked. Note that `absent' will not
                               cause `file' to fail if the `path' does not exist as the state did not change. If `touch' (new in 1.4), an empty
                               file will be created if the `path' does not exist, while an existing file or directory will receive updated file
                               access and modification times (similar to the way `touch` works from the command line).
      unsafe_writes:         # Normally this module uses atomic operations to prevent data corruption or inconsistent reads from the target files, sometimes systems are
                               configured or just broken in ways that prevent this. One example are docker mounted files, they cannot be updated
                               atomically and can only be done in an unsafe manner. This boolean option allows ansible to fall back to unsafe
                               methods of updating files for those cases in which you do not have any other choice. Be aware that this is
                               subject to race conditions and can lead to data corruption.
file参数
force #强制执行
group #设置文件的属组
mode  #设置文件的权限
owner #设置文件的属主
path= #被管理文件的路径。别名:'dest','name'
recurse #递归设置指定的文件属性(仅适用于state =目录)
src  #链接到的文件的路径(仅适用于“state = link”)。将接受绝对的,相对的和不存在的路径。相对路径未扩展。
state    #file代表拷贝后是文件;link代表最终是个软链接;directory代表文件夹;hard代表硬链接;touch代表生成一个空文件;absent代表删除

  授权:

  单文件授权,将目标主机上的/root/test文件设置755权限,属主leihaidong,属组leihaidong。

[root@localhost ~]# ansible test239 -m file -a 'dest=/root/test mode=755 owner=leihaidong group=leihaidong '

  目录递归授权,将目标主机上/root/test-dir目录下的所有文件(包括test-dir文件夹),设置755权限,属主,属组都是leihaidong,注意后面的参数recurse

ansible  test239  -m file -a 'dest=/root/test-dir  mode=755 owner=leihaidong group=leihaidong recurse=yes'

  更改权限:在这里path等同于dest参数,这里将/root/test3更改权限为644,需要改其他权限,加参数即可。

ansible  test239  -m file -a 'path=/root/test3  mode=644'

  新建:

  新建目录:在目标/root/建立一个名为test2的目录,是目录还是文件由参数决定state=directory

ansible  test239  -m file -a 'dest=/root/test2   mode=755 owner=leihaidong group=leihaidong state=directory'

  新建文件:在目标/root/建立一个名为test2的文件,是目录还是文件由参数决定state=touch

ansible  test239  -m file -a 'dest=/root/test3   mode=755 owner=leihaidong group=leihaidong state=touch'

  删除:state=absent是代表删除操作,如果删除目录,注意结尾/

ansible  test239  -m file -a 'path=/root/test2  state=absent'

  软连接:state是link的时候代表软连接

# ansible  test239  -m file -a 'src=/root/test1 dest=/root/test2   state=link'

  ansible的模块基本使用(三)

   1.4、yum模块

  安装

ansible all -m yum -a "state=present name=lrzsz"

  批量安装:

ansible all -m yum -a "state=latest name=lrzsz,gcc,gcc-c++"

  ansible的模块基本使用(三) 

  1.5、service模块

   设置开机启动:

# ansible all -m service -a "name=httpd enabled=yes

  停止服务:

ansible all -m service -a "name=httpd state=stopped

  启动服务:

ansible all -m service -a "name=sshd state=started"

  重启服务:

# ansible all -m service -a "name=httpd state=restarted"

  1.6. cron模块

  #ansible-doc -s cron

backup #如果yes,那么在修改之后会进行备份,备份的路径在backup_file
cron_file #如果指定,请在cron.d中使用此文件,而不是单个用户的crontab。
day   #工作应该运行的月份的第几天(1-31,*,*/2等)
hour  #工作应该运行的小时(0-23,*,* / 2等)
job   #执行命令。 如果state =present则为必需。
minute #工作应该运行一分钟(0-59,*,*/2等)
month  #工作应该运行的一个月(1-12,*,*/2等)
name  #crontab条目的说明。
state #present(不存在就添加,存在如果是注释状态就取消状态启动此定时任务),absent为删除定时任务
user  #crontab应该修改的具体用户。
weekday #工作应该运行的星期几(周六至周六为0-6)
state:状态,absent意味删除

  案例一:

[root@localhost ~]# ansible all -m cron -a 'name="pingbaidu" minute=*/1 user=root job="/usr/bin/ping www.baidu.com -c 4 >> /root/test.ping"

  #name为定时任务的名称也就是定时任务的注释,minute为分钟,hour=为小时,day=为天,month为月,weekday为星期,他们默认都为*,user=用户名称的意思为制定将定时任务添加到哪个用户的定时任务中去,job=""里面的内容为定时任务的内容,注意引号。下面看下执行后的截图:

   ansible的模块基本使用(三)

  #state=absent删除当前这条计划任务

  ansible的模块基本使用(三)

  1.7. script模块

   # ansible-doc -s script

creates:一个文件名,当这个文件存在,则该命令不执行
free_form= :本地脚本路径
removes : removes:一个文件名,当这个文件不存在,则该命令不执行

  #只要控制节点上面存在这个脚本就可以,被执行端上面无需有此脚本,一样可以运行此脚本,就连脚本的权限都不用特意给可执行权限。

#ansible all -m script -a '/root/scripts.sh'

ansible的模块基本使用(三)

  1.8. user模块

  # ansible-doc -s user

append : 如果是yes,就是给这个用户添加一个组
comment:可选择地设置用户帐户的描述(也称为“GECOS”)。
createhome :除非设置为“no”,否则当创建帐户或主目录不存在时,将为用户创建主目录。
force : 当与`state = absent'一起使用时,行为与`userdel --force'一样。
generate_ssh_key : 为yes时,生成秘钥对。生成密钥时,只会生成公钥文件和私钥文件,和直接使用ssh-keygen指令效果相同,不会生成authorized_keys文件。
group:设置用户主组,后面跟用户组名称
groups:设置多个组,当设置为'groups='的时候,用户将从主组以外的所有组移除
home:可以选择设置用户的主目录。
move_home :如果与“home =”一起使用时设置为“yes”,则尝试将用户的主目录移动到指定的目录(如果尚未存在)。
name= :创建,删除或修改用户的名称。
non_unique :可选地,当与-u选项一起使用时,该选项允许将用户ID更改为非唯一值。
password:(可选)将用户密码设置为此加密值。
remove:当与`state = absent'一起使用时,行为与`userdel --remove'一样。
shell:可选择地设置用户的shell。
ssh_key_bits:可选择指定要创建的SSH密钥中的位数。
ssh_key_comment:(可选)定义SSH密钥的注释。
ssh_key_file :(可选)指定SSH密钥文件名。
ssh_key_passphrase:设置SSH密钥的密码。 如果没有提供密码,SSH密钥将默认没有密码。
ssh_key_type:(可选)指定要生成的SSH密钥的类型。 可用的SSH密钥类型将取决于目标主机上的实现。
state : 帐户是否应该存在 当“absent”时,删除用户帐户。
system : 创建帐户时,将其设置为“yes”将使用户成为系统帐户。 现有用户无法更改此设置。
uid : 可选择地设置用户的“UID”。
update_password : 如果不同,“always”会更新密码。 ‘on_create'只会为新创建的用户设置密码。

  新建账户test3,这里password不能直接设置密码,需要先生成密码方式

ansible all -m user -a 'name=test3 password=$6$51niux$Ki2bkGs1V4bX682a252YsLzMsZstXdWMZjJoc2lMAbcW8sXICJMsysYWDcs3EE7srp0CpZ4.HDqrbQSaAPZ3a1 state=present'

  #linux的用户的密码是通过sha512加密生成的,下面只介绍一种生成方式:

# perl -e 'print crypt("12345678","\$6\$51niux\$") . "\n"'  #这里密码是12345678,然后又加了个51niux的盐,当然你可以随机加盐

  删除账户

ansible all -m user -a 'name=test3 state=absent remove=yes'

  创建一个名字为testgr组

# ansible all -m group  -a 'name=testgr gid=8000 state=present'

  删除testgr组

# ansible all -m group  -a 'name=testgr gid=8000 state=absent'

  1.10.get_url模块

   # ansible-doc -s get_url

dest= : 下载到哪里(绝对路径),如果目标是一个目录,就用服务器上面文件的名称,如果目标设置了名称就用目标设置的名称。
force : 如果yes,dest不是目录,将每次下载文件,如果内容改变,替换文件。如果否,则只有在目标不存在时才会下载该文件。
others : [file]模块接受的所有参数也可以在这里工作
sha256sum : 如果将SHA-256校验和传递给此参数,目标文件的摘要将在下载后计算,以确保其完整性
url= : HTTP,HTTPS或FTP URL(http | https | ftp)
url_password : 用于HTTP基本认证的密码。 如果未指定`url_username'参数,则不会使用`url_password'参数。
url_username : 用于HTTP基本认证的用户名。 对于允许空密码的站点,此参数可以不使用`url_password'使用。
use_proxy : 如果是no,它将不使用代理,即使在目标主机上的环境变量中定义了一个代理。
validate_certs :如果“no”,SSL证书将不会被验证。 这只能使用自签名证书在个人控制的网站上使用。

  ##url为要下载的链接,dest为要下载到的目录,-vvvv可以查看详细的执行过程,这个过程不是下载进度条,是更详细的下载信息。

ansible all  -m get_url -a 'url=http://nginx.org/download/nginx-1.8.1.tar.gz dest=/tmp/' -vvvv

  1.12 setup模块

  类似saltstack的grains静态信息收集,收集一些主机硬件信息或者以及其他如fqdn等等

  #ansible all -m setup 就相当于ansible all -m setup -a “”#收集所有的信息

  # ansible all -m setup -a "filter=ansible_nodename"  #filter=就是后面跟过滤的键名,这里就是查看所有的主机名

  ansible的模块基本使用(三)

  # ansible test239 -m setup -a "filter=ansible_ens33" 查看网卡信息

  # ansible test239 -m setup -a "filter=*ipv4*"   这里是支持正则表达式的

  ansible的模块基本使用(三)

  本文操作与大佬的http://www.51niux.com/?id=50这篇博客