Ansible
1. ansible 相关文件
1.1 ansible配置文件
- /etc/ansible/ansible.cfg 主配置文件,配置ansible工作特性
- /etc/ansible/hosts 主机清单
- /etc/ansible/roles/ 存放角色的目录
1.1.1 ansible主配置文件
- Ansible 的配置文件/etc/ansible/ansible.cfg,其中大部分的配置内容无需进行修改
[root@hostserver ansible]#vim /etc/ansible/ansible.cfg
# config file for ansible -- https://ansible.com/
# ===============================================
# nearly all parameters can be overridden in ansible-playbook
# or with command line flags. ansible will read ANSIBLE_CONFIG,
# ansible.cfg in the current working directory, .ansible.cfg in
# the home directory or /etc/ansible/ansible.cfg, whichever it
# finds first
[defaults]
# some basic default values...
#inventory = /etc/ansible/hosts # 主机列表配置文件
#library = /usr/share/my_modules/ # 库文件存放目录
#module_utils = /usr/share/my_module_utils/
#remote_tmp = ~/.ansible/tmp #临时py命令文件存放在远程主机目录
#local_tmp = ~/.ansible/tmp # 本机的临时命令执行目录
#plugin_filters_cfg = /etc/ansible/plugin_filters.yml
#forks = 5 # 默认并发数
#poll_interval = 15
#sudo_user = root
#ask_sudo_pass = True #每次执行ansible命令是否询问ssh密码
#ask_pass = True
#transport = smart
#remote_port = 22
#module_lang = C
#module_set_locale = False
# uncomment this to disable SSH key host checking
host_key_checking = False # 检查对应服务器的host_key,建议取消注释
# logging is off by default unless this path is defined
# if so defined, consider logrotate
log_path = /var/log/ansible.log #日志文件,建议启用
# default module name for /usr/bin/ansible
module_name = shell #默认模块,可以修改为shell模块 已修改为了shell
1.1.2 inventory 主机清单
- ansible的主要功用在于批量主机操作,为了便捷地使用其中的部分主机,可以在inventory file中将其分组命名
- 默认的inventory file为/etc/ansible/hosts
- inventory file可以有多个,且也可以通过Dynamic Inventory来动态生成
- 主机清单文件格式
inventory文件遵循INI文件风格,中括号中的字符为组名。可以将同一个主机同时归并到多个不同的组中
此外,当如若目标主机使用了非默认的SSH端口,还可以在主机名称之后使用冒号加端口号来标明
如果主机名称遵循相似的命名模式,还可以使用列表的方式标识各主机
范例:
[root@hostserver ansible]# vim /etc/ansible/hosts
# This is the default ansible 'hosts' file.
#
# It should live in /etc/ansible/hosts
#
# - Comments begin with the '#' character
# - Blank lines are ignored
# - Groups of hosts are delimited by [header] elements
# - You can enter hostnames or ip addresses
# - A hostname/ip can be a member of multiple groups
# This is the default ansible 'hosts' file.
#
# It should live in /etc/ansible/hosts
#
# - Comments begin with the '#' character
# - Blank lines are ignored
# - Groups of hosts are delimited by [header] elements
# - You can enter hostnames or ip addresses
# - A hostname/ip can be a member of multiple groups
# Ex 1: Ungrouped hosts, specify before any group headers.
## green.example.com
## blue.example.com
## 192.168.100.1
## 192.168.100.10
# Ex 2: A collection of hosts belonging to the 'webservers' group
## [webservers]
## alpha.example.org
## beta.example.org
## 192.168.1.100
## 192.168.1.110
# If you have multiple hosts following a pattern you can specify
# them like this:
## www[001:006].example.com
# Ex 3: A collection of database servers in the 'dbservers' group
## [dbservers]
##
## db01.intranet.mydomain.net
## db02.intranet.mydomain.net
## 10.25.1.56
## 10.25.1.57
# Here's another example of host ranges, this time there are no
# leading 0s:
## db-[99:101]-node.example.com
[websrvs] # 这里为自己添加的被管理主机
192.168.66.18
[dbsrvs] # 这里为自己添加的被管理主机
192.168.66.28
1.1.3 ansible相关工具
+ /usr/bin/ansible #主程序,临时命令执行工具
+ /usr/bin/ansible-doc #查看配置文档,模块功能查看工具
+ /usr/bin/ansible-galaxy #下载/上传优秀代码或Roles模块的官网平台
+ /usr/bin/ansible-playbook #定制自动化任务,编排剧本工具
+ /usr/bin/ansible-pull #远程执行命令的工具
+ /usr/bin/ansible-vault #文件加密工具
+ /usr/bin/ansible-console #基于Console界面与用户交互的执行工具
利用ansible实现管理的主要方式:
- Ad-Hoc 即利用ansible命令,主要用于临时命令使用场景
- Ansible-playbook 主要用于长期规划好的,大型项目的场景,需要有前期的规划过程
1.1.3.1 ansible-doc
此工具用来显示模块帮助
格式:ansible-doc [options] [module...]
-l, --list #列出可用模块
-s, --snippet #显示指定模块的playbook片段
范例:
#列出所有模块
ansible-doc -l
#查看指定模块帮助用法
ansible-doc ping
#查看指定模块帮助用法
ansible-doc -s ping
1.1.3.2 ansible
此工具通过ssh协议,实现对远程主机的配置管理、应用部署、任务执行等功能
建议:使用此工具前,先配置ansible主控端能基于密钥认证的方式联系各个被管理节点
范例:利用sshpass批量实现基于key验证
ssh-keygen -f /root/.ssh/id_rsa -P ''
NET=192.168.100
export SSHPASS=centos
for IP in {1..200};do
sshpass -e ssh-copy-id $NET.$IP
done
格式:ansible <host-pattern> [-m module_name] [-a args]
选项说明:
--version #显示版本
-m module #指定模块,默认为command
-v #详细过程 –vv -vvv更详细
--list-hosts #显示主机列表,可简写 --list
-k, --ask-pass #提示输入ssh连接密码,默认Key验证
-C, --check #检查,并不执行
-T, --timeout=TIMEOUT #执行命令的超时时间,默认10s
-u, --user=REMOTE_USER #执行远程执行的用户
-b, --become #代替旧版的sudo 切换
--become-user=USERNAME #指定sudo的runas用户,默认为root
-K, --ask-become-pass #提示输入sudo时的口令
ansible的Host-pattern
用于匹配被控制的主机的列表
All :表示所有Inventory中的所有主机
范例:
ansible all –m ping
# *:通配符
ansible “*” -m ping
ansible 192.168.1.* -m ping
ansible “srvs” -m ping
# 或关系
ansible “websrvs:appsrvs” -m ping
ansible “192.168.66.8:192.168.66.18” -m ping
逻辑与
#在websrvs组并且在dbsrvs组中的主机
ansible “websrvs:&dbsrvs” –m ping
逻辑非
#在websrvs组,但不在dbsrvs组中的主机
#注意:此处为单引号
ansible ‘websrvs:!dbsrvs’ –m ping
综合逻辑
ansible ‘websrvs:dbsrvs:&appsrvs:!ftpsrvs’ –m ping
正则表达式
ansible “websrvs:&dbsrvs” –m ping
ansible “~(web|db).*\.centos\.com” –m ping
ansible命令执行过程
- 加载自己的配置文件 默认/etc/ansible/ansible.cfg
- 加载自己对应的模块文件,如:command
- 通过ansible将模块或命令生成对应的临时py文件,并将该文件传输至远程服务器的对应执行用户
$HOME/.ansible/tmp/ansible-tmp-数字/XXX.PY文件 - 给文件+x执行
- 执行并返回结果
- 删除临时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
**1 绿色:执行成功并且不需要做改变的操作**
**2 黄色:执行成功并且对目标主机做变更**
**3 红色:执行失败**
ansible使用范例
#以wang用户执行ping存活检测
ansible all -m ping -u wang -k
#以wang sudo至root执行ping存活检测
ansible all -m ping -u wang -k -b
#以wang sudo至mage用户执行ping存活检测
ansible all -m ping -u wang -k -b --become-user=mage
#以wang sudo至root用户执行ls
ansible all -m command -u wang -a 'ls /root' -b --become-user=root -k -K
1.1.3.3 ansible-galaxy
此工具会连接 https://galaxy.ansible.com 下载相应的roles
范例:
#列出所有已安装的galaxy
ansible-galaxy list
#安装galaxy
ansible-galaxy install geerlingguy.redis
#删除galaxy
ansible-galaxy remove geerlingguy.redis
1.1.3.4 ansible-pull
此工具会推送ansible的命令至远程,效率无限提升,对运维要求较高
1.1.3.5 ansible-playbook
重点内容
- 此工具用于执行编写好的playbook任务
ansible-playbook hello.yml
cat hello.yml
---
#hello world yml file
- hosts: websrvs
remote_user: root
tasks:
- name: hello world
command: /usr/bin/wall hello world
2. ansible常用模块 #重点关注项
- 常用模块帮助文档参考:https://docs.ansible.com/ansible/latest/modules/modules_by_category.html
2.1.1 Command 模块
- 功能:在远程主机执行命令,此为默认模块,可忽略-m选项
- **注意:此命令不支持 $VARNAME < > | ; & 等,用shell模块实现
- 范例:**
ansible srvs -m command -a ‘service vsftpd start’
ansible srvs -m command -a ‘echo magedu |passwd --stdin centos’
2.1.2 Shell模块
- 功能:和command相似,用shell执行命令
- 范例:
ansible srv -m shell -a ‘echo magedu |passwd --stdin centos’
- 注意:调用bash执行命令 类似 cat /tmp/test.md | awk -F‘|’ ‘{print $1,$2}’ &> /tmp/example.txt 这些复杂命令,即使使用shell也可能会失败,解决办法:写到脚本时,copy到远程,执行,再把需要的结果拉回执行命令的机器
2.1.3 Script模块
- 功能::在远程主机上运行ansible服务器上的脚本
- 范例:
ansible websrvs -m script -a /data/test.sh #引用脚本
2.1.4 Copy模块
- 功能:从ansible服务器主控端复制文件到远程主机
#如目标存在,默认覆盖,此处指定先备份
ansible srv -m copy -a “src=/root/test1.sh dest=/tmp/test2.sh owner=wang
mode=600 backup=yes”
#指定内容,直接生成目标文件
ansible srv -m copy -a “content='testcontent\n'dest=/tmp/test.txt”
#复制/etc/下的文件,不包括/etc/目录自身
ansible srv -m copy -a “src=/etc/ dest=/backup”
2.1.5 Fetch模块
- 功能:从远程主机提取文件至ansible的主控端,copy相反,目前不支持目录
- 范例:
ansible srv -m fetch -a ‘src=/root/test.sh dest=/data/scripts’
2.1.6 File模块
- 功能:设置文件属性
- 范例:
#创建空文件
ansible srv -m file -a 'path=/data/test.txt state=touch'
ansible srv -m file -a 'path=/data/test.txt state=absent'
ansible srv -m file -a "path=/root/test.sh owner=wang mode=755“
#创建目录
ansible srv -m file -a "path=/data/mysql state=directory owner=mysql
group=mysql"
#创建软链接
ansible srv -m file -a ‘src=/data/testfile dest=/data/testfile-link state=link’
2.1.7 unarchive模块
- 功能:解包解压缩
- 实现有两种用法:
1、将ansible主机上的压缩包传到远程主机后解压缩至特定目录,设置copy=yes
2、将远程主机上的某个压缩包解压缩到指定路径下,设置copy=no - 常见参数:
- copy:默认为yes,当copy=yes,拷贝的文件是从ansible主机复制到远程主机上,如果设置为copy=no,会在远程主机上寻找src源文件
- remote_src:和copy功能一样且互斥,yes表示在远程主机,不在ansible主机,no表示文件在ansible主机上
- src:源路径,可以是ansible主机上的路径,也可以是远程主机上的路径,如果是远程主机上的路径,则需要设置copy=no
- dest:远程主机上的目标路径
- mode:设置解压缩后的文件权限
- 范例:
ansible srv -m unarchive -a 'src=/data/foo.tgz dest=/var/lib/foo'
ansible srv -m unarchive -a 'src=/tmp/foo.zip dest=/data copy=no mode=0777'
ansible srv -m unarchive -a 'src=https://example.com/example.zip dest=/data
copy=no'
2.1.8 Archive模块
- 功能:打包压缩
- 范例:
ansible websrvs -m archive -a 'path=/var/log/ dest=/data/log.tar.bz2 format=bz2
owner=wang mode=0600'
2.1.9 Hostname模块
- 功能:管理主机名
- 范例:
ansible node1 -m hostname -a “name=websrv”
ansible 192.168.66.18 -m hostname -a 'name=dbsrvs'
2.1.10 Cron模块
- 功能:计划任务
- 支持时间:minute,hour,day,month,weekday
- 范例:
#备份数据库脚本
[root@centos8 ~]#cat mysql_backup.sh
mysqldump -A -F --single-transaction --master-data=2 -q -uroot |gzip >
/data/mysql_`date +%F_%T`.sql.gz
#创建任务
ansible 192.168.39.28 -m cron -a 'hour=2 minute=30 weekday=1-5 name="backup
mysql" job=/root/mysql_backup.sh'
ansible srv -m cron -a "minute=*/5 job='/usr/sbin/ntpdate 172.20.0.1
&>/dev/null' name=Synctime"
#禁用计划任务
ansible srv -m cron -a "minute=*/5 job='/usr/sbin/ntpdate 172.20.0.1
&>/dev/null' name=Synctime disabled=yes"
#启用计划任务
ansible srv -m cron -a "minute=*/5 job='/usr/sbin/ntpdate 172.20.0.1
&>/dev/null' name=Synctime disabled=no"
#删除任务
ansible srv -m cron -a "name='backup mysql' state=absent"
ansible srv -m cron -a ‘state=absent name=Synctime
2.1.11 Yum模块
- 功能:管理软件包
- 范例:
ansible srv -m yum -a 'name=httpd state=present'#安装
ansible srv -m yum -a 'name=httpd state=absent'#删除
2.1.12 Service模块
- 功能:管理服务
- 范例:
ansible srv -m service -a 'name=httpd state=started enabled=yes'
ansible srv -m service -a 'name=httpd state=stopped'
ansible srv -m service -a 'name=httpd state=reloaded’
ansible srv -m shell -a "sed -i 's/^Listen 80/Listen 8080/'
/etc/httpd/conf/httpd.conf"
ansible srv -m service -a 'name=httpd state=restarted'
2.1.13 User模块
- 功能:管理用户
- 范例:
#创建用户
ansible srv -m user -a 'name=user1 comment=“test user” uid=2048 home=/app/user1
group=root‘
ansible srv -m user -a 'name=nginx comment=nginx uid=88 group=nginx
groups="root,daemon" shell=/sbin/nologin system=yes create_home=no
home=/data/nginx non_unique=yes'
#删除用户及家目录等数据
ansible srv -m user -a 'name=nginx state=absent remove=yes'
2.1.14 Group模块
- 功能:管理组
- 范例:
#创建组
ansible websrvs -m group -a 'name=nginx gid=88 system=yes'
#删除组
ansible websrvs -m group -a 'name=nginx state=absent'
2.1.15 Setup模块
- 功能:返回系统状态信息
- 范例:
ansible srv -m setup
ansible srv -m setup -a "filter=ansible_nodename"
ansible srv -m setup -a "filter=ansible_hostname"
ansible srv -m setup -a "filter=ansible_domain"
ansible srv -m setup -a "filter=ansible_memtotal_mb"
ansible srv -m setup -a "filter=ansible_memory_mb"
ansible srv -m setup -a "filter=ansible_memfree_mb"
ansible srv -m setup -a "filter=ansible_os_family"
ansible srv -m setup -a "filter=ansible_distribution_major_version"
ansible srv -m setup -a "filter=ansible_distribution_version"
ansible srv -m setup -a "filter=ansible_processor_vcpus"
ansible srv -m setup -a "filter=ansible_all_ipv4_addresses"
ansible srv -m setup -a "filter=ansible_architecture"