第十六节
创建及使用角色
在日常编写剧本时,会存在剧本越来越长的情况,这不利于进行阅读和维护,而且还无法让其他剧本灵活地调用其中的功能代码。角色(role)这一功能则是自Ansible 1.2版本开始引入的新特性,用于层次性、结构化地组织剧本。角色功能分别把变量、文件、任务、模块及处理器配置放在各个独立的目录中,然后对其进行便捷加载。简单来说,角色功能是把常用的一些功能“类模块化”,然后在用的时候加载即可。
角色的获取有3种方法,分别是加载系统内置角色、从外部环境获取角色以及自行创建角色。
系统内置角色
系统内置角色是由系统镜像自带的角色,它们在日常的工作中能派上大用场。
安装系统内置角色
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
[root@linuxprobe ~]# <strong>dnf install -y rhel-system-roles</strong>Updating Subscription Management repositories.Unable to read consumer identityThis system is not registered to Red Hat Subscription Management. You can use subscription-manager to register.Last metadata expiration check: 1:06:26 ago on Tue 13 Apr 2021 07:22:03 AM CST.Dependencies resolved.================================================================================ Package Arch Version Repository Size================================================================================Installing: rhel-system-roles noarch 1.0-5.el8 AppStream 127 kTransaction Summary================================================================================Install 1 Package………………省略部分输出信息……………… Installed: rhel-system-roles-1.0-5.el8.noarch Complete! |
查看系统内置角色
ansible-galaxy list命令查看系统中有哪些自带的角色可用。
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
[root@linuxprobe ~]# ansible-galaxy list# /usr/share/ansible/roles- linux-system-roles.kdump, (unknown version)- linux-system-roles.network, (unknown version)- linux-system-roles.postfix, (unknown version)- linux-system-roles.selinux, (unknown version)- linux-system-roles.timesync, (unknown version)- rhel-system-roles.kdump, (unknown version)- rhel-system-roles.network, (unknown version)- rhel-system-roles.postfix, (unknown version)- rhel-system-roles.selinux, (unknown version)- rhel-system-roles.timesync, (unknown version)# /etc/ansible/roles[WARNING]: - the configured path /root/.ansible/roles does not exist. |
示例1
以rhel-system-roles.timesync角色为例,它用于设置系统的时间和NTP服务,让主机能够同步准确的时间信息。剧本模板文件存放在/usr/share/doc/rhel-system-roles/目录中,可以复制过来修改使用:
|
1
|
[root@linuxprobe ~]# cp /usr/share/doc/rhel-system-roles/timesync/example-timesync-playbook.yml timesync.yml |
|
1
2
3
4
5
6
7
8
9
|
[root@linuxprobe ~]# vim timesync.yml---- hosts: all vars: timesync_ntp_servers: - hostname: pool.ntp.org iburst: yes roles: - rhel-system-roles.timesync |
从外部获取角色
Ansible Galaxy(https://galaxy.ansible.com)是Ansible的一个官方社区,用于共享角色和功能代码,用户可以在网站自由地共享和下载Ansible角色。
1.从ansible官方社区下载角色
从网站查询要下载的角色,然后使用命令“ansible-galaxy install 角色名称”下载,需要能访问互联网。
|
1
2
3
4
5
|
[root@linuxprobe ~]# <strong>ansible-galaxy install nginxinc.nginx //安装ngixn角色</strong>- downloading role 'nginx', owned by nginxinc- downloading role from https://github.com/nginxinc/ansible-role-nginx/archive/0.19.1.tar.gz- extracting nginxinc.nginx to /etc/ansible/roles/nginxinc.nginx- nginxinc.nginx (0.19.1) was installed successfully |
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
[root@linuxprobe ~]# ansible-galaxy list# /etc/ansible/roles<strong>- nginxinc.nginx, 0.19.1 //已经安装了nginx角色</strong># /usr/share/ansible/roles- linux-system-roles.kdump, (unknown version)- linux-system-roles.network, (unknown version)- linux-system-roles.postfix, (unknown version)- linux-system-roles.selinux, (unknown version)- linux-system-roles.timesync, (unknown version)- rhel-system-roles.kdump, (unknown version)- rhel-system-roles.network, (unknown version)- rhel-system-roles.postfix, (unknown version)- rhel-system-roles.selinux, (unknown version)- rhel-system-roles.timesync, (unknown version) |
2.从ansible官方社区外下载角色
在这种情况下,就不能再用“ansible-galaxy install角色名称”的命令直接加载了,而是需要手动先编写一个YAML语言格式的文件,指明网址链接和角色名称,然后再用-r参数进行加载。
1.编辑yml文件
|
1
2
3
4
|
[root@linuxprobe ~]# vim nginx.yml---- src: <strong>https://www.linuxprobe.com/Software/nginxinc-nginx_core-0.3.0.tar.gz //获取角色的地址</strong> name: nginx-core |
2.使用ansible-galaxy命令的-r参数加载这个文件
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
[root@linuxprobe ~]# <strong>ansible-galaxy install -r nginx.yml //-r参数一定要加</strong>- downloading role from https://www.linuxprobe.com/nginxinc-nginx_core-0.3.0.tar.gz- extracting nginx to /etc/ansible/roles/nginx- nginx was installed successfully[root@linuxprobe ~]# <strong>ansible-galaxy list</strong># /etc/ansible/roles<strong>- nginx-core, (unknown version)</strong>- nginxinc.nginx, 0.19.1# /usr/share/ansible/roles- linux-system-roles.kdump, (unknown version)- linux-system-roles.network, (unknown version)- linux-system-roles.postfix, (unknown version)- linux-system-roles.selinux, (unknown version)- linux-system-roles.timesync, (unknown version)- rhel-system-roles.kdump, (unknown version)- rhel-system-roles.network, (unknown version)- rhel-system-roles.postfix, (unknown version)- rhel-system-roles.selinux, (unknown version)- rhel-system-roles.timesync, (unknown version) |
自建角色
在Ansible的主配置文件中,第68行(#roles_path)定义的是角色保存路径。如果用户新建的角色信息不在规定的目录内,则无法使用ansible-galaxy list命令找到。因此需要手动填写新角色的目录路径,或是进入/etc/ansible/roles目录内再进行创建。为了避免后期角色信息过于分散导致不好管理,建议在默认目录下进行创建。
|
1
2
3
4
5
|
[root@linuxprobe roles]# cat -n /etc/ansible/ansible.cfg 66 67 # additional paths to search for roles in, colon separated 68 <strong>#roles_path = /etc/ansible/roles</strong> 69 |
示例1:自建apache角色
自建角色需要使用ansible-galaxy命令的init参数,格式为“ansible-galaxy init 角色名称”。
第1步:创建自建角色名称及目录结构
|
1
2
3
4
5
|
[root@linuxprobe ~]# <strong>cd /etc/ansible/roles //切换到角色默认路径下进行创建</strong>[root@linuxprobe roles]# <strong>ansible-galaxy init apache //需要使用init参数</strong>- Role apache was created successfully[root@linuxprobe roles]# ls //会生成一个以角色名称命名的目录apache nginx nginxinc.nginx |
|
1
2
3
|
[root@linuxprobe roles]# cd apache //进入自建的角色目录[root@linuxprobe apache]# ls //自建角色目录下有若干文件defaults files handlers meta README.md tasks templates tests vars |
Ansible角色目录结构及含义
| 目录 | 含义 |
| defaults | 包含角色变量的默认值(优先级低)。 |
| files | 包含角色执行tasks任务时做引用的静态文件。 |
| handlers | 包含角色的处理程序定义。 |
| meta | 包含角色的作者、许可证、频台和依赖关系等信息。 |
| tasks | 包含角色所执行的任务。 |
| templates | 包含角色任务所使用的Jinja2模板。 |
| tests | 包含用于测试角色的剧本文件。 |
| vars | 包含角色变量的默认值(优先级高)。 |
第2步:编辑用于定义角色任务的tasks/main.yml文件。
在该文件中不需要定义要执行的主机组列表,因为后面会单独编写剧本进行调用,此时应先对apache角色能做的事情(任务)有一个明确的思路,在调用角色后yml文件会按照从上到下的顺序自动执行。即向main.yml文件写入若干任务。
任务1:安装httpd网站服务。
任务2:运行httpd网站服务,并加入到开机启动项中。
任务3:配置防火墙,使其放行HTTP协议。
任务4:根据每台主机的变量值,生成不同的主页文件。
写第一个任务。
使用yum模块安装httpd网站服务程序(注意格式):
|
1
2
3
4
5
6
|
[root@linuxprobe apache]# vim tasks/main.yml---- name: one yum: name: httpd state: latest |
写第二个任务。
使用service模块启动httpd网站服务程序,并加入开机自启动。
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
[root@linuxprobe apache]# <strong>ansible-doc service //查询service模块信息及使用格式</strong>> SERVICE (/usr/lib/python3.6/site-packages/ansible/modules/system/service.py) Controls services on remote hosts. Supported init systems include BSD init, OpenRC, SysV, Solaris SMF, systemd, upstart. For Windows targets, use the [win_service] module instead. * This module is maintained by The Ansible Core Team * note: This module has a corresponding action plugin.………………省略部分输出信息………………EXAMPLES:<strong>- name: Start service httpd, if not started service: name: httpd state: started- name: Enable service httpd, and not touch the state service: name: httpd enabled: yes</strong> |
|
1
2
3
4
5
6
7
8
9
10
11
12
|
[root@linuxprobe apache]# vim tasks/main.yml---- name: one yum: name: httpd state: latest<strong>- name: two service: name: httpd state: started enabled: yes</strong> |
写第三个任务。
配置防火墙的允许策略,让其他主机可以正常访问。在配置防火墙时,需要使用firewalld模块。
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
[root@linuxprobe defaults]# <strong>ansible-doc firewalld //查看firewalld模块信息及使用格式</strong>> FIREWALLD (/usr/lib/python3.6/site-packages/ansible/modules/system/firewalld.py) This module allows for addition or deletion of services and ports (either TCP or UDP) in either running or permanent firewalld rules. * This module is maintained by The Ansible CommunityOPTIONS (= is mandatory):EXAMPLES:<strong>- firewalld: service: https permanent: yes state: enabled- firewalld: port: 8081/tcp permanent: yes state: disabled immediate: yes</strong> |
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
[root@linuxprobe apache]# vim tasks/main.yml---- name: one yum: name: httpd state: latest- name: two service: name: httpd state: started enabled: yes<strong>- name: three firewalld: service: http permanent: yes state: enabled immediate: yes</strong> |
写第四个任务。
根据每台主机的变量值,生成不同的主页文件,让每台主机显示的主页文件均不相同。
让每台主机上运行的httpd网站服务都能显示不同的内容,要用到template模块及Jinja2技术。
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
|
[root@linuxprobe apache]# <strong>ansible-doc template //查询template模块及使用格式</strong>> TEMPLATE (/usr/lib/python3.6/site-packages/ansible/modules/files/template.> Templates are processed by the L(Jinja2 templating language,http://jinja.pocoo.org/docs/). Documentation on the template formatting can be found in the L(Template Designer Documentation,http://jinja.pocoo.org/docs/templates/). Additional variables listed below can be used in templates. `ansible_managed' (configurable via the `defaults' section of `ansible.cfg') contains a string which can be used to describe the template name, host, modification time of the template file and the owner uid. `template_host' contains the node name of the template's machine. `template_uid' is the numeric user id of the owner. `template_path' is the path of the template. `template_fullpath' is the absolute path of the template. `template_destpath' is the path of the template on the remote system (added in 2.8). `template_run_date' is the date that the template was rendered. * This module is maintained by The Ansible Core Team * note: This module has a corresponding action plugin.………………省略部分输出信息………………EXAMPLES:<strong>- name: Template a file to /etc/files.conf template: src: /mytemplates/foo.j2 dest: /etc/file.conf owner: bin group: wheel mode: '0644'</strong> |
从template模块的输出信息中可得知,这是一个用于复制文件模板的模块,能够把文件从Ansible服务器复制到受管主机上。其中,src参数用于定义本地文件的路径,dest参数用于定义复制到受管主机的文件路径,而owner、group、mode参数可选择性地设置文件归属及权限信息。
正常来说,我们可以直接复制文件的操作,受管主机上会获取到一个与Ansible服务器上的文件一模一样的文件。但有时候,我们想让每台客户端根据自身系统的情况产生不同的文件信息,这就需要用到Jinja2技术了,Jinja2格式的模板文件后缀是.j2。
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
[root@linuxprobe apache]# vim tasks/main.yml---- name: one yum: name: httpd state: latest- name: two service: name: httpd state: started enabled: yes- name: three firewalld: service: http permanent: yes state: enabled immediate: yes<strong>- name: four template: src: index.html.j2 //本地文件路径 dest: /var/www/html/index.html //受管主机路径</strong> |
Jinja2是Python语言中一个被广泛使用的模板引擎,能够让受管主机根据自身变量产生出不同的文件内容。换句话说,正常情况下的复制操作会让新旧文件一模一样,但在使用Jinja2技术时,不是在原始文件中直接写入文件内容,而是写入一系列的变量名称。在使用template模块进行复制的过程中,由Ansible服务负责在受管主机上收集这些变量名称所对应的值,然后再逐一填写到目标文件中,从而让每台主机的文件都根据自身系统的情况独立生成。
例如让每个网站的输出信息值为“Welcome to 主机名 on 主机地址”,也就是用每个主机自己独有的名称和IP地址来替换文本中的内容。
可以用setup模块进行查询对应的变量名称、主机名及地址所对应的值保存在哪里。setup模块的作用是自动收集受管主机上的变量信息,使用-a参数外加filter命令可以对收集来的信息进行二次过滤。相应的语法格式为ansible all -m setup -a 'filter="*关键词*",其中*号是通配符,用于进行关键词查询。
|
1
2
3
4
5
6
7
8
9
10
|
[root@linuxprobe apache]# ansible-doc setup> SETUP (/usr/lib/python3.6/site-packages/ansible/modules/system/setup.py) This module is automatically called by playbooks to gather useful variables about remote hosts that can be used in playbooks. It can also be executed directly by `/usr/bin/ansible' to check what variables are available to a host. Ansible provides many `facts' about the system, automatically. This module is also supported for Windows targets. |
FQDN(Fully Qualified Domain Name,完全限定域名)用于在逻辑上准确表示出主机的位置。fqdn常常被作为主机名的完全表达形式,比/etc/hostname文件中定义的主机名更加严谨和准确。
|
1
2
3
4
5
6
7
8
9
|
[root@linuxprobe ~]# <strong>ansible all -m setup -a 'filter="*fqdn*"'</strong>192.168.10.20 | SUCCESS => { "ansible_facts": { "<strong>ansible_fqdn": "linuxprobe.com",</strong> "discovered_interpreter_python": "/usr/libexec/platform-python" }, "changed": false}………………省略部分输出信息……………… |
过滤IP
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
[root@linuxprobe ~]# ansible all -m setup -a 'filter="*ip*"'192.168.10.20 | SUCCESS => { "ansible_facts": { "<strong>ansible_all_ipv4_addresses": [</strong> "192.168.10.20", "192.168.122.1" ], "ansible_all_ipv6_addresses": [ "fe80::d0bb:17c8:880d:e719" ], "ansible_default_ipv4": {}, "ansible_default_ipv6": {}, "ansible_fips": false, "discovered_interpreter_python": "/usr/libexec/platform-python" }, "changed": false}………………省略部分输出信息……………… |
在角色所对应的templates目录内新建一个与上面的template模块参数相同的文件名称(index.html.j2)。Jinja2在调用变量值时,格式为在变量名称的两侧格加两个大括号,且大括号内两侧均有一个空格。
|
1
2
|
[root@linuxprobe apache]# vim templates/index.html.j2Welcome to<strong> {{ ansible_fqdn }}</strong> on <strong>{{ ansible_all_ipv4_addresses }}</strong> //大括号内两侧均有一个空格 |
第3步:编写一个用于调用角色的yml文件,以及执行这个文件
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
|
[root@linuxprobe apache]# cd ~[root@linuxprobe ~]# <strong>vim roles.yml</strong><strong>---- name: 调用自建角色 hosts: all roles: - apache</strong>[root@linuxprobe ~]# <strong>ansible-playbook roles.yml</strong>PLAY [调用自建角色] **************************************************************************TASK [Gathering Facts] **********************************************************************ok: [192.168.10.20]ok: [192.168.10.21]ok: [192.168.10.22]ok: [192.168.10.23]ok: [192.168.10.24]TASK [apache : one] *************************************************************************changed: [192.168.10.20]changed: [192.168.10.21]changed: [192.168.10.22]changed: [192.168.10.23]changed: [192.168.10.24]TASK [apache : two] *************************************************************************changed: [192.168.10.20]changed: [192.168.10.21]changed: [192.168.10.22]changed: [192.168.10.23]changed: [192.168.10.24]TASK [apache : three] ***********************************************************************changed: [192.168.10.20]changed: [192.168.10.21]changed: [192.168.10.22]changed: [192.168.10.23]changed: [192.168.10.24]TASK [apache : four] ***********************************************************************changed: [192.168.10.20]changed: [192.168.10.21]changed: [192.168.10.22]changed: [192.168.10.23]changed: [192.168.10.24]PLAY RECAP **********************************************************************************192.168.10.20 : ok=5 changed=4 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 192.168.10.21 : ok=5 changed=4 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 192.168.10.22 : ok=5 changed=4 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 192.168.10.23 : ok=5 changed=4 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 192.168.10.24 : ok=4 changed=4 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 |
执行完毕后,在浏览器中随机输入几台主机的IP地址,即可访问到包含主机FQDN和IP地址的网页了。

浙公网安备 33010602011771号