一、ansible简介

  ansible是一款由python语言编写的一款自动化运维工具,它集合了众多运维工具(puppet、cfengine、chef、func、fabric)优点,实现了批量系统配置、批量程序部署、批量运行命令等功能。它的创始人,Michael DeHaan(cobbler与Func软件的作者),他在2012年3月9日发布了ansible 0.01版。2015年10月17日被RedHat宣布收购。

  二、ansible的特点

  1、无客户端,只需安装SSH、python即可,其中python建议版本2.6.6以上

  2、基于openssh通信,底层基于ssh协议(Windows基于powershell)

  3、支持密码和SSH认证,因可以通过系统帐户密码认证或公钥私钥认证,所以整个过程简单、方便、安全。

  4、支持Windows,但仅支持被管理端是Windows,管理端必须是Linux系统 

  5、模块化:调用特定的模块,完成特定任务

  6、支持playbook编排任务(类似shell中的脚本)

  7、幂等性:一个任务执行一遍和执行N遍的效果一样,不因重复执行带来意外情况

  8、可以使用任何编程语言编写模块(python可以调用其他语言的库)

  9、YAML格式,编排任务,支持丰富的数据结构

  三、ansible是如何工作的?

  Ansible没有客户端,因此底层通信依赖系统软件,在Linux系统下基于openssh通信,在Windows下基于powershell,管理端必须是Linux系统,使用者认证通过后在管理节点通过ansible工具调用各应用模块指令推送至被管理端执行,并在执行完毕后自动删除产生的临时文件。

  四、ansible的组成

ansible主要组成部分有:

  ANSIBLE-PLAYBOOKS:任务剧本(任务集),编排定义ansible任务集的配置文件,由ansible顺序依次执行,通常是json格式的YAML文件

  INVENTORY:ansible管理主机的清单/etc/ansible/hosts

  MODULES:ansible执行命令的功能模块,多数为内置核心模块,当然也可以自定义

  PLUGINS:模块功能的补充,如连接类型插件、循环插件、变量插件、过滤插件等,该功能不常用

  API:供第三方程序调用的应用程序编程接口

  ANSIBLE:组合INVENTORY、API、MODULES、PLUGINS的绿框,可以理解为ansible命令工具,其为核心执行工具

ansible命令执行来源:

  user,普通用户,即system administrator

  cmdb(配置管理数据库)API调用

  public/private cloud api 调用

  user--->ansible-playbook---->ansible

利用ansible实现管理的方式有以下两种:

  ad-hoc即ansible命令,主要用于临时命令使用场景

  ansible-playbook主要用于长期规划好的,大型项目的场景,需要有前提的规划

ansible-playbook(剧本)执行过程:
  将已有编排好的任务集写入Ansible-Playbook
  通过ansible-playbook命令分拆任务集至逐条ansible命令,按预定规则逐条执行
ansible主要操作对象:
  HOSTS主机
  NETWORKING网络设备

  五、ansible的安装

  1、rpm包安装:epel源

yum install ansible -y

  2、编译安装

    2.1、安装编译需要的依赖文件

yum -y install python-jinja2 PyYAML python-paramiko python-babel python-crypto

    2.2、下载源码包,解压源码包

wget https://releases.ansible.com/ansible/ansible-latest.tar.gz
tar xf ansible-latest.tar.gz

    2.3、进入到解压后的目录,运行setup.py 编译并安装

cd ansible-2.9.0
python setup.py build
python setup.py install

    2.4创建ansible配置文件目录,并拷贝配置文件到相应目录下

mkdir /etc/ansible
cp -r examples/* /etc/ansible

  3、git方式

git clone git://github.com/ansible/ansible.git --recursive
cd ./ansible
source ./hacking/env-setu

  4、pip安装

    4.1、安装python包管理工具pip,以及python开发库,以及ansible依赖包

yum install python-pip python-devel
yum install gcc glibc-devel zibl-devel rpm-bulid openssl-devel

  说明:pip是安装python包的管理器,类似yum

    4.2、pip安装ansible

pip install --upgrade pip
pip install ansible --upgrade

   说明:yum安装的pip默认不是最新版本,所以要先更新pip

以上四种安装选择自己喜欢的方式安装即可,安装好了,我们用ansible --version来确定是否安装成功

  六、ansible相关文件

    1、配置文件

      /etc/ansible/ansible.cfg主配置文件,配置ansible工作特性

      /etc/ansible/hosts主机清单

      /etc/ansible/roles/存放角色的目录

    2、ansible程序相关文件

      /usr/bin/ansible 主程序,临时命令执行工具

      /usr/bin/ansible-doc 查看配置文档,模块功能的工具

      /usr/bin/ansible-galaxy 下载/上传优秀代码或角色模块的官网平台

      /usr/bin/ansiable-playbook定制自动化任务,编排剧本工具

      /usr/bin/ansible-pull远程执行命令的工具

      /usr/bin/ansible-vault文件加密工具

      /usr/bin/ansible-console基于终端界面与用户交互的执行工具

  七、主机清单inventory

  ansible的主要功能用于批量主机操作,为了便捷地使用其中的部分主机,可以在主机清单文件中将其分组命名,默认的主机清单为/etc/ansible/hosts文件。

# This is the default ansible 'hosts' file.
#
# It should live in /etc/ansible/hosts
#
# - Comments begin with the '#' character
# - Blank lines are ignored
# - Groups of hosts are delimited by [header] elements
# - You can enter hostnames or ip addresses
# - A hostname/ip can be a member of multiple groups # Ex 1: Ungrouped hosts, specify before any group headers. ## green.example.com
## blue.example.com
## 192.168.100.1
## 192.168.100.10 # Ex 2: A collection of hosts belonging to the 'webservers' group ## [webservers]
## alpha.example.org
## beta.example.org
## 192.168.1.100
## 192.168.1.110 # If you have multiple hosts following a pattern you can specify
# them like this: ## www[001:006].example.com # Ex 3: A collection of database servers in the 'dbservers' group ## [dbservers]
##
## db01.intranet.mydomain.net
## db02.intranet.mydomain.net
## 10.25.1.56
## 10.25.1.57 # Here's another example of host ranges, this time there are no
# leading 0s: ## db-[99:101]-node.example.com

  说明:/etc/ansible/hosts文件给我们了几个定义主机清单的示例,我们可以参考它给的示例来定义主机清单,/etc/ansible/hosts文件遵循INI文件风格,中括号中的字符为组名,可以将一个主机同时归并到多个不同的组;其中未分组的主机,需要在任何组标题之前指定,也就是在第一个中括号以上来定义。若要分组,需要在中括号里写明组名,然后把对应的主机写在中括号之下,和下一个中括号之间。如果我们有多个主机遵循我们指定的模式,我们可以把多个主机写成像www[001:006].example.com,它表示www.001.example.com、www.002.example.com....www.006.example.com,相信看了以上给我们的示例样本,我们可以根据自己的实际情况来定义主机清单。此外,若目标主机使用了非默认的ssh端口,还可以在主机名称后面使用加冒号加端口号来标明。

  示例:

ntp.magedu.com
[webservers]
www1.magedu.com:2222
www2.magedu.com
[dbservers]
db1.magedu.com
db2.magedu.com
db3.magedu.com [websrvs]
www[01:100].example.com
[dbsrvs]
db-[a:f].example.com

  八、ansible主配置文件说明

ansible主配置文件/etc/ansible/ansible.cfg一般情况我们保持默认,不去修改它。

 [defaults]
#inventory = /etc/ansible/hosts # 主机列表配置文件
#library = /usr/share/my_modules/ # 库文件存放目录
#remote_tmp = $HOME/.ansible/tmp #临时py命令文件存放在远程主机目录
#local_tmp = $HOME/.ansible/tmp # 本机的临时命令执行目录
#forks = 5 # 默认并发数
#sudo_user = root # 默认sudo 用户
#ask_sudo_pass = True #每次执行ansible命令是否询问ssh密码
#ask_pass = True
#remote_port = 22
#host_key_checking = False # 检查对应服务器的host_key,建议取消注释
#log_path=/var/log/ansible.log #日志文件
#module_name = command #默认模块

  了解了ansible的简介,安装和基本配置文件的说明我们接下来配置几台主机来用一下ansible,感受下这个软件的魅力

首先我们要安装ansible,和配置好主机清单,上面介绍了怎么安装和配置主机清单,这里就不阐述了。

定义主机清单:

[websers]
192.168.0.128
192.168.0.218
[appsers]
192.168.0.217

  说明:本人用三个虚拟机分别模拟了三台服务器,且ssh端口默认的22号端口,所以不用指定其ssh端口

查看ansible命令用法

[root@docker ~]#ansible --help
Usage: ansible <host-pattern> [options] Define and run a single task 'playbook' against a set of hosts Options:
-a MODULE_ARGS, --args=MODULE_ARGS
module arguments
--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
-D, --diff when changing (small) files and templates, show the
differences in those files; works great with --check
-e EXTRA_VARS, --extra-vars=EXTRA_VARS
set additional variables as key=value or YAML/JSON, if
filename prepend with @
-f FORKS, --forks=FORKS
specify number of parallel processes to use
(default=5)
-h, --help show this help message and exit
-i INVENTORY, --inventory=INVENTORY, --inventory-file=INVENTORY
specify inventory host path or comma separated host
list. --inventory-file is deprecated
-l SUBSET, --limit=SUBSET
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
module name to execute (default=command)
-M MODULE_PATH, --module-path=MODULE_PATH
prepend colon-separated path(s) to module library
(default=[u'/root/.ansible/plugins/modules',
u'/usr/share/ansible/plugins/modules'])
--new-vault-id=NEW_VAULT_ID
the new vault identity to use for rekey
--new-vault-password-file=NEW_VAULT_PASSWORD_FILES
new vault password file for rekey
-o, --one-line condense output
-P POLL_INTERVAL, --poll=POLL_INTERVAL
set the poll interval if using -B (default=15)
--syntax-check perform a syntax check on the playbook, but do not
execute it
-t TREE, --tree=TREE log output to this directory
--vault-id=VAULT_IDS the vault identity to use
--vault-password-file=VAULT_PASSWORD_FILES
vault password file
-v, --verbose verbose mode (-vvv for more, -vvvv to enable
connection debugging)
--version show program's version number and exit Connection Options:
control as whom and how to connect to hosts -k, --ask-pass ask for connection password
--private-key=PRIVATE_KEY_FILE, --key-file=PRIVATE_KEY_FILE
use this file to authenticate the connection
-u REMOTE_USER, --user=REMOTE_USER
connect as this user (default=None)
-c CONNECTION, --connection=CONNECTION
connection type to use (default=smart)
-T TIMEOUT, --timeout=TIMEOUT
override the connection timeout in seconds
(default=10)
--ssh-common-args=SSH_COMMON_ARGS
specify common arguments to pass to sftp/scp/ssh (e.g.
ProxyCommand)
--sftp-extra-args=SFTP_EXTRA_ARGS
specify extra arguments to pass to sftp only (e.g. -f,
-l)
--scp-extra-args=SCP_EXTRA_ARGS
specify extra arguments to pass to scp only (e.g. -l)
--ssh-extra-args=SSH_EXTRA_ARGS
specify extra arguments to pass to ssh only (e.g. -R) Privilege Escalation Options:
control how and which user you become as on target hosts -s, --sudo run operations with sudo (nopasswd) (deprecated, use
become)
-U SUDO_USER, --sudo-user=SUDO_USER
desired sudo user (default=root) (deprecated, use
become)
-S, --su run operations with su (deprecated, use become)
-R SU_USER, --su-user=SU_USER
run operations with su as this user (default=None)
(deprecated, use become)
-b, --become run operations with become (does not imply password
prompting)
--become-method=BECOME_METHOD
privilege escalation method to use (default=sudo),
valid choices: [ sudo | su | pbrun | pfexec | doas |
dzdo | ksu | runas | pmrun ]
--become-user=BECOME_USER
run operations as this user (default=root)
--ask-sudo-pass ask for sudo password (deprecated, use become)
--ask-su-pass ask for su password (deprecated, use become)
-K, --ask-become-pass
ask for privilege escalation password Some modules do not make sense in Ad-Hoc (include, meta, etc)

  说明:上面帮助,我们了解了ansible命令的基本格式是ansible <host-pattern> [options],其中host-pattern表示匹配主机的模式,这里我们先大概的认为就是指定的主机吧,后续我们在说说匹配的模式有哪些。这里大概说一下常用选项 -a表示模块的参数,-m表示指定模块的名称,ansible命令的基本格式是 ansible +指定主机(当然这个也可以是我们定义的主机清单的组名,指定组名,匹配的就是其组名下的所有主机)+模块的名称  + 模块的参数,大概意思就是 用ansible去操作哪些主机,用什么模块,干什么事(要做的操作就是对模块传递参数)

查看ping模块使用方法

root@docker ~]#ansible-doc  ping
> PING (/usr/lib/python2.7/site-packages/ansible/modules/system/ping.py) A trivial test module, this module always returns `pong' on successful contact. It does
not make sense in playbooks, but it is useful from `/usr/bin/ansible' to verify the
ability to login and that a usable python is configured. This is NOT ICMP ping, this is
just a trivial test module. For Windows targets, use the [win_ping] module instead. OPTIONS (= is mandatory): - data
Data to return for the `ping' return value.
If this parameter is set to `crash', the module will cause an exception.
[Default: pong] NOTES:
* For Windows targets, use the [win_ping] module instead. AUTHOR: Ansible Core Team, Michael DeHaan
METADATA:
status:
- stableinterface
supported_by: core
:

  说明:看到以上说明是不是有点像Linux man帮助的界面呀,我们可以理解为ansible-doc 就相当于查看ansible模块的man帮助,这个文档显示的比较详细,但通常我们查看其基本用法有一个选项 -s 可以查看模块的简要说明和主要参数的说明,这个选项有点像我们Linux里使用命令的 -h选项或--help选项,如下所示

[root@docker ~]#ansible-doc -s ping
- name: Try to connect to host, verify a usable python and return `pong' on success
ping:
data: # Data to return for the `ping' return value. If this parameter is set to `crash', the
module will cause an exception.
[root@docker ~]#

  说明:用-s选项是不是更加快速的了解了ping模块的基本使用说明,从上面的帮助信息我们了解到ping模块的主要功能就是尝试去连接主机,若主机在线则返回‘pong’

用ping模块测试远程主机是否在线

[root@docker ~]#ansible websers -m ping
192.168.0.128 | SUCCESS => {
"changed": false,
"ping": "pong"
}
192.168.0.218 | SUCCESS => {
"changed": false,
"ping": "pong"
}
[root@docker ~]#ansible appsers -m ping
192.168.0.217 | SUCCESS => {
"changed": false,
"ping": "pong"
}
[root@docker ~]#ansible all -m ping
192.168.0.128 | SUCCESS => {
"changed": false,
"ping": "pong"
}
192.168.0.218 | SUCCESS => {
"changed": false,
"ping": "pong"
}
192.168.0.217 | SUCCESS => {
"changed": false,
"ping": "pong"
}
[root@docker ~]#

  说明:由于本人测试环境的三台主机,已经做好了ssh基于key验证,所以没有执行失败的信息返回,也没有提示输入密码,这里值得说一下ansible默认就是用的ssh基于key验证的方式去认证的(有关ssh基于key验证配置请参考本人博客https://www.cnblogs.com/qiuhom-1874/p/11783371.html),如果远端主机未做SSH基于key验证,则我们需要加选项 -k指定是用户名口令的方式认证,如下所示

[root@docker ~]#ansible all -m ping -k
SSH password:
192.168.0.128 | SUCCESS => {
"changed": false,
"ping": "pong"
}
192.168.0.218 | SUCCESS => {
"changed": false,
"ping": "pong"
}
192.168.0.217 | SUCCESS => {
"changed": false,
"ping": "pong"
}
[root@docker ~]#

  说明:可以看到我们输入了一个口令,则三台主机都返回了结果,这是为什么呢?ansible认为我们的主机都是同一口令,所以它会拿我们输入的口令去我们指定的主机上认证,如果认证成功,则返回成功,失败则返回失败,这样一来不当紧,如果我们三个主机口令不一样呢?这样就会给我们对管控远程主机带来诸多不便,所以建议各位在使用ansible之前做好SSH基于key认证。

以上就是ansible软件的基本使用和介绍,后续本人将持续更新ansible的其他用法,喜欢的朋友可以加加关注。写的不好,请大家指正,谢谢!!! 

最新文章

  1. C/C++ makefile自动生成工具(comake2,autotools,linux),希望能为开源做点微薄的贡献!
  2. 移动平台webApp的meta标签-----神奇的功效
  3. agile学习
  4. Google Picasa
  5. Ubuntu16.04下编译vim with python support失败的原因
  6. 禁用ios7 手势滑动返回功能
  7. ibatis-&gt;mybatis升级过程
  8. 201521123062《Java程序设计》第9周学习总结
  9. arclistsg文档独立模型标签
  10. linux ss 命令
  11. java使用代理发post请求
  12. 万能poi导入功能模板
  13. [visual studio]visual studio 2017激活码
  14. LearnOpenGL学习笔记(四)——着色器类编写
  15. linux下混杂模式
  16. delphi checklistbox用法
  17. 935. Knight Dialer
  18. pmm 监控mysql、mongodb、系统
  19. AJAX跨域请求json数据的实现方法
  20. Kotlin基础学习笔记(2)

热门文章

  1. Mybatis入门简版(补充)
  2. Vue-cli中axios传参的方式以及后端取的方式
  3. Mysql综述(1)数据是如何读存的
  4. Unity 场景中看不到物体或者OnDrawGizmos画的线看不到
  5. luoguP4779 【模板】单源最短路径
  6. 概念理解:boost::asio::io_service
  7. HDU 6607 Time To Get Up(状态压缩+枚举)
  8. prefer-object-spread
  9. JAVA实现扫描线算法
  10. QButtonGroup 的使用