阿里云-云小站(无限量代金券发放中)
【腾讯云】云服务器、云数据库、COS、CDN、短信等热卖云产品特惠抢购

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

163次阅读
没有评论

共计 7880 个字符,预计需要花费 20 分钟才能阅读完成。

一、简介

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 流程架构:

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

wKioL1ncXunh8DRkAAHwKsC_JoE071.png

1.5 优缺点:

优点:

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

缺点:

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

二、安装部署

 

名称主机名IP 地址
A 主机ansible-A172.20.4.10
B 主机ansible-B172.20.4.11
C 主机ansible-C172.20.4.12

2.1 Ansible 安装

  安装方式可使用源码编译安装,也可以更新 yum 源后 yum 安装,由于依赖较多模块,编译安装易出现异常,此次采用 yum 安装,CentOS 6.x 安装 epel 源后,直接可以 yum 安装,python 版本 2.6 以上,在各个节点均需要安装

rpm -ivh http://mirrors.sohu.com/Fedora-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 root@172.20.4.11            # 将公钥传输给对端服务器

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

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

同样方式,可以做 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:,此文件定义执行命令的主机列表

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

设置 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 查看详细过程

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

三、模块介绍

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 服务分组里:

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

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

使用 Ansible 批量管理远程服务器  http://www.linuxidc.com/Linux/2015-05/118080.htm

在 CentOS 7 中安装并使用自动化工具 Ansible  http://www.linuxidc.com/Linux/2015-10/123801.htm

CentOS 7 上搭建 Jenkins+Ansible 服务  http://www.linuxidc.com/Linux/2016-12/138737.htm

Linux 下源码编译安装 Ansible 及排错记录  http://www.linuxidc.com/Linux/2017-03/141427.htm

Ansible 基础—安装与常用模块  http://www.linuxidc.com/Linux/2017-02/140216.htm

Ansible 配置及使用  http://www.linuxidc.com/Linux/2017-03/142121.htm

自动化运维工具之 Ansible 介绍及安装使用  http://www.linuxidc.com/Linux/2016-12/138104.htm

自动化运维之 Ansible 详解  http://www.linuxidc.com/Linux/2017-03/142191.htm

Ansible 入门 notify 和 handlers  http://www.linuxidc.com/Linux/2017-02/140871.htm

CentOS 6.5 安装自动化工具 Ansible 和图形化工具 Tower  http://www.linuxidc.com/Linux/2017-03/141422.htm

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

本文永久更新链接地址:http://www.linuxidc.com/Linux/2017-12/149671.htm

正文完
星哥说事-微信公众号
post-qrcode
 0
星锅
版权声明:本站原创文章,由 星锅 于2022-01-21发表,共计7880字。
转载说明:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。
【腾讯云】推广者专属福利,新客户无门槛领取总价值高达2860元代金券,每种代金券限量500张,先到先得。
阿里云-最新活动爆款每日限量供应
评论(没有评论)
验证码
【腾讯云】云服务器、云数据库、COS、CDN、短信等云产品特惠热卖中