mikechenjs 发表于 2018-3-21 09:32:33

ansible 常用模块使用练习


ansible 常用模块使用

#目录
      #一、用来查看远程主机的一些基本信息 setup,列出很多
      #二、用来测试远程主机的运行状态 PING
      #三、在远程主机上执行命令 command,缺点:运行的命令中无法使用变量,管道。
      #四、切换到某个shell执行指定的指令,参数与command相同。与command不同的是,此模块可以支持命令管道,同时还有另一个模块也具备此功能:raw
      #五、将本机的.sh脚本在被管理主机运行 script
      #六、设置管理节点生成定时任务
      #七、用户和用户组
      #八、设置文件属性及软链接 file
      #九、将文件复制到被管理主机
      #十、yum 安装程序包
      #十一 、用于管理服务 service模块

模块使用:
如何查看模块帮助:
   ansible-doc -l          #查看所有模块
    ansible-doc -s MODULE_NAME       #查看指定模块的详细帮助
ansible命令应用基础:
语法: ansible <host-pattern> [-f forks] [-m module_name] [-a args]
   -f forks:启动的并发线程数;
   -m module_name: 要使用的模块;
   -a args: 模块特有的参数;

   # 一、 用来查看远程主机的一些基本信息 setup,列出很多

# ansible apachesvrs -m setup |grep hostname
      "ansible_hostname": "docker01",
      "facter_hostname": "docker01",

# ansible apachesvrs -m setup -a 'filter=ansible_memfree_mb'
172.16.0.98 | SUCCESS => {
    "ansible_facts": {
      "ansible_memfree_mb": 883
    },
    "changed": false
}

# 二、用来测试远程主机的运行状态 PING

# ansible apachesvrs -m ping
172.16.0.98 | SUCCESS => {
    "changed": false,
    "ping": "pong"
}

# 三、在远程主机上执行命令 command,缺点:运行的命令中无法使用变量,管道。
# ansible apachesvrs -m command -a "ip route"
172.16.0.98 | SUCCESS | rc=0 >>
default via 172.16.0.1 dev eth1proto staticmetric 100
10.0.0.0/24 dev eth0proto kernelscope linksrc 10.0.0.98metric 100
172.16.0.0/24 dev eth1proto kernelscope linksrc 172.16.0.98metric 100
172.16.18.0/24 dev docker0proto kernelscope linksrc 172.16.18.1

      chdir         # 在执行命令之前,先切换到该目录
      creates         # 一个文件名,当这个文件存在,则该命令不执行
      executable      # 切换shell来执行命令,需要使用命令的绝对路径
      free_form=      #要执行的Linux指令,一般使用Ansible的-a参数代替。
      removes         #一个文件名,这个文件不存在,则该命令不执行
      
      
#四、切换到某个shell执行指定的指令,参数与command相同。与command不同的是,此模块可以支持命令管道,同时还有另一个模块也具备此功能:raw

# ansible apachesvrs -m command -a "echo 'a2p13mvh' | passwd --stdin root"
172.16.0.98 | SUCCESS | rc=0 >>
a2p13mvh | passwd --stdin root//没有成功

# ansible apachesvrs -m shell -a "echo 'a2p13mvh' | passwd --stdin root"
172.16.0.98 | SUCCESS | rc=0 >>
更改用户 root 的密码 。
passwd:所有的身份验证令牌已经成功更新。


# 五、将本机的.sh脚本在被管理主机运行 script
       creates      # 一个文件名,当这个文件存在,则该命令不执行
       free_form=   # 本地脚本路径
       removes      # 一个文件名,这个文件不存在,则该命令不执行

# ls
ansible.cfgansible.cfg.bakhostsroles
# vi /tmp/testdate.sh
# chmod +x /tmp/testdate.sh
# cat /tmp/testdate.sh
#!/bin/sh
date +%F_%H:%M:%S
# ansible apachesvrs -m script -a "/tmp/testdate.sh"
172.16.0.98 | SUCCESS => {
    "changed": true,
    "rc": 0,
    "stderr": "Shared connection to 172.16.0.98 closed.\r\n",
    "stdout": "2017-09-12_13:55:17\r\n",
    "stdout_lines": [
      "2017-09-12_13:55:17"
    ]
}

# 六、设置管理节点生成定时任务
# cat /tmp/testdate.sh
#!/bin/sh
date +%F_%H:%M:%S
# ansible apachesvrs -m cron -a "minute=*/10 job=/bin/echo $date name=testcron"
172.16.0.98 | SUCCESS => {
    "changed": true,
    "envs": [],
    "jobs": [
      "testcron"
    ]
}
# ansible apachesvrs -m command -a "crontab -l"
172.16.0.98 | SUCCESS | rc=0 >>
#Ansible: testcron
*/10 * * * * /bin/echo

# ansible apachesvrs -m cron -a "minute=*/10 job=/bin/echo $date name=testcron state=absent"   //加state=absent删除
172.16.0.98 | SUCCESS => {
    "changed": true,
    "envs": [],
    "jobs": []
}
# ansible apachesvrs -m command -a "crontab -l"
172.16.0.98 | SUCCESS | rc=0 >>

      ansible-doc -s cron
   - name: 设置管理节点生成定时任务
   action: cron
   backup             # 如果设置,创建一个crontab备份
   cron_file          #如果指定, 使用这个文件cron.d,而不是单个用户crontab
   day                # 日应该运行的工作( 1-31, *, */2, etc )
   hour               # 小时 ( 0-23, *, */2, etc )
   job                #指明运行的命令是什么
   minute             #分钟( 0-59, *, */2, etc )
   month            # 月( 1-12, *, */2, etc )
   name               #定时任务描述
   reboot             # 任务在重启时运行,不建议使用,建议使用special_time
   special_time       # 特殊的时间范围,参数:reboot(重启时),annually(每年),monthly(每月),weekly(每周),daily(每天),hourly(每小时)
   state            #指定状态,prsent表示添加定时任务,也是默认设置,absent表示删除定时任务
   user               # 以哪个用户的身份执行
   weekday            # 周 ( 0-6 for Sunday-Saturday, *, etc )




#七、用户和用户组
管理用户帐号 user

# ansible dockersvrs -m user -a "name=test1"
172.16.0.97 | SUCCESS => {
    "changed": true,
    "comment": "",
    "createhome": true,
    "group": 1000,
    "home": "/home/test1",
    "name": "test1",
    "shell": "/bin/bash",
    "state": "present",
    "system": false,
    "uid": 1000
}

# ansible apachesvrs -m user -a "name=test1 password=test123"
172.16.0.98 | SUCCESS => {
    "append": false,
    "changed": true,
    "comment": "",
    "group": 201,
    "home": "/home/test1",
    "move_home": false,
    "name": "test1",
    "password": "NOT_LOGGING_PASSWORD",
    "shell": "/bin/bash",
    "state": "present",
    "uid": 1000
}

# ansible dockersvrs -m user -a "name=test1 state=absent"
172.16.0.96 | SUCCESS => {
    "changed": true,
    "force": false,
    "name": "test1",
    "remove": false,
    "state": "absent"
}

       action: user
       comment          # 用户的描述信息
       createhome       # 是否创建家目录
       force            # 在使用`state=absent'是, 行为与`userdel --force'一致.
       group            # 指定基本组
       groups         # 指定附加组,如果指定为('groups=')表示删除所有组
       home             # 指定用户家目录
       login_class      #可以设置用户的登录类 FreeBSD, OpenBSD and NetBSD系统.
       move_home      # 如果设置为`home='时, 试图将用户主目录移动到指定的目录
       name=            # 指定用户名
       non_unique       # 该选项允许改变非唯一的用户ID值
       password         # 指定用户密码
       remove         # 在使用 `state=absent'时, 行为是与 `userdel --remove'一致.
       shell            # 指定默认shell
       state            #设置帐号状态,不指定为创建,指定值为absent表示删除
       system         # 当创建一个用户,设置这个用户是系统用户。这个设置不能更改现有用户。
       uid            #指定用户的uid
       update_password# 更新用户密码

添加或删除组
# ansible apachesvrs -m group -a "name=group1 gid=201"
172.16.0.98 | SUCCESS => {
    "changed": true,
    "gid": 201,
    "name": "group1",
    "state": "present",
    "system": false
}
# ansible apachesvrs -m user -a "name=test1 group=group1"
172.16.0.98 | SUCCESS => {
    "changed": true,
    "comment": "",
    "createhome": true,
    "group": 201,
    "home": "/home/test1",
    "name": "test1",
    "shell": "/bin/bash",
    "state": "present",
    "system": false,
    "uid": 1000
}

      - name: 添加或删除组
      action: group
      gid       # 设置组的GID号
      name=   # 管理组的名称
      state   # 指定组状态,默认为创建,设置值为absent为删除
      system    # 设置值为yes,表示为创建系统组


#八、设置文件属性及软链接 file
# ansible apachesvrs -m file -a "owner=test1 group=group1 mode=644 path=/tmp/testfile"
172.16.0.98 | SUCCESS => {
    "changed": true,
    "gid": 201,
    "group": "group1",
    "mode": "0644",
    "owner": "test1",
    "path": "/tmp/testfile",
    "secontext": "unconfined_u:object_r:user_tmp_t:s0",
    "size": 14,
    "state": "file",
    "uid": 1000
}
# ansible apachesvrs -m command -a "ls -l /tmp/testfile"
172.16.0.98 | SUCCESS | rc=0 >>
-rw-r--r--. 1 test1 group1 14 9月12 14:24 /tmp/testfile

# ansible apachesvrs -m file -a "path=/tmp/testfile.link src=/tmp/testfile state=link"   //软链接
172.16.0.98 | SUCCESS => {
    "changed": true,
    "dest": "/tmp/testfile.link",
    "gid": 0,
    "group": "root",
    "mode": "0777",
    "owner": "root",
    "secontext": "unconfined_u:object_r:user_tmp_t:s0",
    "size": 13,
    "src": "/tmp/testfile",
    "state": "link",
    "uid": 0
}

# ansible apachesvrs -m shell -a "ls -l /tmp/ |grep testfile"
172.16.0.98 | SUCCESS | rc=0 >>
-rw-r--r--. 1 test1 group1   14 9月12 14:24 testfile
lrwxrwxrwx. 1 rootroot   13 9月12 14:30 testfile.link -> /tmp/testfile

      - name: 设置文件属性
      action: file
      force          # 需要在两种情况下强制创建软连接,一种是源文件不存在但之后会建立的情况下;另一种是目标连接已存在,需要先取消之前的软连接,有两个选项:yes|no
      group          # 设置文件或目录的属组
      mode         # 设置文件或目录的权限
      owner          # 设置文件或目录的属主
      path=          # 必选项,定义文件或目录的路径
      recurse      # 递归设置文件的属性,只对目录有效
      src            # 要被链接到的路径,只应用与state=link的情况
      state          # directory:如果目录不存在,创建目录;file:即使文件不存在,也不会被创建;link:创建软连接;hard:创建



# 九、将文件复制到被管理主机
# ansible apachesvrs -m copy -a "src=/tmp/testcopy dest=/tmp/ mode=600"
172.16.0.98 | SUCCESS => {
    "changed": true,
    "checksum": "da39a3ee5e6b4b0d3255bfef95601890afd80709",
    "dest": "/tmp/testcopy",
    "gid": 0,
    "group": "root",
    "md5sum": "d41d8cd98f00b204e9800998ecf8427e",
    "mode": "0600",
    "owner": "root",
    "secontext": "unconfined_u:object_r:admin_home_t:s0",
    "size": 0,
    "src": "/root/.ansible/tmp/ansible-tmp-1505200274.23-223836564805494/source",
    "state": "file",
    "uid": 0
}
# ansible apachesvrs -m command -a "ls -l /tmp/testcopy"
172.16.0.98 | SUCCESS | rc=0 >>
-rw-------. 1 root root 0 9月12 15:11 /tmp/testcopy

# ansible apachesvrs -m copy -a 'content="this is a copy testfile" dest=/tmp/testfile01 mode=600'//指定内容
172.16.0.98 | SUCCESS => {
    "changed": true,
    "checksum": "4384604f3bad7b6a499644382d4abf946cea8ef3",
    "dest": "/tmp/testfile01",
    "gid": 0,
    "group": "root",
    "md5sum": "c5b8807edaeab938ff0965ef3745c502",
    "mode": "0600",
    "owner": "root",
    "secontext": "unconfined_u:object_r:admin_home_t:s0",
    "size": 23,
    "src": "/root/.ansible/tmp/ansible-tmp-1505200442.6-221173053342878/source",
    "state": "file",
    "uid": 0
}

# ansible apachesvrs -m command -a "cat /tmp/testfile01"
172.16.0.98 | SUCCESS | rc=0 >>
this is a copy testfile


      - name: 将文件复制到被管理主机
      action: copy
      backup          # 创建一个备份文件包括时间戳信息,如果以某种方式重创错了,还可以拿回原始文件
      content         # 取代src=,表示直接用此处指定的信息生成为目标文件内容;
      dest=         # 远程节点存放文件的路径,必须是绝对路径
      directory_mode# 递归复制设置目录权限,默认为系统默认权限
      force         # 如果目标主机包含该文件,但内容不同,如果设置为yes,则强制覆盖,如果设置为no,则只有当目标主机的目标位置不存在该文件时,才复制。默认为yes
      group         # 复制到远程主机后,指定文件或目录的属
      mode            # 复制到远程主机后,指定文件或目录权限,类似与 `chmod'指明如 0644
      owner         # 复制到远程主机后,指定文件或目录属主
      src             # 指定复制的源文件,可以是相对路径或者绝对路径,如果给出的源是目录,那么会把目录下的所有文件都复制过去


# 十、yum 安装程序包


# ansible apachesvrs -m yum -a "name=lrzsz"
172.16.0.98 | SUCCESS => {
    "changed": true,
    "msg": "Warning: RPMDB altered outside of yum.\n",
    "rc": 0,
    "results": [
      "Loaded plugins: fastestmirror, langpacks, product-id, search-disabled-repos,\n            : subscription-manager\nThis system is not registered with Subscription Management. You can use subscription-manager to register.\nLoading mirror speeds from cached hostfile\n * base: mirrors.cn99.com\n * epel: mirrors.aliyun.com\n * extras: mirrors.cn99.com\n * updates: mirrors.163.com\nResolving Dependencies\n--> Running transaction check\n---> Package lrzsz.x86_64 0:0.12.20-36.el7 will be installed\n--> Finished Dependency Resolution\n\nDependencies Resolved\n\n================================================================================\n Package         Arch             Version                  Repository      Size\n================================================================================\nInstalling:\n lrzsz         x86_64         0.12.20-36.el7         base            78 k\n\nTransaction Summary\n================================================================================\nInstall1 Package\n\nTotal download size: 78 k\nInstalled size: 181 k\nDownloading packages:\nRunning transaction check\nRunning transaction test\nTransaction test succeeded\nRunning transaction\nInstalling : lrzsz-0.12.20-36.el7.x86_64                                  1/1 \nVerifying: lrzsz-0.12.20-36.el7.x86_64                                  1/1 \n\nInstalled:\nlrzsz.x86_64 0:0.12.20-36.el7                                                 \n\nComplete!\n"
    ]
}


root@ansible01 ansible]# ansible apachesvrs -m shell -a "yum list installed |grep lrzsz"
: Consider using yum module rather than running yum

172.16.0.98 | SUCCESS | rc=0 >>
lrzsz.x86_64                         0.12.20-36.el7                  @base   

      action: yum
      conf_file          # yum的配置文件
      disable_gpg_check# 关闭gpg_check
      disablerepo      # 不启用某个源
      enablerepo         # 启用某个源
      name=            # 指定要安装的包,如果有多个版本需要指定版本,否则安装最新的包
      state            # 安装(`present'),安装最新版(`latest'),卸载程序包(`absent')


# 十一 、用于管理服务 service模块

}
# ansible apachesvrs -m service -a "name=rsyncd state=started enabled=yes"
172.16.0.98 | SUCCESS => {
    "changed": true,
    "enabled": true,
    "name": "rsyncd",
    "state": "started",
    "status": {
。。。。。。。

# ansible apachesvrs -m shell -a "netstat -ltupn |grep rsync"
172.16.0.98 | SUCCESS | rc=0 >>
tcp      0      0 0.0.0.0:873             0.0.0.0:*               LISTEN      933/rsync         
tcp6       0      0 :::873                  :::*                  LISTEN      933/rsync   

# ansible apachesvrs -m shell -a "systemctl list-unit-files |grep rsyncd"
172.16.0.98 | SUCCESS | rc=0 >>
rsyncd.service                              enabled


# ansible apachesvrs -m service -a "name=rsyncd state=restarted"
172.16.0.98 | SUCCESS => {
    "changed": true,
    "name": "rsyncd",
    "state": "started",
    "status": {

# ansible apachesvrs -m service -a "name=rsyncd state=stopped"
172.16.0.98 | SUCCESS => {
    "changed": true,
    "name": "rsyncd",
    "state": "stopped",
    "status": {



      该模块包含如下选项:
      arguments:给命令行提供一些选项
      enabled:是否开机启动 yes|no
      name:必选项,服务名称
      pattern:定义一个模式,如果通过status指令来查看服务的状态时,没有响应,就会通过ps指令在进程中根据该模式进行查找,如果匹配到,则认为该服务依然在运行
      runlevel:运行级别
      sleep:如果执行了restarted,在则stop和start之间沉睡几秒钟
      state:对当前服务执行启动,停止、重启、重新加载等操作(started,stopped,restarted,reloaded)

其它:
synchronize模块
使用rsync同步文件,其参数如下:
archive: 归档,相当于同时开启recursive(递归)、links、perms、times、owner、group、-D选项都为yes ,默认该项为开启
checksum: 跳过检测sum值,默认关闭
compress:是否开启压缩
copy_links:复制链接文件,默认为no ,注意后面还有一个links参数
delete: 删除不存在的文件,默认no
dest:目录路径
dest_port:默认目录主机上的端口 ,默认是22,走的ssh协议
dirs:传速目录不进行递归,默认为no,即进行目录递归
rsync_opts:rsync参数部分
set_remote_user:主要用于/etc/ansible/hosts中定义或默认使用的用户与rsync使用的用户不同的情况
mode: push或pull 模块,push模的话,一般用于从本机向远程主机上传文件,pull 模式用于从远程主机上取文件
使用示例:
    src=some/relative/path dest=/some/absolute/path rsync_path="sudo rsync"
    src=some/relative/path dest=/some/absolute/path archive=no links=yes
    src=some/relative/path dest=/some/absolute/path checksum=yes times=no
    src=/tmp/helloworld dest=/var/www/helloword rsync_opts=--no-motd,--exclude=.git mode=pull


filesystem模块
在块设备上创建文件系统
选项:
dev:目标块设备
force:在一个已有文件系统 的设备上强制创建
fstype:文件系统的类型
opts:传递给mkfs命令的选项
示例:
    ansible test -m filesystem -a 'fstype=ext2 dev=/dev/sdb1 force=yes'
    ansible test -m filesystem -a 'fstype=ext4 dev=/dev/sdb1 opts="-cc"'


mount模块
配置挂载点
选项:
dump
fstype:必选项,挂载文件的类型
name:必选项,挂载点
opts:传递给mount命令的参数
src:必选项,要挂载的文件
state:必选项
present:只处理fstab中的配置
absent:删除挂载点
mounted:自动创建挂载点并挂载之
umounted:卸载
示例:
    name=/mnt/dvd src=/dev/sr0 fstype=iso9660 opts=ro state=present
    name=/srv/disk src='LABEL=SOME_LABEL' state=present
    name=/home src='UUID=b3e48f45-f933-4c8e-a700-22a159ec9077' opts=noatime state=present
    ansible test -a 'dd if=/dev/zero of=/disk.img bs=4k count=1024'
    ansible test -a 'losetup /dev/loop0 /disk.img'
    ansible test -m filesystem 'fstype=ext4 force=yes opts=-F dev=/dev/loop0'
    ansible test -m mount 'name=/mnt src=/dev/loop0 fstype=ext4 state=mounted opts=rw'

get_url 模块
该模块主要用于从http、ftp、https服务器上下载文件(类似于wget),主要有如下选项:
sha256sum:下载完成后进行sha256 check;
timeout:下载超时时间,默认10s
url:下载的URL
url_password、url_username:主要用于需要用户名密码进行验证的情况
use_proxy:是事使用代理,代理需事先在环境变更中定义
示例:
    get_url: url=http://example.com/path/file.conf dest=/etc/foo.conf mode=0440
    get_url: url=http://example.com/path/file.conf dest=/etc/foo.conf sha256sum=b5bb9d8014a0f9b1d61e21e796d78dccdf1352f23cd32812f4850b878ae4944c

unarchive模块
用于解压文件,模块包含如下选项:
copy:在解压文件之前,是否先将文件复制到远程主机,默认为yes。若为no,则要求目标主机上压缩包必须存在。
creates:指定一个文件名,当该文件存在时,则解压指令不执行
dest:远程主机上的一个路径,即文件解压的路径
grop:解压后的目录或文件的属组
list_files:如果为yes,则会列出压缩包里的文件,默认为no,2.0版本新增的选项
mode:解决后文件的权限
src:如果copy为yes,则需要指定压缩文件的源路径
owner:解压后文件或目录的属主
示例如下:
- unarchive: src=foo.tgz dest=/var/lib/foo
- unarchive: src=/tmp/foo.zip dest=/usr/local/bin copy=no
- unarchive: src=https://example.com/example.zip dest=/usr/local/bin copy=no

yyfq521 发表于 2018-3-26 11:37:26

mark mark
页: [1]
查看完整版本: ansible 常用模块使用练习