【自动化运维专题3】ansible的Ad-hoc使用场景及举例2

此处接上节专题《【自动化运维专题2】ansible的Ad-hoc使用场景及举例》。

 

【自动化运维专题2】ansible的Ad-hoc使用场景及举例

moonrong,公众号:Python运维实践【自动化运维专题2】ansible的Ad-hoc使用场景及举例

2.10个常用模块

2.6 file模块

file模块主要用于远程主机上的文件操作。

常用选项如下:

  • force:需要在两种情况下强制创建软链接,一种是源文件不存在但之后会建立的情况下;另一种是目标软链接已存在,需要先取消之前的软链,然后创建新的软链,有两个选项:yes|no
  • group:定义文件/目录的属组
  • mode:定义文件/目录的权限
  • owner:定义文件/目录的属主
  • path:必选项,定义文件/目录的路径
  • recurse:递归的设置文件的属性,只对目录有效
  • src:要被链接的源文件的路径,只应用于state=link的情况
  • dest:被链接到的目标路径,只应用于state=link的情况
  • state:有如下几个选项:
    • directory:表示目录,如果目录不存在,则创建目录。
    • link:创建软链接
    • hard:创建硬链接
    • touch:如果文件不存在,则会创建一个新的文件,如果文件或目录已存在,则更新其最后修改时间
    • absent:删除目录、文件或者取消链接文件。
2.6.1使用场景一

在远程主机192.168.250.50/mnt目录下,如果名字为test123的目录不存在,则创建它。

[root@ansible-control ~]# ansible 192.168.250.50 -m file -a "path=/mnt/test123 state=directory"
192.168.250.50 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "gid": 0, 
    "group": "root", 
    "mode": "0755", 
    "owner": "root", 
    "path": "/mnt/test123", 
    "secontext": "unconfined_u:object_r:mnt_t:s0", 
    "size": 6, 
    "state": "directory", 
    "uid": 0
}
[root@ansible-control ~]# 

再执行一次:

[root@ansible-control ~]# ansible 192.168.250.50 -m file -a "path=/mnt/test123 state=directory"
192.168.250.50 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false, 
    "gid": 0, 
    "group": "root", 
    "mode": "0755", 
    "owner": "root", 
    "path": "/mnt/test123", 
    "secontext": "unconfined_u:object_r:mnt_t:s0", 
    "size": 6, 
    "state": "directory", 
    "uid": 0
}
[root@ansible-control ~]# 

由于/mnt/test123目录已经存在,所以不再创建。

2.6.2使用场景二

修改远程主机192.168.250.50/mnt/test123目录下文件名字为qiyou.txt的属主、属组和权限为属主读写、属组读、其他人读权限。

[root@ansible-control ~]# ansible 192.168.250.50 -m file -a "path=/mnt/test123/qiyou.txt owner=moonrong group=moonrong mode=0644"
192.168.250.50 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "gid": 1000, 
    "group": "moonrong", 
    "mode": "0644", 
    "owner": "moonrong", 
    "path": "/mnt/test123/qiyou.txt", 
    "secontext": "unconfined_u:object_r:mnt_t:s0", 
    "size": 33, 
    "state": "file", 
    "uid": 1000
}
[root@ansible-control ~]# 
2.7 copy模块

Copy模块用于复制文件到远程主机,copy模块包含如下选项:

  • backup:在覆盖之前将原文件备份,备份文件包含时间信息。有两个选项:yes|no
  • content:用于替代src,可以直接设定指定文件的值
  • dest:必选项。要将源文件复制到的远程主机的绝对路径,如果源文件是一个目录,那么该路径也必须是个目录
  • directory_mode:递归的设定目录的权限,默认为系统默认权限
  • force:如果目标主机包含该文件,但内容不同,如果设置为yes,则强制覆盖,如果为no,则只有当目标主机的目标位置不存在该文件时,才复制。默认为yes
  • others:所有的file模块里的选项都可以在这里使用
  • src:要复制到远程主机的文件在本地的地址,可以是绝对路径,也可以是相对路径。如果路径是一个目录,它将递归复制。在这种情况下,如果路径使用/来结尾,则只复制目录里的内容,如果没有使用”/”来结尾,则包含目录在内的整个内容全部复制,类似于rsync
2.7.1使用场景一

将本地管理主机192.168.250.245上的/etc/passwd文件复制到远程主机192.168.250.50/mytmp目录下。

[root@ansible-control ~]# ansible 192.168.250.50 -m copy -a 'src=/etc/passwd dest=/mytmp/passwd'
192.168.250.50 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "checksum": "0c51d60d51388ad801d762498dee6432165af082", 
    "dest": "/mytmp/passwd", 
    "gid": 0, 
    "group": "root", 
    "md5sum": "d002c685535472f511b71de71aa4ae4f", 
    "mode": "0644", 
    "owner": "root", 
    "secontext": "system_u:object_r:default_t:s0", 
    "size": 2271, 
    "src": "/root/.ansible/tmp/ansible-tmp-1660363009.14-31991-131807722518625/source", 
    "state": "file", 
    "uid": 0
}
[root@ansible-control ~]# 
2.7.2使用场景二

将本地管理主机192.168.250.245上的/etc/yum目录及其目录下整个内容全部复制到远程主机192.168.250.50/mytmp目录下,同时修改属主为root,属组为root,目录权限为644

[root@ansible-control ~]# ansible 192.168.250.50 -m copy -a 'src=/etc/yum dest=/mytmp/ owner=root group=root  directory_mode=644 backup=yes'
192.168.250.50 | CHANGED => {
    "changed": true, 
    "dest": "/mytmp/", 
    "src": "/etc/yum"
}
[root@ansible-control ~]# 

命令执行完后,可以到被管理机上查看一下:

[root@rsyncnew01 mytmp]# ll
总用量 8
……
drw-r--r--. 6 root root  100 8月  13 12:01 yum
[root@rsyncnew01 mytmp]# cd yum
[root@rsyncnew01 yum]# ll
总用量 4
drw-r--r--. 2 root root   6 8月  13 12:01 fssnap.d
drw-r--r--. 2 root root  54 8月  13 12:01 pluginconf.d
drw-r--r--. 2 root root  26 8月  13 12:01 protected.d
drw-r--r--. 2 root root  37 8月  13 12:01 vars
-rw-r--r--. 1 root root 444 8月  13 12:01 version-groups.conf
[root@rsyncnew01 yum]# 

2.8 service模块

该模块主要用于管理远程主机上的服务,该模块包含如下选项:

  • enabled:是否开机启动 yes|no
  • name:必选项,服务名称
  • pattern:定义一个模式,如果通过status指令来查看服务的状态时,没有响应,就会通过ps指令在进程中根据该模式进行查找,如果匹配到,则认为该服务依然在运行
  • sleep:如果执行了restarted,在stopstart之间沉睡几秒钟
  • state:对当前服务执行启动、停止等操作
    • started 启动
    • stopped 停止
    • restarted 重启
    • reloaded  重新加载
2.8.1使用场景一

启动远程主机192.168.250.50上的httpd服务:

[root@ansible-control ~]# ansible 192.168.250.50 -m service -a "name=httpd state=started"
192.168.250.50 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "name": "httpd", 
    "state": "started", 
    "status": {
……
        "Documentation": "man:httpd(8) man:apachectl(8)", 
        "EnvironmentFile": "/etc/sysconfig/httpd (ignore_errors=no)", 
        "ExecMainCode": "0", 
        "ExecMainExitTimestampMonotonic": "0", 
        "ExecMainPID": "0", 
        "ExecMainStartTimestampMonotonic": "0", 
        "ExecMainStatus": "0", 
        "ExecReload": "{ path=/usr/sbin/httpd ; argv[]=/usr/sbin/httpd $OPTIONS -k graceful ; ignore_errors=no ; start_time=[n/a] ; stop_time=[n/a] ; pid=0 ; code=(null) ; status=0/0 }", 
        "ExecStart": "{ path=/usr/sbin/httpd ; argv[]=/usr/sbin/httpd $OPTIONS -DFOREGROUND ; ignore_errors=no ; start_time=[n/a] ; stop_time=[n/a] ; pid=0 ; code=(null) ; status=0/0 }", 
        "ExecStop": "{ path=/bin/kill ; argv[]=/bin/kill -WINCH ${MAINPID} ; ignore_errors=no ; start_time=[n/a] ; stop_time=[n/a] ; pid=0 ; code=(null) ; status=0/0 }", 
        "FailureAction": "none", 
        "FileDescriptorStoreMax": "0", 
        "FragmentPath": "/usr/lib/systemd/system/httpd.service", 
……
    }
}
[root@ansible-control ~]# 
2.8.2使用场景二

设置远程主机192.168.250.50上的httpd服务开机自启:

[root@ansible-control ~]# ansible 192.168.250.50  -m service -a "name=httpd  enabled=yes"
192.168.250.50 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "enabled": true, 
    "name": "httpd", 
    "status": {
        "ActiveEnterTimestamp": "六 2022-08-13 12:31:38 CST", 
        ……
2.9 cron模块

它用于管理计划任务,包含如下选项:

  • backup:对远程主机上的原任务计划内容修改之前做备份
  • cron_file:用来指定一个计划任务文件,也就是将计划任务写到远程主机上/etc/cron.d目录下,创建一个文件对应的计划任务。
day:日(1-31,*,*/2,……) 
hour:小时(0-23,*,*/2,……)  
minute:分钟(0-59,*,*/2,……) 
month:月(1-12,*,*/2,……) 
weekday:周(0-7,*,……)
  • job:要执行的任务,依赖于state=present
  • name:定义定时任务的描述信息
  • special_time:特殊的时间范围,参数:reboot(重启时),annually(每年),monthly(每月),weekly(每周),daily(每天),hourly(每小时)
  • state:确认该任务计划是创建还是删除,有两个值可选,分别是presentabsentpresent表示创建定时任务,absent表示删除定时任务,默认为present
  • user:以哪个用户的身份执行job指定的任务。
2.9.1使用场景一

在远程主机192.168.250.50上创建1条计划任务,每周六的1点45分,执行yum update更新操作:

[root@ansible-control ~]# ansible 192.168.250.50  -m cron -a  'name="yum autoupdate"  weekday="6" minute=45 hour=1 user="root" job="yum -y update"'
192.168.250.50 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "envs": [], 
    "jobs": [
        "yum autoupdate"
    ]
}
[root@ansible-control ~]# 

执行成功后,现在到192.168.250.50主机上查看计划任务列表:

[root@rsyncnew01 /]# crontab -l
#Ansible: yum autoupdate
45 1 * * 6 yum -y update
[root@rsyncnew01 /]# 
2.9.2使用场景二

设置自动备份任务,每周六1点45分,执行auto_pg_bak.sh脚本:

[root@ansible-control ~]# ansible 192.168.250.50  -m cron -a  'backup="True" name="autobackup" weekday="6" minute=45 hour=1 user="root" job="/bin/auto_pg_bak.sh"'
192.168.250.50 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "backup_file": "/tmp/crontabXdJlCz", 
    "changed": true, 
    "envs": [], 
    "jobs": [
        "yum autoupdate", 
        "autobackup"
    ]
}
[root@ansible-control ~]# 
2.10 yum模块

它是一个常用的模块,使用yum包管理器来管理软件包,其选项有:

  • config_file:yum的配置文件
  • disable_gpg_check:关闭gpg_check
  • disablerepo:不启用某个源
  • enablerepo:启用某个源
  • name:要进行操作的软件包的名字,也可以传递一个url或者一个本地的rpm包的路径
  • state:表示要安装还是删除软件包,要安装软件包,可选择present(安装)、installed(安装)、 latest(安装最新版本),删除软件包可选择absentremoved
2.10.1使用场景一

在主机192.168.250.50上安装redis

[root@ansible-control ~]# ansible 192.168.250.50 -m yum -a "name=redis state=installed"
192.168.250.50 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "changes": {
        "installed": [
            "redis"
        ]
    }, 
    "msg": "", 
    "rc": 0, 
    "results": [
        "Loaded plugins: fastestmirror, langpacks\nLoading mirror speeds from cached hostfile\n * base: mirrors.aliyun.com\n * epel: mirrors.bfsu.edu.cn\n * extras: mirrors.aliyun.com\n * updates: mirrors.aliyun.com\nResolving Dependencies\n--> Running transaction check\n---> Package redis.x86_64 0:3.2.12-2.el7 will be installed\n--> Processing Dependency: libjemalloc.so.1()(64bit) for package: redis-3.2.12-2.el7.x86_64\n--> Running transaction check\n---> Package jemalloc.x86_64 0:3.6.0-1.el7 will be installed\n--> Finished Dependency Resolution\n\nDependencies Resolved\n\n================================================================================\n Package           Arch            Version                  Repository     Size\n================================================================================\nInstalling:\n redis             x86_64          3.2.12-2.el7             epel          544 k\nInstalling for dependencies:\n jemalloc          x86_64          3.6.0-1.el7              epel          105 k\n\nTransaction Summary\n================================================================================\nInstall  1 Package (+1 Dependent package)\n\nTotal download size: 648 k\nInstalled size: 1.7 M\nDownloading packages:\n--------------------------------------------------------------------------------\nTotal                                              1.6 MB/s | 648 kB  00:00     \nRunning transaction check\nRunning transaction test\nTransaction test succeeded\nRunning transaction\n  Installing : jemalloc-3.6.0-1.el7.x86_64                                  1/2 \n  Installing : redis-3.2.12-2.el7.x86_64                                    2/2 \n  Verifying  : redis-3.2.12-2.el7.x86_64                                    1/2 \n  Verifying  : jemalloc-3.6.0-1.el7.x86_64                                  2/2 \n\nInstalled:\n  redis.x86_64 0:3.2.12-2.el7                                                   \n\nDependency Installed:\n  jemalloc.x86_64 0:3.6.0-1.el7                                                 \n\nComplete!\n"
    ]
}
[root@ansible-control ~]# 
2.10.2使用场景二

在主机192.168.250.50上安装redis最新版,并启用epel源:

[root@ansible-control ~]# ansible 192.168.250.50 -m yum -a "name=redis state=latest enablerepo=epel"
192.168.250.50 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false, 
    "changes": {
        "installed": [], 
        "updated": []
    }, 
    "msg": "", 
    "rc": 0, 
    "results": [
        "All packages providing redis are up to date", 
        ""
    ]
}
[root@ansible-control ~]# 

3.ansible的其他模块

上面一共列举了10ansible模块,其他模块在下面介绍:

3.1user模块与group模块

user模块是请求的是useradduserdelusermod三个指令。

group模块请求的是groupaddgroupdelgroupmod 三个指令。

它们选项如下:

  • name           # 指定用户名
  • group          # 指定用户的主组
  • groups        # 指定附加组,如果指定为groups=表示删除所有组。
  • shell            # 指定默认shell
  • state           #设置帐号状态,不指定为默认为present,表示创建,指定值为absent表示删除
  • remove      #当使用状态为state=absent时使用,类似于userdel --remove选项。

使用举例:批量给myweb主机组添加webuser用户:

[root@ansible-control ~]# ansible myweb -m user -a "name=webuser"
192.168.250.50 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "comment": "", 
    "create_home": true, 
    "group": 1001, 
    "home": "/home/webuser", 
    "name": "webuser", 
    "shell": "/bin/bash", 
    "state": "present", 
    "system": false, 
    "uid": 1001
}
192.168.250.51 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "comment": "", 
    "create_home": true, 
    "group": 1001, 
    "home": "/home/webuser", 
    "name": "webuser", 
    "shell": "/bin/bash", 
    "state": "present", 
    "system": false, 
    "uid": 1001
}
[root@ansible-control ~]# 
3.2setup模块

setup模块,主要用于获取主机信息,在下一节专题里要提到的playbooks里经常会用到的一个参数gather_facts就与该模块相关。setup模块下经常使用的一个参数是filter参数来提取有用的信息。

查看主机内存信息:

[root@ansible-control ~]# ansible 192.168.250.50 -m setup -a 'filter=ansible_*_mb'
192.168.250.50 | SUCCESS => {
    "ansible_facts": {
        "ansible_memfree_mb": 2139, 
        "ansible_memory_mb": {
            "nocache": {
                "free": 3228, 
                "used": 561
            }, 
            "real": {
                "free": 2139, 
                "total": 3789, 
                "used": 1650
            }, 
            "swap": {
                "cached": 0, 
                "free": 8063, 
                "total": 8063, 
                "used": 0
            }
        }, 
        "ansible_memtotal_mb": 3789, 
        "ansible_swapfree_mb": 8063, 
        "ansible_swaptotal_mb": 8063, 
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false
}
[root@ansible-control ~]# 
3.3synchronize模块

此模块通过调用rsync进行文件或目录同步。

  • archive:归档,相当于同时开启recursive(递归),links,perms,itmes,owner,group,-D选项都为yes,默认该选项为开启
  • checksum:跳过检测sum值,默认关闭
  • compress:是不开启压缩,默认开启
  • copy_links:复制链接文件,默认为no,注意后面还有一个links参数
  • delete:删除不存在的文件,默认为no
  • dest:目录路径
  • dest_prot:默认为22ssh协议
  • mode:pushpull模块,push模块的话,一般用于从本机向远程主机上传文件,pull模式用于从远程主机上拉取文件
3.4 get_url模块

该模块主要用于从httpftphttps服务器上下载文件(类似于wget),主要有如下选项:

  • sha256sum:下载完成后进行sha256 check
  • timeout:下载超时时间,默认10s
  • url:下载的URL
  • url_password、url_username:主要用于需要用户名密码进行验证的情况
  • use_proxy:表示使用代理,代理需事先在环境变更中定义

以上关于ansible模块介绍到这里,请关注下一节《【自动化运维专题4】ansible-playbook及使用》。

原文地址:https://mp.weixin.qq.com/s/m-xytV57nGoMD1V8WgcMEw

posted @ 2022-08-14 21:51  北极之光的博客  阅读(128)  评论(0编辑  收藏  举报