Ansible角色

本文介绍了Ansible的 roles 功能,它允许开发者打包和复用基础设施代码,提高效率。文章详细阐述了角色的优点,如代码共享、项目管理简化、并行开发。详细描述了角色的结构,包括 Defaults、Files、Handlers、Meta、Tasks、Templates 等目录的作用。还展示了如何在 playbook 中使用角色,控制执行顺序,以及系统角色的安装和管理。同时,文章提供了实例,演示了如何创建、安装和使用自定义及Galaxy中的角色来配置Web服务器、数据库服务器和负载均衡。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

角色

利用角色构造ansible playbook

随着开发更多的playbook,会发现有很多机会重复利用以前编写的playbook中的代码。或许,一个用于为某一应用配置MySQL数据库的play可以改变用途。通过利用不同的主机名、密码和用户来为另一个应用配置MySQL数据库。
但在现实中,这个play可能比较冗长且复杂,有许多包含或导入的文件,以及用于管理各种情况的任务和处理程序。将所有这些代码复制到另一playbook种可能并不简单。
ansible提供了一种方法,能以通用的方式更加轻松地重复利用ansible代码。可以在标准化目录结构中打包所有的任务、变量、文件、模板,以及调整基础架构或部署应用所需的其他资源。只需通过复制相关的目录,将角色从一个项目复制到另外一个项目。然后,只需从一个play调用该角色就能执行。
借助编写好的角色,可以从playbook中向角色传递调整其行为的变量,设置所有站点相关的主机名、IP地址、用户名,或其他在本地需要的具体详细信息。例如,部署数据库服务器的角色可能已编写为支持多个变量,这些变量用于设置主机名、数据库管理员用户和密码,以及需要为安装进行自定义的其他参数。角色的作者也可以确保在选择不在play中设置变量值时,为这些变量设定合理的默认值。

ansible角色具有下列优点

  • 角色可以分组内容,从而与他人轻松共享代码
  • 可以编写角色来定义系统类型的基本要素:Web服务器、数据库服务器、Git存储库,或满足其他用途
  • 角色使得较大型项目更容易管理
  • 角色可以由不同的管理员并行开发

除了自行编写、使用、重用和共享角色以外,还可以从其他来源获取角色。一些角色以及包含在rhel-system-rolses软件包中,作为红帽企业Linux的一部分。可以从ansible Galaxy网站获取由社区提供支持的许多角色。

ANSIBLE角色结构

ansible角色由字母和文件的标准化结构定义。顶级目录定义角色本身的名称。文件整理到子目录中,子目录按照各个文件在角色中的用途进行命名,如tasks何handlers。files和templates子目录中包含其他YAML文件中的任务引用的文件。

Defaults:此目录中的main.yml文件包含角色变量的默认值,使用角色时可以覆盖这些默认值。这些变量的优先级较低,应该在play中更改和自定义。
Files:此目录包含由角色任务引用的静态文件
Handlers:此目录中的main.yml文件包含角色的处理程序定义,也就是触发器的内容。
Meta:此目录中的main.yml文件包含与角色相关的信息,如作者、许可证、平台和可选的角色的依赖项。
Tasks: 此目录中的mian.yml文件包含角色的任务定义。
Template: 此目录包含由角色任务引用的jinja2模板(j2模板)
Tests:此目录可以包含清单和test.yml剧本,可用于测试角色
Vars: 此目录的main.yml文件定义角色的变量值,这些变量通常用于角色内部用途,这些变量的优先级较高,在playbook中使用时不应更改。

playbook中使用ansible角色

[student@ansible ansible]$ vim test.yml
---
- name: test
 hosts: node1
 roles: 
   - role1
   - role2

对于每个指定的角色,角色任务、角色处理程序、角色变量和角色依赖项将按照顺序导入到playbook中。角色中的任何copy、script、template或include_tasks/import_tasks任务都可引用角色中相关的文件、模板或任务文件,且无需相对或绝对路径名称。ansible将分别在角色的files、templates或tasks子目录中寻找他们。
如果使用roles部分将角色导入到play中,这些角色会为该play定义的任何任务之前运行。
以下示例设置cy的角色变量a1和a2的值,使用cy角色时,任何defaults和vars变量都会被覆盖。
示例:
创建角色

[student@ansible ansible]$ cd  /home/student/ansible/roles
[student@ansible roles]$ ansible-galaxy  init  haha

在vars里给角色定义变量

[student@ansible ansible]$ vim  haha/vars/main.yml
---
# vars file for in
a1: 11
a2: 22

在tasks目录中的main.yml中写角色的任务

[student@ansible ansible]$ vim  haha/tasks/main.yml
---
# tasks file for in
- name: test
  debug:
    msg: "{{a1}}"

在/home/student/ansible/目录下创建一个test.yml的playbook来使用haha角色

[student@ansible ansible]$ vim test.yml
---
- name: test1
  hosts: node1
  roles: 
    - haha
此时会发现,我们能够调用角色vars目录下main.yml定义的变量可以被调用

在test.yml的playbook中来定义变量

[student@ansible ansible]$ vim test.yml
---
- name: test1
  hosts: node1
  roles:
    - role: haha
      a1: 333

执行test.yml,就会发现test.yml中定义的a1变量覆盖了角色中vars目录中定义的变量。

控制执行顺序

对于playbook中的每个play,任务按照任务列表中的顺序来执行,执行完所有任务后,将执行任何通知的处理程序。
在角色添加到play后,角色任务将添加到任务列表的开头。如果play中包含第二个角色,其任务列表添加到第一个角色之后。
角色处理程序添加到play中的方式与角色任务添加到play中相同。每个play定义一个处理程序列表。角色处理程序先添加到处理程序列表,后跟play的handlers部分中定义的任何处理程序。
在某些情形中,可能需要在角色之前执行一些play任务。可以为play配置pre_tasks部分。列在此部分中的所有任务将在执行任何角色之前执行。如果这些任务中有任何一个通知了处理程序,则这些处理程序任务也在角色或普通任务之前执行。
此外,play也支持post_tasks关键字。这些任务在play的普通任务和他们通知的任何处理程序之后执行。

[student@ansible ansible]$ vim hehe.yml
---
- name: test1
  hosts: node1
  pre_tasks:
    - name: debug1
      shell: echo aaa
      notify: cc
  roles:
    - cy
  post_tasks:
    - name: debug2
      debug:
        msg: ooo
  handlers:
    - name: cc
      debug:
        msg: ttt

执行该playbook,我们发现pre_tasks任务在角色之前执行的,而且触发器是在触发后马上执行的。
Post_tasks任务是在触发器和角色执行完成后,才来执行的。

除了将角色包含在play的roles部分中外,也可以使用普通任务将角色添加到play中,使用include_role模块可以动态包含角色,使用import_role模块可以静态导入角色。

[student@ansible ansible]$ vim test.yml
---
- name: test23
  hosts: node1
  tasks:
    - debug:
        msg: chenyufdsf

    - name: a task to include cy here
      Include_role:                         //或者使用import_role
        name: cy

    - name: debug2
      debug:
        msg: 11111

系统角色

安装系统角色

[root@ansible]# yum -y install rhel-system-roles

rhel系统角色

Rhel-system-roles.kdump 配置kdump崩溃恢复服务
Rhel-system-roles.network 配置网络接口
Rhel-system-roles.selinux 配置和管理selinux(selinux模式 文件和端口上下文、布尔值 )
Rhel-system-roles.timesync 配置时钟同步
Rhel-system-roles.postfix 使用postfix服务将每个主机配置为邮件传输代理
Rhel-system-roles.firewall 配置主机的防火墙
Rhel-system-roles.tuned 配置tuned服务,以调优系统性能

RHEL系统角色位于/usr/share/ansible/roles/目录下

安装 RHEL 系统角色软件包,并创建符合以下条件的playbook /etc/ansible/timesync.yml:
在所有受管节点上运行
使用 timesync 角色
配置该角色,以使用当前有效的 NTP 提供商
配置该角色,以使用时间服务器 classroom.example.com
配置该角色,以启用 iburst 参数

安装系统角色
[student@ansible ansible]$ sudo dnf  -y  install  rhel-system-roles

将时钟同步的系统角色复制到home/student/ansible/roles目录下,并重名了角色名为timesync
[student@ansible ansible]$ cp  -r  /usr/share/ansible/roles/rhel-system- roles.timesync/  roles/timesync
书写playbook,并执行。
[student@ansible ansible]$ vim timesync.yml
---
- name: set time sync
  hosts: all
  vars:  
    timesync_ntp_servers:
      - hostname: classroom.example.com
        iburst: yes
  roles:
    - timesync
[student@ansible ansible]$ ansible-playbook timesync.yml

从ansible-galaxy安装角色

ansible-galaxy install子命令从Ansible Galaxy下载角色,并将它站桩到控制节点本地。
默认情况下,角色安装到用户的roles_path下的第一个可写目录中。根据ansible设置的默认roles_path,角色通常安装到用户的~/.ansible/roles目录。默认的roles_path可能会被当前的ansible配置文件或环境变量ANSIBLE_ROLES_PATH覆盖,这将影响ansible-galaxy的行为。
可以使用-p DIRECTORY选项,指定具体的目录来安装角色。

安装角色
首先在roles目录下书写一个playbook,把需要安装角色的路径定义到playbook中

[student@ansible ansible]$ vim test.yml 
- name: balancer
 src: http://classroom.example.com/content/haproxy.tar.gz
- name: phpinfo
 src: http://classroom.example.com/content/phpinfo.tar.gz

其中src指定角色的来源,可以是本地的(file://),也可以是远程的(http:// )

使用ansible-galaxy命令安装角色

[student@ansible ansible]$ ansible-galaxy install -r test.yml -p roles/

在roles目录下查看安装好的角色

[student@ansible ansible]$ cd roles/
[student@ansible ansible]$ ls
haproxy  phpinfo  test.yml

管理下载的角色

ansible-galaxy命令也可管理本地的角色,如位于playbook项目的roles目录中的角色。ansible-galaxy list子命令列出本地找到的角色。

[student@ansible ansible]$ ansible-galaxy list
# /home/student/ansible/roles
- haproxy, (unknown version)
- phpinfo, (unknown version)

可以使用ansible-galaxy remove子命令本地删除角色
[student@ansible ansible]$ ansible-galaxy remove haproxy
- successfully removed haproxy
[student@ansible ansible]$ ansible-galaxy list
# /home/student/ansible/roles
- phpinfo, (unknown version)

拓展

安装 RHEL 系统角色软件包,并创建符合以下条件的playbook
/home/student/ansible/timesync.yml:
在所有受管节点上运行
使用 timesync 角色
配置该角色,以使用当前有效的 NTP 提供商
配置该角色,以使用时间服务器 classroom.example.com
配置该角色,以启用 iburst 参数

[student@workstation ansible]$ sudo yum -y install rhel-system-roles
[student@workstation ansible]$ mkdir roles
[student@workstation ansible]$ cp -r /usr/share/ansible/roles/rhel-system
-roles.timesync/ /home/student/ansible/roles/timesync
[student@workstation ansible]$ vim timesync.yml
---
- name: set time sync
  hosts: all
  vars:
    timesync_ntp_servers:
      - hostname: classroom.example.com
        iburst: yes
  roles:
    - timesync
[student@workstation ansible]$ ansible-playbook timesync.yml

使用selinux角色
配置该角色,编写selinux.yml的playbook开启所有受控节点的selinux

[student@workstation ansible]$ cp -r /usr/share/ansible/roles/rhel-system
-roles.selinux /home/student/ansible/roles/selinux
[student@workstation ansible]$ vim selinux.yml
---
- name: set selinux
  hosts: all
  vars:
    selinux_state: enforcing
  roles:
    - role: selinux
      become: true
[student@workstation ansible]$ ansible-playbook selinux.yml

使用Ansible Galaxy安装角色
使用 Ansible Galaxy 和要求文件 /home/student/ansible/roles/requirements.yml,从以下 URL 下载
角色并安装到 /home/student/ansible/roles:
http://content.example.com/haproxy.tar.gz 此角色的名称应当为 balancer
http://content.example.com/phpinfo.tar.gz 此角色的名称应当为 phpinfo

[student@workstation ansible]$ vim roles/requirements.yml
---
- name: balancer
  src: http://content.example.com/ansible2.8/haproxy.tar.gz
- name: phpinfo
  src: http://content.example.com/ansible2.8/phpinfo.tar.gz
[student@workstation ansible]$ ansible-galaxy install -r requirements.yml -p roles/
- downloading role from http://content.example.com/ansible2.8/haproxy.tar.gz
- extracting balancer to /home/student/ansible/roles/roles/balancer
- balancer was installed successfully
- downloading role from http://content.example.com/ansible2.8/phpinfo.tar.gz
- extracting phpinfo to /home/student/ansible/roles/roles/phpinfo
- phpinfo was installed successfully

创建和使用角色
根据下列要求,在/home/student/ansible/roles中创建名为apache的角色:
httpd软件包已安装,设为在系统启动时启用并启动
防火墙已启用并正在运行,并使用允许访问Web服务器的规则
模板文件 index.html.j2 已存在,用于创建具有以下输出的文件/var/www/html/index.html:
Welcome to HOSTNAME on IPADDRESS
其中,HOSTNAME是受管节点的完全限定域名,IPADDRESS则是受管节点的IP地址。
按照下方所述,创建一个使用此角色的playbook /home/student/ansible/newrole.yml:
该playbook在webservers主机组中的主机上运行

[student@workstation ansible]$ cd roles/
[student@workstation roles]$ ansible-galaxy init apache
- apache was created successfully
[student@workstation roles]$ ls
apache requirements.yml selinux timesync
[student@workstation roles]$ cd apache/
[student@workstation apache]$ ls
defaults files handlers meta README.md tasks templates tests vars
[student@workstation apache]$ cd tasks/
[student@workstation tasks]$ ls
main.yml
[student@workstation tasks]$ vim main.yml
---
# tasks file for apache
- name: install httpd firewalld
  yum:
    name:
      - httpd
      - firewalld
    state: present
- name: copy file
  template:
    src: index.html.j2
    dest: /var/www/html/index.html
- name: start httpd
  service:
    name: httpd
    state: started
    enabled: yes
- name: restart firewalld
  service:
    name: firewalld
    state: restarted
    enabled: yes
- name: set http firewalld
  firewalld:
    service: http
    state: enabled
    permanent: yes
    immediate: yes
[student@workstation tasks]$ cd ..
[student@workstation apache]$ ls
defaults files handlers meta README.md tasks templates tests vars
[student@workstation apache]$ cd templates/
[student@workstation templates]$ vim index.html.j2
Welcome to {{ansible_fqdn}} on {{ansible_enp1s0.ipv4.address}}
[student@workstation ansible]$ vim newrole.yml
---
- name: use http role
  hosts: webservers
  roles:
    - apache
[student@workstation ansible]$ ansible-playbook newrole.yml
PLAY [use http role] ****************************************************************************************
TASK [Gathering Facts]***************************************************************************************
ok: [serverd]
ok: [serverc]
TASK [apache : install httpd firewalld] *********************************************************************
changed: [serverc]
changed: [serverd]
TASK [apache : copy file] ***********************************************************************************
changed: [serverd]
changed: [serverc]
TASK [apache : start httpd]**********************************************************************************
changed: [serverc]
changed: [serverd]
TASK [apache : restart firewalld] ***************************************************************************
changed: [serverc]
changed: [serverd]
TASK [apache : set http firewalld] **************************************************************************
changed: [serverd]
changed: [serverc]
PLAY RECAP **************************************************************************************************
serverc : ok=6 changed=5 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
serverd : ok=6 changed=5 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
[student@workstation ansible]$ curl http://serverc
Welcome to serverc.lab.example.com on 172.25.250.12
[student@workstation ansible]$ curl http://serverd
Welcome to serverd.lab.example.com on 172.25.250.13

从Ansible Galaxy使用角色
根据下列要求,创建一个名为 /home/student/ansible/roles.yml的playbook:
playbook中包含一个play,该play在balancers主机组中的主机上运行并将使用balancer角色。
此角色配置一项服务,以在webservers主机组中的主机之间平衡Web服务器请求的负载。
浏览到balancers主机组中的主机(例如http://bastion.lab.example.com/ )将生成以下输出:
Welcome to serverc.example.com on 172.25.1.12
重新加载浏览器将从另一Web服务器生成输出:
Welcome to serverd.example.com on 172.25.1.13
playbook 中包含一个 play,该 play 在 webservers主机组中的主机上运行并将使用 phpinfo 角色。
通过 URL /hello.php 浏览到 webservers 主机组中的主机将生成以下输出:
Hello PHP World from FQDN
其中,FQDN是主机的完全限定名称。
例如,浏览到 http://serverc.lab.example.com/hello.php 会生成以下输出:
Hello PHP World from serverc.lab.example.com
另外还有 PHP 配置的各种详细信息,如安装的PHP 版本等。
同样,浏览到 http://serverd.lab.example.com/hello.php 会生成以下输出:
Hello PHP World from serverd.lab.example.com
另外还有 PHP 配置的各种详细信息,如安装的PHP 版本等。

[student@workstation ansible]$ ssh root@bastion 'systemctl stop httpd &&
systemctl disable httpd'     //关闭bastion主机上的httpd服务,以免冲突
Removed /etc/systemd/system/multi-user.target.wants/httpd.service.
[student@workstation ansible]$ vim roles.yml
---
- name: gather facts for webservers
  hosts: webservers
  
- name: balancer role
  hosts: balancers
  roles:
    - balancer
    
- name: php role
  hosts: webservers
  roles:
    - phpinfo
[student@workstation ansible]$ ansible-playbook roles.yml
PLAY [gather facts for webservers] *************************************************************************************************************************************
TASK [Gathering Facts]*************************************************************************************************************************************************
ok: [serverc]
ok: [serverd]
PLAY [balancer role] ***************************************************************************************************************************************************
TASK [Gathering Facts]*************************************************************************************************************************************************
ok: [bastion]
TASK [balancer : Install haproxy] **************************************************************************************************************************************
[DEPRECATION WARNING]: Invoking "yum" only once while using a loop via squash_actions is deprecated. Instead of using a loop to supply multiple items and specifying
`name: "{{ item }}"`, please use `name: ['haproxy']` and remove the loop.
This feature will be removed in version 2.11. Deprecation warnings can be disabled by setting
deprecation_warnings=False in ansible.cfg.
ok: [bastion] => (item=['haproxy'])
TASK [balancer : Configure the haproxy cnf file] ***********************************************************************************************************************
ok: [bastion]
TASK [balancer : Start the haproxy service] ****************************************************************************************************************************
changed: [bastion]
TASK [balancer : Install firewalld] ************************************************************************************************************************************
ok: [bastion]
TASK [balancer : Start and enable firewalld] ***************************************************************************************************************************
ok: [bastion]
TASK [balancer : Enable http in firewall] ******************************************************************************************************************************
changed: [bastion]
TASK [balancer : Install Apache]***************************************************************************************************************************************
skipping: [bastion]
TASK [balancer : Install firewalld] ************************************************************************************************************************************
skipping: [bastion]
TASK [balancer : Copy the index_ver.html.j2] ***************************************************************************************************************************
skipping: [bastion]
TASK [balancer : Start and enable firewalld] ***************************************************************************************************************************
skipping: [bastion]
TASK [balancer : Enable http in firewall] ******************************************************************************************************************************
skipping: [bastion]
TASK [balancer : Start and enable httpd] *******************************************************************************************************************************
skipping: [bastion]
PLAY [php role] *******************************************************************************************************************************************************
TASK [Gathering Facts]*************************************************************************************************************************************************
ok: [serverc]
ok: [serverd]
TASK [phpinfo : Install Apache] ****************************************************************************************************************************************
ok: [serverc]
ok: [serverd]
TASK [phpinfo : Install firewalld] *************************************************************************************************************************************
ok: [serverc]
ok: [serverd]
TASK [phpinfo : Start and enable firewalld] ****************************************************************************************************************************
ok: [serverc]
ok: [serverd]
TASK [phpinfo : Enable http in firewall] *******************************************************************************************************************************
ok: [serverc]
ok: [serverd]
TASK [phpinfo : Copy the hello_ver.html.j2] ****************************************************************************************************************************
changed: [serverc]
changed: [serverd]
TASK [phpinfo : Start and enable httpd] ********************************************************************************************************************************
ok: [serverc]
ok: [serverd]
RUNNING HANDLER [phpinfo : restart httpd] ******************************************************************************************************************************
changed: [serverc]
changed: [serverd]
PLAY RECAP *************************************************************************************************************************************************************
bastion : ok=7 changed=2 unreachable=0 failed=0 skipped=6 rescued=0 ignored=0
serverc : ok=9 changed=2 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
serverd : ok=9 changed=2 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
[student@workstation ansible]$ curl http://bastion.lab.example.com
Welcome to serverc.lab.example.com on 172.25.250.12
[student@workstation ansible]$ curl http://bastion.lab.example.com
Welcome to serverd.lab.example.com on 172.25.250.13
[student@workstation ansible]$ curl http://serverc.lab.example.com/hello.php
Hello PHP World form serverc.lab.example.com
[student@workstation ansible]$ curl http://serverd.lab.example.com/hello.php
Hello PHP World form serverd.lab.example.com
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值