Ansible - 自动化配置管理工具详解
1 - 配置管理基础
配置管理工具(SCM,Software Configuration Management)用于保存代码、软件方式实现的基础设施配置信息,并能根据需求变化进行反复变更。 此类工具包括Ansible、Chef、Puppet、SaltStack等,版本管理工具有Git、Subversion等。 配置管理工具具有以下特点:
- 声明式:通过配置信息明确描述目标状态并管理该状态;形式简单、易于理解;
- 抽象化:配置信息能涵盖细微的环境差异,无需针对不同环境编写不同配置,消除代码执行时的特殊性;
- 收敛性:无论目标对象当前状态如何,最终都会变为指定的期望状态
- 幂等性:无论执行多少次都能得到相同的结果
- 高效便捷:配置信息轻量,易于传输,可提高审查速度,能够快速回滚到上一个版本;开源;可通过自动化进行快速设置;
2 - Ansible概述
Ansible是基于Python语言开发的开源自动化运维工具,集合了多种运维工具的优点,实现了批量配置管理、应用部署和命令执行等功能。 Ansible通过SSH与远程主机通信,无需在远程主机上安装客户端/代理。 其配置语法简单,命令简洁,易于学习。 Ansible本身仅提供框架,实际批量部署能力依赖于其运行的模块。主要包括:
- 连接插件(connection plugins):负责与被管理端实现通信
- 主机清单(host inventory):指定操作的主机,是在配置文件中定义的管理主机列表
- 各种模块:核心模块、命令模块、自定义模块等
- 插件系统:用于实现日志记录、邮件通知等功能
- playbook:剧本,可让节点一次性运行多个任务
- 容器管理:具备管理Docker容器的功能
Ansible资源
- 官方网站:https://www.ansible.com/
- Ansible中文权威指南:http://ansible.com.cn/
- Ansible自动化运维教程:https://www.w3cschool.cn/automate_with_ansible/
3 - Ansible安装
安装过程简单,例如在CentOS 7中安装Ansible只需执行以下命令:
yum -y install epel-release
yum -y install ansible
3.1 Ansible命令参数
[root@server ~]# ansible
usage: ansible [-h] [--version] [-v] [-b] [--become-method BECOME_METHOD]
[--become-user BECOME_USER] [-K] [-i INVENTORY] [--list-hosts]
[-l SUBSET] [-P POLL_INTERVAL] [-B SECONDS] [-o] [-t TREE] [-k]
[--private-key PRIVATE_KEY_FILE] [-u REMOTE_USER]
[-c CONNECTION] [-T TIMEOUT]
[--ssh-common-args SSH_COMMON_ARGS]
[--sftp-extra-args SFTP_EXTRA_ARGS]
[--scp-extra-args SCP_EXTRA_ARGS]
[--ssh-extra-args SSH_EXTRA_ARGS] [-C] [--syntax-check] [-D]
[-e EXTRA_VARS] [--vault-id VAULT_IDS]
[--ask-vault-pass | --vault-password-file VAULT_PASSWORD_FILES]
[-f FORKS] [-M MODULE_PATH] [--playbook-dir BASEDIR]
[-a MODULE_ARGS] [-m MODULE_NAME]
pattern
ansible: error: too few arguments
[root@server ~]# ansible --version
ansible 2.9.0
config file = /etc/ansible/ansible.cfg
configured module search path = [u'/root/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
ansible python module location = /usr/lib/python2.7/site-packages/ansible
executable location = /bin/ansible
python version = 2.7.5 (default, Apr 11 2018, 07:36:10) [GCC 4.8.5-20150623 (Red Hat 4.8.5-28)]
[root@server ~]# ll /etc/ansible/
total 24
-rw-r--r-- 1 root root 19985 Nov 9 05:11 ansible.cfg
-rw-r--r-- 1 root root 1016 Nov 9 05:11 hosts
drwxr-xr-x 2 root root 6 Nov 9 05:11 roles
3.2 Inventory文件
默认的Inventory文件是"/etc/ansible/hosts",它定义了Ansible进行远程控制的服务器列表。 运行时也可使用-i参数指定其他文件作为Inventory文件。
[root@server ~]# echo "localhost" >> /etc/ansible/hosts
4 - Ansible实践示例
4.1 安装并启动Nginx
# yum -y install epel-release
# yum -y install nginx
# echo "hello, Nginx" > /usr/share/nginx/html/index.html
# systemctl start nginx
[root@server ~]# systemctl status nginx
● nginx.service - The nginx HTTP and reverse proxy server
Loaded: loaded (/usr/lib/systemd/system/nginx.service; disabled; vendor preset: disabled)
Active: active (running) since Tue 2019-11-19 16:54:56 CST; 7min ago
Process: 6752 ExecStart=/usr/sbin/nginx (code=exited, status=0/SUCCESS)
Process: 6749 ExecStartPre=/usr/sbin/nginx -t (code=exited, status=0/SUCCESS)
Process: 6747 ExecStartPre=/usr/bin/rm -f /run/nginx.pid (code=exited, status=0/SUCCESS)
Main PID: 6754 (nginx)
Tasks: 3
CGroup: /system.slice/nginx.service
├─6754 nginx: master process /usr/sbin/nginx
├─6755 nginx: worker process
└─6756 nginx: worker process
Nov 19 16:54:56 server systemd[1]: Starting The nginx HTTP and reverse proxy server...
Nov 19 16:54:56 server nginx[6749]: nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
Nov 19 16:54:56 server nginx[6749]: nginx: configuration file /etc/nginx/nginx.conf test is successful
Nov 19 16:54:56 server systemd[1]: Started The nginx HTTP and reverse proxy server.
4.2 示例 - 启动已运行的Nginx服务
[root@server ~]# ansible localhost -b -c local -m service -a "name=nginx state=started"
localhost | SUCCESS => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false,
"name": "nginx",
"state": "started",
"status": {
"ActiveEnterTimestamp": "Tue 2019-11-19 17:08:33 CST",
"ActiveEnterTimestampMonotonic": "8773946590",
"ActiveExitTimestampMonotonic": "0",
"ActiveState": "active",
"MainPID": "6754",
"Status": "running"
}
}
4.3 示例 - 启动未运行的Nginx服务
[root@server ~]# systemctl stop nginx
[root@server ~]# ansible localhost -b -c local -m service -a "name=nginx state=started"
localhost | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"name": "nginx",
"state": "started",
"status": {
"ActiveEnterTimestampMonotonic": "0",
"ActiveExitTimestampMonotonic": "0",
"ActiveState": "inactive",
"MainPID": "0",
"Status": "stopped"
}
}
5 - Ansible Playbook详解
5.1 Playbook简介
使用ansible-playbook命令能够以分组的方式处理或操作对象,执行从安装、配置到启动等一系列操作。 这些操作必须提前定义在playbook文件中,然后通过指定playbook文件自动开始执行。
- playbook文件(YAML格式,后缀名为.yml)指定角色(roles)
- roles目录中的tasks具体定义一系列操作
- group_vars目录和roles下的templates目录为不同环境设置变量值
命令参数
通过ansible-playbook -h可以查看相关参数
检查模式(Check Mode)
用于预先验证要做的更改操作是否与预期一致。 在此模式下,Ansible不会真正在实际环境中执行更改,而是显示在实际执行时哪些内容会被更改。 具体使用方法是同时使用"--check"和"--diff"选项,表示以检查模式运行并显示详细的变更内容。
5.2 示例项目结构
示例项目下载:https://github.com/devops-book/ansible-playbook-sample
[root@server ansible-playbook-sample]# ll
total 12
-rw-r--r-- 1 root root 81 Nov 19 17:25 development
drwxr-xr-x 2 root root 73 Nov 19 17:25 group_vars
-rw-r--r-- 1 root root 79 Nov 19 17:25 production
drwxr-xr-x 7 root root 91 Nov 19 17:25 roles
-rw-r--r-- 1 root root 150 Nov 19 17:25 site.yml
5.3 示例 - 构建开发环境
[root@server ansible-playbook-sample]# cat development
[development-webservers]
localhost
[webservers:children]
development-webservers
[root@server ansible-playbook-sample]# ansible-playbook -i development site.yml
PLAY [webservers] **************************************************************************************************
TASK [Gathering Facts] *********************************************************************************************
ok: [localhost]
TASK [common : install epel] ***************************************************************************************
ok: [localhost]
TASK [nginx : install nginx] ***************************************************************************************
ok: [localhost]
TASK [nginx : replace index.html] **********************************************************************************
changed: [localhost]
TASK [nginx : nginx start] *****************************************************************************************
changed: [localhost]
PLAY RECAP *********************************************************************************************************
localhost : ok=5 changed=2 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
5.4 示例 - 构建生产环境
[root@server ansible-playbook-sample]# cat production
[production-webservers]
localhost
[webservers:children]
production-webservers
[root@server ansible-playbook-sample]# ansible-playbook -i production site.yml
PLAY [webservers] *****************************************************************************************
TASK [Gathering Facts] ************************************************************************************
ok: [localhost]
TASK [common : install epel] ******************************************************************************
ok: [localhost]
TASK [nginx : install nginx] ******************************************************************************
ok: [localhost]
TASK [nginx : replace index.html] *************************************************************************
changed: [localhost]
TASK [nginx : nginx start] ********************************************************************************
ok: [localhost]
PLAY RECAP *********************************************************************************************************************************************************************************************************************************
localhost : ok=5 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
6 - Ansible高级应用
- 核心模块:Ansible功能的实现依赖于各种核心模块
- 标签(Tags):只执行指定的任务
- 动态清单(Dynamic Inventory):从外部动态获取主机列表
- Ansible Galaxy:从网络获取并使用roles
- Ansible Tower:基于Web的仪表板及REST API接口,用于管理Ansible操作