zoukankan      html  css  js  c++  java
  • Ansible 常见模块介绍

    Ansible 常见模块介绍

    ansible-doc 命令,可以查看当前ansible有哪些已安装的模块并且可以使用

    ansible-doc -s MODULE_NAME 可以查看该模块的使用说明

    常用模块介绍

    模块名 说明
    at 定义at任务
    cron 定义定时任务
    copy 复制文件
    command 默认模块,运行命令
    shell 执行复杂命令
    yum 管理yum安装卸载
    user 管理用户
    group 管理组
    file 管理文件

    Ansible 基本语法

    基础语法:ansible [-f forks] [-m module_name] [-a args]

    • hosts-pattern : 表示对那些主机生效的,可以使单个主机ip,也可以是在Inverteroy文件中定义的组名。
    • -f fors : 表示一次性处理多少个主机,也就是并发数量
    • -m module_name : 指定使用哪个模块
    • -a args : 表示需要给使用的模块传递的参数

    ping 模块

    测试主机连通性

    演示

    [root@node01 ansible]# ansible all -m ping
    10.0.0.66 | SUCCESS => {
        "changed": false, 
        "ping": "pong"
    }
    10.0.0.65 | SUCCESS => {
        "changed": false, 
        "ping": "pong"
    }
    

    command 模块

    在远程的主机上执行特定的命令

    首先查看一下帮助

    [root@node01 ansible]# ansible-doc -s command
    - name: Executes a command on a remote node
      command:
          argv:                  # Allows the user to provide the command as a list vs. a string.  Only the string or the list form can be provided, not both.  One or the other must be
                                   provided.
          chdir:                 # Change into this directory before running the command.
          creates:               # A filename or (since 2.0) glob pattern. If it already exists, this step *won't* be run.
          free_form:             # (required) The command module takes a free form command to run.  There is no parameter actually named 'free form'. See the examples!
          removes:               # A filename or (since 2.0) glob pattern. If it already exists, this step *will* be run.
          stdin:                 # Set the stdin of the command directly to the specified value.
          warn:                  # If command_warnings are on in ansible.cfg, do not warn about this particular line if set to `no'.
    
    

    演示

    直接操控某个主机
    [root@node01 ansible]# ansible 10.0.0.65 -m command -a 'ls -ld /root'
    10.0.0.65 | CHANGED | rc=0 >>
    dr-xr-x---. 5 root root 168 Oct 15 13:28 /root
    
    # 操控Inventory中定义的组名对应的主机
    [root@node01 ansible]# ansible webservs -m command -a 'ls -ld /root'
    10.0.0.65 | CHANGED | rc=0 >>
    dr-xr-x---. 5 root root 168 Oct 15 13:28 /root
    

    有一个默认的组all,Inventory中定义的所有主机都需要执行

    [root@node01 ansible]# ansible all -m command -a 'ls -ld /root'
    10.0.0.66 | CHANGED | rc=0 >>
    dr-xr-x---. 5 root root 191 Oct 15 13:28 /root
    
    10.0.0.65 | CHANGED | rc=0 >>
    dr-xr-x---. 5 root root 168 Oct 15 13:28 /root
    

    cron 模块

    管理远程主机的定时任务

    首先查看一下帮助

    [root@node01 ansible]# ansible-doc -s cron
    - name: Manage cron.d and crontab entries
      cron:
          backup:                # If set, create a backup of the crontab before it is modified. The location of the backup is returned in the `backup_file' variable by this module.
          cron_file:             # If specified, uses this file instead of an individual user's crontab. If this is a relative path, it is interpreted with respect to /etc/cron.d. (If it is
                                   absolute, it will typically be /etc/crontab). Many linux distros expect (and some require) the filename portion to consist
                                   solely of upper- and lower-case letters, digits, underscores, and hyphens. To use the `cron_file' parameter you must specify
                                   the `user' as well.
          day:                   # Day of the month the job should run ( 1-31, *, */2, etc )
          disabled:              # If the job should be disabled (commented out) in the crontab. Only has effect if `state=present'.
          env:                   # If set, manages a crontab's environment variable. New variables are added on top of crontab. "name" and "value" parameters are the name and the value of
                                   environment variable.
          hour:                  # Hour when the job should run ( 0-23, *, */2, etc )
          insertafter:           # Used with `state=present' and `env'. If specified, the environment variable will be inserted after the declaration of specified environment variable.
          insertbefore:          # Used with `state=present' and `env'. If specified, the environment variable will be inserted before the declaration of specified environment variable.
          job:                   # The command to execute or, if env is set, the value of environment variable. The command should not contain line breaks. Required if state=present.
          minute:                # Minute when the job should run ( 0-59, *, */2, etc )
          month:                 # Month of the year the job should run ( 1-12, *, */2, etc )
          name:                  # Description of a crontab entry or, if env is set, the name of environment variable. Required if state=absent. Note that if name is not set and state=present,
                                   then a new crontab entry will always be created, regardless of existing ones.
          reboot:                # If the job should be run at reboot. This option is deprecated. Users should use special_time.
          special_time:          # Special time specification nickname.
          state:                 # Whether to ensure the job or environment variable is present or absent.
          user:                  # The specific user whose crontab should be modified.
          weekday:               # Day of the week that the job should run ( 0-6 for Sunday-Saturday, *, etc )
    

    特别说明:state参数,表示是增加present,还是删除absent.

    演示添加

    下面在webservs组中,创建一个定时任务,每十分钟,echo 一个 hello/tmp/test.ans.

    [root@node01 ansible]# ansible webservs -m cron -a 'minute="*/10" job="/bin/echo hello >> /tmp/test.ans" name="test cron job" state=present' 
    10.0.0.65 | CHANGED => {
        "changed": true, 
        "envs": [], 
        "jobs": [
            "test cron job"
        ]
    }
    [root@node01 ansible]# ansible webservs -m command -a 'crontab -l'
    10.0.0.65 | CHANGED | rc=0 >>
    #Ansible: test cron job
    */10 * * * * /bin/echo hello > /tmp/test.ans
    

    说明:

    • name参数是给这个定时任务起一个名字,相当于是个注释,解释该定时任务的含义
    • 定时任务中分时日月周中,如果是*号,则可以不用增加参数
    • 如果是添加,state=present 参数可以不用添加,如果是删除,则需要加入state=absent参数

    演示删除

    [root@node01 ansible]# ansible webservs -m cron -a 'minute="*/10" job="/bin/echo hello >> /tmp/test.ans" name="test cron job" state=absent'
    10.0.0.65 | CHANGED => {
        "changed": true, 
        "envs": [], 
        "jobs": []
    }
    [root@node01 ansible]# ansible webservs -m command -a 'crontab -l'
    10.0.0.65 | CHANGED | rc=0 >>
    
    
    [root@node01 ansible]#
    

    user 模块

    管理远程主机的用户和组

    演示

    在所有主机上创建一个user1 用户

    [root@node01 ansible]# ansible all -m user -a 'name="user1"'
    10.0.0.65 | CHANGED => {
        "changed": true, 
        "comment": "", 
        "create_home": true, 
        "group": 1002, 
        "home": "/home/user1", 
        "name": "user1", 
        "shell": "/bin/bash", 
        "state": "present", 
        "system": false, 
        "uid": 1002
    }
    10.0.0.66 | CHANGED => {
        "changed": true, 
        "comment": "", 
        "create_home": true, 
        "group": 1001, 
        "home": "/home/user1", 
        "name": "user1", 
        "shell": "/bin/bash", 
        "state": "present", 
        "system": false, 
        "uid": 1001
    }
    [root@node01 ansible]# ansible all -a 'tail -1 /etc/passwd'
    10.0.0.65 | CHANGED | rc=0 >>
    user1:x:1002:1002::/home/user1:/bin/bash
    
    10.0.0.66 | CHANGED | rc=0 >>
    user1:x:1001:1001::/home/user1:/bin/bash
    
    [root@node01 ansible]# ansible all -a 'tail -1 /etc/group'
    10.0.0.66 | CHANGED | rc=0 >>
    user1:x:1001:
    
    10.0.0.65 | CHANGED | rc=0 >>
    user1:x:1002:
    

    说明:

    • 同样,user模块也有state选项,默认是state=persent,如果要删除,则是state=absent
    • 不指定组,则系统会自动创建一个和用户名相同的组
    • 默认会创建家目录
    • UID 和 GID 都是远程用户默认给的

    删除用户

    [root@node01 ansible]# ansible all -m user -a 'name="user1" state=absent'
    10.0.0.65 | CHANGED => {
        "changed": true, 
        "force": false, 
        "name": "user1", 
        "remove": false, 
        "state": "absent"
    }
    10.0.0.66 | CHANGED => {
        "changed": true, 
        "force": false, 
        "name": "user1", 
        "remove": false, 
        "state": "absent"
    }
    
    [root@node01 ansible]# ansible all -a 'grep "user1" /etc/passwd'
    10.0.0.66 | FAILED | rc=1 >>
    non-zero return code
    
    10.0.0.65 | FAILED | rc=1 >>
    non-zero return code
    
    [root@node01 ansible]# ansible all -a 'grep "user1" /etc/group'
    10.0.0.66 | FAILED | rc=1 >>
    non-zero return code
    
    10.0.0.65 | FAILED | rc=1 >>
    non-zero return code
    [root@node01 ansible]# ansible all -a 'ls /home/'
    10.0.0.66 | CHANGED | rc=0 >>
    user1
    
    10.0.0.65 | CHANGED | rc=0 >>
    user1
    

    说明:

    • 删除的同时,远端的主机同样会把组删除
    • 删除用户时,默认不会删除家目录

    group 模块

    帮助

    [root@node01 ansible]# ansible-doc -s group
    - name: Add or remove groups
      group:
          gid:                   # Optional `GID' to set for the group.
          local:                 # Forces the use of "local" command alternatives on platforms that implement it. This is
                                   useful in environments that use centralized authentification
                                   when you want to manipulate the local groups. I.E. it uses
                                   `lgroupadd` instead of `useradd`. This requires that these
                                   commands exist on the targeted host, otherwise it will be a
                                   fatal error.
          name:                  # (required) Name of the group to manage.
          state:                 # Whether the group should be present or not on the remote host.
          system:                # If `yes', indicates that the group created is a system group.
    

    演示

    给dbservs组创建一个GID为306的mysql组,并且是系统组件

    [root@node01 ansible]# ansible dbservs -m group -a 'name="mysql" gid="306" system="yes"'
    10.0.0.66 | CHANGED => {
        "changed": true, 
        "gid": 306, 
        "name": "mysql", 
        "state": "present", 
        "system": true
    }
    [root@node01 ansible]# ansible dbservs -a 'grep "mysql" /etc/group'
    10.0.0.66 | CHANGED | rc=0 >>
    mysql:x:306:
    

    说明:

    • state=present 默认不用写
    • system参数表示是否为系统用户组,也就是可登陆不可登陆的意思

    删除组

    [root@node01 ansible]# ansible dbservs -m group -a 'name="mysql" gid="306" state=absent'
    10.0.0.66 | CHANGED => {
        "changed": true, 
        "name": "mysql", 
        "state": "absent"
    }
    [root@node01 ansible]# ansible dbservs -a 'grep "mysql" /etc/group'
    10.0.0.66 | FAILED | rc=1 >>
    non-zero return code
    

    添加一个mysql用户并加入MySQL组

    [root@node01 ansible]# ansible dbservs -m group -a 'name="mysql" gid="306"'
    10.0.0.66 | CHANGED => {
        "changed": true, 
        "gid": 306, 
        "name": "mysql", 
        "state": "present", 
        "system": false
    }
    [root@node01 ansible]# ansible dbservs -m user -a 'name="mysql" uid="306" group="mysql" system="yes" create_home="no" shell="/sbin/nologin"'
    10.0.0.66 | CHANGED => {
        "changed": true, 
        "comment": "", 
        "create_home": false, 
        "group": 306, 
        "home": "/home/mysql", 
        "name": "mysql", 
        "shell": "/sbin/nologin", 
        "state": "present", 
        "system": true, 
        "uid": 306
    }
    [root@node01 ansible]#
    [root@node01 ansible]# ansible dbservs -a 'grep "mysql" /etc/passwd'
    10.0.0.66 | CHANGED | rc=0 >>
    mysql:x:306:306::/home/mysql:/bin/bash
    
    [root@node01 ansible]# ansible dbservs -a 'grep "mysql" /etc/group'
    10.0.0.66 | CHANGED | rc=0 >>
    mysql:x:306:
    

    说明:

    • 在创建用户的时候,可以使用不创建家目录create_home=no的参数
    • 创建用户可以手动指定shell

    copy 模块

    把文件复制到远程主机上的指定位置

    演示 1

    把本机的/etc/fstab 文件拷贝到所有主机的/tmp/fstab.ans下,权限是640 并且属主是root

    [root@node01 ansible]# ansible all -m copy -a 'src="/etc/fstab" dest="/tmp/fstab.ans" owner="root" mode="0640"'
    10.0.0.66 | CHANGED => {
        "changed": true, 
        "checksum": "34859ccbb64d455305bbec515c11559e7dc284e9", 
        "dest": "/tmp/fstab.ans", 
        "gid": 0, 
        "group": "root", 
        "md5sum": "ac872c0d2dad7298437e627e7d42e6aa", 
        "mode": "0640", 
        "owner": "root", 
        "size": 465, 
        "src": "/root/.ansible/tmp/ansible-tmp-1539655396.04-274627446116615/source", 
        "state": "file", 
        "uid": 0
    }
    10.0.0.65 | CHANGED => {
        "changed": true, 
        "checksum": "34859ccbb64d455305bbec515c11559e7dc284e9", 
        "dest": "/tmp/fstab.ans", 
        "gid": 0, 
        "group": "root", 
        "md5sum": "ac872c0d2dad7298437e627e7d42e6aa", 
        "mode": "0640", 
        "owner": "root", 
        "size": 465, 
        "src": "/root/.ansible/tmp/ansible-tmp-1539655396.06-281216105403302/source", 
        "state": "file", 
        "uid": 0
    }
    [root@node01 ansible]# ansible all -a 'ls -l /tmp/fstab.ans'
    10.0.0.65 | CHANGED | rc=0 >>
    -rw-r----- 1 root root 465 Oct 16 10:03 /tmp/fstab.ans
    
    10.0.0.66 | CHANGED | rc=0 >>
    -rw-r----- 1 root root 465 Oct 16 10:03 /tmp/fstab.ans
    

    说明:

    • src=: 定义本地源文件路径,可以是相对路径,也可以是绝对路径,如果是目录,则会把该目录下的所有文件都拷贝过去
    • dest=: 定义远程目标路径,只能是绝对路径

    演示 2

    [root@node01 ansible]# ansible all -m copy -a 'content="Hello 
    MaGeEdu" dest="/tmp/test.ans"'
    10.0.0.65 | CHANGED => {
        "changed": true, 
        "checksum": "5ace02e755fb1f8ab280a6a7b99b2191223a60a2", 
        "dest": "/tmp/test.ans", 
        "gid": 0, 
        "group": "root", 
        "md5sum": "63c83d5aca3bb9de569268f0d01b3147", 
        "mode": "0644", 
        "owner": "root", 
        "size": 14, 
        "src": "/root/.ansible/tmp/ansible-tmp-1539655840.82-272515170635281/source", 
        "state": "file", 
        "uid": 0
    }
    10.0.0.66 | CHANGED => {
        "changed": true, 
        "checksum": "5ace02e755fb1f8ab280a6a7b99b2191223a60a2", 
        "dest": "/tmp/test.ans", 
        "gid": 0, 
        "group": "root", 
        "md5sum": "63c83d5aca3bb9de569268f0d01b3147", 
        "mode": "0644", 
        "owner": "root", 
        "size": 14, 
        "src": "/root/.ansible/tmp/ansible-tmp-1539655840.81-221772323754627/source", 
        "state": "file", 
        "uid": 0
    }
    [root@node01 ansible]# ansible all -a 'cat /tmp/test.ans'
    10.0.0.65 | CHANGED | rc=0 >>
    Hello 
    MaGeEdu
    
    10.0.0.66 | CHANGED | rc=0 >>
    Hello 
    MaGeEdu
    

    说明:

    • content= 取代 src=,二者不能同时使用
    • content参数,指定一些内容,在远程主机上生成文件,支持特殊字符

    file 模块

    设定文件的属性,如属主、属主组、权限、创建软连接等

    演示

    给 dbservs组 创建mysql用户,定义/tmp/test.ans 属主和属主组都是mysql,权限是600,

    [root@node01 ansible]# ansible dbservs -m user -a 'name="mysql"'
    10.0.0.65 | CHANGED => {
        "changed": true, 
        "comment": "", 
        "create_home": true, 
        "group": 1002, 
        "home": "/home/mysql", 
        "name": "mysql", 
        "shell": "/bin/bash", 
        "state": "present", 
        "system": false, 
        "uid": 1001
    }
    [root@node01 ansible]# ansible dbservs -m file -a 'owner=mysql group=mysql mode=600 path=/tmp/test.ans'
    10.0.0.66 | CHANGED => {
        "changed": true, 
        "gid": 1001, 
        "group": "mysql", 
        "mode": "0600", 
        "owner": "mysql", 
        "path": "/tmp/test.ans", 
        "size": 14, 
        "state": "file", 
        "uid": 1001
    }
    [root@node01 ansible]# ansible dbservs -a 'ls -ld /tmp/test.ans'
    10.0.0.66 | CHANGED | rc=0 >>
    -rw------- 1 mysql mysql 14 Oct 16 10:10 /tmp/test.ans
    

    创建软连接

    给/tmp/test.ans 创建一个软链接 /tmp/test.ans.link

    [root@node01 ansible]# ansible dbservs -m file -a 'path=/tmp/test.ans.link src=/tmp/test.ans state=link'
    10.0.0.66 | CHANGED => {
        "changed": true, 
        "dest": "/tmp/test.ans.link", 
        "gid": 0, 
        "group": "root", 
        "mode": "0777", 
        "owner": "root", 
        "size": 13, 
        "src": "/tmp/test.ans", 
        "state": "link", 
        "uid": 0
    }
    [root@node01 ansible]# ansible dbservs -a 'ls -ld /tmp/test.ans /tmp/test.ans.link'
    10.0.0.66 | CHANGED | rc=0 >>
    -rw------- 1 mysql mysql 14 Oct 16 10:10 /tmp/test.ans
    lrwxrwxrwx 1 root  root  13 Oct 16 13:22 /tmp/test.ans.link -> /tmp/test.ans
    

    service 模块

    管理远程主机的服务的启动,自启等

    [root@node01 ansible]# ansible-doc -s service
    - name: Manage services
      service:
          arguments:             # Additional arguments provided on the command line
          enabled:               # Whether the service should start on boot. *At least one of state and enabled are required.*
          name:                  # (required) Name of the service.
          pattern:               # If the service does not respond to the status command, name a substring to look for as
                                   would be found in the output of the `ps' command as a stand-
                                   in for a status result.  If the string is found, the service
                                   will be assumed to be started.
          runlevel:              # For OpenRC init scripts (ex: Gentoo) only.  The runlevel that this service belongs to.
          sleep:                 # If the service is being `restarted' then sleep this many seconds between the stop and start
                                   command. This helps to workaround badly behaving init
                                   scripts that exit immediately after signaling a process to
                                   stop.
          state:                 # `started'/`stopped' are idempotent actions that will not run commands unless necessary.
                                   `restarted' will always bounce the service.  `reloaded' will
                                   always reload. *At least one of state and enabled are
                                   required.* Note that reloaded will start the service if it
                                   is not already started, even if your chosen init system
                                   wouldn't normally.
          use:                   # The service module actually uses system specific modules, normally through auto detection,
                                   this setting can force a specific module. Normally it uses
                                   the value of the 'ansible_service_mgr' fact and falls back
                                   to the old 'service' module when none matching is found.
    

    演示

    在node-1 上yum安装httpd,然后使用ansible的service模块来管理测试

    查看httpd运行状态

    [root@node01 ansible]# ansible webservs -a 'systemctl status httpd'
    10.0.0.65 | FAILED | rc=3 >>
    ● httpd.service - The Apache HTTP Server
       Loaded: loaded (/usr/lib/systemd/system/httpd.service; enabled; vendor preset: disabled)
       Active: inactive (dead) since Tue 2018-10-16 13:36:28 CST; 10min ago
         Docs: man:httpd(8)
               man:apachectl(8)
      Process: 26794 ExecStop=/bin/kill -WINCH ${MAINPID} (code=exited, status=0/SUCCESS)
      Process: 21541 ExecReload=/usr/sbin/httpd $OPTIONS -k graceful (code=exited, status=0/SUCCESS)
      Process: 17814 ExecStart=/usr/sbin/httpd $OPTIONS -DFOREGROUND (code=exited, status=0/SUCCESS)
     Main PID: 17814 (code=exited, status=0/SUCCESS)
       Status: "Total requests: 0; Current requests/sec: 0; Current traffic:   0 B/sec"
    
    Oct 12 13:57:44 node02 systemd[1]: Starting The Apache HTTP Server...
    Oct 12 13:57:44 node02 httpd[17814]: AH00558: httpd: Could not reliably determine the server's fully qualified domain name, using 10.0.0.65. Set the 'ServerName' directive globally to suppress this message
    Oct 12 13:57:44 node02 systemd[1]: Started The Apache HTTP Server.
    Oct 14 03:41:01 node02 httpd[21541]: AH00558: httpd: Could not reliably determine the server's fully qualified domain name, using 10.0.0.65. Set the 'ServerName' directive globally to suppress this message
    Oct 14 03:41:01 node02 systemd[1]: Reloaded The Apache HTTP Server.
    Oct 16 13:36:27 node02 systemd[1]: Stopping The Apache HTTP Server...
    Oct 16 13:36:28 node02 systemd[1]: Stopped The Apache HTTP Server.non-zero return code
    

    停止状态

    启动httpd并且配置开机自动启动

    [root@node01 ansible]# ansible webservs -m service -a 'name=httpd enabled=true state=started'
    10.0.0.65 | CHANGED => {
        "changed": true, 
        "enabled": true, 
        "name": "httpd", 
        "state": "started", 
        "status": {
            "ActiveEnterTimestamp": "Fri 2018-10-12 13:57:44 CST", 
            "ActiveEnterTimestampMonotonic": "255153312616", 
            "ActiveExitTimestamp": "Tue 2018-10-16 13:36:27 CST", 
            "ActiveExitTimestampMonotonic": "599476522029", 
            "ActiveState": "inactive", 
            "After": "system.slice -.mount basic.target systemd-journald.socket remote-fs.target tmp.mount nss-lookup.target network.target", 
            "AllowIsolate": "no", 
            "AmbientCapabilities": "0", 
            "AssertResult": "yes", 
            "AssertTimestamp": "Fri 2018-10-12 13:57:44 CST", 
            "AssertTimestampMonotonic": "255153282859", 
            "Before": "multi-user.target shutdown.target", 
            "BlockIOAccounting": "no", 
            "BlockIOWeight": "18446744073709551615", 
            "CPUAccounting": "no", 
            "CPUQuotaPerSecUSec": "infinity", 
            "CPUSchedulingPolicy": "0", 
            "CPUSchedulingPriority": "0", 
            "CPUSchedulingResetOnFork": "no", 
            "CPUShares": "18446744073709551615", 
            "CanIsolate": "no", 
            "CanReload": "yes", 
            "CanStart": "yes", 
            "CanStop": "yes", 
            "CapabilityBoundingSet": "18446744073709551615", 
            "ConditionResult": "yes", 
            "ConditionTimestamp": "Fri 2018-10-12 13:57:44 CST", 
            "ConditionTimestampMonotonic": "255153282859", 
            "Conflicts": "shutdown.target", 
            "ControlPID": "0", 
            "DefaultDependencies": "yes", 
            "Delegate": "no", 
            "Description": "The Apache HTTP Server", 
            "DevicePolicy": "auto", 
            "Documentation": "man:httpd(8) man:apachectl(8)", 
            "EnvironmentFile": "/etc/sysconfig/httpd (ignore_errors=no)", 
            "ExecMainCode": "1", 
            "ExecMainExitTimestamp": "Tue 2018-10-16 13:36:28 CST", 
            "ExecMainExitTimestampMonotonic": "599477552217", 
            "ExecMainPID": "17814", 
            "ExecMainStartTimestamp": "Fri 2018-10-12 13:57:44 CST", 
            "ExecMainStartTimestampMonotonic": "255153283361", 
            "ExecMainStatus": "0", 
            "ExecReload": "{ path=/usr/sbin/httpd ; argv[]=/usr/sbin/httpd $OPTIONS -k graceful ; ignore_errors=no ; start_time=[Sun 2018-10-14 03:41:01 CST] ; stop_time=[Sun 2018-10-14 03:41:01 CST] ; pid=21541 ; code=exited ; status=0 }", 
            "ExecStart": "{ path=/usr/sbin/httpd ; argv[]=/usr/sbin/httpd $OPTIONS -DFOREGROUND ; ignore_errors=no ; start_time=[Fri 2018-10-12 13:57:44 CST] ; stop_time=[Tue 2018-10-16 13:36:28 CST] ; pid=17814 ; code=exited ; status=0 }", 
            "ExecStop": "{ path=/bin/kill ; argv[]=/bin/kill -WINCH ${MAINPID} ; ignore_errors=no ; start_time=[Tue 2018-10-16 13:36:27 CST] ; stop_time=[Tue 2018-10-16 13:36:27 CST] ; pid=26794 ; code=exited ; status=0 }", 
            "FailureAction": "none", 
            "FileDescriptorStoreMax": "0", 
            "FragmentPath": "/usr/lib/systemd/system/httpd.service", 
            "GuessMainPID": "yes", 
            "IOScheduling": "0", 
            "Id": "httpd.service", 
            "IgnoreOnIsolate": "no", 
            "IgnoreOnSnapshot": "no", 
            "IgnoreSIGPIPE": "yes", 
            "InactiveEnterTimestamp": "Tue 2018-10-16 13:36:28 CST", 
            "InactiveEnterTimestampMonotonic": "599477552573", 
            "InactiveExitTimestamp": "Fri 2018-10-12 13:57:44 CST", 
            "InactiveExitTimestampMonotonic": "255153283387", 
            "JobTimeoutAction": "none", 
            "JobTimeoutUSec": "0", 
            "KillMode": "control-group", 
            "KillSignal": "18", 
            "LimitAS": "18446744073709551615", 
            "LimitCORE": "18446744073709551615", 
            "LimitCPU": "18446744073709551615", 
            "LimitDATA": "18446744073709551615", 
            "LimitFSIZE": "18446744073709551615", 
            "LimitLOCKS": "18446744073709551615", 
            "LimitMEMLOCK": "65536", 
            "LimitMSGQUEUE": "819200", 
            "LimitNICE": "0", 
            "LimitNOFILE": "4096", 
            "LimitNPROC": "3747", 
            "LimitRSS": "18446744073709551615", 
            "LimitRTPRIO": "0", 
            "LimitRTTIME": "18446744073709551615", 
            "LimitSIGPENDING": "3747", 
            "LimitSTACK": "18446744073709551615", 
            "LoadState": "loaded", 
            "MainPID": "0", 
            "MemoryAccounting": "no", 
            "MemoryCurrent": "18446744073709551615", 
            "MemoryLimit": "18446744073709551615", 
            "MountFlags": "0", 
            "Names": "httpd.service", 
            "NeedDaemonReload": "no", 
            "Nice": "0", 
            "NoNewPrivileges": "no", 
            "NonBlocking": "no", 
            "NotifyAccess": "main", 
            "OOMScoreAdjust": "0", 
            "OnFailureJobMode": "replace", 
            "PermissionsStartOnly": "no", 
            "PrivateDevices": "no", 
            "PrivateNetwork": "no", 
            "PrivateTmp": "yes", 
            "ProtectHome": "no", 
            "ProtectSystem": "no", 
            "RefuseManualStart": "no", 
            "RefuseManualStop": "no", 
            "RemainAfterExit": "no", 
            "Requires": "-.mount basic.target", 
            "RequiresMountsFor": "/var/tmp", 
            "Restart": "no", 
            "RestartUSec": "100ms", 
            "Result": "success", 
            "RootDirectoryStartOnly": "no", 
            "RuntimeDirectoryMode": "0755", 
            "SameProcessGroup": "no", 
            "SecureBits": "0", 
            "SendSIGHUP": "no", 
            "SendSIGKILL": "yes", 
            "Slice": "system.slice", 
            "StandardError": "inherit", 
            "StandardInput": "null", 
            "StandardOutput": "journal", 
            "StartLimitAction": "none", 
            "StartLimitBurst": "5", 
            "StartLimitInterval": "10000000", 
            "StartupBlockIOWeight": "18446744073709551615", 
            "StartupCPUShares": "18446744073709551615", 
            "StatusErrno": "0", 
            "StatusText": "Total requests: 0; Current requests/sec: 0; Current traffic:   0 B/sec", 
            "StopWhenUnneeded": "no", 
            "SubState": "dead", 
            "SyslogLevelPrefix": "yes", 
            "SyslogPriority": "30", 
            "SystemCallErrorNumber": "0", 
            "TTYReset": "no", 
            "TTYVHangup": "no", 
            "TTYVTDisallocate": "no", 
            "TasksAccounting": "no", 
            "TasksCurrent": "18446744073709551615", 
            "TasksMax": "18446744073709551615", 
            "TimeoutStartUSec": "1min 30s", 
            "TimeoutStopUSec": "1min 30s", 
            "TimerSlackNSec": "50000", 
            "Transient": "no", 
            "Type": "notify", 
            "UMask": "0022", 
            "UnitFilePreset": "disabled", 
            "UnitFileState": "enabled", 
            "WantedBy": "multi-user.target", 
            "Wants": "system.slice", 
            "WatchdogTimestampMonotonic": "0", 
            "WatchdogUSec": "0"
        }
    }
    

    shell 模块

    shell模块和command模块类似,支持变量,管道等复杂的命令

    演示

    为root用户设置密码

    先测试使用command模块来配置:

    [root@node01 ansible]# ansible all -m command -a 'echo 123456 | passwd root --stdin'
    10.0.0.65 | CHANGED | rc=0 >>
    123456 | passwd root --stdin
    
    10.0.0.66 | CHANGED | rc=0 >>
    123456 | passwd root --stdin
    

    这里可以看到,直接把所有的信息都输出了,并没有执行

    下面用shell模块来运行:

    [root@node01 ansible]# ansible all -m shell -a 'echo 123456 | passwd root --stdin'
    10.0.0.65 | CHANGED | rc=0 >>
    Changing password for user root.
    passwd: all authentication tokens updated successfully.
    
    10.0.0.66 | CHANGED | rc=0 >>
    Changing password for user root.
    passwd: all authentication tokens updated successfully.
    

    这里可以看到,已经修改成功了

    script 模块

    将本地的脚本复制到远程主机上并运行它。

    首先在本地创建一个shell脚本

    [root@node01 ansible]# pwd
    [root@node01 ansible]# cat test.sh 
    #!/bin/bash
    useradd test
    [root@node01 ansible]# chmod +x test.sh
    

    然后使用script模块来运行

    [root@node01 ansible]# ansible all -m script -a 'test.sh'
    10.0.0.66 | CHANGED => {
        "changed": true, 
        "rc": 0, 
        "stderr": "Shared connection to 10.0.0.66 closed.
    ", 
        "stderr_lines": [
            "Shared connection to 10.0.0.66 closed."
        ], 
        "stdout": "", 
        "stdout_lines": []
    }
    10.0.0.65 | CHANGED => {
        "changed": true, 
        "rc": 0, 
        "stderr": "Shared connection to 10.0.0.65 closed.
    ", 
        "stderr_lines": [
            "Shared connection to 10.0.0.65 closed."
        ], 
        "stdout": "", 
        "stdout_lines": []
    }
    [root@node01 ansible]# ansible all -a 'grep test /etc/passwd'
    10.0.0.66 | CHANGED | rc=0 >>
    test:x:1002:1002::/home/test:/bin/bash
    
    10.0.0.65 | CHANGED | rc=0 >>
    test:x:1001:1001::/home/test:/bin/bash
    

    注意:脚本路径要使用相对路径来执行,因为在远程主机上也是使用相对路径来执行的

    可以看到已经执行成功了

    yum 模块

    管理yum,可以指定版本

    演示

    安装zsh

    [root@node01 ansible]# ansible all -m yum -a 'name=zsh state=present' 
    10.0.0.65 | CHANGED => {
        "ansible_facts": {
            "pkg_mgr": "yum"
        }, 
        "changed": true, 
        "msg": "", 
        "rc": 0, 
        "results": [
            "Loaded plugins: fastestmirror
    Loading mirror speeds from cached hostfile
     * base: mirrors.aliyun.com
     * extras: mirrors.aliyun.com
     * updates: mirrors.aliyun.com
    Resolving Dependencies
    --> Running transaction check
    ---> Package zsh.x86_64 0:5.0.2-28.el7 will be installed
    --> Finished Dependency Resolution
    
    Dependencies Resolved
    
    ================================================================================
     Package        Arch              Version                 Repository       Size
    ================================================================================
    Installing:
     zsh            x86_64            5.0.2-28.el7            base            2.4 M
    
    Transaction Summary
    ================================================================================
    Install  1 Package
    
    Total download size: 2.4 M
    Installed size: 5.6 M
    Downloading packages:
    Running transaction check
    Running transaction test
    Transaction test succeeded
    Running transaction
      Installing : zsh-5.0.2-28.el7.x86_64                                      1/1 
      Verifying  : zsh-5.0.2-28.el7.x86_64                                      1/1 
    
    Installed:
      zsh.x86_64 0:5.0.2-28.el7                                                     
    
    Complete!
    "
        ]
    }
    10.0.0.66 | CHANGED => {
        "ansible_facts": {
            "pkg_mgr": "yum"
        }, 
        "changed": true, 
        "msg": "", 
        "rc": 0, 
        "results": [
            "Loaded plugins: fastestmirror
    Loading mirror speeds from cached hostfile
     * base: mirrors.aliyun.com
     * extras: mirrors.aliyun.com
     * updates: mirrors.aliyun.com
    Resolving Dependencies
    --> Running transaction check
    ---> Package zsh.x86_64 0:5.0.2-28.el7 will be installed
    --> Finished Dependency Resolution
    
    Dependencies Resolved
    
    ================================================================================
     Package        Arch              Version                 Repository       Size
    ================================================================================
    Installing:
     zsh            x86_64            5.0.2-28.el7            base            2.4 M
    
    Transaction Summary
    ================================================================================
    Install  1 Package
    
    Total download size: 2.4 M
    Installed size: 5.6 M
    Downloading packages:
    Running transaction check
    Running transaction test
    Transaction test succeeded
    Running transaction
      Installing : zsh-5.0.2-28.el7.x86_64                                      1/1 
      Verifying  : zsh-5.0.2-28.el7.x86_64                                      1/1 
    
    Installed:
      zsh.x86_64 0:5.0.2-28.el7                                                     
    
    Complete!
    "
        ]
    }
    
    # 查看
    
    [root@node01 ansible]# ansible all -a 'rpm -qa zsh'
     [WARNING]: Consider using the yum, dnf or zypper module rather than running rpm.  If you need to use command because yum,
    dnf or zypper is insufficient you can add warn=False to this command task or set command_warnings=False in ansible.cfg to
    get rid of this message.
    
    10.0.0.66 | CHANGED | rc=0 >>
    zsh-5.0.2-28.el7.x86_64
    
    10.0.0.65 | CHANGED | rc=0 >>
    zsh-5.0.2-28.el7.x86_64
    
    

    说明:

    • state=present 参数在安装的时候,可以加上,默认是安装

    会输出很多信息

    卸载

    [root@node01 ansible]# ansible all -m yum -a 'name=zsh state=absent'
    10.0.0.66 | CHANGED => {
        "ansible_facts": {
            "pkg_mgr": "yum"
        }, 
        "changed": true, 
        "msg": "", 
        "rc": 0, 
        "results": [
            "Loaded plugins: fastestmirror
    Resolving Dependencies
    --> Running transaction check
    ---> Package zsh.x86_64 0:5.0.2-28.el7 will be erased
    --> Finished Dependency Resolution
    
    Dependencies Resolved
    
    ================================================================================
     Package       Arch             Version                   Repository       Size
    ================================================================================
    Removing:
     zsh           x86_64           5.0.2-28.el7              @base           5.6 M
    
    Transaction Summary
    ================================================================================
    Remove  1 Package
    
    Installed size: 5.6 M
    Downloading packages:
    Running transaction check
    Running transaction test
    Transaction test succeeded
    Running transaction
      Erasing    : zsh-5.0.2-28.el7.x86_64                                      1/1 
      Verifying  : zsh-5.0.2-28.el7.x86_64                                      1/1 
    
    Removed:
      zsh.x86_64 0:5.0.2-28.el7                                                     
    
    Complete!
    "
        ]
    }
    10.0.0.65 | CHANGED => {
        "ansible_facts": {
            "pkg_mgr": "yum"
        }, 
        "changed": true, 
        "msg": "", 
        "rc": 0, 
        "results": [
            "Loaded plugins: fastestmirror
    Resolving Dependencies
    --> Running transaction check
    ---> Package zsh.x86_64 0:5.0.2-28.el7 will be erased
    --> Finished Dependency Resolution
    
    Dependencies Resolved
    
    ================================================================================
     Package       Arch             Version                   Repository       Size
    ================================================================================
    Removing:
     zsh           x86_64           5.0.2-28.el7              @base           5.6 M
    
    Transaction Summary
    ================================================================================
    Remove  1 Package
    
    Installed size: 5.6 M
    Downloading packages:
    Running transaction check
    Running transaction test
    Transaction test succeeded
    Running transaction
      Erasing    : zsh-5.0.2-28.el7.x86_64                                      1/1 
      Verifying  : zsh-5.0.2-28.el7.x86_64                                      1/1 
    
    Removed:
      zsh.x86_64 0:5.0.2-28.el7                                                     
    
    Complete!
    "
        ]
    }
    
    # 查看
    
    [root@node01 ansible]# ansible all -a 'rpm -qa zsh'
     [WARNING]: Consider using the yum, dnf or zypper module rather than running rpm.  If you need to use command because yum,
    dnf or zypper is insufficient you can add warn=False to this command task or set command_warnings=False in ansible.cfg to
    get rid of this message.
    
    10.0.0.66 | CHANGED | rc=0 >>
    
    
    10.0.0.65 | CHANGED | rc=0 >>
    

    说明:

    • state=absent 参数表示卸载

    setup 模块

    收集远程主机的facts,也就是主机的详细信息,主机名、IP、MAC等等等

    作用:

    • 在facts中,有每个被管理节点在接受并运行管理命令之前,会将自己主机相关信息,如操作系统版本、IP地址等会报告给远程ansible主机
    [root@node01 ansible]# ansible-doc -s setup
    - name: Gathers facts about remote hosts
      setup:
          fact_path:             # path used for local ansible facts (`*.fact') - files in this dir will be run (if
                                   executable) and their results be added to `ansible_local'
                                   facts if a file is not executable it is read. Check notes
                                   for Windows options. (from 2.1 on) File/results format can
                                   be json or ini-format
          filter:                # if supplied, only return facts that match this shell-style (fnmatch) wildcard.
          gather_subset:         # if supplied, restrict the additional facts collected to the given subset. Possible values:
                                   `all', `min', `hardware', `network', `virtual', `ohai', and
                                   `facter'. Can specify a list of values to specify a larger
                                   subset. Values can also be used with an initial `!' to
                                   specify that that specific subset should not be collected.
                                   For instance: `!hardware,!network,!virtual,!ohai,!facter'.
                                   If `!all' is specified then only the min subset is
                                   collected. To avoid collecting even the min subset, specify
                                   `!all,!min'. To collect only specific facts, use
                                   `!all,!min', and specify the particular fact subsets. Use
                                   the filter parameter if you do not want to display some
                                   collected facts.
          gather_timeout:        # Set the default timeout in seconds for individual fact gathering
    

    由于setup模块显示的内容太多,这里就不演示了

  • 相关阅读:
    websocket+nodejs+redis实现消息订阅和发布系统
    nodejs下载图片到本地,根据百度图片查找相应的图片,通过nodejs保存到本地文件夹
    基于vue 2.X和高德地图的vue-amap组件获取经纬度
    获取Class对象的三种方式
    java中的回调机制的理解(小例子)
    URL和URI的区别
    java web开发中各类地址的写法
    ListView性能
    Android中的Handler, Looper, MessageQueue和Thread对应关系
    java几种常用的算法
  • 原文地址:https://www.cnblogs.com/winstom/p/9791481.html
Copyright © 2011-2022 走看看