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
功能:
- 调用Ansible的模块
- 开发动态的Inventory数据源
- 更好的控制playbook等功能的运行
调用Ansible模块:
- 引入Ansible runner库
- 初始化runner对象,传入相关参数
- 运行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:
- 定义一个结果对象
- 初始化Ansible节点对象
- 初始化结果对象
- 创建一个任务
- 运行ansible节点
举例【ansible 2.0】:
待学习补充...
6、自定义Ansible Module
6.1 自己写一个模块 test.py
6.2 把模块放到木块文件夹下
配置文件ansible.cfg中的lilbrary配置参数为ansible module的放置路径。
6.3 运行自己的模块ansible all -m test