Ansible之基础知识

Ansible 相关文件

配置文件

/etc/ansible/ansible.cfg 主配置文件,配置ansible工作特性,也可以在项目的目录中创建此文件,
当前目录下如果也有ansible.cfg,则此文件优先生效,建议每个项目目录下,创建独有的ansible.cfg文件
/etc/ansible/hosts 主机清单
/etc/ansible/roles/ 存放角色的目录

ansible 主配置文件

Ansible 的配置文件可以放在多个不同地方,优先级从高到低顺序如下

ANSIBLE_CONFIG   #环境变量
./ansible.cfg    #当前目录下的ansible.cfg
~/.ansible.cfg   #当前用户家目录下的.ansible.cfg
/etc/ansible/ansible.cfg   #系统默认配置文件

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   #默认模块,可以修改为shell模块
[privilege_escalation]   #普通用户提权配置
#become=True
#become_method=sudo
#become_user=root
#become_ask_pass=False

范例: 当前目录下的ansible的配置文件优先生效

[root@centos8 ~]# ansible --version
ansible 2.9.21
  config file = /etc/ansible/ansible.cfg  #默认的
  configured module search path = ['/root/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
  ansible python module location = /usr/lib/python3.6/site-packages/ansible
  executable location = /usr/bin/ansible
  python version = 3.6.8 (default, Nov 21 2019, 19:31:34) [GCC 8.3.1 20190507 (Red Hat 8.3.1-4)]
  
[root@centos8 ~]# cp /etc/ansible/ansible.cfg .
[root@centos8 ~]# ansible --version
ansible 2.9.21
  config file = /root/ansible.cfg  #改过的,注意配置文件路径
  configured module search path = ['/root/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
  ansible python module location = /usr/lib/python3.6/site-packages/ansible
  executable location = /usr/bin/ansible
  python version = 3.6.8 (default, Nov 21 2019, 19:31:34) [GCC 8.3.1 20190507 (Red Hat 8.3.1-4)]

inventory 主机清单文件

ansible的主要功用在于批量主机操作,为了便捷地使用其中的部分主机,可以在inventory file中将其分组命名

默认的inventory file为/etc/ansible/hosts
inventory file可以有多个,且也可以通过Dynamic Inventory来动态生成
注意: 生产建议在每个项目目录下创建项目独立的hosts文件
官方文档:

https://docs.ansible.com/ansible/latest/user_guide/intro_inventory.html
主机清单文件格式

inventory文件遵循INI文件风格,中括号中的字符为组名。可以将同一个主机同时归并到多个不同的组中

此外,当如若目标主机使用了非默认的SSH端口,还可以在主机名称之后使用冒号加端口号来标明

如果主机名称遵循相似的命名模式,还可以使用列表的方式标识各主机

Inventory 参数说明
ansible_ssh_host #将要连接的远程主机名.与你想要设定的主机的别名不同的话,可通过此变量设置.

ansible_ssh_port #ssh端口号.如果不是默认的端口号,通过此变量设置.这种可以使用 ip:端口192.168.1.100:2222

ansible_ssh_user #默认的 ssh 用户名

ansible_ssh_pass #ssh 密码(这种方式并不安全,我们强烈建议使用 --ask-pass 或 SSH 密钥)

ansible_sudo_pass #sudo 密码(这种方式并不安全,我们强烈建议使用 --ask-sudo-pass)

ansible_sudo_exe (new in version 1.8) #sudo 命令路径(适用于1.8及以上版本)

ansible_connection #与主机的连接类型.比如:local, ssh 或者 paramiko. Ansible 1.2 以前默认使用 paramiko.1.2 以后默认使用 'smart','smart' 方式会根据是否支持 ControlPersist, 来判断'ssh' 方式是否可行.

ansible_ssh_private_key_file #ssh 使用的私钥文件.适用于有多个密钥,而你不想使用 SSH 代理的
情况.

ansible_shell_type #目标系统的shell类型.默认情况下,命令的执行使用 'sh' 语法,可设置为'csh' 或 'fish'.

ansible_python_interpreter #目标主机的 python 路径.适用于的情况: 系统中有多个 Python,或者命令路径不是"/usr/bin/python",比如 *BSD, 或者 /usr/bin/python 不是 2.X 版本的Python.之所以不使用 "/usr/bin/env" 机制,因为这要求远程用户的路径设置正确,且要求 "python"可执行程序名不可为python以外的名字(实际有可能名为python26).与ansible_python_interpreter的工作方式相同,可设定如 ruby 或 perl 的路径....

范例:

ntp.longxuan.vip
[webservers]
www1.longxuan.vip:2222
www2.longxuan.vip
[dbservers]
db1.longxuan.com
db2.longxuan.com
db3.longxuan.com
#或者
db[1:3].longxuan.com

范例:组嵌套

[webservers]
www[1:100].example.com
[dbservers]
db-[a:f].example.com
[appservers]
172.31.0.[1:100]
#定义testsrvs组中包括两个其它分组,实现组嵌套
[testsrvs:children]
webservers
dbservers

范例:

[test]
172.31.0.8 ansible_connection=local #指定本地连接,无需ssh配置
#ansible_connection=ssh 需要StrictHostKeyChecking no
172.31.0.7 ansible_connection=ssh ansible_ssh_port=2222 ansible_ssh_user=wang
ansible_ssh_password=centos
172.31.0.6 ansible_connection=ssh ansible_ssh_user=root
ansible_ssh_password=123456
#执行ansible命令时显示别名,如web01
[websrvs]
web01 ansible_ssh_host=172.31.0.101
web02 ansible_ssh_host=172.31.0.102
[websrvs:vars]
ansible_ssh_password=centos
some_host ansible_ssh_port=2222 ansible_ssh_user=manager
aws_host ansible_ssh_private_key_file=/home/example/.ssh/aws.pem
freebsd_host ansible_python_interpreter=/usr/local/bin/python
ruby_module_host ansible_ruby_interpreter=/usr/bin/ruby.1.9.3

Ansible相关工具

/usr/bin/ansible           #主程序,临时命令执行工具
/usr/bin/ansible-doc       #查看配置文档,模块功能查看工具,相当于man
/usr/bin/ansible-playbook  #定制自动化任务,编排剧本工具,相当于脚本
/usr/bin/ansible-pull      #远程执行命令的工具
/usr/bin/ansible-vault     #文件加密工具
/usr/bin/ansible-console   #基于Console界面与用户交互的执行工具
/usr/bin/ansible-galaxy    #下载/上传优秀代码或Roles模块的官网平台
利用ansible实现管理的主要方式:

Ansible Ad-Hoc 即利用ansible命令,主要用于临时命令使用场景

Ansible playbook 主要用于长期规划好的,大型项目的场景,需要有前期的规划过程

ansible 使用前准备:

ansible 相关工具大多数是通过ssh协议,实现对远程主机的配置管理、应用部署、任务执行等功能
建议:使用此工具前,先配置ansible主控端能基于密钥认证的方式联系各个被管理节点

范例:利用sshpass批量实现基于key验证脚本1

[root@centos8 ~]# vim /etc/ssh/ssh_config
#修改下面一行
StrictHostKeyChecking no
[root@centos8 ~]# cat hosts.list
172.31.0.18
172.31.0.28
[root@centos8 ~]# vim push_ssh_key.sh
#!/bin/bash
rpm -q sshpass &> /dev/null || yum -y install sshpass
[ -f /root/.ssh/id_rsa ] || ssh-keygen -f /root/.ssh/id_rsa -P ''

export SSHPASS=centos
while read IP;do
sshpass -e ssh-copy-id -o StrictHostKeyChecking=no $IP
done < hosts.list

范例: 实现基于key验证的脚本2

#!/bin/bash
# Date: 2021-05-23
# Atuhro: xuanlv

IPLIST="
172.31.0.8
172.31.0.18
172.31.0.7
172.31.0.6
172.31.0.100"

rpm -q sshpass &> /dev/null || yum -y install sshpass
[ -f /root/.ssh/id_rsa ] || ssh-keygen -f /root/.ssh/id_rsa -P ''
export SSHPASS=123456
for IP in $IPLIST;do
  { sshpass -e ssh-copy-id -o StrictHostKeyChecking=no $IP; } &
done
wait

ansible-doc

此工具用来显示模块帮助,相当于man

格式:

ansible-doc [options] [module...]
-l, --list    #列出可用模块
-s, --snippet #显示指定模块的playbook片段

范例: 查看帮助

[root@centos8 ~]# ansible-doc --help
usage: ansible-doc [-h] [--version] [-v] [-M MODULE_PATH]
                   [--playbook-dir BASEDIR]
                   [-t {become,cache,callback,cliconf,connection,httpapi,inventory,lookup,netconf,shell,module,strategy,vars}]
                   [-j] [-F | -l | -s | --metadata-dump]
                   [plugin [plugin ...]]

plugin documentation tool

positional arguments:
  plugin                Plugin

optional arguments:
  --metadata-dump       **For internal testing only** Dump json metadata for
                        all plugins.
  --playbook-dir BASEDIR
                        Since this tool does not use playbooks, use this as a
                        substitute playbook directory.This sets the relative
                        path for many features including roles/ group_vars/
                        etc.
  --version             show program's version number, config file location,
                        configured module search path, module location,
                        executable location and exit
  -F, --list_files      Show plugin names and their source files without
                        summaries (implies --list)
  -M MODULE_PATH, --module-path MODULE_PATH
                        prepend colon-separated path(s) to module library (def
                        ault=~/.ansible/plugins/modules:/usr/share/ansible/plu
                        gins/modules)
  -h, --help            show this help message and exit
  -j, --json            Change output into json format.
  -l, --list            List available plugins
  -s, --snippet         Show playbook snippet for specified plugin(s)
  -t {become,cache,callback,cliconf,connection,httpapi,inventory,lookup,netconf,shell,module,strategy,vars}, --type {become,cache,callback,cliconf,connection,httpapi,inventory,lookup,netconf,shell,module,strategy,vars}
                        Choose which plugin type (defaults to "module").
                        Available plugin types are : ('become', 'cache',
                        'callback', 'cliconf', 'connection', 'httpapi',
                        'inventory', 'lookup', 'netconf', 'shell', 'module',
                        'strategy', 'vars')
  -v, --verbose         verbose mode (-vvv for more, -vvvv to enable
                        connection debugging)

See man pages for Ansible CLI options or website for tutorials
https://docs.ansible.com

范例:

#列出所有模块
[root@centos8 ~]# ansible-doc -l
#查看指定模块帮助用法
[root@centos8 ~]# ansible-doc ping
#查看指定模块帮助用法
[root@centos8 ~]# ansible-doc -s ping

范例: 查看指定的插件

[root@centos8 ~]# ansible-doc -t connection -l
[root@centos8 ~]# [root@centos8 ~]# ansible-doc -t lookup -l

ansible

格式:

ansible <host-pattern> [-m module_name] [-a args]

选项说明:

--version #显示版本
-m module #指定模块,默认为command
-v #详细过程 -vv -vvv更详细
--list-hosts #显示主机列表,可简写 --list
-C, --check #检查,并不执行
-T, --timeout=TIMEOUT #执行命令的超时时间,默认10s
-k, --ask-pass #提示输入ssh连接密码,默认Key验证
-u, --user=REMOTE_USER #执行远程执行的用户,默认root
-b, --become #代替旧版的sudo 切换
--become-user=USERNAME #指定sudo的runas用户,默认为root
-K, --ask-become-pass #提示输入sudo时的口令
-f FORKS, --forks FORKS #指定并发同时执行ansible任务的主机数

范例: 将普通用户提升权限

#先在被控制端sudo授权
[root@centos8 ~]# grep long /etc/sudoers
wang ALL=(ALL) NOPASSWD: ALL
#以wang的用户连接用户,并利用sudo代表mage执行whoami命令
[root@ansible ~]# ansible 172.31.0.8 -m shell -a 'whoami' -u long -k -b --becomeuser=centos

SSH password: #输入远程主机wang用户ssh连接密码
172.31.0.8 | CHANGED | rc=0 >> centos

ansible的Host-pattern
用于匹配被控制的主机的列表
All :表示所有Inventory中的所有主机

范例:

[root@centos8 ~]# ansible all -m ping

*:通配符

[root@centos8 ~]# ansible "*" -m ping
[root@centos8 ~]# ansible 192.168.1.* -m ping
[root@centos8 ~]# ansible "srvs" -m ping
[root@centos8 ~]# ansible "172.31.0.6 172.31.0.7" -m ping

或关系

[root@centos8 ~]# ansible "websrvs:appsrvs" -m ping
[root@centos8 ~]# ansible "192.168.1.10:192.168.1.20" -m ping

逻辑与

#在websrvs组并且在dbsrvs组中的主机
[root@centos8 ~]# ansible "websrvs:&dbsrvs" -m ping

逻辑非

#在websrvs组,但不在dbsrvs组中的主机
#注意:此处为单引号
[root@centos8 ~]# ansible 'websrvs:!dbsrvs' -m ping

综合逻辑

[root@centos8 ~]# ansible 'websrvs:dbsrvs:&appsrvs:!ftpsrvs' -m ping

正则表达式

[root@centos8 ~]# ansible "websrvs:dbsrvs" -m ping
[root@centos8 ~]# ansible "~(web|db).*.longxuan.com" -m ping

范例:先重启所有kube和etcd开头的机器,然后再重启本机172.31

[root@kube-master1 ~]# ansible 'kube*:etcd:!172.31.0.101' -a reboot && reboot

范例:

[root@centos8 ~]# ansible all --list-hosts
hosts (3):
10.0.0.6
10.0.0.7
10.0.0.8
[root@centos8 ~]# ansible websrvs --list-hosts
hosts (3):
10.0.0.6
10.0.0.7
10.0.0.8
[root@centos8 ~]# ansible appsrvs --list-hosts
hosts (2):
10.0.0.7
10.0.0.8
[root@centos8 ~]# ansible "appsrvs:dbsrvs" --list-hosts
hosts (3):
10.0.0.7
10.0.0.8
10.0.0.6
[root@centos8 ~]# ansible "dbsrvs" --list-hosts
hosts (2):
10.0.0.6
10.0.0.7
[root@centos8 ~]# ansible appsrvs --list-hosts
hosts (2):
10.0.0.7
10.0.0.8
[root@centos8 ~]# ansible "appsrvs:dbsrvs" --list-hosts
hosts (3):
10.0.0.7
10.0.0.8
10.0.0.6
[root@centos8 ~]# ansible "appsrvs:&dbsrvs" --list-hosts
hosts (1):
10.0.0.7
#引用!号时,不要用双引号,而使用单引号
[root@centos8 ~]# ansible "appsrvs:!dbsrvs" --list-hosts
-bash: !dbsrvs: event not found
[root@centos8 ~]# ansible 'appsrvs:!dbsrvs' --list-hosts
hosts (1):
10.0.0.8

范例: 并发执行控制

#分别执行下面两条命令观察结果
[root@ansible ~]# ansible websrvs -a 'sleep 5' -f10
[root@ansible ~]# ansible websrvs -a 'sleep 5' -f1
ansible命令执行过程
  1. 加载自己的配置文件,默认/etc/ansible/ansible.cfg
  2. 加载自己对应的模块文件,如:command
  3. 通过ansible将模块或命令生成对应的临时py文件,并将该文件传输至远程服务器的对应执行用户 $HOME/.ansible/tmp/ansible-tmp-数字/YYY.py文件
  4. 给文件+x执行
  5. 执行并返回结果
  6. 删除临时py文件,退出
ansible 的执行状态:
[root@centos8 ~]# grep -A 14 '[colors]' /etc/ansible/ansible.cfg
[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

绿色:执行成功并且不需要做改变的操作

黄色:执行成功并且对目标主机做变更

红色:执行失败

ansible使用范例

#以wang用户执行ping存活检测
[root@centos8 ~]# ansible all -m ping -u wang -k
#以wang sudo至root执行ping存活检测
[root@centos8 ~]# ansible all -m ping -u wang -k -b
#以longwang sudo至long用户执行ping存活检测
[root@centos8 ~]# ansible all -m ping -u longwang -k -b --become-user=long
#以long sudo至root用户执行ls
[root@centos8 ~]# ansible all -m command -u long -a 'ls /root' -b --become-user=root -k -K

ansible-console

此工具可交互执行命令,支持tab,ansible 2.0+新增

提示符格式:

执行用户@当前操作的主机组 (当前组的主机数量)[f:并发数]$

常用子命令:

设置并发数: forks n 例如: forks 10
切换组: cd 主机组 例如: cd web
列出当前组主机列表: list
列出所有的内置命令: ?或help

范例:

[root@ansible ~]# ansible-console
Welcome to the ansible console.
Type help or ? to list commands.
root@all (3)[f:5]$ ping
172.31.0.7 | SUCCESS => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false,
"ping": "pong"
}
172.31.0.6 | SUCCESS => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false,
"ping": "pong"
}
172.31.0.8 | SUCCESS => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/libexec/platform-python"
},
"changed": false,
"ping": "pong"
}

root@all (3)[f:5]$ list
172.31.0.8
172.31.0.7
172.31.0.6
root@all (3)[f:5]$ cd websrvs
root@websrvs (2)[f:5]$ list
172.31.0.7
172.31.0.8
root@websrvs (2)[f:5]$ forks 10
root@websrvs (2)[f:10]$ cd appsrvs
root@appsrvs (2)[f:5]$ yum name=httpd state=present
root@appsrvs (2)[f:5]$ service name=httpd state=started

ansible-playbook

此工具用于执行编写好的 playbook 任务

范例

[root@ansible ~]# ansible-playbook hello.yml
cat hello.yml
---
#hello world yml file
- hosts: websrvs
  remote_user: root
  gather_facts: no
  tasks:
    - name: hello world
      command: /usr/bin/wall hello world

ansible-vault

此工具可以用于加密解密yml文件

格式:

ansible-vault [create|decrypt|edit|encrypt|rekey|view]

范例

[root@ansible ~]# ansible-vault encrypt hello.yml  #加密
[root@ansible ~]# ansible-vault decrypt hello.yml  #解密
[root@ansible ~]# ansible-vault view hello.yml     #查看
[root@ansible ~]# ansible-vault edit hello.yml     #编辑加密文件
[root@ansible ~]# ansible-vault rekey hello.yml    #修改口令
[root@ansible ~]# ansible-vault create new.yml     #创建新文件

ansible-galaxy

Galaxy 是一个免费网站,类似于github网站,网站上发布了很多的共享的roles角色。Ansible提供了ansible-galaxy命令行工具连接 https://galaxy.ansible.com 网站下载相应的roles, 进行
init(初始化、search(查拘、install(安装、remove(移除)等操作。
范例:

# 搜索项目
[root@ansible ~]# ansible-galaxy search lamp
# 列出所有已安装的galaxy
[root@ansible ~]# ansible-galaxy list
# 安装galaxy,默认下载到~/.ansible/roles下
[root@ansible ~]# ansible-galaxy install geerlingguy.mysql
[root@ansible ~]# ansible-galaxy install geerlingguy.redis
# 删除galaxy
[root@ansible ~]# ansible-galaxy remove geerlingguy.redis

免密登陆脚本

#!/bin/bash
#
#*********************************************
#Author:            xuanlv
#Description:      基于key验证多主机ssh访问
#Date:              2021-05-20
#*********************************************

PASS=123456
#设置网段最后的地址,4-255之间,越小扫描越快
END=254

IP=`ip a s eth0 | awk -F'[ /]+' 'NR==3{print $3}'`
NET=${IP%.*}.

rm -f /root/.ssh/id_rsa
[ -e ./SCANIP.log ] && rm -f SCANIP.log
for((i=3;i<="$END";i++));do
ping -c 1 -w 1  ${NET}$i &> /dev/null  && echo "${NET}$i" >> SCANIP.log &
done
wait

ssh-keygen -P "" -f /root/.ssh/id_rsa
rpm -q sshpass || yum -y install sshpass
sshpass -p $PASS ssh-copy-id -o StrictHostKeyChecking=no $IP 

AliveIP=(`cat SCANIP.log`)
for n in ${AliveIP[*]};do
sshpass -p $PASS scp -o StrictHostKeyChecking=no -r /root/.ssh root@${n}:
done

#把.ssh/known_hosts拷贝到所有主机,使它们第一次互相访问时不需要输入回车
for n in ${AliveIP[*]};do
scp /root/.ssh/known_hosts ${n}:.ssh/
done
原文地址:https://www.cnblogs.com/xuanlv-0413/p/14806581.html