zoukankan      html  css  js  c++  java
  • ansible使用1

    常用软件安装及使用目录   ansible软件2

    ### ansible软件部署安装需求####

    01. 需要有epel

        系统yum源(base epel--pip gem

        sshpass---epel

    02. ssh+key免密码环境必须部署完成

    ### ansible常用模块总结

    01. ping---ansible测试模块

        ansible 172.16.1.41 -m ping

        172.16.1.41 | SUCCESS => {

        "changed": false,

        "ping": "pong"

        }

        说明:ansible连接测试成功结果

        ansible 172.16.1.31 -m ping

        172.16.1.31 | UNREACHABLE! => {

        "changed": false,

        "msg": "Failed to connect to the host via ssh: Permission denied (publickey,password). ",

        "unreachable": true

        }

        说明:ansible连接测试不成功结果

        

    02. command-ansible远程执行命令模块

        a 命令模块中的多个参数设置用空格进行分割

        b 命令模块中不能出现 "<", ">", "|", ";" and "&"

        ## chdir    在执行命令之前,通过cd命令进入到指定目录中

        ansible oldboy -m command -a "chdir=/tmp pwd"

        172.16.1.31 | SUCCESS | rc=0 >>

        /tmp

        

        ## creates   定义一个文件是否存在,如果不存在运行相应命令;如果存在跳过此步骤

        ansible oldboy -m command -a "pwd creats=/tmp/oldboy_file"

        172.16.1.31 | SUCCESS | rc=0 >>

        skipped, since /tmp/oldboy_file exists

        172.16.1.8 | SUCCESS | rc=0 >>

        /root

        

        ## removes   定义一个文件是否存在,如果存在运行相应命令;如果不存在跳过此步骤

        

        

    03. shell-ansible远程节点执行命令(万能模块)

        ansible oldboy -m shell -a "pwd;ifconfig eth0"

        说明:shell模块在远程执行脚本时,远程主机上一定要有相应的脚本

        

        ansible oldboy -m shell -a "/server/scripts/hostname.sh"

        172.16.1.8 | SUCCESS | rc=0 >>

        web01

    04. script-在本地执行脚本时,将脚本中的内容传输到远程节点上运行

        ansible oldboy -m script -a "/server/scripts/free.sh"

        172.16.1.8 | SUCCESS => {

        "changed": true,

        "rc": 0,

        "stderr": "Shared connection to 172.16.1.8 closed. ",

        "stdout": "             total       used       free     shared    buffers     cached Mem:          980M       362M       617M       556K        32M       222M -/+ buffers/cache:       107M       873M Swap:         767M         0B       767M ",

        "stdout_lines": [

            "             total       used       free     shared    buffers     cached",

            "Mem:          980M       362M       617M       556K        32M       222M",

            "-/+ buffers/cache:       107M       873M",

            "Swap:         767M         0B       767M"

        ]

        }  

        说明:不用讲脚本传输到远程节点上,脚本本身不用进行授权,即可利用script模块批量执行脚本

        

    05. copy---将本地数据传输到远端,或者将远程节点上数据进行移动

        src           --- 指定本地要传输复制的数据信息

        remote_src    --- 如果这个值设置为True,将到远程/目标主机的机器上搜索

        dest          --- 将数据复制到目标路径信息(远程主机)

        owner         --- 设置复制传输后的数据属主信息

        group         --- 设置复制传输后的数据属组信息

        mode          --- 设置文件数据权限信息

        backup        --- 对文件进行覆盖前备份

        content       --- 替代src,定义文件中的内容

        force         --- 默认为yes,当远程文件内容和源文件内容不同时,将覆盖目标文件

                          如果为no,文件将只被传输,在目标主机不存在此文件时;以免原文件被覆盖

                          别名:thirsty

          

        管理主机数据---远程主机

        ansible oldboy -m copy -a "src=/server/scripts/hostname.sh dest=/server/scripts mode=ugo+x"

    172.16.1.31 | SUCCESS => {

        "changed": true,

        "checksum": "4c668aeb503bd26f5cb1f2d8dae6685c8d3f6a92",

        "dest": "/server/scripts/hostname.sh",

        "gid": 0,

        "group": "root",

        "mode": "0755",

        "owner": "root",

        "path": "/server/scripts/hostname.sh",

        "size": 308,

        "state": "file",

        "uid": 0

    }

        远程主机数据进行移动

    # ansible oldboy -m copy -a "remote_src=true src=/server/scripts/hostname.sh dest=/tmp"

    172.16.1.41 | SUCCESS => {

        "changed": true,

        "checksum": "4c668aeb503bd26f5cb1f2d8dae6685c8d3f6a92",

        "dest": "/tmp/hostname.sh",

        "gid": 0,

        "group": "root",

        "md5sum": "d5e56e25b2140657cbc5279325873494",

        "mode": "0644",

        "owner": "root",

        "size": 308,

        "src": "/server/scripts/hostname.sh",

        "state": "file",

        "uid": 0

    }

        定义创建的文件内容

    ansible oldboy -m copy -a "content=oldboyedu.com dest=/tmp/oldboy666.txt"

    172.16.1.41 | SUCCESS => {

        "changed": true,

        "checksum": "291694840cd9f9c464263ea9b13421d8e74b7d00",

        "dest": "/tmp/oldboy666.txt",

        "gid": 0,

        "group": "root",

        "md5sum": "0a6bb40847793839366d0ac014616d69",

        "mode": "0644",

        "owner": "root",

        "size": 13,

        "src": "/root/.ansible/tmp/ansible-tmp-1508465581.84-1077420994316/source",

        "state": "file",

        "uid": 0

    }

        copy命令创建多级目录

        ansible oldboy -m copy -a "src=/etc/hosts dest=/tmp/a/b/c/d/"

    06. file---设置文件属性

        owner         --- 设置复制传输后的数据属主信息

        group         --- 设置复制传输后的数据属组信息

        mode          --- 设置文件数据权限信息

        dest          --- 要创建的文件或目录命令,以及路径信息

        state         --- 如果指定参数为directory 创建目录;所有不存在的子目录将会被创建,并且从1.7开始支持设置目录权限

                          如果指定参数为file      创建文件;如果文件不存在将不能被创建,如果想创建可以参考copytemplate模块

                          如果指定参数为link      创建软链接; 符号链接将被创建或更改。

                          如果指定参数为hard      便会创建出硬链接

                          如果指定参数为absent    目录将被递归删除以及文件,而链接将被取消链接。

                                                  请注意,定义文件不存在不会失败,只是输出没有发生任何改变的结果

                          如果指定参数为touch     如果路径不存在将创建一个空文件,如果文件或目录存在将接收更新的文件访问和修改时间

                                                 (类似于touch”从命令行工作的方式)

        src           --- 指定要创建软链接的文件信息

        创建目录:

        ansible oldboy -m file -a "dest=/tmp/oldboy_dir state=directory"

    172.16.1.8 | SUCCESS => {

        "changed": true,

        "gid": 0,

        "group": "root",

        "mode": "0755",

        "owner": "root",

        "path": "/tmp/oldboy_dir",

        "size": 4096,

        "state": "directory",

        "uid": 0

    }

        创建多级目录:

    # ansible oldboy -m file -a "dest=/tmp/oldboy_dir/01/02/03 state=directory"

    172.16.1.8 | SUCCESS => {

        "changed": true,

        "gid": 0,

        "group": "root",

        "mode": "0755",

        "owner": "root",

        "path": "/tmp/oldboy_dir/01/02/03",

        "size": 4096,

        "state": "directory",

        "uid": 0

    }

        创建文件:

        ansible oldboy -m file -a "dest=/tmp/oldboy_file state=touch"

    172.16.1.8 | SUCCESS => {

        "changed": true,

        "dest": "/tmp/oldboy_file",

        "gid": 0,

        "group": "root",

        "mode": "0644",

        "owner": "root",

        "size": 0,

        "state": "file",

        "uid": 0

    }

        创建软链接;

        ansible oldboy -m file -a "src=/tmp/oldboy_file dest=/tmp/oldboy_file_link state=link"

    172.16.1.8 | SUCCESS => {

        "changed": true,

        "dest": "/tmp/oldboy_file_link",

        "gid": 0,

        "group": "root",

        "mode": "0777",

        "owner": "root",

        "size": 16,

        "src": "/tmp/oldboy_file",

        "state": "link",

        "uid": 0

    }

        删除目录 文件信息

        [root@m01 scripts]# ansible oldboy -m file -a "dest=/tmp/oldboy_dir state=absent"

    172.16.1.8 | SUCCESS => {

        "changed": true,

        "path": "/tmp/oldboy_dir",

        "state": "absent"

    }

    }

        [root@m01 scripts]# ansible oldboy -m file -a "dest=/tmp/oldboy_file state=absent"

    172.16.1.31 | SUCCESS => {

        "changed": true,

        "path": "/tmp/oldboy_file",

        "state": "absent"

    }

    07  fetch---将远程主机上的文件,拉取到本地主机

        dest     --- 将远程主机拉取过来的文件保存在本地的路径信息

        src      --- 指定从远程主机要拉取的文件信息

        flat     --- 默认设置为no,如果设置为yes,将不显示172.16.1.8/etc/信息

        

        从远程主机拉取文件

        ansible oldboy -m fetch -a "dest=/tmp  src=/etc/hosts"

    172.16.1.8 | SUCCESS => {

        "changed": true,

        "checksum": "bd9a0f82db17051a305f6a5974fa1fd95ead73d5",

        "dest": "/tmp/172.16.1.8/etc/hosts",

        "md5sum": "27b1ddf7c360698b439627b057f77d51",

        "remote_checksum": "bd9a0f82db17051a305f6a5974fa1fd95ead73d5",

        "remote_md5sum": null

    }

        flat参数实践

        ansible oldboy -m fetch -a "dest=/tmp/  src=/etc/hosts flat=yes"

    172.16.1.41 | SUCCESS => {

        "changed": true,

        "checksum": "bcb7c85bad6008ede9e73d18ae0bb78f2b11f612",

        "dest": "/tmp/hosts",

        "md5sum": "211bd00bf9ba8a735db1c7953d7cebc4",

        "remote_checksum": "bcb7c85bad6008ede9e73d18ae0bb78f2b11f612",

        "remote_md5sum": null

    }

    08. mount---控制激活和配置挂载点模块

        fstype    --- 指定挂载文件类型;-t nfs == fstype=nfs

        opts      --- 设定挂载的参数选项信息; -o ro == opts=ro

        path      --- 指定挂载点   path=/mnt

        src       --- 要被挂载的目录设备信息   src=172.16.1.31:/data/w

        state     --- # 如果为mountd

                      fstab文件中的设备将被激活挂载和适当配置

                      # 如果为unmounted

                      设备将被卸载并不会改变fstab文件信息

                      absentpresent只处理fstab,但不影响目前的挂载

        

        进行挂载

        mount -t nfs -o ro  172.16.1.31:/data /mnt

        ansible oldboy -m mount -a “fstype=nfs opts=ro src=172.16.1.31:/data path=/mnt state=mounted”

    172.16.1.41 | SUCCESS => {

        "changed": true,

        "dump": "0",

        "fstab": "/etc/fstab",

        "fstype": "nfs",

        "name": "/mnt",

        "opts": "ro",

        "passno": "0",

        "src": "172.16.1.31:/data/w"

    }

        卸载操作

        ansible oldboy -m mount -a “fstype=nfs opts=ro src=172.16.1.31:/data path=/mnt state=unmounted”

        [root@m01 tmp]# ansible oldboy -m mount -a "fstype=nfs opts=ro src=172.16.1.31:/data path=/mnt state=unmounted"

        172.16.1.8 | SUCCESS => {

        "changed": false,

        "dump": "0",

        "fstab": "/etc/fstab",

        "fstype": "nfs",

        "name": "/mnt",

        "opts": "ro",

        "passno": "0",

        "src": "172.16.1.31:/data"

    }

        mounted

        01. 将挂载信息添加到/etc/fstab

        02. 加载/etc/fstab实现挂载

        unmounted

        01. 加载/etc/fstab实现卸载

        absent

        01. fstab文件中删除挂载配置

        present

        01. fstab文件中添加挂载配置

        

    09. cron--定时任务模块(Manage cron.d and crontab entries.)

        crontab -e

        0 0 * * *  /bin/sh /server/scripts/hostname.sh &>/dev/null

        minute                 # Minute when the job should run ( 0-59, *, */2, etc )

        hour                   # Hour when the job should run ( 0-23, *, */2, etc )

        day                    # Day of the month the job should run ( 1-31, *, */2, etc )

        month                  # Month of the year the job should run ( 1-12, *, */2, etc )

        weekday                # Day of the week that the job should run ( 0-6 for Sunday-Saturday, *, etc )

        name                   # 定义定时任务的描述信息

        disabled               # 注释定时任务

        state                  # absent删除定时任务;present创建定时任务(默认为present

        

        创建定时任务

        ansible oldboy -m  cron -a  "minute=0 hour=0 job='/bin/sh /server/scripts/hostname.sh &>/dev/null'"

    172.16.1.41 | SUCCESS => {

        "changed": true,

        "envs": [],

        "jobs": [

            "None"

        ]

    }

        ansible oldboy -m  cron -a  "name=oldboycron01 minute=0 hour=0 job='/bin/sh /server/scripts/hostname.sh &>/dev/null'"

        172.16.1.31 | SUCCESS => {

        "changed": true,

        "envs": [],

        "jobs": [

            "oldboycron01",

            "oldboycron02"

        ]

    }

        

        删除定时任务

        ansible oldboy -m  cron -a  "name=oldboycron01 minute=0 hour=0 job='/bin/sh /server/scripts/hostname.sh &>/dev/null' state=absent"

        ansible oldboy -m  cron -a  "name=oldboycron01 state=absent"

        注释定时任务

        # ansible oldboy -m  cron -a  "name=oldboycron02 job='/bin/sh /server/scripts/hostname.sh &>/dev/null' disabled=yes"

    172.16.1.31 | SUCCESS => {

        "changed": true,

        "envs": [],

        "jobs": [

            "oldboycron02"

        ]

    }

        # ansible oldboy -m  cron -a  "name=oldboycron02 job='/bin/sh /server/scripts/hostname.sh &>/dev/null' disabled=no"

    10  yum---安装软件模块

        ansible oldboy -m yum -a "name=nmap state=installed"

        

    11  service---服务启动关闭管理模块

        ansible oldboy -m service -a "name= state=stopped enabled=yes"

        说明:设置服务状态信息为过去时;service管理的服务必须存在在/etc/init.d/下面有的服务脚本

        

       

    ### ansible在没有秘钥的时候如何批量管理 ####

    01. 编写hosts文件

        不基于ssh+key方式使用ansible

        ### ansible测试受控端连通性方法 ######

        [root@m01 ansible]# ansible 172.16.1.7 -m ping

        2.16.1.7 | UNREACHABLE! => {

        "changed": false,

        "msg": "Failed to connect to the host via ssh: Permission denied (publickey,password). ",

        "unreachable": true

        }

        

        # vim /etc/ansible/hosts

        172.16.1.7 ansible_ssh_user=root ansible_ssh_pass=123456

        [root@m01 ansible]# ansible 172.16.1.7 -m ping

        172.16.1.7 | SUCCESS => {

        "changed": false,

        "ping": "pong"

        }

        

        # 不在hosts文件写入密码实现ansible远程管理

        [root@m01 ansible]# ansible -k 172.16.1.7 -m ping

        SSH password:

        172.16.1.7 | SUCCESS => {

        "changed": false,

        "ping": "pong"

        }

        

    02. 未分发公钥如何实现远程管理主机

        vim /etc/ansible/hosts

        [oldboy]

        172.16.1.31 ansible_ssh_user=root ansible_ssh_pass=123456                                                         

        172.16.1.41:52113

        172.16.1.8

        

    ###### shell模块说明

    [root@m01 ssh]# ansible 172.16.1.31 -m command -a "free -m >/tmp/free.txt"

    172.16.1.31 | SUCCESS | rc=0 >>

                 total       used       free     shared    buffers     cached

    Mem:          1990        348       1642          0         30        180

    -/+ buffers/cache:        138       1852

    Swap:          767          0        767

    [root@m01 ssh]# ansible 172.16.1.31 -m command -a "cat /tmp/free.txt"

    172.16.1.31 | FAILED | rc=1 >>

    cat: /tmp/free.txt: No such file or directory

    [root@m01 ssh]# ansible 172.16.1.31 -m shell -a "free -m >/tmp/free.txt"

    172.16.1.31 | SUCCESS | rc=0 >>

    [root@m01 ssh]# ansible 172.16.1.31 -m command -a "cat /tmp/free.txt"

    172.16.1.31 | SUCCESS | rc=0 >>

                 total       used       free     shared    buffers     cached

    Mem:          1990        348       1642          0         30        180

    -/+ buffers/cache:        138       1852

    Swap:          767          0        767

    ########shell模块和command模块功能类似,但是shell模块可以识别一些特殊符号信息 > >> | * ^    

        

    ########通过yum模块安装nmap软件:#############

    ansible oldboy -m yum -a "name=nmap state=installed"

    ########通过service模块管理软件服务:

    ansible oldboy -m service -a "name=crond state=stop enabled=no"

    ########通过file模块设置文件属性信息:

    ansible oldboy -m file -a "src=/etc/hosts dest=/tmp/hosts state=link own=oldboy mode=0600"

    说明:表示批量创建软件

    ##### expect软件介绍 ###

    ssh 连接时

    在文件中定义好:

    yes/no yes

    password 123456

    04: ansible基础知识部分补充

        1ansible软件特点:

        · 可以实现批量管理

    · 可以实现批量部署

    · ad-hoc(批量执行命令)---针对临时性的操作

      ansible oldboy -m command -a "hostname"   <- 批量执行命令举例

    · 编写剧本-脚本(playbook)---针对重复性的操作

        2ansible核心功能:

            · pyYAML-----用于ansible编写剧本所使用的语言格式(saltstack---python

            · paramiko---远程连接与数据传输

    · Jinja2-----用于编写ansible的模板信息

        ======================================================================================

    扩展说明:jinja2模板作用:

       for循环语句jinja模板】

        为远程主机生成服务器列表,加入该列表info192.168.13.201 web01.test.com 192.168.13.211 web11.test.com 结束,

    如果手动添加就很不科学了,这里需要使用jinja2语法的for循环通过模板批量生成对应的配置文件,如下:

        ansible目录结构:

        #cd /etc/ansible/roles/test_hosts

        .

        ├── meta

        │   └── main.yml

        ├── tasks

        │   ├── file1.yml

        │   └── main.yml

        ├── templates

        │   └── test1.j2

        └── vars

            └── main.yml

        各个目录下yml文件内容:

        # cat tasks/main.yml

        - include: file1.yml

        # cat tasks/file1.yml

        - name: ansible jinja2 template for hosts config

          template: src=test1.j2 dest=/etc/httpd/conf/httpd.conf.test

        # cat templates/test1.j2

          {% for id in range(201,211) %}

          192.168.13.{{ id }} web{{ "%02d" |format(id-200) }}.test.com

          {% endfor %}

          解释:

          {{ id }} 提取for循环中对应的变量id

          "%02d"   调用的是python内置的字符串格式化输出(%d格式化整数)因为是01,02这种格式,所以是保留2位,故用02

          然后将结果通过管道符|” 传递给format 函数做二次处理。

          执行结果:

          #cat httpd.conf.test

          192.168.13.201 web01.test.com

          192.168.13.202 web02.test.com

          192.168.13.203 web03.test.com

          192.168.13.204 web04.test.com

          192.168.13.205 web05.test.com

          192.168.13.206 web06.test.com

          192.168.13.207 web07.test.com

          192.168.13.208 web08.test.com

          192.168.13.209 web09.test.com

          192.168.13.210 web10.test.com

          192.168.13.211 web11.test.com

    参考资料:http://linuxg.blog.51cto.com/4410110/1788574

        ======================================================================================

      说明:很多ansible的报错都是和python有关,因为ansible的底层开发是利用python编写的

    05: ansible扩展模块功能介绍

        ①. ansible实现检查被管理服务器端网络连接是否通畅(检查道路是否通畅)

            # ansible oldboy -m command -a "hostname"    <-- 最开始检查道路是否通畅方法

            # ansible oldboy -m ping          <-- 专业检查道路是否通畅方法

            172.16.1.31 | SUCCESS => {

            "changed": false,

            "ping": "pong"

            }

            172.16.1.7 | SUCCESS => {

                "changed": false,

                "ping": "pong"

            }

            172.16.1.41 | SUCCESS => {

                "changed": false,

                "ping": "pong"

            }

    以上信息不清楚,可以通过利用ansible查看帮助信息方法获取新模块功能说明

    # ansible-doc -s ping

            - name: Try to connect to host, verify a usable python and return `pong' on success.

            action: ping

    说明:尝试连接到主机,验证网络连接是否通畅,如果通畅返回pong信息表示成功

          激活验证功能,利用ping模块

      

        ②. ansible实现定时任务功能执行相应的操作(定时任务)

            回顾传统的定时任务为:

            # crontab -l

            #time sync by oldboy at 2010-2-1

            */5 * * * * /usr/sbin/ntpdate time.nist.gov >/dev/null 2>&1

    说明:日期格式为 分钟:minute,小时:hour,日期:day,月:month,周:weekday  

          日期格式后面接需要执行的命令或脚本文件

        获取ansible定时任务模块说明信息:

    # ansible-doc -s cron

            - name: Manage cron.d and crontab entries.

            cron模块主要管理cron.dcrontab条目信息;即实现配置定时任务

              action: cron    激活定时任务功能,利用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). 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 )

                               运行job任务的日期时间信息(编写方式1-31*, */2, )

                  disabled               # If the job should be disabled (commented out) in the crontab. Only has effect if state=present

                               如果job应该关闭(被注释掉)。只能影响状态是开启状态的定时任务条目

                  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.

                                           如果设置,管理crontab的环境变量信息。新的环境变量信息会被增加到定时任务表顶部。描述或数值会被环境变得的名称或数值所定义

      hour                   # Hour when the job should run ( 0-23, *, */2, etc )

                               运行job任务的小时时间信息(编写方式0-23*, */2, )

                  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. Required if state=present.

                               执行相应的命令,如果env被设置,将作为环境变量的值,但前提是state=present

                  minute                 # Minute when the job should run ( 0-59, *, */2, etc )

                               运行job任务的分钟时间信息(编写方式0-59**/2,等等)

                  month                  # Month of the year the job should run ( 1-12, *, */2, etc )

                               运行job任务的月份时间信息(编写方式1-12*, */2, )

                  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.

       定时任务条目的描述信息;如果env被设定了,描述信息将为环境变量信息。前提是定时任务状态为关闭状态

       注意:如果名称没有被指定并且定时任务状态为开启,那么新的定时任务将总被创建,不管这个定时任务是否存在

                  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.

                               确认job或环境变量是开启或是关闭

                  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 )

                               job任务应该在一周的哪天进行运行(编写方式0-6表示周日到周六,以及用*符号等)

             

            # ansible 172.16.1.7 -a "crontab -l"                  <- 查看当前被管理服务器定时任务文件信息

              172.16.1.7 | SUCCESS | rc=0 >>

              #crond-id-001:time sync by hq

              */5 * * * * /usr/sbin/ntpdate time.nist.gov >/dev/null 2>&1

            

    参考下面编写的定时任务条目,进行编写ansible定时任务命令

    # restart network

    00 00 * * * /etc/init.d/network restart >/dev/null 2>&1

    # ansible 172.16.1.7 -m cron -a "minute=00 hour=00 job='/usr/sbin/ntpdate time.nist.gov >/dev/null 2>&1'"

              172.16.1.7 | SUCCESS => {

                  "changed": true,

                  "envs": [],

                  "jobs": [

                      "None"

                  ]

              }

            # ansible 172.16.1.7 -a "crontab -l"

              172.16.1.7 | SUCCESS | rc=0 >>

              #Ansible: None

              00 00 * * * /usr/sbin/ntpdate time.nist.gov >/dev/null 2>&1

    如果没有定义定时任务描述信息,每次执行ansible创建定时任务,都会被反复创建

    # ansible 172.16.1.7 -m cron -a "name='restart network' minute=00 hour=00 job='/usr/sbin/ntpdate time.nist.gov >/dev/null 2>&1'"

              172.16.1.7 | SUCCESS => {

                  "changed": true,

                  "envs": [],

                  "jobs": [

                      "None",

                      "restart network"

                  ]

              }

            # ansible 172.16.1.7 -a "crontab -l"

              172.16.1.7 | SUCCESS | rc=0 >>

              #Ansible: None

              00 00 * * * /usr/sbin/ntpdate time.nist.gov >/dev/null 2>&1

              #Ansible: restart network

              00 00 * * * /usr/sbin/ntpdate time.nist.gov >/dev/null 2>&1

      

    利用ansible的模拟检查参数-C,实现模拟检查ansible命令语法格式是否正确,但命令并不会执行产生效果   

    # ansible 172.16.1.7 -C -m cron -a "name='restart network' minute=00 hour=00 job='/usr/sbin/ntpdate time.nist.gov >/dev/null 2>&1'"

              172.16.1.7 | SUCCESS => {

                  "changed": false,

                  "envs": [],

                  "jobs": [

                      "None",

                      "restart network"

                  ]

              }

    删除无用的定时任务信息

            # ansible 172.16.1.7 -C -m cron -a "name='None' minute=00 hour=00 job='/usr/sbin/ntpdate time.nist.gov >/dev/null 2>&1' state=absent"  <- 先进行测试,测试成功后再进行删除

        # ansible 172.16.1.7  -m cron -a "name='None' minute=00 hour=00 job='/usr/sbin/ntpdate time.nist.gov >/dev/null 2>&1' state=absent"

              172.16.1.7 | SUCCESS => {

                  "changed": true,

                  "envs": [],

                  "jobs": [

                      "restart network"

                  ]

              }

            # ansible 172.16.1.7  -m cron -a "name='None' state=absent"   <- 指定当前任务名称,即可进行删除操作

    临时关闭与开启指定定时任务效果,但不删除定时任务条目

            # ansible 172.16.1.7 -m cron -a "name='restart network' minute=00 hour=00 job='/usr/sbin/ntpdate time.nist.gov >/dev/null 2>&1' disabled=yes"

              172.16.1.7 | SUCCESS => {

                  "changed": true,

                  "envs": [],

                  "jobs": [

                      "restart network"

                  ]

              }

              [root@m01 ~]# ansible 172.16.1.7 -a "crontab -l"

              172.16.1.7 | SUCCESS | rc=0 >>

              #Ansible: restart network

              #00 00 * * * /usr/sbin/ntpdate time.nist.gov >/dev/null 2>&1

              

    # ansible 172.16.1.7 -m cron -a "name='restart network' minute=00 hour=00 job='/usr/sbin/ntpdate time.nist.gov >/dev/null 2>&1' disabled=no"

              172.16.1.7 | SUCCESS => {

                  "changed": true,

                  "envs": [],

                  "jobs": [

                      "restart network"

                  ]

              }

              [root@m01 ~]# ansible 172.16.1.7 -a "crontab -l"

              172.16.1.7 | SUCCESS | rc=0 >>

              #Ansible: restart network

              00 00 * * * /usr/sbin/ntpdate time.nist.gov >/dev/null 2>&1

              

              

              cron模块总结:

              01:对定时任务的状态进行注释时,-a后面信息,一定要包含定时任务的name信息以及job信息

              02:如果没有定义定时任务描述信息,每次执行ansible创建定时任务,都会被反复创建

              03:利用ansible的模拟检查参数-C,实现模拟检查ansible命令语法格式是否正确,但命令并不会执行产生效果

              04:指定当前任务名称,即可进行删除操作

              

    06: ansible重要模块功能总结

        command (重要模块) 执行命令模块,ansible命令执行默认模块

        shell (重要模块) 执行shell脚本模块

        script (重要模块) 把脚本发到客户端,然后执行;执行脚本命令在远端服务器上

        copy (重要模块) 把本地文件发送到远端

        

        

    ansible学精通:--- saltstack

    01. 模块

    02. 剧本

    03. 开发python(自定义编写模块)

    模块==命令 ansible执行命令

    剧本==脚本

    04: ansible基础知识部分补充

        1ansible软件特点:

        · 可以实现批量管理

    · 可以实现批量部署

    · ad-hoc(批量执行命令)---针对临时性的操作

      ansible oldboy -m command -a "hostname"   <- 批量执行命令举例

    · 编写剧本-脚本(playbook)---针对重复性的操作

            

            帮助方法:

            ansible-doc -l

            ansible-doc -s 模块名称

            

        2ansible核心功能:

            · pyYAML-----用于ansible编写剧本所使用的语言格式(saltstack---python)  rsync-ini语法  sersync-xml ansible-pyYAML

            · paramiko---远程连接与数据传输

    · Jinja2-----用于编写ansible的模板信息  

            

            172.16.1.1--100=IP

            PATH        

           

    07: ansible剧本编写规则说明

        pyYAML语法规则:

    规则一:缩进

        yaml使用一个固定的缩进风格表示数据层结构关系,Saltstack需要每个缩进级别由两个空格组成。一定不能使用tab

        注意:编写yaml文件,就忘记键盘有tab

            

        规则二:冒号

        CMD="echo"

        yaml:

        mykey:

        每个冒号后面一定要有一个空格(以冒号结尾不需要空格,表示文件路径的模版可以不需要空格)

        

        规则三:短横线

        想要表示列表项,使用一个短横杠加一个空格。多个项使用同样的缩进级别作为同一个列表的一部分

        核心规则:有效的利用空格进行剧本的编写,剧本编写是不支持tab

        ---

        ### 剧本的开头,可以不写

        - hosts: all         <- 处理所有服务器,找到所有服务器;  -(空格)hosts:(空格)all

          tasks:             <- 剧本所要干的事情;                (空格)(空格)task:

            - command: echo hello oldboy linux.                  (空格)(空格)空格)(空格)-(空格)模块名称:(空格)模块中对应的功能

          

          ansible all -m command -a "echo hello oldboy linux"      

            

            

        剧本编写内容扩展:剧本任务定义名称

    - hosts: 172.16.1.7  <- 处理指定服务器                   -(空格)hosts:(空格)all

      task:                <- 剧本所要干的事情;                (空格)(空格)task:

        - name:

              command: echo hello oldboy linux.                  (空格)(空格)空格)(空格)-(空格)模块名称:(空格)模块中对应的功能

        剧本编写内容扩展:剧本任务编写定时任务

    # ansible all -m cron -a "name='restart network' minute=00 hour=00 job='/usr/sbin/ntpdate time.nist.gov >/dev/null 2>&1'"

    - hosts: all

          tasks:

            - name: restart-network

              cron: name='restart network' minute=00 hour=00 job='/usr/sbin/ntpdate time.nist.gov >/dev/null 2>&1'

        # ansible-playbook -C /etc/ansible/network-restart.yml  -vvvx

    说明:测试剧本命令后面可以跟多个-v进行调试检查

        

        

        剧本编写后检查方法:

        01ansible-playbook --syntax-check 01.yml   --- 进行剧本配置信息语法检查

        02ansible-playbook -C 01.yml               --- 模拟剧本执行(彩排)

        

    剧本编写内容扩展:剧本任务编写多个任务

    - hosts: all

          tasks:

            - name: restart-network

              cron: name='restart network' minute=00 hour=00 job='/usr/sbin/ntpdate time.nist.gov >/dev/null 2>&1'

            - name: sync time

              cron: name='sync time' minute=*/5 job="/usr/sbin/ntpdate pool.ntp.com >/dev/null 2>&1"

    剧本编写内容扩展:剧本任务编写多个主机

    - hosts: 172.16.1.7

          tasks:

            - name: restart-network

              cron: name='restart network' minute=00 hour=00 job='/usr/sbin/ntpdate time.nist.gov >/dev/null 2>&1'

            - name: sync time

              cron: name='sync time' minute=*/5 job="/usr/sbin/ntpdate pool.ntp.com >/dev/null 2>&1"

    - hosts: 172.16.1.31

          tasks:

            - name: show ip addr to file

              shell: echo $(hostname -i) >> /tmp/ip.txt

        **************************************************************************************

    扩展知识说明:vim编辑器使用说明

    01:复制当前行到最后一行的内容,然后粘贴到最后一行的后面

        :/172.16.1.31/,$copy$

    :.,$copy$

    **************************************************************************************

        剧本编写方式

        01 多主机单任务编写方式

        02 多主机多任务编写方式

        03 不同主机多任务编写方式

            

    08: ansible剧本编写总结说明

        找什么服务器,让服务器干写什么

    多使用检查命令-C

    利用ansible安装rsync服务器

    01. 重新克隆两台主机,一台作为rsync服务端 -台作为rsync客户端

    02. 利用ansible管理主机(编写剧本),部署rsync服务端,与rsync客户端

    03. rsync客户端主机不需分发公钥文件,实现ansible管理

    09:课后作业:

        ①. 请总结一下mount模块是否存在,mount模块如何使用

        ②. 利用ansible安装rsync服务器

        ③. 利用ansible安装nfs服务器

    . 利用ansible配置sersync数据同步

    附录01pssh命令使用扩展

    =========================================

    原文:http://liang3391.blog.51cto.com/178205/732100

    参考:http://www.ibm.com/developerworks/cn/aix/library/au-spunix_remoteserver/index.html

    01pssh命令使用场景说明

        假如同时给上千台服务器执行一个命令,拷贝一个文件,杀一个进程等,有什么简化运维管理的工具呢?

    在小型企业中通常使用for循环,但是数量巨大时:

    · 一方面不确定操作是否成功一方面不确定操作是否成功

    · 一方面for循环语句性能不好估计且是不是同步并行执行。

    因此需要使用批量并行执行的命令,这类工具比如 pdshmusshcsshdsh等还有下面说明提到的pssh

    02pssh软件安装部署方式

        ①. 通过yum安装pssh软件

        yum install -y pssh    <- pssh软件下载需要依靠epel

    说明:pssh是一个软件大礼包,里面有很多软件命令

    # rpm -ql pssh

            /usr/bin/pnuke

            /usr/bin/prsync

            /usr/bin/pscp.pssh

            /usr/bin/pslurp

            /usr/bin/pssh

    ....省略部分信息....

        ①. 通过编译方式安装pssh软件

            wget http://peak.telecommunity.com/dist/ez_setup.py

            python ez_setup.py

            wget http://parallel-ssh.googlecode.com/files/pssh-2.2.2.tar.gz

            tar zxvf pssh-2.2.2.tar.gz

            cd pssh-2.2.2

            python setup.py install

    03pssh软件使用操作说明(ssh key认证密钥配置完毕)

        pssh工具包主要有5个程序:

        ①. pssh  多主机并行运行命令

        [root@server pssh-2.2.2]# vim hosts_info.txt

            172.16.1.31:22

            172.16.1.41:22

            172.16.1.7:22             //注意我的端口号不仅是默认的22        

            [root@m01 tmp]# pssh -P -h /tmp/hosts_info.txt uptime

            172.16.1.31:  00:05:58 up 3 days, 18:34,  2 users,  load average: 0.00, 0.01, 0.05

            [1] 00:05:58 [SUCCESS] 172.16.1.31:22

            172.16.1.41:  00:05:58 up 9 days, 22:39,  2 users,  load average: 0.00, 0.01, 0.05

            [2] 00:05:58 [SUCCESS] 172.16.1.41:22

            172.16.1.7:  00:05:58 up 9 days, 22:39,  2 users,  load average: 0.00, 0.01, 0.05

            [3] 00:05:58 [SUCCESS] 172.16.1.41:22        

            说明:如果想将执行命令的批量输出信息重定向到一个文件 -o 目录 选项

                  -h HOST_FILE,  --hosts=HOST_FILE       hosts file (each line "[user@]host[:port]")

      -o OUTDIR,     --outdir=OUTDIR         output directory for stdout files (OPTIONAL)

      -P,            --print                 print output as we get it

        ②. pscp  把文件并行地复制到多个主机上

            注意 是从服务器端给客户端传送文件:

            [root@server pssh-2.2.2]# pscp -h test.txt /etc/sysconfig/network /tmp/network   

    //标示将本地的/etc/sysconfig/network传到目标服务器的/tmp/network

        ③. prsync 使用rsync协议从本地计算机同步到远程主机

            [root@server ~]# pssh -h test.txt -P mkdir /tmp/etc

            [root@server ~]# prsync -h test.txt -l dongwm -a -r /etc/sysconfig /tmp/etc

    //标示将本地的/etc/sysconfig目录递归同步到目标服务器的 /tmp/etc目录下,并保持原来的时间戳,使用用户 dongwm

        ④. pslurp 将文件从远程主机复制到本地,pscp方向相反:

            [root@server ~]# pslurp -h test.txt   -L /tmp/test -l root /tmp/network test  

    //标示将目标服务器的/tmp/network文件复制到本地的/tmp/test目录下,并更名为test

            [1] 14:53:54 [SUCCESS] 192.168.9.102 9922

            [2] 14:53:54 [SUCCESS] 192.168.9.104 9922

            [root@server ~]# ll /tmp/test/192.168.9.10

            192.168.9.102/ 192.168.9.104/

            [root@server ~]# ll /tmp/test/192.168.9.102/

            总计 4.0K

            -rw-r--r-- 1 root root 60 2011-04-22 14:53 test

            [root@server ~]# ll /tmp/test/192.168.9.104/

            总计 4.0K

            -rw-r--r-- 1 root root 60 2011-04-22 14:53 test

        ⑤. pnuke 并行在远程主机杀进程:

            [root@server ~]# pnuke -h test.txt  syslog

    //杀死目标服务器的syslog进程,只要ps进程中出现相关词语 都能杀死

            [1] 15:05:14 [SUCCESS] 192.168.9.102 9922

            [2] 15:05:14 [SUCCESS] 192.168.9.104 9922

    =========================================

    常见问题一:

    [root@m01 ~]# ansible  -k 172.16.1.51 -m ping  

    SSH password:

    [WARNING]: No hosts matched, nothing to do

    原因分析:

    ansiblehosts文件中,没有配置相应主机地址信息

            

    常见问题二:        

    # ansible -k 172.16.1.51 -m ping

    SSH password:

    172.16.1.51|FAILED! => {

    "failed": true,

    "msg": "Using a SSH password instead of a key is not possible because Host Key checking is enabled and sshpass does not support this.  Please add this host's fingerprint to your known_hosts file to manage this host."

    }

    原因分析:

    因为没有受控端的指纹信息,在known_hosts文件中

    command   --- 执行命令

    shell     --- 执行脚本 执行命令(万能模块 支持正则或特殊符号信息)

    script    --- 执行脚本

  • 相关阅读:
    解决WPF中异常导致的程序Crash
    Python---pep8规范
    Python---13面向对象编程
    Python---12函数式编程------12.3匿名函数&装饰器&偏函数
    Python---12函数式编程------12.2返回函数
    Python中*args和**kwargs的区别
    测试干货-接口测试(接口测试工具+接口测试用例)
    Python---13靠谱的Pycharm安装详细教程
    Python---12函数式编程------12.1高阶函数
    Python---11模块
  • 原文地址:https://www.cnblogs.com/machangwei-8/p/10409827.html
Copyright © 2011-2022 走看看