Ansible基础概述

一、Ansible简介

       Ansible基于Python语言实现,由paramiko和PyYAML两个关键模块构建。Ansible的编排引擎可以出色地完成配置管理,流程控制,资源部署等多方面工作。Ansible公司负责Ansible开源软件的维护,管理。一般软件的更新大概每2个月发布一次(目前版本在2.4)Ansible主要承担的工作有以下几种:

  1. 配置管理
  2. 服务即时开通
  3. 应用部署
  4. 流程编排
  5. 监控告警
  6. 日志记录

   AnsibleSaltstack最大的区别是Ansible无需在被控主机部署任何客户端代理,默认直接通过SSH通道进行远程命令执行或下发配置:相同点是都具备功能强大、灵活的系统管理、状态配置,两者都提供丰富的模板及API,对云计算平台、大数据都有很好的支持。

 特点:

  • 部署简单,只需在主控端部署Ansible环境,被控端无需做任何操作;
  • 默认使用SSH协议对设备进行管理;
  • 主从集中化管理;
  • 配置简单、功能强大、扩展性强;
  • 支持API及自定义模块,可通过Python轻松扩展;
  • 通过Playbooks来定制强大的配置、状态管理;
  • 对云计算平台、大数据都有很好的支持;
  • 提供一个功能强大、操作性强的Web管理界面和REST API接口——AWX平台。
  • 幂等性:一种操作重复多次结果相同
简评:
(1)、轻量级,无需在客户端安装agent,更新时,只需在操作机上进行一次更新即可;
(2)、批量任务执行可以写成脚本,而且不用分发到远程就可以执行;
(3)、使用python编写,维护更简单,ruby语法过于复杂;
(4)、支持sudo。

 

、Ansible架构及组件说明

1、架构图:

2、Ansible核心组件说明:

  • Ansible:Ansible的核心程序
  • Host Lnventory:记录了每一个由Ansible管理的主机信息,信息包括ssh端口,root帐号密码,ip地址等等。可以通过file来加载,可以通过CMDB加载

  • Playbooks:YAML格式文件,多个任务定义在一个文件中,使用时可以统一调用,“剧本”用来定义那些主机需要调用那些模块来完成的功能.

  • Core Modules:Ansible执行任何管理任务都不是由Ansible自己完成,而是由核心模块完成;Ansible管理主机之前,先调用core Modules中的模块,然后指明管理Host Lnventory中的主机,就可以完成管理主机。

  • Custom Modules:自定义模块,完成Ansible核心模块无法完成的功能,此模块支持任何语言编写。

  • Connection Plugins:连接插件,Ansible和Host通信使用

3、ansible任务执行流程
Ansible针对Ansible服务器对执行操作服务器的操作方式,分为两种执行模式:

  1. ad-hoc:这个模式支持执行单个模块,支持批量执行单条命令。
  2. playbook:这个可以理解成为面向对象的编程,就像上面举例那样可以把多个你想要执行的任务放到一个playbook当中,当然多个任务在事物逻辑上最好是有上下联系的。通过这多个任务可以完成一个总体的目标,这就是playbook。

 

三、Ansible部署及密钥分发

1、通过epel原安装ansible

[root@Node3 yum.repos.d]# rpm Uvh https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm   //安装epel源
[root@Node3 yum.repos.d]# yum -y install ansible                          //安装ansible
Loaded plugins: fastestmirror, langpacks
extras                                                                                                                        | 3.4 kB  00:00:00     
Loading mirror speeds from cached hostfile
 * base: mirrors.aliyun.com
 * epel: mirrors.tongji.edu.cn
 * extras: mirrors.163.com
 * updates: mirrors.aliyun.com
Resolving Dependencies
--> Running transaction check
.........省略中间部分.........
Installed:
  ansible.noarch 0:2.4.2.0-1.el7                                                                                                                     

Dependency Installed:(安装依赖程序包)
  PyYAML.x86_64 0:3.10-11.el7                    libtomcrypt.x86_64 0:1.17-26.el7             libtommath.x86_64 0:0.42.0-6.el7                     
  libyaml.x86_64 0:0.1.4-11.el7_0                python-babel.noarch 0:0.9.6-8.el7            python-cffi.x86_64 0:1.6.0-5.el7                     
  python-enum34.noarch 0:1.0.4-1.el7             python-httplib2.noarch 0:0.9.2-1.el7         python-idna.noarch 0:2.4-1.el7                       
  python-ipaddress.noarch 0:1.0.16-2.el7         python-jinja2.noarch 0:2.7.2-2.el7           python-keyczar.noarch 0:0.71c-2.el7                  
  python-markupsafe.x86_64 0:0.11-10.el7         python-paramiko.noarch 0:2.1.1-2.el7         python-ply.noarch 0:3.4-11.el7                       
  python-pycparser.noarch 0:2.14-1.el7           python2-crypto.x86_64 0:2.6.1-15.el7         python2-cryptography.x86_64 0:1.7.2-1.el7_4.1        
  python2-jmespath.noarch 0:0.9.0-3.el7          python2-pyasn1.noarch 0:0.1.9-7.el7          sshpass.x86_64 0:1.06-2.el7                          

Complete!

 2、SSH免密钥登录设置

[root@Node3 yum.repos.d]# ssh-keygen -t rsa -P ''   //生成公钥和私钥
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa): 
Your identification has been saved in /root/.ssh/id_rsa.
Your public key has been saved in /root/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:nmuEMSEBMJF2uZXpE4EBfowEuKm504OkS+8Urwrq2TA root@Node3.contoso.com
The key's randomart image is:
+---[RSA 2048]----+
|B*oo=o+          |
|=oo+.=.          |
|.=.o+...         |
|o .. oo          |
|.. .  .+S        |
|o.  o ....       |
|+E . . .o        |
|O X .   ..       |
|+*o*   ..        |
+----[SHA256]-----+
[root@Node3 yum.repos.d]# ssh-copy-id -i ~/.ssh/id_rsa.pub root@Node1     //分发公钥至Node1节点
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_rsa.pub"
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
root@node1's password: 
Permission denied, please try again.
root@node1's password: 

Number of key(s) added: 1

Now try logging into the machine, with:   "ssh 'root@Node1'"  
and check to make sure that only the key(s) you wanted were added.
[root@Node3 yum.repos.d]# ssh-copy-id -i ~/.ssh/id_rsa.pub root@Node2 //分发公钥至Node2节点

 

三、Ansible命令介绍及配置文件

1、常用命令介绍及配置文件
  /usr/bin/ansible: Ansibe AD-Hoc 临时命令执行工具,常用于临时命令的执行
  /usr/bin/ansible-doc: Ansible 模块功能查看工具
  /usr/bin/ansible-galaxy: 下载/上传优秀代码或Roles模块的官网平台,基于网络的
  /usr/bin/ansible-playbook: Ansible 定制自动化的任务集编排工具
  /usr/bin/ansible-pull: Ansible远程执行命令的工具(使用较少,海量机器时使用,对运维的架构能力要求较高)
  /usr/bin/ansible-vault:  Ansible 文件加密工具
  /usr/bin/ansible-console:  Ansible基于Linux Consoble界面可与用户交互的命令执行工具

  /usr/share/ansible_plugins:Ansible高级自定义插件目录(需要python基础)
  /etc/ansible/ansible.cfg:配置文件
  /etc/ansible/hosts:主机清单

2、/etc/ansible/ansible.cfgansible.cfg配置文件

1)[defaults]
    #inventory      = /etc/ansible/hosts  # 主机列表配置文件
    #library        = /usr/share/my_modules/ # 库文件存放目录 
    #remote_tmp     = $HOME/.ansible/tmp  # 生成的临时py命令文件存放在远程主机的目录
    #local_tmp      = $HOME/.ansible/tmp # 本机的临时命令执行目录
    #forks          = 5   # 默认并发数
    #poll_interval  = 15   # 默认的线程池
    #sudo_user      = root  # 默认sudo 用户
    #ask_sudo_pass = True
    #ask_pass      = True
    #transport      = smart
    #remote_port    = 22
    #module_lang    = C
    #module_set_locale = False

    host_key_checking = False  ### 检查对应服务器的host_key2)[privilege_escalation]
(3)[paramiko_connection]
(4)[ssh_connection]
(5)[accelerate]
(6)[selinux]
(7)[colors]

 

 3、Ansible主机清单(/etc/ansible/hosts)

  •  Hosts部分中经常用到的变量部分:
    ansible_ssh_host     #用于指定被管理的主机的真实IP
    ansible_ssh_port     #用于指定连接到被管理主机的ssh端口号,默认是22
    ansible_ssh_user     #ssh连接时默认使用的用户名
    ansible_ssh_pass     #ssh连接时的密码
    ansible_sudo_pass     #使用sudo连接用户时的密码
    ansible_sudo_exec     #如果sudo命令不在默认路径,需要指定sudo命令路径
    ansible_ssh_private_key_file     #秘钥文件路径,秘钥文件如果不想使用ssh-agent管理时可以使用此选项
    ansible_shell_type     #目标系统的shell的类型,默认sh
    ansible_connection     #SSH 连接的类型: local , ssh , paramiko,在 ansible 1.2 之前默认是 paramiko ,后来智能选择,优先使用基于 ControlPersist 的 ssh (支持的前提)
    ansible_python_interpreter     #用来指定python解释器的路径,默认为/usr/bin/python 同样可以指定ruby 、perl 的路径
    ansible_*_interpreter     #其他解释器路径,用法与ansible_python_interpreter类似,这里"*"可以是ruby或才perl等其他语
    示列如下:
    [test]
    192.168.10.1 ansible_ssh_user=root ansible_ssh_pass='P@ssw0rd'
    192.168.10.2 ansible_ssh_user=tony ansible_ssh_pass='123456'
    192.168.10.3 ansible_ssh_user=tom ansible_ssh_port=3022 ansible_ssh_pass='456789'
    上面的示例中指定了三台主机,三台主机的用密码分别是P@ssw0rd、123456、45789,指定的ssh连接的用户名分别为root、tony、tom,ssh 端口分别为22、22、3022 ,这样在ansible命令执行的时候就不用再指令用户和密码等了

     

  • 简单的主机和组
        [webservers]
        web1.contoso.com
        web2.contoso.com
        [dbservers]
        db1.contoso.com
        db2.contoso.com
    a、中括号中的名字代表组名,可以根据自己的需求将庞大的主机分成具有标识的组,如上面分了两个组webservers和dbservers组;
    b、主机(hosts)部分可以使用域名、主机名、IP地址表示;当然使用前两者时,也需要主机能反解析到相应的IP地址,一般此类配置中多使用IP地址;

 、Ansible使用

1、定义主机清单(/etc/ansible/hosts)

[root@Node3 ansible]# tail -5 /etc/ansible/hosts 

## db-[99:101]-node.example.com
[Webservers]                  //定义Web组
172.17.21.206
172.17.21.207

2、使用ping模块测试主机是否在线

[root@Node3 ansible]# ansible all -m ping        //测试所有主机是否在线
172.17.21.206 | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}
172.17.21.207 | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}

3、ansible命令的使用说明

常用选项

  • ansible -m MOD_NAME -a MOD_ARGS 表示调用什么模块,使用模块的那些参数
  • ansible-doc -l 获取模块信息
  • ansible-doc -s MOD_NAME 获取指定模块的使用帮助
  •  ansible -h
    [root@Node3 ansible]# ansible -h
    Usage: ansible <host-pattern> [options]
    Options:
      -a MODULE_ARGS, --args=MODULE_ARGS    模块的参数,如果执行默认COMMAND的模块,即是命令参数,如:“date”,"pwd"等等
                            module arguments    模块参数
      -k, --ask-pass        ask for SSH password  登录密码,提示输入SSH密码而不是假设基于密钥的验证
      --ask-su-pass         ask for su password    su切换密码
      -K, --ask-sudo-pass   ask for sudo password  提示密码使用sudo,sudo表示提权操作
      --ask-vault-pass      ask for vault password
      -B SECONDS, --background=SECONDS     后台运行超时时间
                            run asynchronously, failing after X seconds
                            (default=N/A)
      -C, --check           don't make any changes; instead, try to predict some    只是测试一下会改变什么内容,不会真正去执行;相反,试图预测一些可能发生的变化
                            of the changes that may occur
      -c CONNECTION, --connection=CONNECTION   连接类型使用。可能的选项是paramiko(SSH),SSH和地方。当地主要是用于crontab或启动。
                            connection type to use (default=smart)
      -f FORKS, --forks=FORKS   并行任务数。NUM被指定为一个整数,默认是5
                            specify number of parallel processes to use
                            (default=5)
      -h, --help            show this help message and exit   打开帮助文档API
      -i INVENTORY, --inventory-file=INVENTORY    指定库存主机文件的路径,默认为/etc/ansible/hosts
                            specify inventory host file
                            (default=/etc/ansible/hosts)
      -l SUBSET, --limit=SUBSET    进一步限制所选主机/组模式  --limit=192.168.91.135 只对这个ip执行
                            further limit selected hosts to an additional pattern
      --list-hosts          outputs a list of matching hosts; does not execute
                            anything else
      -m MODULE_NAME, --module-name=MODULE_NAME   执行模块的名字,默认使用 command 模块,所以如果是只执行单一命令可以不用 -m参数
                            module name to execute (default=command)
      -M MODULE_PATH, --module-path=MODULE_PATH    要执行的模块的路径,默认为/usr/share/ansible/
                            specify path(s) to module library
                            (default=/usr/share/ansible/)
      -o, --one-line        condense output      压缩输出,摘要输出.尝试一切都在一行上输出。
      -P POLL_INTERVAL, --poll=POLL_INTERVAL    调查背景工作每隔数秒。需要- b
                            set the poll interval if using -B (default=15)
      --private-key=PRIVATE_KEY_FILE    私钥路径,使用这个文件来验证连接
                            use this file to authenticate the connection
      -S, --su              run operations with susu 命令
      -R SU_USER, --su-user=SU_USER      指定SU的用户,默认是root用户
                            run operations with su as this user (default=root)
      -s, --sudo            run operations with sudo (nopasswd)    
      -U SUDO_USER, --sudo-user=SUDO_USER    sudo到哪个用户,默认为 root  
                            desired sudo user (default=root)
      -T TIMEOUT, --timeout=TIMEOUT    指定SSH默认超时时间,  默认是10S
                            override the SSH timeout in seconds (default=10)
      -t TREE, --tree=TREE  log output to this directory     将日志内容保存在该输出目录,结果保存在一个文件中在每台主机上。
      -u REMOTE_USER, --user=REMOTE_USER    远程用户, 默认是root用户
                            connect as this user (default=root)
      --vault-password-file=VAULT_PASSWORD_FILE  
                            vault password file
      -v, --verbose         verbose mode (-vvv for more, -vvvv to enable    详细信息
                            connection debugging)
      --version             show program's version number and exit   输出ansible的版本
  • ansible-doc -h
    [root@Node3 ansible]# ansible-doc  -h
    Usage: ansible-doc [options] [module...]
    Show Ansible module documentation     显示Ansible模块文档
    Options:
      --version             show program's version number and exit    显示ansible-doc的版本号
      -h, --help            show this help message and exit  显示命令参数API文档
      -M MODULE_PATH, --module-path=MODULE_PATH   查询模块,--module-path=MODULE_PATH  指定模块的路径
                            Ansible modules/ directory
      -l, --list            List available modules   显示已存在的所有模块列表
      -s, --snippet         Show playbook snippet for specified module(s)   显示playbook制定模块的用法
      -v                    Show version number and exit   显示ansible-doc的版本号

     

posted @ 2018-01-22 13:01  cloudos  阅读(800)  评论(0编辑  收藏  举报