• Ansible自动化运维笔记2(Ansible的组件介绍)


    1.Ansible Inventory##

    (1)静态主机文件

    默认的ansible invetory是/etc/hosts文件,可以通过ANSIBLE_HOSTS环境变量或者通过运行命令的时候加上-i

    vim /tmp/hosts
    # 定义组
    [webservers]
    10.187.11.34
    10.187.137.191
    
    # 组变量
    [webservers:vars]
    ansible_ssh_pass = '123456'
    

    多个静态文件,可以写不同的文件里,文件名字hosts不是必须

    inventory可以指向一个目录,这样目录里面所有的文件都会被加载进来,可以通过--list-hosts()来验证

    [admin@host-10-187-196-225 hosts_file]$ ansible -i /tmp/hosts_file/ webservers --list-hosts
        10.187.109.116
        10.189.92.46
    

    (2)动态主机文件

    ansible.cfg配置文件中的inventory配置项指向一个脚本
    这个脚本有一定规范和参数要求
    1.支持--list或者-l,这个参数运行后会显示所有的主机以及主机组的信息(JSON格式)
    2.支持--host或者-H,这个参数后面需要指定一个host,运行结果会返回这台主机的所有信息(包括认证信息,主机变量等),也是json格式

    #!/usr/bin/env python
    # -*- coding=utf-8 -*-
    #########################
    import argparse
    import sys
    import json
    
    def lists():
        r = dict()
        h = ['172.17.42.10' + str(i) for i in range(1,4)]
        hosts = {'hosts':h}
        r['docker'] = hosts
        return json.dumps(r,indent=4)
    
    def hosts(name):
        r = {'ansible_ssh_pass':'123456'}
        cpis = dict(r.items())
        return json.dumps(cpis,indent=4)
    
    if __name__ == "__main__":
        '''添加argparse的参数类实例,添加一些-l和-H的帮助显示提示'''
        parser = argparse.ArgumentParser()
        parser.add_argument('-l','--list',help='hosts list',action='store_true')
        parser.add_argument('-H','--host',help='hosts vars')
        '''vars方法把parser.parse_args()字典转换过去判断用户输入的内容'''
        args = vars(parser.parse_args())
        if args['list']:
            print lists()
        elif args['host']:
            print hosts(args['host'])
        else:
            parser.print_help()
    

    用实际主机来跑一批任务

    ansible -i hosts.py docker -m ping -k 
    

    (3)主机文件支持的变量

    ansible_ssh_host 定义host ssh地址
    ansible_ssh_port 定义host ssh端口
    ansible_ssh_user 定义hosts ssh认证用户
    ansible_ssh_pass 定义hosts ssh 认证密码
    ansible_sudo 定义hosts sudo用户
    ansible_sudo_pass 定义hosts sudo密码
    ansible_sudo_exe 定义hosts sudo 路径
    ansible_connection 定义hosts连接方式
    ansible_ssh_private_key_file 定义hosts私钥
    ansible_shell_type 定义hosts shell类型
    ansible_python_interpreter 定义hosts任务执行python路径
    ansible_*_interpreter 定义hosts其他语言解析器路径

    2.Ansible Ad-Hoc##

    命令行方式使用ansible模块,使用ad-Hoc形式,插件功能无法使用,比如loop,facts功能

    2.1命令模式(shell)###

    1.普通同步模式等待后端返回结果的

    ansible -i /tmp/hosts docker -m shell -a 'uptime'
    

    2.异步模式,放后台,每隔几秒去看下任务状态,取回来数据

    # -B 120 :把执行slee 10的任务放到后台120秒,超过120秒后就报超时了
    # -P 2: 放到后台后,每隔2秒去远程主机上获取下任务状态,有返回取回数据,没返回,隔2秒后再去取一次结果,直到都取完后,任务完成
    ansible -i /tmp/hosts docker -m shell -a 'sleep 10' -B 120 -P 2
    

    异步原理:使用-P 参数后,会返回一个job_id,然后针对主机根据job_id去查询执行结果,每台主机产生不同的job_id,可以通过async_status模块查看异步任务的状态和结果,当-P 0的时候返回job_id就没了,后续操作需要自己去调用async_status模块取结果

    如果-P 参数大于0,ansible会根据job_id去轮训查询执行结果

    2.2.1复制文件(copy)###

    ansible -i /tmp/hosts webservers -m copy -a 'src=/tmp/hosts dest=/tmp/ owner=admin group=admin mode=644 backup=yes'
    

    其余帮助参数如下

    [admin@host-10-187-196-225 tmp]$ ansible-doc -s copy
    less 436
    Copyright (C) 1984-2009 Mark Nudelman
    
    less comes with NO WARRANTY, to the extent permitted by law.
    For information about the terms of redistribution,
    see the file named README in the less distribution.
    Homepage: http://www.greenwoodsoftware.com/less
    - name: C o p i e s   f i l e s   t o   r e m o t e   l o c a t i o n s .
      action: copy
          backup                 # Create a backup file including the timestamp information so you can get the original file back if you somehow clobbered it incorrectly.
          content                # When used instead of 'src', sets the contents of a file directly to the specified value.
          dest=                  # Remote absolute path where the file should be copied to. If src is a directory, this must be a directory too.
          directory_mode         # When doing a recursive copy set the mode for the directories. If this is not set we will use the system defaults. The mode is only set on directories which ar
          follow                 # This flag indicates that filesystem links, if they exist, should be followed.
          force                  # the default is `yes', which will replace the remote file when contents are different than the source.  If `no', the file will only be transferred if the desti
          group                  # name of the group that should own the file/directory, as would be fed to `chown'
          mode                   # mode the file or directory should be, such as 0644 as would be fed to `chmod'. As of version 1.8, the mode may be specified as a symbolic mode (for example, `
          owner                  # name of the user that should own the file/directory, as would be fed to `chown'
          selevel                # level part of the SELinux file context. This is the MLS/MCS attribute, sometimes known as the `range'. `_default' feature works as for `seuser'.
          serole                 # role part of SELinux file context, `_default' feature works as for `seuser'.
          setype                 # type part of SELinux file context, `_default' feature works as for `seuser'.
          seuser                 # user part of SELinux file context. Will default to system policy, if applicable. If set to `_default', it will use the `user' portion of the policy if availab
          src                    # Local path to a file to copy to the remote server; can be absolute or relative. If path is a directory, it is copied recursively. In this case, if path ends w
          validate               # The validation command to run before copying into place.  The path to the file to validate is passed in via '%s' which must be present as in the visudo exampl
    

    2.2.2拽文件(fetch)###

    把远程节点的/tmp/1.txt文件拽到本机/tmp/目录下,最后一定要/结尾,flat=yes代表的是直接以原文件名在/tmp/目录下命名创建

    [admin@host-10-187-196-225 tmp]$ ansible -i 1 all -m fetch -a "src=/tmp/1.txt dest=/tmp/ flat=yes" -k
    SSH password: 
    10.185.12.10 | success >> {
        "changed": true,
        "checksum": "52db334a166050298648cb3ba63336d9e9a9ac09",
        "dest": "/tmp/1.txt",
        "md5sum": "c41da816ae05a847b668da48bf8653d5",
        "remote_checksum": "52db334a166050298648cb3ba63336d9e9a9ac09",
        "remote_md5sum": null
    }
    

    其余帮助参数

    [admin@host-10-187-196-225 tmp]$ ansible-doc -s fetch
    less 436
    Copyright (C) 1984-2009 Mark Nudelman
    
    less comes with NO WARRANTY, to the extent permitted by law.
    For information about the terms of redistribution,
    see the file named README in the less distribution.
    Homepage: http://www.greenwoodsoftware.com/less
    - name: F e t c h e s   a   f i l e   f r o m   r e m o t e   n o d e s
      action: fetch
          dest=                  # A directory to save the file into. For example, if the `dest' directory is `/backup' a `src' file named `/etc/profile' on host `host.example.com', would be sa
          fail_on_missing        # Makes it fails when the source file is missing.
          flat                   # Allows you to override the default behavior of prepending hostname/path/to/file to the destination.  If dest ends with '/', it will use the basename of the so
          src=                   # The file on the remote system to fetch. This `must' be a file, not a directory. Recursive fetching may be supported in a later release.
          validate_checksum      # Verify that the source and destination checksums match after the files are fetched.
    

    dest:用来存放文件的目录,例如存放目录为backup,源文件名称为/etc/profile在主机pythonserver中,那么保存为/backup/pythonserver/etc/profile
    Fail_on_missing:当源文件不存在的时候,标识为失败
    Flat:允许覆盖默认行为从hostname/path到/file的,如果dest以/结尾,它将使用源文件的基础名称
    Src:在远程拉取的文件,并且必须是一个file,不能是目录
    Validate_checksum:当文件fetch之后进行md5检查

    2.3包管理(yum)###

    ansible -i /tmp/hosts webservers -m yum -a 'name=mysql state=latest'
    

    其余帮助文档

    > YUM
    
      Installs, upgrade, removes, and lists packages and groups with the
      `yum' package manager.
    
    Options (= is mandatory):
    
    - conf_file
            The remote yum configuration file to use for the transaction.
            [Default: None]
    
    - disable_gpg_check
            Whether to disable the GPG checking of signatures of packages
            being installed. Has an effect only if state is `present' or
            `latest'. (Choices: yes, no) [Default: no]
    
    - disablerepo
            `Repoid' of repositories to disable for the install/update
            operation. These repos will not persist beyond the
            transaction. When specifying multiple repos, separate them
            with a ",". [Default: None]
    
    - enablerepo
            `Repoid' of repositories to enable for the install/update
            operation. These repos will not persist beyond the
            transaction. When specifying multiple repos, separate them
            with a ",". [Default: None]
    
    - list
            Various (non-idempotent) commands for usage with
            `/usr/bin/ansible' and `not' playbooks. See examples.
            [Default: None]
    
    = name
            Package name, or package specifier with version, like
            `name-1.0'. When using state=latest, this can be '*' which
            means run: yum -y update. You can also pass a url or a local
            path to a rpm file. [Default: None]
    
    - state
            Whether to install (`present', `latest'), or remove (`absent')
            a package. (Choices: present, latest, absent) [Default:
            present]
    
    = name
            Package name, or package specifier with version, like
            `name-1.0'. When using state=latest, this can be '*' which
            means run: yum -y update. You can also pass a url or a local
            path to a rpm file. [Default: None]
    
    - state
            Whether to install (`present', `latest'), or remove (`absent')
            a package. (Choices: present, latest, absent) [Default:
            present]
    
    - update_cache
            Force updating the cache. Has an effect only if state is
            `present' or `latest'. (Choices: yes, no) [Default: no]
    
    Requirements:  yum
    
    EXAMPLES:
    - name: install the latest version of Apache
      yum: name=httpd state=latest
    
    - name: remove the Apache package
      yum: name=httpd state=absent
    
    - name: install the latest version of Apache from the testing repo
      yum: name=httpd enablerepo=testing state=present
    
    - name: install one specific version of Apache
      yum: name=httpd-2.2.29-1.4.amzn1 state=present
    
    - name: upgrade all packages
      yum: name=* state=latest
    
    - name: install the nginx rpm from a remote repo
      yum: name=http://nginx.org/packages/centos/6/noarch/RPMS/nginx-release-centos-6-0.el6.ngx.noarch.rpm state=present
    
    - name: install nginx rpm from a local file
      yum: name=/usr/local/src/nginx-release-centos-6-0.el6.ngx.noarch.rpm state=present
    
    - name: install the 'Development tools' package group
      yum: name="@Development tools" state=present
    

    2.4用户管理(user)###

    ansible -i /tmp/hosts webservers -m user -a 'name=diaodiao password="123456"'
    

    其余帮助文档

    > USER
    
      Manage user accounts and user attributes.
    
    Options (= is mandatory):
    
    - append
            If `yes', will only add groups, not set them to just the list
            in `groups'. (Choices: yes, no) [Default: no]
    
    - comment
            Optionally sets the description (aka `GECOS') of user account.
    
    - createhome
            Unless set to `no', a home directory will be made for the user
            when the account is created or if the home directory does not
            exist. (Choices: yes, no) [Default: yes]
    
    - expires
            An expiry time for the user in epoch, it will be ignored on
            platforms that do not support this. Currently supported on
            Linux and FreeBSD. [Default: None]
    
    - force
            When used with `state=absent', behavior is as with `userdel
            --force'. (Choices: yes, no) [Default: no]
    
    - generate_ssh_key
            Whether to generate a SSH key for the user in question. This
            will *not* overwrite an existing SSH key. (Choices: yes, no)
            [Default: no]
    
    - group
            Optionally sets the user's primary group (takes a group name).
    
    - groups
            Puts the user in this comma-delimited list of groups. When set
            to the empty string ('groups='), the user is removed from all
            groups except the primary group.
    
    - home
            Optionally set the user's home directory.
    - login_class
            Optionally sets the user's login class for FreeBSD, OpenBSD
            and NetBSD systems.
    
    - move_home
            If set to `yes' when used with `home=', attempt to move the
            user's home directory to the specified directory if it isn't
            there already. (Choices: yes, no) [Default: no]
    
    = name
            Name of the user to create, remove or modify.
    
    - non_unique
            Optionally when used with the -u option, this option allows to
            change the user ID to a non-unique value. (Choices: yes, no)
            [Default: no]
    
    - password
            Optionally set the user's password to this crypted value.  See
            the user example in the github examples directory for what
            this looks like in a playbook. The `FAQ
            <http://docs.ansible.com/faq.html#how-do-i-generate-crypted-
            passwords-for-the-user-module>`_ contains details on various
            ways to generate these password values. Note on Darwin system,
            this value has to be cleartext. Beware of security issues.
    
    - remove
            When used with `state=absent', behavior is as with `userdel
            --remove'. (Choices: yes, no) [Default: no]
    
    - shell
            Optionally set the user's shell.
    
    - ssh_key_bits
            Optionally specify number of bits in SSH key to create.
            [Default: 2048]
    
    - ssh_key_comment
            Optionally define the comment for the SSH key. [Default:
            ansible-generated on $HOSTNAME]
    
    - ssh_key_file
            Optionally specify the SSH key filename. If this is a relative
            filename then it will be relative to the user's home
            directory. [Default: .ssh/id_rsa]
    
    - ssh_key_passphrase
            Set a passphrase for the SSH key.  If no passphrase is
            provided, the SSH key will default to having no passphrase.
    
    - ssh_key_type
            Optionally specify the type of SSH key to generate. Available
            SSH key types will depend on implementation present on target
            host. [Default: rsa]
    
    - state
            Whether the account should exist or not, taking action if the
            state is different from what is stated. (Choices: present,
            absent) [Default: present]
    
    - system
            When creating an account, setting this to `yes' makes the user
            a system account.  This setting cannot be changed on existing
            users. (Choices: yes, no) [Default: no]
    
    - uid
            Optionally sets the `UID' of the user.
    
    - update_password
            `always' will update passwords if they differ.  `on_create'
            will only set the password for newly created users. (Choices:
            always, on_create) [Default: always]
    
    Requirements:  useradd, userdel, usermod
    
    EXAMPLES:
    # Add the user 'johnd' with a specific uid and a primary group of 'admin'
    - user: name=johnd comment="John Doe" uid=1040 group=admin
    
    # Add the user 'james' with a bash shell, appending the group 'admins' and 'developers' to the user's groups
    - user: name=james shell=/bin/bash groups=admins,developers append=yes
    
    # Remove the user 'johnd'
    - user: name=johnd state=absent remove=yes
    
    # Create a 2048-bit SSH key for user jsmith in ~jsmith/.ssh/id_rsa
    
    # added a consultant whose account you want to expire
    - user: name=james18 shell=/bin/zsh groups=developers expires=1422403387
    

    3.Ansible facts##

    facts组件呢是ansible用于采集被管理机器设备信息的一个功能,可以使用setup检查机器的所有facts信息,用filter来查看指定信息.返回一个大json

    ansible -i /tmp/hosts webservers -m setup
    
  • 相关阅读:
    测试脚本
    浅谈优化SQLServer数据库服务器内存配置的策略
    真正的取真实IP地址及利弊Asp.net
    ASP.NET一些常用正则表达式
    (CHMSoftware)工具集锦
    仿真方面的文章
    TPlan测试过程管理工具技术摘要
    Linux 2.6内核的精彩世界(多媒体)
    Ajax技术实践之完成Ajax自动完成功能
    硬件测试
  • 原文地址:https://www.cnblogs.com/PythonOrg/p/6588727.html
Copyright © 2020-2023  润新知