自动化运维工具Ansible使用教程

一、简介

1.1 基本概念:

ansible是一个基于python开发的轻量级自动化运维管理工具,可以用来批量执行命令,安装程序,支持playbook编排。它通过ssh协议来连接主机,去中心化,相对比puppet和saltstack无需安装客户即可实现文件传输、命令执行、应用部署、配置管理、任务编排等,显得更为简单与轻量。ansible只是提供一种框架,其基于模块工作的,本身没有批量部署。

1.2 核心组件:

(1)、连接插件connection plugins:负责和被监控端实现通信;

(2)、host inventory:指定操作的主机,是一个配置文件里面定义监控的主机;

(3)、各种模块核心模块、command模块、自定义模块;

(4)、借助于插件完成记录日志邮件等功能;

(5)、playbook:剧本执行多个任务时,非必需可以让节点一次性运行多个任务。

1.3 工具特性:

(1)、no agents:不需要在被管控主机上安装任何客户端;

(2)、no server:无服务器端,使用时直接运行命令即可;

(3)、modules in any languages:基于模块工作,可使用任意语言开发模块;

(4)、yaml,not code:使用yaml语言定制剧本playbook;

(5)、ssh by default:基于SSH工作;

(6)、strong multi-tier solution:可实现多级指挥。

1.4 流程架构:

wKioL1ncR6eADyO1AAEvXQjifhw076.png

wKioL1ncXunh8DRkAAHwKsC_JoE071.png

1.5 优缺点:

优点:

  • 轻量级,无需在客户端安装agent,更新时,只需在操作机上进行一次更新即可;
  • 批量任务执行可以写成脚本,而且不用分发到远程就可以执行;
  • 使用python编写,维护更简单;
  • 使用push方式,控制节点向其他节点推方式,可先测试变更,方便控制管理。

缺点:

  • 基于ssh,串行,故超过500台主机效率较低;

二、安装部署

名称 主机名 IP地址
A主机 ansible-A 172.20.4.10
B主机 ansible-B 172.20.4.11
C主机 ansible-C 172.20.4.12

2.1 Ansible安装

rpm -ivh http: //mirrors .sohu.com /-epel/6/x86_64/epel-release-6-8 .noarch.rpm
yum  install  ansible -y

2.2 各主机SSH互信

例如:在A主机执行以下命令,将公钥发送到B主机

ssh -keygen -t rsa                              #创建公钥与私钥
ssh -copy- id  -i ~/. ssh /id_rsa .pub [email protected]            #将公钥传输给对端服务器

此时A服务器可以免密码登录B服务器

wKioL1ncYvGgfSjkAACbI1nUyrk391.png

同样方式,可以做A到C主机,如果控制端为B主机,需要B反向将公钥发布到A主机,实现互信。

2.3 命令参数介绍

Usage: ansible <host-pattern> [options]
 
Options:
-a MODULE_ARGS, --args=MODULE_ARGS                  #制定调用的模块(ansible-doc查看模块)
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
-f FORKS, --forks=FORKS                                        #一次执行并发的连接数
specify number of parallel processes to use
(default=5)
-h, --help            show this help message and  exit
-i INVENTORY, --inventory- file =INVENTORY                                #调用的hosts文件
specify inventory host path
(default= /etc/ansible/hosts ) or comma separated host
list.
-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
specify path(s) to module library (default=None)
--new-vault-password- file =NEW_VAULT_PASSWORD_FILE 
new vault password  file  for  rekey
-o, --one-line        condense output
--output=OUTPUT_FILE  output  file  name  for  encrypt or decrypt; use -  for
stdout
-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-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
 
Connection Options:
control as whom and how to connect to hosts
 
-k, --ask-pass      ask  for  connection password                          #需要安装sshpass  输入密码
--private-key=PRIVATE_KEY_FILE, --key- file =PRIVATE_KEY_FILE
use this  file  to authenticate the connection
-u REMOTE_USER, --user=REMOTE_USER                                        #ssh执行命令的用户,默认为当前执行ansible的用户
connect as this user (default=None)
-c CONNECTION, --connection=CONNECTION
connection  type  to use (default=smart)
-T TIMEOUT, --timeout=TIMEOUT                                      #执行命令的超时时间 (default=10)
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)            #sudo
-U SUDO_USER, -- sudo -user=SUDO_USER      #sudo
desired  sudo  user (default=root) (deprecated, use
become)
-S, -- su            run operations with  su  (deprecated, use become)
-R SU_USER, -- su -user=SU_USER                                        #su 的时候切换到那个用户
run operations with  su  as this user (default=root)
(deprecated, use become)

2.4 配置相关文件

修改主机文件inventory:,此文件定义执行命令的主机列表

wKioL1ncY8bS-Ms9AAAojWh7jgg214.png

设置ansible.cfg参数

inventory = /etc/ansible/hosts              #定义资源清单inventory文件的位置,一般保持默认
library = /usr/share/my_modules/            #library指向ansible模块的目录,一般保持默认
forks =10                                  #设置多少个进程同时工作
sudo_user=root                            #设置默认执行命令的用户,也可在playbook中重新设置此参数
remote_port=22                            #制定连接被管理的管理端口,默认为22
timeout =10                                #设置SSH连接的超时时间间隔,单位为秒

2.5 测试

ansible agent -m  command  -a  "touch /tmp/aaa"  -vvv
#-m  使用command模块  -a 使用command里面支持的命令参数 -vvv 查看详细过程

wKioL1ncbXmA9xmVAAB-f9ZOtgs514.png

三、模块介绍

ansible模块较多,对应可以查看相关文档,此处列出一下日常工作中常用的模块

【copy】模块
ansible agent -m copy -a  "src=/root/test.sh dest=/tmp"
file
调用-s 参数,需要客户端能够无密码使用 sudo 命令;
ansible agent -m  file  -a  "dest=/tmp/test.sh mode=755 owner=root group=root"  -s
【script】
ansible agent -m script -a  "/tmp/test.sh"
【shell】创建用户
ansible agent -m shell -a  "/tmp/test.sh" 
【group】创建组
ansible agent -m group -a  "name=test1 state=present"  -s
【user】
ansible agent -m user -a  "name=xuel home=/home/xuel state=present"  -s
【yum】
可以提供的status:absent,present,installed,removed,latest
ansible agent -m yum -a  "name=httpd state=latest"  -s
【server】
可以提供的status:running,started,stopped,restarted,reloaded
cron
ansible agent -m  cron  -a  'name="my job" minute=*/1 hour=* day=* month=* weekday=* job="/usr/sbin/ntpdate time1.aliyun.com"'
【get_url】
ansible agent -m get_url -a  "url=http://mirrors.sohu.com/fedora-epel/6/x86_64/epel-release-6-8.noarch.rpm dest=/tmp"
【synchronize】需要安装 rsync
ansible agent -m synchronize -a  "src=/root/test.file dest=/tmp"
模块默认使用的为推送push,如果想使用pull功能需添加mode=pull
ansible agent -m synchronize -a  "mode=pull src=/tmp/test.file dest=/root/"
【ini_file】 
ansible agent -m ini_file -a  "dest=/tmp/test.ini section=Mongo option=Host value=127.0.0.1"
该模块Python需要安装ConfigParser

四、ansible-playbook介绍

4.1 核心组件

hosts              #执行的远程主机列表
tasks              #任务集
varniables        #内置变量或自定义变量
templates          #可替换模版
handlers          #触发操作

4.2 命令

Usage: ansible-playbook playbook.yml
ansible-playbook test1.yml             #执行剧本
ansible-vault encrypt test1.yml          #加密剧本
ansible-vault decrypt test1.yml          #加密剧本
ansible-vault view test1.yml            #加密剧本 

4.3 YAML语法

1.“---”顶行首写

2.#代码注释

3.缩进统一,不可混用空格与tab

4.缩进级别椅子

5.区分大小写

6.k/v值可以同行写也可换行写,同行使用:分割,换行需要-分割

7.一个网址的功能代码需要最少的元素包括name:task

8.一个name只能包括一个task

4.4 安装并启动mysql playbook实例

--- 
- hosts: agent
  remote_user: root
  tasks:
  - name:  install  mysql-server
    yum: name=mysql-server state=present
  - name: start mysql-server
    service: name=mysqld state=started
  - name: check mysql service
    shell:  ps  -ef | grep  mysqld

执行次playbook将mysql数据库安装到agent服务分组里:

wKiom1nc4kuhzrxQAAApekprQ-Y385.pngwKioL1ncc1ajFfZZAABQ2c97ioY532.png

下面关于Ansible的文章您也可能喜欢,不妨参考下:

Ansible 的详细介绍请点这里
Ansible 的下载地址请点这里

猜你喜欢

转载自www.linuxidc.com/Linux/2017-12/149671.htm