• ansible


    0、介绍

    默认使用SSH协议对设备进行管理,
    在主控端部署Ansible环境,
    无需在客户端安装agent,
    基于Python开发的实现批量系统配置、程序部署、运行命令等功能的自动化运维工具

    1、安装            192.168.1.155安装ansible

    EPEL源:yum -y install epel-release
    yum install -y ansible

    配置文件 (/etc/ansible/roles              #存放角色的目录)

    (base) [root@hdp1 ~]# rpm -qc  ansible
    /etc/ansible/ansible.cfg
    /etc/ansible/hosts 

    2、配置主机清单    hosts ,                默认 /etc/ansible/hosts ,也可以 -i  指定文件

    (base) [root@hdp1 ~]# cat /etc/ansible/hosts            |grep -v ^#|grep -v ^$
    [hdp]
    192.168.1.156
    192.168.1.[157:159]

    cfg配置

    # 表示是否检查受控端的 SSH 密钥,默认为 True 。当 SSH 使用【账号/口令】认证的方式登录受控端时,应设置为 "False"(当注释该选项时,默认值为 "True");当 SSH 使用【非对称加密】认证的方式登录受控端应设置为 "True"。
    host_key_checking = False
    
    # 表示受控端清单文件的位置。默认为 【/etc/ansible/hosts】 。
    inventory = /etc/ansible/hosts
    
    # 表示远程执行临时文件目录。默认为 【~/.ansible/tmp】 。
    remote_tmp = ~/.ansible/tmp
    
    # 表示本地临时文件目录。默认为 【~/.ansible/tmp】 。
    local_tmp = ~/.ansible/tmp
    
    # 表示存放模块的目录,多个目录使用冒号(:)分隔。默认为 【 /usr/share/ansible】 。
    library = /usr/share/ansible
    
    # 表示存放角色的目录。认为 【/etc/ansible/roles】 。
    roles_path = /etc/ansible/roles
    
    # 表示受控端的并发连接数,默认为 5 。
    forks = 5
    
    # 表示 sudo 程序,默认为 sudo 。
    sudo_exe = sudo
    
    # 表示使用 sudo 执行指令的用户,默认为 root 。
    sudo_user = root
    
    # 表示每次执行指令时是否询问 sudo 口令,默认为 True 。
    ask_sudo_pass = True
    
    # 表示是否允许提权。默认为 True 。
    become=True
    
    # 表示提权指令,如:sudo、su 。 默认为 sudo。
    become_method=sudo
    
    # 表示默认的提权用户。默认为 root 。
    become_user=root
    
    # 表示每次执行指令时是否询问提权口令,默认为 False 。
    become_ask_pass=False
    
    # 表示使用 sudo 执行指令的 Shell 环境。
    executable = /bin/sh
    
    # ssh 远程登录用户名,默认为 root 。
    remote_user = root
    
    # 表示每次执行指令时是否询问 ssh 口令,默认为 True 。
    ask_pass = True
    
    # 表示受控端的 SSH 服务端口,默认为22。
    remote_port = 22
    
    # 表示 SSH 的连接超时时间,单位为秒,默认为 60 秒。
    timeout = 60
    
    # 表示传输模式,默认为 smart 。
    transport = smart
    
    # 表示默认执行的模块,默认为 command 。
    module_name = command
    
    # 表示日志文件的位置,默认不记录日志。
    log_path = /var/log/ansible.log
    
    
    host_key_checking = False                           #此行注释去除,否则每次将检查主机的host_key
    log_path = /var/log/ansible.log                     #将日志文件打开,方便查看操作日志
    module_name = shell                                 #将默认的模块改为shell,command模块功能太弱
    

      

     

    3、列出所有主机

    (  base ) [root@hdp1 ~]# ansible all --list-hosts
      hosts (4):
        192.168.1.156
        192.168.1.157
        192.168.1.158
        192.168.1.159

    模块查看

    (base) [root@hdp1 ~]# ansible-doc -l      |egrep -w 'yum|ping|shell|cron'|grep -v _
    shell                                                         Execute shell commands on targets        
    ping                                                          Try to connect to host, verify a usable p...
    yum                                                           Manages packages with the `yum' package m...
    cron                                                          Manage cron.d and crontab entries 
    

      

    4、模块 ping

    (base) [root@hdp1 ~]# ansible    -m ping   all -o
    192.168.1.158 | SUCCESS => {"ansible_facts": {"discovered_interpreter_python": "/usr/bin/python"}, "changed": false, "ping": "pong"}
    192.168.1.156 | SUCCESS => {"ansible_facts": {"discovered_interpreter_python": "/usr/bin/python"}, "changed": false, "ping": "pong"}
    192.168.1.157 | SUCCESS => {"ansible_facts": {"discovered_interpreter_python": "/usr/bin/python"}, "changed": false, "ping": "pong"}
    192.168.1.159 | UNREACHABLE!: Failed to connect to the host via ssh: ssh: connect to host 192.168.1.159 port 22: No route to host
    

    5、模块 shell         (command 模块  先忽略)

    (base) [root@hdp1 ~]# ansible -m shell -a 'cat /etc/passwd|grep zzx' hdp  -o
    192.168.1.158 | CHANGED | rc=0 | (stdout) zzx:x:1000:1000:centos7pure:/home/zzx:/bin/bash
    192.168.1.156 | CHANGED | rc=0 | (stdout) zzx:x:1000:1000:centos7pure:/home/zzx:/bin/bash
    192.168.1.157 | CHANGED | rc=0 | (stdout) zzx:x:1000:1000:centos7pure:/home/zzx:/bin/bash
    

     通过参数 

    --list-hosts	#查看有哪些主机组
    -m MODULE_NAME	#执行模块的名字,默认使用 command 模块,所以如果是只执行单一命令可以不用 -m参数
    -a MODULE_ARGS   #模块的参数,如果执行默认COMMAND的模块,即是命令参数,如: “date”,“pwd”等等
    -o	#压缩输出,尝试将所有结果在一行输出,一般针对收集工具使用
    -u,–user=REMOTE_USER     指定远程执行的用户
    -b --become-user=xxx_user   类似runuser ,不用验证password
    -k,--ask-pass	#ask for SSH password。登录密码,提示输入SSH密码而不是假设基于密钥的验证

    ansible 192.168.1.156   -u abc -m shell -a 'crontab -l'   需要abc的密码   需要加 -k  输入一次密码后续不用再次-k

    -b参数如下:

    (base) [root@hdp1 ~]# ansible  192.168.1.158  -m shell -a 'cd /tmp/;touch zzx.test' -b --become-user=zzx 
    192.168.1.158 | CHANGED | rc=0 >>
    
    
    (base) [root@hdp1 ~]# ansible  192.168.1.158  -m shell -a 'ls -l /tmp/zzx.test' -b --become-user=zzx 
    192.168.1.158 | CHANGED | rc=0 >>
    -rw-r--r-- 1 zzx zzx 0 Jun 11 22:09 /tmp/zzx.test
    
    
    (base) [root@hdp1 ~]# ansible  192.168.1.158  -m shell -a 'ls -l /tmp/zzx.test' -u zzx
    192.168.1.158 | UNREACHABLE! => {
        "changed": false, 
        "msg": "Failed to connect to the host via ssh: Permission denied (publickey,gssapi-keyex,gssapi-with-mic,password).", 
        "unreachable": true
    }
    
    
    (base) [root@hdp1 ~]# ansible  192.168.1.158  -m shell -a 'ls -l /tmp/zzx.test' -u zzx -k
    SSH password: 
    192.168.1.158 | CHANGED | rc=0 >>
    -rw-r--r-- 1 zzx zzx 0 Jun 11 22:09 /tmp/zzx.test
    

      

    默认不加 -m 就是command模块,   不过command模块不支持管道、特殊字符等,一般还是用shell模块比较好       比如不支持    cat /etc/host*      cat /etc/hosts|grep xxx   

    (base) [root@hdp1 ~]# ansible all -a 'cat /etc/hostname' -o
    192.168.1.158 | CHANGED | rc=0 | (stdout) hdp4
    192.168.1.157 | CHANGED | rc=0 | (stdout) hdp3
    192.168.1.156 | CHANGED | rc=0 | (stdout) hdp2
    

    6、copy模块

    src    #被复制到远程主机的本地文件。可以是绝对路径,也可以是相对路径。如果路径是一个目录,则会递归复制,用法类似于"rsync"
    dest    #必选项,将源文件复制到的远程主机的绝对路径
    
    (base) [root@hdp1 ~]# ansible all -m copy -a 'src=~/test.txt dest=/tmp/cp.test.txt' 
    192.168.1.158 | CHANGED => {
        "ansible_facts": {
            "discovered_interpreter_python": "/usr/bin/python"
        }, 
        "changed": true, 
        "checksum": "e6dff7904004227cc55ad9a3b52122d4793f76ce", 
        "dest": "/tmp/cp.test.txt", 
        "gid": 0, 
        "group": "root", 
        "md5sum": "854b46d7345628169fe9107f6c4e6735", 
        "mode": "0644", 
        "owner": "root", 
        "size": 20, 
        "src": "/root/.ansible/tmp/ansible-tmp-1654270827.59-95240-47386337382468/source", 
        "state": "file", 
        "uid": 0
    }
    
    
    (base) [root@hdp1 ~]# ansible all -m shell -a 'cat /tmp/cp.*' -o
    192.168.1.158 | CHANGED | rc=0 | (stdout) wjqfjqo\nhello flask
    192.168.1.156 | CHANGED | rc=0 | (stdout) wjqfjqo\nhello flask
    192.168.1.157 | CHANGED | rc=0 | (stdout) wjqfjqo\nhello flask
    

      

      

    7、fetch模块               该模块用于从远程某主机获取(复制)文件到本地。

                             有两个选项:dest:用来存放文件的目录                     src:在远程拉取的文件,并且必须是一个file,不能是目录

    (base) [root@hdp1 ~]# ansible all -m fetch -a 'src=/etc/hostname dest=/tmp'  
    192.168.1.158 | CHANGED => {
        "changed": true, 
        "checksum": "7cd41f5e49a7af4752ccb8dbcdc491e6d2983ee5", 
        "dest": "/tmp/192.168.1.158/etc/hostname", 
        "md5sum": "819226484589f2a5f9bfb7242d2e98b0", 
        "remote_checksum": "7cd41f5e49a7af4752ccb8dbcdc491e6d2983ee5", 
        "remote_md5sum": null
    }
    
    (base) [root@hdp1 ~]# cat /tmp/192.168.1.156/etc/hostname
    hdp2
    

      

    8、script 模块

    (base) [root@hdp1 ~]# echo "cat /etc/hostname;echo 'scrip test'; echo \`seq -w 00 03\`" > test.sh
    
    (base) [root@hdp1 ~]# cat test.sh 
    cat /etc/hostname; 
     echo 'scrip test'; 
     echo `seq -w 00 03`
     
      ansible all -m script -a '/root/test.sh'  -o
    192.168.1.157 | CHANGED => {"changed": true, "rc": 0, "stderr": "Shared connection to 192.168.1.157 closed.\r\n", "stderr_lines": ["Shared connection to 192.168.1.157 closed."], "stdout": "hdp3\r\nscrip test\r\n00 01 02 03\r\n", "stdout_lines": ["hdp3", "scrip test", "00 01 02 03"]}
    

      

    9cron 模块     

    user指定用户(需要认证指定用户 或者 加-k参数) 
    (base) [root@hdp1 ~]# ansible 192.168.1.156 -m cron -a 'name="date every 1 min" minute=*/1 job="/usr/bin/date >> /tmp/root.date.log  &> /dev/null"'
    
    (base) [root@hdp1 ~]# ansible 192.168.1.156 -m cron -a 'user=zzx name="date every 2 min" minute=*/2 job="/usr/bin/date >> /tmp/zzx.date.log  &> /dev/null"'
    
    操作结果如下:
    
    [root@hdp2 ~]# crontab -l
    #Ansible: date every 1 min
    */1 * * * * /usr/bin/date >> /tmp/root.date.log  &> /dev/null
    
    [root@hdp2 ~]# cat /var/spool/cron/zzx 
    #Ansible: date every 2 min
    */2 * * * * /usr/bin/date >> /tmp/zzx.date.log  &> /dev/null
    

    参数 说明

    backup	在计划任务创建前先备份
    day	天
    hour	小时
    minute	分钟
    month	月
    weekday	星期
    name	计划任务的名称
    reboot	重启后执行
    state	absent:删除
    job	计划任务的内容
    disabled	启用和禁用
    

       

    增删改

    更新 name不变,job内容变化
    (base) [root@hdp1 ~]# ansible 192.168.1.156 -m cron -a 'name="date every 1 min" minute=*/1 job="/usr/bin/date  &>> /tmp/root.date.log  "'
    
    禁用 disabled=true 
    (base) [root@hdp1 ~]# ansible 192.168.1.156 -m cron -a 'disabled=true name="date every 1 min" minute=*/1 job="/usr/bin/date  &>> /tmp/root.date.log  "'
    
    启用 disabled=false 
    (base) [root@hdp1 ~]# ansible 192.168.1.156 -m cron -a 'disabled=false name="date every 1 min" minute=*/1 job="/usr/bin/date  &>> /tmp/root.date.log  "'
    
    删除state=absent
    (base) [root@hdp1 ~]# ansible 192.168.1.156 -m cron -a 'disabled=false name="date every 1 min" minute=*/1 job="/usr/bin/date  &>> /tmp/root.date.log  " state=absent'
    

    state

    #yum模块
    state=latest   #yum 安装。latest最新的包
    #服务模块
    state=started  
    state=stopped
    state=restarted
    #文件模块
    state=touch
    state=directory
    state=link
    #其他
    state=absent   #删除文件  取消cron  删除用户
    state=present  #创建文件  创建cron  创建用户
    

    yum、service 、user 、hostname 、File等模块  

    10、playbook  

    以上只是执行当个的命令和脚本,下面演示playbook

    playbook 字面意思,即剧本,现实中由演员按照剧本表演,在Ansible中,这次由计算机进行表演,由计算机安装,部署应用,提供对外服务,以及组织计算机处理各种各样的事情。

     执行shell命令与写shell脚本一样,也可以理解为批处理任务,不过playbook有自己的语法格式。

    以下为playbook常用到的YMAL格式:

      1、文件的第一行应该以 "---" (三个连字符)开始,表明YMAL文件的开始。
      2、在同一行中,#之后的内容表示注释,类似于shell,python和ruby。
      3、YMAL中的列表元素以”-”开头然后紧跟着一个空格,后面为元素内容。
      4、同一个列表中的元素应该保持相同的缩进。否则会被当做错误处理。
      5、play中hosts,variables,roles,tasks等对象的表示方法都是键值中间以":"分隔表示,":"后面还要增加一个空格。
    

    执行第一个playbook

    (base) [root@hdp1 ~]# vi playbook.yml 
    ---
    - hosts: hdp
      gather_facts: no
      tasks:
        - name: first task
          shell: cat /etc/hostname >> /tmp/hostname ;echo "123" >> /tmp/hostname
    
    
    (base) [root@hdp1 ~]# ansible-playbook -u root playbook.yml
    
    PLAY [hdp] *************************************************************************************************
    
    TASK [first task] ******************************************************************************************
    changed: [192.168.1.157]
    changed: [192.168.1.158]
    changed: [192.168.1.156]
    
    PLAY RECAP *************************************************************************************************
    192.168.1.156              : ok=1    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
    192.168.1.157              : ok=1    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
    192.168.1.158              : ok=1    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
    
    
    
    
    [root@hdp2 ~]# cat  /tmp/hostname 
    hdp2
    123
    

      

    gather_facts   获取被控机器的 fact 数据 

    其中 hosts 表示对哪些主机进行操作,

    become 就是我们在命令行上用过的 -b 选项

    这里我们通过 become_user: root 显式的指定把当前用户的权限提升为 root 用户权限来执行命令。

    (base) [root@hdp1 ~]# cat playbook.yml 
    ---
    - hosts: 192.168.1.156 
      gather_facts: no 
      become: yes
      become_user: zzx
      tasks:
        - name: first task
          shell: rm -f /tmp/*zzx*;    cat /etc/hostname > /tmp/hostname_zzx
        - name: task2
          shell: ls -l /tmp/*zzx*;    cat /tmp/hostname_zzx
    
    
    
    (base) [root@hdp1 ~]# ansible-playbook   playbook.yml 
    
    PLAY [192.168.1.156] *******************************************************************************************************************************************************************
    
    TASK [first task] **********************************************************************************************************************************************************************
    [WARNING]: Consider using the file module with state=absent rather than running 'rm'.  If you need to use command because file 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.
    changed: [192.168.1.156]
    
    TASK [task2] ***************************************************************************************************************************************************************************
    changed: [192.168.1.156]
    
    PLAY RECAP *****************************************************************************************************************************************************************************
    192.168.1.156              : ok=2    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
    
    
    (base) [root@hdp1 ~]# ansible 192.168.1.156 -m shell -a 'ls -lrt /tmp/*zzx*'
    192.168.1.156 | CHANGED | rc=0 >>
    -rw-r--r-- 1 zzx zzx 5 Jun 11 22:39 /tmp/hostname_zzx
    

      

     tasks 是对任务的定义,

    name 是独一无二的一个任务名(如果有多个同名的 task,只执行第一个),

    接着是 task 中的module,比如 command或者shell 等模块,      注意:shell和command模块后面直接跟命令,而非key=value类的参数列表;

    
    

    多任务:

      tasks:
        - name: first task
          shell: cat /etc/hostname >> /tmp/hostname ;echo "123" >> /tmp/hostname
        - name: task2
          shell: cat /etc/hostname >> /tmp/hostname2 ;echo "123" >> /tmp/hostname2
    

      

    handlers:任务,在特定条件下触发;接收到其它任务的通知时被触发;

      (1) 某任务的状态在运行后为changed时,可通过“notify”通知给相应的handlers;
      (2) 任务可以通过“tags“打标签,而后可在ansible-playbook命令上使用-t指定进行调用;

    格式:
        tasks:
          – name: TASK_NAME
           module: arguments
           notify: HANDLER_NAME
           handlers:
          – name: HANDLER_NAME
           module: arguments
    

     

    查语法有没有错误,没有提示即表示语法应该没有问题。    

    (base) [root@hdp1 ~]# ansible-playbook --syntax-check  nginx.yml
    
    playbook: nginx.yml
    

      

    测试运行看看,-C表示仅测试跑一边,但是不会实际操作         ansible-playbook -C nginx.yml

    (base) [root@hdp1 ~]# cat test.nginx.yml 
    ---
    - hosts: 192.168.1.158
      remote_user: root
      roles:
      tasks:
        - name: install epel-release
          shell: yum -y install epel-release
        - name: install nginx  
          yum: name=nginx state=present
        - name: start nginx service
          service: name=nginx state=started
          tags: startnginx
        - name: get nginx port 1
          shell: netstat -anltp|grep nginx|tee  /tmp/get_nginx_port_1
          tags: getPort1
        - name: copy nginx.conf
          copy: src=/tmp/nginx.conf dest=/etc/nginx/nginx.conf backup=yes
          notify: reload
          tags: reloadnginx
        - name: get nginx port 2
          shell: netstat -anltp|grep nginx|tee  /tmp/get_nginx_port_2
          tags: getPort2
    
      handlers:
        - name: reload
          service: name=nginx state=reloaded
    
    
    
    
    (base) [root@hdp1 ~]# ansible-playbook  test.nginx.yml
    
    PLAY [192.168.1.158] *******************************************************************************************************************************************************************
    
    TASK [Gathering Facts] *****************************************************************************************************************************************************************
    ok: [192.168.1.158]
    
    TASK [install epel-release] ************************************************************************************************************************************************************
    [WARNING]: Consider using the yum module rather than running 'yum'.  If you need to use command because yum 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.
    changed: [192.168.1.158]
    
    TASK [install nginx] *******************************************************************************************************************************************************************
    changed: [192.168.1.158]
    
    TASK [start nginx service] *************************************************************************************************************************************************************
    changed: [192.168.1.158]
    
    TASK [get nginx port 1] ****************************************************************************************************************************************************************
    changed: [192.168.1.158]
    
    TASK [copy nginx.conf] *****************************************************************************************************************************************************************
    changed: [192.168.1.158]
    
    TASK [get nginx port 2] ****************************************************************************************************************************************************************
    changed: [192.168.1.158]
    
    RUNNING HANDLER [reload] ***************************************************************************************************************************************************************
    changed: [192.168.1.158]
    
    PLAY RECAP *****************************************************************************************************************************************************************************
    192.168.1.158              : ok=8    changed=7    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
    

     结果

    (base) [root@hdp1 ~]# ansible 192.168.1.158 -m shell -a 'cat /tmp/get_nginx_port*'
    192.168.1.158 | CHANGED | rc=0 >>
    tcp        0      0 0.0.0.0:80              0.0.0.0:*               LISTEN      102213/nginx: maste 
    tcp6       0      0 :::80                   :::*                    LISTEN      102213/nginx: maste 
    tcp        0      0 0.0.0.0:80              0.0.0.0:*               LISTEN      102213/nginx: maste 
    tcp6       0      0 :::80                   :::*                    LISTEN      102213/nginx: maste 
    
    
    
    (base) [root@hdp1 ~]# ansible 192.168.1.158 -m shell -a 'netstat -anltp|grep nginx'
    192.168.1.158 | CHANGED | rc=0 >>
    tcp        0      0 0.0.0.0:818             0.0.0.0:*               LISTEN      102213/nginx: maste 
    tcp6       0      0 :::80                   :::*                    LISTEN      102213/nginx: maste 
    

      

    以上只有copy执行了(changed)才会触发handlers的reload,且是先执行 'get nginx port 2' 后再reload,不是copy完立马reload最后再 'get nginx port 2'

    handle执行的顺序与notify的顺序无关,仅按照playbook中handles的任务顺序执行,如果需要执行某个tasks任务后立即执行handles任务,那么使用meta模块

    1、卸载nginx
    (base) [root@hdp1 ~]# ansible 192.168.1.158 -m shell -a 'yum remove nginx -y'
    [WARNING]: Consider using the yum module rather than running 'yum'.  If you need to use command because yum 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.
    192.168.1.158 | CHANGED | rc=0 >>
    Loaded plugins: fastestmirror, langpacks
    Resolving Dependencies
    --> Running transaction check
    ---> Package nginx.x86_64 1:1.20.1-9.el7 will be erased
    --> Finished Dependency Resolution
    
    Dependencies Resolved
    
    ================================================================================
     Package        Arch            Version                    Repository      Size
    ================================================================================
    Removing:
     nginx          x86_64          1:1.20.1-9.el7             @epel          1.7 M
    
    Transaction Summary
    ================================================================================
    Remove  1 Package
    
    Installed size: 1.7 M
    Downloading packages:
    Running transaction check
    Running transaction test
    Transaction test succeeded
    Running transaction
      Erasing    : 1:nginx-1.20.1-9.el7.x86_64                                  1/1 
    warning: /etc/nginx/nginx.conf saved as /etc/nginx/nginx.conf.rpmsave
      Verifying  : 1:nginx-1.20.1-9.el7.x86_64                                  1/1 
    
    Removed:
      nginx.x86_64 1:1.20.1-9.el7                                                   
    
    Complete!There are unfinished transactions remaining. You might consider running yum-complete-transaction, or "yum-complete-transaction --cleanup-only" and "yum history redo last", first to finish them. If those don't work you'll have to try removing/installing packages by hand (maybe package-cleanup can help).
    
    
    2、添加 - meta: flush_handlers
    (base) [root@hdp1 ~]# vi test.nginx.yml 
         /etc/nginx/nginx.conf
    ---
    - hosts: 192.168.1.158
      remote_user: root
      roles:
      tasks:
        - name: install epel-release
          shell: yum -y install epel-release
        - name: install nginx
          yum: name=nginx state=present
        - name: start nginx service
          service: name=nginx state=started
          tags: startnginx
        - name: get nginx port 1
          shell: netstat -anltp|grep nginx|tee  /tmp/get_nginx_port_1
          tags: getPort1
        - name: copy nginx.conf
          copy: src=/tmp/nginx.conf dest=/etc/nginx/nginx.conf backup=yes
          notify: reload
          tags: reloadnginx
    
        - meta: flush_handlers
    
        - name: get nginx port 2
          shell: netstat -anltp|grep nginx|tee  /tmp/get_nginx_port_2
          tags: getPort2
    
      handlers:
        - name: reload
          service: name=nginx state=reloaded
    
    
    3、重新运行
    (base) [root@hdp1 ~]# ansible 192.168.1.158 -m shell -a 'netstat -anltp|grep nginx'
    192.168.1.158 | FAILED | rc=1 >>
    non-zero return code
    (base) [root@hdp1 ~]# ansible-playbook  test.nginx.yml
    
    PLAY [192.168.1.158] *******************************************************************************************************************************************************************
    
    TASK [Gathering Facts] *****************************************************************************************************************************************************************
    ok: [192.168.1.158]
    
    TASK [install epel-release] ************************************************************************************************************************************************************
    [WARNING]: Consider using the yum module rather than running 'yum'.  If you need to use command because yum 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.
    changed: [192.168.1.158]
    
    TASK [install nginx] *******************************************************************************************************************************************************************
    changed: [192.168.1.158]
    
    TASK [start nginx service] *************************************************************************************************************************************************************
    changed: [192.168.1.158]
    
    TASK [get nginx port 1] ****************************************************************************************************************************************************************
    changed: [192.168.1.158]
    
    TASK [copy nginx.conf] *****************************************************************************************************************************************************************
    changed: [192.168.1.158]
    
    RUNNING HANDLER [reload] ***************************************************************************************************************************************************************
    changed: [192.168.1.158]
    
    TASK [get nginx port 2] ****************************************************************************************************************************************************************
    changed: [192.168.1.158]
    
    PLAY RECAP *****************************************************************************************************************************************************************************
    192.168.1.158              : ok=8    changed=7    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
    
    (base) [root@hdp1 ~]# ansible 192.168.1.158 -m shell -a 'netstat -anltp|grep nginx'
    192.168.1.158 | CHANGED | rc=0 >>
    tcp        0      0 0.0.0.0:818             0.0.0.0:*               LISTEN      109606/nginx: maste 
    tcp6       0      0 :::80                   :::*                    LISTEN      109606/nginx: maste 
    (base) [root@hdp1 ~]# ansible 192.168.1.158 -m shell -a 'cat /tmp/get_nginx_port*'
    192.168.1.158 | CHANGED | rc=0 >>
    tcp        0      0 0.0.0.0:80              0.0.0.0:*               LISTEN      109606/nginx: maste 
    tcp6       0      0 :::80                   :::*                    LISTEN      109606/nginx: maste 
    tcp        0      0 0.0.0.0:818             0.0.0.0:*               LISTEN      109606/nginx: maste 
    tcp6       0      0 :::80                   :::*                    LISTEN      109606/nginx: maste 
    

      

    进一步验证    - meta: flush_handlers

    1、
    (base) [root@hdp1 ~]# cat meta.yaml
    ---
    - hosts: 192.168.1.158
      tasks:
        - name: touch file 1
          shell: echo "" > /tmp/1
    
        - name: test1
          shell: echo "1 shell " >> /tmp/1
          notify: handlers1
          tags: tagshell1
        - name: test2
          shell: echo "2 shell " >> /tmp/1
          notify: handlers2
          tags: tagshell2
    
        - meta: flush_handlers
    
        - name: test3
          shell: echo "3 shell " >> /tmp/1
          notify: handlers3
          tags: tagshell3
    
        - name: test4
          shell: echo "4 shell   end" >> /tmp/1
          notify: handlers4
          tags: tagshell4
    
      handlers:
        - name: handlers1
          shell: echo "1 handlers " >> /tmp/1
        - name: handlers2
          shell: echo "2 handlers " >> /tmp/1
        - name: handlers3
          shell: echo "3 handlers " >> /tmp/1
        - name: handlers4
          shell: echo "4 handlers " >> /tmp/1
    
    
    2、执行
    (base) [root@hdp1 ~]# ansible-playbook meta.yaml
    
    PLAY [192.168.1.158] *******************************************************************************************************************************************************************
    
    TASK [Gathering Facts] *****************************************************************************************************************************************************************
    ok: [192.168.1.158]
    
    TASK [touch file 1] ********************************************************************************************************************************************************************
    changed: [192.168.1.158]
    
    TASK [test1] ***************************************************************************************************************************************************************************
    changed: [192.168.1.158]
    
    TASK [test2] ***************************************************************************************************************************************************************************
    changed: [192.168.1.158]
    
    RUNNING HANDLER [handlers1] ************************************************************************************************************************************************************
    changed: [192.168.1.158]
    
    RUNNING HANDLER [handlers2] ************************************************************************************************************************************************************
    changed: [192.168.1.158]
    
    TASK [test3] ***************************************************************************************************************************************************************************
    changed: [192.168.1.158]
    
    TASK [test4] ***************************************************************************************************************************************************************************
    changed: [192.168.1.158]
    
    RUNNING HANDLER [handlers3] ************************************************************************************************************************************************************
    changed: [192.168.1.158]
    
    RUNNING HANDLER [handlers4] ************************************************************************************************************************************************************
    changed: [192.168.1.158]
    
    PLAY RECAP *****************************************************************************************************************************************************************************
    192.168.1.158              : ok=10   changed=9    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
    
    
    3、结果
    (base) [root@hdp1 ~]# ansible 192.168.1.158 -m shell -a 'cat /tmp/1'
    192.168.1.158 | CHANGED | rc=0 >>
    
    1 shell 
    2 shell 
    1 handlers 
    2 handlers 
    3 shell 
    4 shell   end
    3 handlers 
    4 handlers 
    

      

    task中如何一次性调用多个handler,使用 listen,通过把handler分组实现

    1、handlers添加listen,演示触发listen  实现一个notify触发多个handler
    (base) [root@hdp1 ~]# cat listen.yaml
    ---
    - hosts: 192.168.1.158 
      tasks:
        - name: touch file 1
          shell: echo "" > /tmp/1
     
        - name: test1
          shell: echo "1 shell " >> /tmp/1
          notify: handlers2
          tags: tagshell1
    
        - name: test2
          shell: echo "2 shell " >> /tmp/1
          notify: handler group 
          tags: tagshell2
     
        - meta: flush_handlers
     
        - name: test3
          shell: echo "3 shell " >> /tmp/1
          notify: handlers3
          tags: tagshell3
     
        - name: test4
          shell: echo "4 shell   end" >> /tmp/1
          tags: tagshell4
     
      handlers:
        - name: handlers1
          listen: handler group
          shell: echo "1 handlers ,group" >> /tmp/1
        - name: handlers2
          listen: handler group
          shell: echo "2 handlers ,group" >> /tmp/1
    
        - name: handlers3
          shell: echo "3 handlers " >> /tmp/1
    
        - name: handlergrop
          listen: handler group
          shell: echo "handlergrop ,group" >> /tmp/1
    
    
    
    2、执行
    (base) [root@hdp1 ~]# ansible-playbook listen.yaml
    
    PLAY [192.168.1.158] *******************************************************************************************************************************************************************
    
    TASK [Gathering Facts] *****************************************************************************************************************************************************************
    ok: [192.168.1.158]
    
    TASK [touch file 1] ********************************************************************************************************************************************************************
    changed: [192.168.1.158]
    
    TASK [test1] ***************************************************************************************************************************************************************************
    changed: [192.168.1.158]
    
    TASK [test2] ***************************************************************************************************************************************************************************
    changed: [192.168.1.158]
    
    RUNNING HANDLER [handlers1] ************************************************************************************************************************************************************
    changed: [192.168.1.158]
    
    RUNNING HANDLER [handlers2] ************************************************************************************************************************************************************
    changed: [192.168.1.158]
    
    RUNNING HANDLER [handlergrop] **********************************************************************************************************************************************************
    changed: [192.168.1.158]
    
    TASK [test3] ***************************************************************************************************************************************************************************
    changed: [192.168.1.158]
    
    TASK [test4] ***************************************************************************************************************************************************************************
    changed: [192.168.1.158]
    
    RUNNING HANDLER [handlers3] ************************************************************************************************************************************************************
    changed: [192.168.1.158]
    
    PLAY RECAP *****************************************************************************************************************************************************************************
    192.168.1.158              : ok=10   changed=9    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
    
    
    
    3、结果
    (base) [root@hdp1 ~]# ansible 192.168.1.158 -m shell -a 'cat /tmp/1'
    192.168.1.158 | CHANGED | rc=0 >>
    
    1 shell 
    2 shell 
    1 handlers ,group
    2 handlers ,group
    handlergrop ,group
    3 shell 
    4 shell   end
    3 handlers 
    

      

    多次执行 同一个notify,只会触发一次,

    需要每次都触发就得每次都加  - meta: flush_handlers

    1、test2也执行test1的同一个handlers1
    (base) [root@hdp1 ~]# cat notify.yaml
    ---
    - hosts: 192.168.1.158 
      tasks:
        - name: touch file 1
          shell: echo "" > /tmp/1
     
        - name: test1
          shell: echo "1 shell " >> /tmp/1
          notify: handlers1
          tags: tagshell1
    
        - name: test2
          shell: echo "2 shell " >> /tmp/1
          notify: handlers1
          tags: tagshell2
     
        - meta: flush_handlers
     
        - name: test3
          shell: echo "3 shell " >> /tmp/1
          notify: handlers3
          tags: tagshell3
     
        - name: test4
          shell: echo "4 shell   end" >> /tmp/1
          tags: tagshell4
     
      handlers:
        - name: handlers1
          listen: handler group
          shell: echo "1 handlers ,group" >> /tmp/1
        - name: handlers2
          listen: handler group
          shell: echo "2 handlers ,group" >> /tmp/1
    
        - name: handlers3
          shell: echo "3 handlers " >> /tmp/1
    
        - name: handlergrop
          listen: handler group
          shell: echo "handlergrop ,group" >> /tmp/1
    
    2、执行
    
    (base) [root@hdp1 ~]# ansible-playbook notify.yaml
    
    PLAY [192.168.1.158] *********************************************************************************************************
    
    TASK [Gathering Facts] *******************************************************************************************************
    ok: [192.168.1.158]
    
    TASK [touch file 1] **********************************************************************************************************
    changed: [192.168.1.158]
    
    TASK [test1] *****************************************************************************************************************
    changed: [192.168.1.158]
    
    TASK [test2] *****************************************************************************************************************
    changed: [192.168.1.158]
    
    RUNNING HANDLER [handlers1] **************************************************************************************************
    changed: [192.168.1.158]
    
    TASK [test3] *****************************************************************************************************************
    changed: [192.168.1.158]
    
    TASK [test4] *****************************************************************************************************************
    changed: [192.168.1.158]
    
    RUNNING HANDLER [handlers3] **************************************************************************************************
    changed: [192.168.1.158]
    
    PLAY RECAP *******************************************************************************************************************
    192.168.1.158              : ok=8    changed=7    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
    
    3、结果
    (base) [root@hdp1 ~]# ansible 192.168.1.158 -m shell -a 'cat /tmp/1'
    192.168.1.158 | CHANGED | rc=0 >>
    
    1 shell 
    2 shell 
    1 handlers ,group
    3 shell 
    4 shell   end
    3 handlers 
    

      

    多次 - meta: flush_handlers

    1、多个    - meta: flush_handlers
    (base) [root@hdp1 ~]# vi  notify.yaml
    
    ---
    - hosts: 192.168.1.158
      tasks:
        - name: touch file 1
          shell: echo "" > /tmp/1
    
        - name: test1
          shell: echo "1 shell " >> /tmp/1
          notify: handlers1
          tags: tagshell1
    
        - meta: flush_handlers
    
        - name: test2
          shell: echo "2 shell " >> /tmp/1
          notify: handlers1
          tags: tagshell2
    
        - meta: flush_handlers
    
        - name: test3
          shell: echo "3 shell " >> /tmp/1
          notify: handlers3
          tags: tagshell3
    
        - name: test4
          shell: echo "4 shell   end" >> /tmp/1
          tags: tagshell4
    
      handlers:
        - name: handlers1
          listen: handler group
          shell: echo "1 handlers ,group" >> /tmp/1
        - name: handlers2
          listen: handler group
          shell: echo "2 handlers ,group" >> /tmp/1
    
        - name: handlers3
          shell: echo "3 handlers " >> /tmp/1
    
        - name: handlergrop
          listen: handler group
          shell: echo "handlergrop ,group" >> /tmp/1
    
    
    2、执行
    (base) [root@hdp1 ~]# ansible-playbook notify.yaml
    
    PLAY [192.168.1.158] *******************************************************************************************************************************************************************
    
    TASK [Gathering Facts] *****************************************************************************************************************************************************************
    ok: [192.168.1.158]
    
    TASK [touch file 1] ********************************************************************************************************************************************************************
    changed: [192.168.1.158]
    
    TASK [test1] ***************************************************************************************************************************************************************************
    changed: [192.168.1.158]
    
    RUNNING HANDLER [handlers1] ************************************************************************************************************************************************************
    changed: [192.168.1.158]
    
    TASK [test2] ***************************************************************************************************************************************************************************
    changed: [192.168.1.158]
    
    RUNNING HANDLER [handlers1] ************************************************************************************************************************************************************
    changed: [192.168.1.158]
    
    TASK [test3] ***************************************************************************************************************************************************************************
    changed: [192.168.1.158]
    
    TASK [test4] ***************************************************************************************************************************************************************************
    changed: [192.168.1.158]
    
    RUNNING HANDLER [handlers3] ************************************************************************************************************************************************************
    changed: [192.168.1.158]
    
    PLAY RECAP *****************************************************************************************************************************************************************************
    192.168.1.158              : ok=9    changed=8    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
    
    3、结果
    (base) [root@hdp1 ~]# ansible 192.168.1.158 -m shell -a 'cat /tmp/1'
    192.168.1.158 | CHANGED | rc=0 >>
    
    1 shell 
    1 handlers ,group
    2 shell 
    1 handlers ,group
    3 shell 
    4 shell   end
    3 handlers 
    

    --list-hosts

    --list-tasks

    --list-tags

    (base) [root@hdp1 ~]# ansible-playbook listen.yaml --list-hosts
    
    playbook: listen.yaml
    
      play #1 (192.168.1.158): 192.168.1.158        TAGS: []
        pattern: [u'192.168.1.158']
        hosts (1):
          192.168.1.158
    
    
    
    
    
    (base) [root@hdp1 ~]# ansible-playbook listen.yaml --list-tasks
    
    playbook: listen.yaml
    
      play #1 (192.168.1.158): 192.168.1.158        TAGS: []
        tasks:
          touch file 1      TAGS: []
          test1     TAGS: [tagshell1]
          test2     TAGS: [tagshell2]
          test3     TAGS: [tagshell3]
          test4     TAGS: [tagshell4]
    
    
    
    
    
    (base) [root@hdp1 ~]# ansible-playbook listen.yaml --list-tags
    
    playbook: listen.yaml
    
      play #1 (192.168.1.158): 192.168.1.158        TAGS: []
          TASK TAGS: [tagshell1, tagshell2, tagshell3, tagshell4]
    

    TAGS

    (base) [root@hdp1 ~]# ansible-playbook notify.yaml  -t tagshell1
    
    PLAY [192.168.1.158] *******************************************************************************************************************************************************************
    
    TASK [Gathering Facts] *****************************************************************************************************************************************************************
    ok: [192.168.1.158]
    
    TASK [test1] ***************************************************************************************************************************************************************************
    changed: [192.168.1.158]
    
    RUNNING HANDLER [handlers1] ************************************************************************************************************************************************************
    changed: [192.168.1.158]
    
    PLAY RECAP *****************************************************************************************************************************************************************************
    192.168.1.158              : ok=3    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
    
    
    
    (base) [root@hdp1 ~]# ansible 192.168.1.158 -m shell -a 'cat /tmp/1'
    192.168.1.158 | CHANGED | rc=0 >>
    
    1 shell 
    1 handlers ,group
    2 shell 
    1 handlers ,group
    3 shell 
    4 shell   end
    3 handlers 
    1 shell 
    1 handlers ,group
    

      

     

    ansible常用模块

    ansible中的模块和模块内置命令

    ansible-copy模块详解

    【网络】[::]:80是什么意思 / [::]是什么意思

  • 相关阅读:
    spring cloud配置中心
    网关中自定义登陆验证过滤器
    spring cloud网关
    Hystrix断路器 熔断器Hystrix的在Fegin的集成
    Hystrix断路器 熔断器Hystrix的在Ribbon的集成
    负载均衡二Feign
    Eureka负载均衡Ribbon
    Eureka高可用注册中心(解决单点故障)
    Eureka多服务调用
    input错误提示,点击提交,提示有未填项,屏幕滑到input未填项的位置
  • 原文地址:https://www.cnblogs.com/hanxing/p/16340852.html
Copyright © 2020-2023  润新知