Ansible工具使用

1、介绍

Ansible是一个自动化管理IT资源的工具。

功能:

系统环境配置
安装软件
持续集成:自动化部署
热回滚

优点

无客户端
推送式
丰富的第三方module,大概1W多个
基于YAML的Playbook
商业化的支持

缺点

效率低,易挂起:基于ssh通信
并发性能差

自动化运维工具对比

2、Ansible安装与运行

安装

环境准备
Python
Setuptools

方法一: pip安装

pip(可选): pip install ansible

方法二:源码安装

git clone https://github.com/ansible/ansible.git
source ./hacking/env-setup
python setup.py install 替换自带的二进制运行文件

方法三:系统源安装

yum install ansible

运行流程

Ansible -> ssh -> ssh -> shell

Ansible配置文件路径优先级
(1) export ANSIBLE_CONFIG
(2) ./ansible.cfg
(3) ~/.ansible.cfg
(4) /etc/ansible/ansible.cfg

配置文件详解
ansible/ansible.cfg at devel · ansible/ansible · GitHub

(1) defaults默认配置项

[defaults]
#inventory       = /etc/ansible/hosts
#library         = ~/.ansible/plugins/modules:/usr/share/ansible/plugins/modules
#module_utils    = ~/.ansible/plugins/module_utils:/usr/share/ansible/plugins/module_utils
#remote_tmp      = ~/.ansible/tmp
#local_tmp       = ~/.ansible/tmp
#forks           = 5
#poll_interval   = 0.001
#ask_pass        = False
#transport       = smart
...
#gather_subset = all
...
#remote_user = root
...
# set plugin path directories here, separate with colons
#action_plugins     = /usr/share/ansible/plugins/action
#become_plugins     = /usr/share/ansible/plugins/become
#cache_plugins      = /usr/share/ansible/plugins/cache
#callback_plugins   = /usr/share/ansible/plugins/callback
#connection_plugins = /usr/share/ansible/plugins/connection
#lookup_plugins     = /usr/share/ansible/plugins/lookup
#inventory_plugins  = /usr/share/ansible/plugins/inventory
#vars_plugins       = /usr/share/ansible/plugins/vars
#filter_plugins     = /usr/share/ansible/plugins/filter
#test_plugins       = /usr/share/ansible/plugins/test
#terminal_plugins   = /usr/share/ansible/plugins/terminal
#strategy_plugins   = /usr/share/ansible/plugins/strategy

inventory: 存放可通信主机的目录,可修改为普通用户目录
library: Ansible默认搜寻模块路径
forks: 最大开辟的进程数,不易过大,过大性能耗费高;不宜过小,过小并发性能低,一般设置为CPU核数*2。
ask_pass: 可以控制Ansible playbook是否会自动默认弹出输入密码框
ask_sudo_pass: 用户使用的系统平台开启了sudo密码的话,这个参数应该设置为true
gather_subset: 设置收集的内容,包括all、network、hardware、virtual、facter、ohai
remote_port: 设置客户机的端口,一般都是22
remote_tmp: 设置客户机的临时目录
remote_user: 设置客户机的用户
sudo_exe: sudo命令的路径
sudo_flags: sudo参数
sudo_user: 能够使用sudo的user
开发者中心的插件相关功能,开发者可以开发相应的插件,来完成自己的功能:
action_plugins: 激活事件
callback_plugins: 回调
connection_plugins: 连接,比如不使用ssh连接
filter_plugins: 过滤器
loopup_plugins: 加载路径
vars_plugins: 任何地方加载

(2) privilege_escalation执行命令的用户权限设置

[privilege_escalation]
#become = False
#become_method = sudo
#become_ask_pass = False


## Connection Plugins ##

# Settings for each connection plugin go under a section titled '[[plugin_name]_connection]'
# To view available connection plugins, run ansible-doc -t connection -l
# To view available options for a connection plugin, run ansible-doc -t connection [plugin_name]
# https://docs.ansible.com/ansible/latest/plugins/connection.html

(3) paramiko_connection paramika插件设置

[paramiko_connection]
# uncomment this line to cause the paramiko connection plugin to not record new host
# keys encountered. Increases performance on new host additions. Setting works independently of the
# host key checking setting above.
#record_host_keys=False

# by default, Ansible requests a pseudo-terminal for commands executed under sudo. Uncomment this
# line to disable this behaviour.
#pty = False

# paramiko will default to looking for SSH keys initially when trying to
# authenticate to remote devices. This is a problem for some network devices
# that close the connection after a key failure. Uncomment this line to
# disable the Paramiko look for keys function
#look_for_keys = False

# When using persistent connections with Paramiko, the connection runs in a
# background process. If the host doesn't already have a valid SSH key, by
# default Ansible will prompt to add the host key. This will cause connections
# running in background processes to fail. Uncomment this line to have
# Paramiko automatically add host keys.
#host_key_auto_add = True

(4) ssh_connection ssh链接设置

[ssh_connection]
# ssh arguments to use
# Leaving off ControlPersist will result in poor performance, so use
# paramiko on older platforms rather than removing it, -C controls compression use
#ssh_args = -C -o ControlMaster=auto -o ControlPersist=60s

# The base directory for the ControlPath sockets.
# This is the "%(directory)s" in the control_path option
#
# Example:
# control_path_dir = /tmp/.ansible/cp
#control_path_dir = ~/.ansible/cp

# The path to use for the ControlPath sockets. This defaults to a hashed string of the hostname,
# port and username (empty string in the config). The hash mitigates a common problem users
# found with long hostnames and the conventional %(directory)s/ansible-ssh-%%h-%%p-%%r format.
# In those cases, a "too long for Unix domain socket" ssh error would occur.
#
# Example:
# control_path = %(directory)s/%%C
#control_path =

# Enabling pipelining reduces the number of SSH operations required to
# execute a module on the remote server. This can result in a significant
# performance improvement when enabled, however when using "sudo:" you must
# first disable 'requiretty' in /etc/sudoers
#
# By default, this option is disabled to preserve compatibility with
# sudoers configurations that have requiretty (the default on many distros).
#
#pipelining = False

# Control the mechanism for transferring files (old)
#   * smart = try sftp and then try scp [default]
#   * True = use scp only
#   * False = use sftp only
#scp_if_ssh = smart

# Control the mechanism for transferring files (new)
# If set, this will override the scp_if_ssh option
#   * sftp  = use sftp to transfer files
#   * scp   = use scp to transfer files
#   * piped = use 'dd' over SSH to transfer files
#   * smart = try sftp, scp, and piped, in that order [default]
#transfer_method = smart

# If False, sftp will not use batch mode to transfer files. This may cause some
# types of file transfer failures impossible to catch however, and should
# only be disabled if your sftp version has problems with batch mode
#sftp_batch_mode = False

# The -tt argument is passed to ssh when pipelining is not enabled because sudo
# requires a tty by default.
#usetty = True

# Number of times to retry an SSH connection to a host, in case of UNREACHABLE.
# For each retry attempt, there is an exponential backoff,
# so after the first attempt there is 1s wait, then 2s, 4s etc. up to 30s (max).

(4) accelerate
(5) selinux & colors
看源码

[selinux]
# file systems that require special treatment when dealing with security context
# the default behaviour that copies the existing context or uses the user default
# needs to be changed to use the file system dependent context.
#special_context_filesystems=fuse,nfs,vboxsf,ramfs,9p,vfat

# Set this to True to allow libvirt_lxc connections to work without SELinux.
#libvirt_lxc_noseclabel = False


[colors]
#highlight = white
#verbose = blue
#warn = bright purple
#error = red
#debug = dark gray
#deprecate = purple
#skip = cyan
#unreachable = red
#ok = green
#changed = yellow
#diff_add = green
#diff_remove = red
#diff_lines = cyan

3、 添加机器

3.1 编辑/etc/ansible/hosts,添加机器ip
3.2 添加本机的Public SSH key到目标机器的authorized_keys
3.3 添加本机的私钥到Ansible
3.4 ansible all -m ping测试是否添加成功
ansible: 命令主体
all: 默认是所有机器,被操作的目标机器的正则表达式,也可以按需求换做hosts文件中的其他组名
举例:
ansible test -m ping
ansible 192.168.1.10 -m ping
-m ping: 指定要使用的模块
-a: 指定传入模块的参数
举例:
ansible all -a "/sbin/reboot" -f 10 重启所有机器,每次重启10个
ansible all -a "/usr/bin/foo" -u root 指定root用户执行shell命令
-C -D: 两个一起使用,检查hosts规则文件的修改
-l: 限制匹配规则的主机数
--list-hosts: 显示所有匹配规则的主机
-m -M:指定所使用的模块和模块的路径
--syntax-check: 检查语法
-v: 显示详细的日志

4、playbook

playbook可以编排有序的执行过程,甚至可以在多组机器间,来回有序的执行特别指定的步骤,并且可以同步或异步的发起任务。
待学习补充...

5、Ansible API

功能:

  1. 调用Ansible的模块
  2. 开发动态的Inventory数据源
  3. 更好的控制playbook等功能的运行

调用Ansible模块:

  1. 引入Ansible runner库
  2. 初始化runner对象,传入相关参数
  3. 运行runner对象的run函数
    举例:
import ansible.runner
runner = ansible.runner.Runner(
    module_name='ping',
    module_args='',
    pattern='all',
    forks=10
)
datastructure = runner.run()

Ansible 2.0之前和2.0之后API相差很大,注意版本

调用Ansible2.0 API:

  1. 定义一个结果对象
  2. 初始化Ansible节点对象
  3. 初始化结果对象
  4. 创建一个任务
  5. 运行ansible节点
    举例【ansible 2.0】:
待学习补充...

6、自定义Ansible Module

6.1 自己写一个模块 test.py
6.2 把模块放到木块文件夹下
配置文件ansible.cfg中的lilbrary配置参数为ansible module的放置路径。
6.3 运行自己的模块ansible all -m test

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 211,290评论 6 491
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,107评论 2 385
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 156,872评论 0 347
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,415评论 1 283
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,453评论 6 385
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,784评论 1 290
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,927评论 3 406
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,691评论 0 266
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,137评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,472评论 2 326
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,622评论 1 340
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,289评论 4 329
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,887评论 3 312
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,741评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,977评论 1 265
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,316评论 2 360
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,490评论 2 348

推荐阅读更多精彩内容