Ansible上通过roles简化playbook演示介绍

news2024/7/4 5:58:23

目录

一.roles介绍

1.作用

2.role的目录结构

3.role和tasks的执行优先级顺序

二.自定义一个httpd的角色

1.完整目录结构展示

2.主要的各个目录配置

(1)vars目录和templates目录

(2)tasks目录和handlers目录

(3)运行playbook测试

三.ansible galaxy安装roles

1.在线网站

2.配置roles_path

3.ansible-galaxy安装role

4.其他管理

四.系统角色

1.安装系统角色包

2.更改配置文件role路径便于对系统角色进行操作

3.介绍rhel提供的部分系统角色

4.timesync和selinux示例

(1)timesync

(2)selinux


一.roles介绍

1.作用

主要适用于层次性、结构化来组织playbook任务。根据层次型结构自动装载变量文件、tasks、和handlers等。主要应用于基于主机构建服务和构建进程场景、代码服用程度较高的场景。

2.role的目录结构

在playbook中通过“roles: role文件”来引用role,role的目录结构不要求全部完整,根据role要实现的功能来添加目录和文件

名称含义
tasks至少要包含一个main.yaml,用来定义这个角色的任务列表,可以使用include引入其他tasks
files存放copy或script模块调用的文件
templatestemplate模块寻找jinja2模版的目录
handlers要包含一个main.yaml,来定义这个角色用到的handlers
vars要包含一个main.yaml,用来定义这个角色要用到的变量
mate要包含一个main.yaml,用来定义这个角色的特殊设置

3.role和tasks的执行优先级顺序

pre_tasks > roles > tasks > post_tasks

二.自定义一个httpd的角色

1.完整目录结构展示

[root@main roles]# tree .
.
├── ansible.cfg    #存放ansible配置文件
├── httpd     #role目录
│   ├── handlers    #存放handlers
│   │   └── main.yaml   
│   ├── tasks   #存放主要执行的任务
│   │   ├── config.yaml   #关于配置httpd
│   │   ├── group.yaml   #关于配置httpd属组
│   │   ├── install.yaml   #关于安装httpd
│   │   ├── main.yaml   #关于所有任务的引入
│   │   ├── start.yaml   #关于启动httpd
│   │   └── user.yaml   #关于配置httpd属主
│   ├── templates       #存放要部署下发的文件
│   │   └── httpd.conf.j2
│   └── vars   #存放变量
│       └── main.yaml
├── httpd_roles.yaml   #最终指定执行role的playbook文件
└── myhosts   #主机清单文件

2.主要的各个目录配置

(1)vars目录和templates目录

[root@main httpd]# cat vars/main.yaml   #自定义在受管节点的httpd服务要用到的参数
port: 8090
user: sulibao
group: sulibao
​
[root@main httpd]# cp httpd.conf /root/roles/httpd/templates/httpd.conf.j2  
#从本地拷贝httpd的配置文件到templates目录,且为j2格式
#需要修改参数的话就按照j2变量格式去修改
[root@main httpd]# cat templates/httpd.conf.j2 | grep Listen;cat templates/httpd.conf.j2 | grep User;cat templates/httpd.conf.j2 | grep Group
# Listen: Allows you to bind Apache to specific IP addresses and/or
# Change this to Listen on specific IP addresses as shown below to 
#Listen 12.34.56.78:80
Listen "{{ port }}"         #       
# User/Group: The name (or #number) of the user/group to run httpd as.
User "{{ user }}"    #
    LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
      LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio
# User/Group: The name (or #number) of the user/group to run httpd as.
Group "{{ group }}"    #

(2)tasks目录和handlers目录

[root@main httpd]# cat tasks/user.yaml #创建用户
- name: create user
  user:
    name: "sulibao"
    uid: 1050
    system: yes
    shell: /sbin/nologin
[root@main httpd]# cat tasks/group.yaml   #创建组
- name: create group
  group:
    name: "sulibao"
    gid: 1050
    system: yes
[root@main httpd]# cat tasks/install.yaml   #安装httpd
- name: install httpd
  yum:
    name: httpd
    state: present
[root@main httpd]# cat tasks/start.yaml    #启动httpd
- name: start httpd
  service:
    name: httpd
    state: started
    enabled: yes
[root@main httpd]# cat tasks/config.yaml    #将templates内的配置文件推送给受管节点用
- name: config httpd
  template:
    src: /root/roles/httpd/templates/httpd.conf.j2
    dest: /etc/httpd/conf/httpd.conf
  notify: restart httpd
[root@main httpd]# cat tasks/main.yaml  #引用所有的任务
- import_tasks: user.yaml
- import_tasks: group.yaml
- import_tasks: install.yaml
- import_tasks: start.yaml
- import_tasks: config.yaml
​
[root@main httpd]# cat handlers/main.yaml 
- name: restart httpd
  service:
    name: httpd
    state: restarted

(3)运行playbook测试

[root@main roles]# cat httpd_roles.yaml 
---
- hosts: servera
  roles:
    - role: httpd   #指定httpd角色目录
​
[root@main roles]# ansible-playbook httpd_roles.yaml
​
[root@main roles]# ansible servera -m shell -a 'ss -lntup | grep 8090'   #端口变量运行正常
servera | CHANGED | rc=0 >>
tcp    LISTEN     0      128    [::]:8090               [::]:*                   users:(("httpd",pid=2749,fd=4),("httpd",pid=2748,fd=4),("httpd",pid=2747,fd=4),("httpd",pid=2746,fd=4),("httpd",pid=2745,fd=4),("httpd",pid=2744,fd=4))
​
[root@main roles]# ansible servera -m shell -a 'ps u 2748'    #进程确实是我们指定用户
servera | CHANGED | rc=0 >>
USER        PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
sulibao    2748  0.0  0.0 250100  3572 ?        S    14:09   0:00 /usr/sbin/httpd -DFOREGROUND
​
[root@main roles]# ansible servera -m shell -a 'echo hello > /var/www/html/index.html'
servera | CHANGED | rc=0 >>
​
[root@main roles]# ansible servera -m shell -a 'curl localhost:8090'      #能够正常访问
servera | CHANGED | rc=0 >>
hello  

三.ansible galaxy安装roles

ansible-galaxy基于在线网站的公共内容资源库,可以在内进行搜索所需roles,便于从在线网站获取role和git存储库的role。

1.在线网站

Galaxy NG (ansible.com)

时而可用时而不可用,找到role后复制命令进行下载

 

2.配置roles_path

[root@main roles]# cat ansible.cfg | grep role
roles_path=/root/roles/myroles

3.ansible-galaxy安装role

(1)默认通过网站在线安装

[root@main playkongzhi]# ansible-galaxy install role名称

(2)通过文件安装,需要是yaml格式的文件

[root@main playkongzhi]# ansible-galaxy install -r 指定文件 -p 指定安装路径

4.其他管理

(1)初始化角色结构

[root@main playkongzhi]# ansible-galaxy init role名称

(2)列出角色名称

[root@main playkongzhi]# ansible-galaxy list

(3)删除已安装角色

[root@main playkongzhi]# ansible-galaxy remove role名称

(4)搜索角色

可以通过“--author(作者)”、“--platform(平台)”、“--galaxy-tags(标签)“等选项来缩小范围

[root@main playkongzhi]# ansible-galaxy search role名称 选项

四.系统角色

1.安装系统角色包

注意:

角色默认是下载到/usr/share/ansible/roles

其帮助文档位于/usr/share/doc/rhel-system-roles-1.21.2(含示例)

[root@main roles]# yum list | grep roles
rhel-system-roles.noarch                 1.21.2-1.el7_9                extras 
[root@main roles]# yum install -y rhel-system-roles.noarch

2.更改配置文件role路径便于对系统角色进行操作

roles目录路径后再使用":"跟上下载的系统角色目录路径,再就可以查看到我们可用的角色了,若不需要就再把路径改回来即可

[root@main roles]# cat ansible.cfg | grep role
roles_path=/root/roles/myroles:/usr/share/ansible/roles
​
[root@main roles]# ansible-galaxy list
# /root/roles/myroles
# /usr/share/ansible/roles
- linux-system-roles.ad_integration, (unknown version)
- linux-system-roles.certificate, (unknown version)
- linux-system-roles.cockpit, (unknown version)
- linux-system-roles.crypto_policies, (unknown version)
- linux-system-roles.firewall, (unknown version)
- linux-system-roles.ha_cluster, (unknown version)
- linux-system-roles.journald, (unknown version)
- linux-system-roles.kdump, (unknown version)
- linux-system-roles.kernel_settings, (unknown version)
- linux-system-roles.logging, (unknown version)
- linux-system-roles.metrics, (unknown version)
- linux-system-roles.nbde_client, (unknown version)
- linux-system-roles.nbde_server, (unknown version)
- linux-system-roles.network, (unknown version)
- linux-system-roles.podman, (unknown version)
- linux-system-roles.postfix, (unknown version)
- linux-system-roles.rhc, (unknown version)
- linux-system-roles.selinux, (unknown version)
- linux-system-roles.ssh, (unknown version)
- linux-system-roles.sshd, (unknown version)
- linux-system-roles.storage, (unknown version)
- linux-system-roles.timesync, (unknown version)
- linux-system-roles.tlog, (unknown version)
- linux-system-roles.vpn, (unknown version)
- rhel-system-roles.ad_integration, (unknown version)
- rhel-system-roles.certificate, (unknown version)
- rhel-system-roles.cockpit, (unknown version)
- rhel-system-roles.crypto_policies, (unknown version)
- rhel-system-roles.firewall, (unknown version)
- rhel-system-roles.ha_cluster, (unknown version)
- rhel-system-roles.journald, (unknown version)
- rhel-system-roles.kdump, (unknown version)
- rhel-system-roles.kernel_settings, (unknown version)
- rhel-system-roles.logging, (unknown version)
- rhel-system-roles.metrics, (unknown version)
- rhel-system-roles.nbde_client, (unknown version)
- rhel-system-roles.nbde_server, (unknown version)
- rhel-system-roles.network, (unknown version)
- rhel-system-roles.podman, (unknown version)
- rhel-system-roles.postfix, (unknown version)
- rhel-system-roles.rhc, (unknown version)
- rhel-system-roles.selinux, (unknown version)
- rhel-system-roles.ssh, (unknown version)
- rhel-system-roles.sshd, (unknown version)
- rhel-system-roles.storage, (unknown version)
- rhel-system-roles.timesync, (unknown version)
- rhel-system-roles.tlog, (unknown version)
- rhel-system-roles.vpn, (unknown version)

3.介绍rhel提供的部分系统角色

名称描述功能
rhel-system-roles.timesync配置时间同步,使用网络时间协议配置
rhel-system-roles.selinux配置selinux的模式、文件、端口上下文、用户等
rhel-system-roles.network配置网络接口
rhel-system-roles.kdump配置kdump崩溃恢复服务
rhel-system-roles.postfix配置使用postfix配置邮件传输代理
rhel-system-roles.firewall配置防火墙

4.timesync和selinux示例

(1)timesync

实际上,example文件已经给出了完整的模版,按照其中的参数修改为自己需求即可

[root@main roles]# cat /usr/share/doc/rhel-system-roles-1.21.2/timesync/example-multiple-ntp-servers-playbook.yml 
---
- name: Example with multiple servers
  hosts: "{{ targets }}"   #更改为自己管理的主机
  vars:
    timesync_ntp_servers:
      - hostname: 0.pool.ntp.org    #hostname表示要同步的ntp服务器
        iburst: true
      - hostname: 1.pool.ntp.org
        iburst: true
      - hostname: 2.pool.ntp.org
        iburst: true
      - hostname: 3.pool.ntp.org
        iburst: true
  roles:
    - rhel-system-roles.timesync

#将模板文件拷贝过来并改名
[root@main roles]# cp /usr/share/doc/rhel-system-roles-1.21.2/timesync/example-multiple-ntp-servers-playbook.yml timesync.yaml
[root@main roles]# cat timesync.yaml 
---
- name: Example with multiple servers
  hosts: servera   #修改hosts
  vars:
    timesync_ntp_servers:
      - hostname: 0.pool.ntp.org   #就使用模版提供的ntp也行
        iburst: true     #填写布尔值,启用或禁用快速初始化同步,默认为no,一般设置yes
      - hostname: 1.pool.ntp.org
        iburst: true
      - hostname: 2.pool.ntp.org
        iburst: true
      - hostname: 3.pool.ntp.org
        iburst: true
  roles:
    - rhel-system-roles.timesync
​

[root@main roles]# ansible servera -m shell -a 'head /etc/chrony.conf'  
#查看是否应用成功
servera | CHANGED | rc=0 >>
#
# Ansible managed
#
# system_role:timesync
​
​
server 0.pool.ntp.org iburst
server 1.pool.ntp.org iburst
server 2.pool.ntp.org iburst
server 3.pool.ntp.org iburst
​

[root@main roles]# ansible servera -m shell -a 'chronyc sources'
servera | CHANGED | rc=0 >>
210 Number of sources = 4
MS Name/IP address         Stratum Poll Reach LastRx Last sample               
===============================================================================
^+ electrode.felixc.at           2   6    37    96    +49ms[+8671us] +/-  140ms
^- ntp5.flashdance.cx            2   6    75    34    +48ms[  +48ms] +/-  149ms
^* makaki.miuku.net              3   6    77    35    -29ms[  -69ms] +/-  128ms
#测试第一次这个可用,成功
^- a.chl.la                      2   6    75    35    +48ms[  +48ms] +/-  139ms

(2)selinux

修改过后需要重启

[root@main roles]# cp /usr/share/doc/rhel-system-roles-1.21.2/selinux/example-selinux-playbook.yml selinux.yaml
[root@main roles]# vim selinux.yaml 
[root@main roles]# cat selinux.yaml 
---
- name: Manage SELinux policy example
  hosts: all
  vars:
    # Use "targeted" SELinux policy type
    selinux_policy: targeted
    # Set "enforcing" mode
    selinux_state: enforcing    #模版默认设置的是enforcing
    # Switch some SELinux booleans
    selinux_booleans:
      # Set the 'samba_enable_home_dirs' boolean to 'on' in the current
      # session only
      - {name: 'samba_enable_home_dirs', state: 'on'}
      # Set the 'ssh_sysadm_login' boolean to 'on' permanently
      - {name: 'ssh_sysadm_login', state: 'on', persistent: 'yes'}
    # Map '/tmp/test_dir' and its subdirectories to the 'user_home_dir_t'
    # SELinux file type
    selinux_fcontexts:
      - {target: '/tmp/test_dir(/.*)?', setype: 'user_home_dir_t', ftype: 'd'}
    # Restore SELinux file contexts in '/tmp/test_dir'
    selinux_restore_dirs:
      - /tmp/test_dir
    # Map tcp port 22100 to the 'ssh_port_t' SELinux port type
    selinux_ports:
      - {ports: '22100', proto: 'tcp', setype: 'ssh_port_t', state: 'present'}
    # Map the 'sar-user' Linux user to the 'staff_u' SELinux user
    selinux_logins:
      - {login: 'sar-user', seuser: 'staff_u', serange: 's0-s0:c0.c1023',
         state: 'present'}
    # Manage modules
    selinux_modules:
      # Install the 'localpolicy.cil' with priority 300
      - {path: "localpolicy.cil", priority: "300", state: "enabled"}
      # Disable the 'unconfineduser' module with priority 100
      - {name: "unconfineduser", priority: "100", state: "disabled"}
      # Remove the 'temporarypolicy' module with priority 400
      - {name: "temporarypolicy", priority: "400", state: "absent"}
​
  # Prepare the prerequisites required for this playbook
  tasks:
    - name: Creates directory
      file:
        path: /tmp/test_dir
        state: directory
        mode: "0755"
    - name: Add a Linux System Roles SELinux User
      user:
        comment: Linux System Roles SELinux User
        name: sar-user
    - name: Execute the role and catch errors
      block:
        - name: Include selinux role
          include_role:
            name: rhel-system-roles.selinux
      rescue:
        # Fail if failed for a different reason than selinux_reboot_required.
        - name: Handle errors
          fail:
            msg: "role failed"
          when: not selinux_reboot_required
​
        - name: Restart managed host
          reboot:
​
        - name: Wait for managed host to come back
          wait_for_connection:
            delay: 10
            timeout: 300
​
        - name: Reapply the role
          include_role:
            name: rhel-system-roles.selinux

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1142821.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

操作系统中套接字和设备独立性软件的关系

网络编程就是编写程序让两台联网的计算机相互交换数据。在我们不需要考虑物理连接的情况下,我们只需要考虑如何编写传输软件。操作系统提供了名为“套接字”,套接字是网络传输传输用的软件设备。 这是对软件设备的解释: 在操作系统中&#…

Unity ScrollView最底展示

Unity ScrollView最底展示 问题方案逻辑 问题 比如在做聊天界面的时候我们肯定会使用到ScrollView来进行展示我们的聊天内容,那么这个时候来新消息的时候就需要最底展示,我认为这里有两种方案; 一种是通过算法每一条预制体的高度*一共多少…

轮转数组(Java)

大家好我是苏麟 , 这篇文章是凑数的 ... 轮转数组 描述 : 给定一个整数数组 nums,将数组中的元素向右轮转 k 个位置,其中 k 是非负数。 题目 : 牛客 NC110 旋转数组: 这里牛客给出了数组长度我们直接用就可以了 . LeetCode 189.轮转数组 : 189. 轮…

Python---break关键字对for...else结构的影响

for循环中添加else结构 循环可以和else配合使用, else下方缩进的代码指的是当循环正常结束之后要执行的代码。 强调: 循环 正常结束,else之后要执行的代码。 非正常结束,其else中的代码是不会执行的。(如遇到br…

类和对象(1):类,对象,this指针

面向过程和面向对象初步认识: C语言是面向过程的,关注的是过程,分析出问题求解的步骤,用函数调用逐步解决。C是基于面向对象的,关注的是对象,将一件事情拆分成不同的对象,靠对象之间的交互完成。…

【.NET Core】创建一个在后台运行的控制台程序(ConsoleApp)

文章目录 1. 添加Nuget包2. 修改Program.cs3. 添加TestService 借助.NET的通用主机(IHostBuilder)可以轻易创建一个可以执行后台任务的程序 1. 添加Nuget包 Microsoft.Extensions.Hosting 2. 修改Program.cs 通过Host获取IHostService,然…

SSD: Single Shot MultiBox Detector(2016.11)

文章目录 AbstractIntroduction此前本文贡献总结如下: The Single Shot Detector (SSD)SSD ModelMulti-scale feature maps for detectionConvolutional predictors for detectionDefault boxes and aspect ratiosTrainingMatching strategyTraining objectiveChoosing scales …

python---for循环结构中的else结构(是同级关系)

为什么需要在for循环中添加else结构 循环可以和else配合使用, else下方缩进的代码指的是当循环正常结束之后要执行的代码。 强调: 循环 正常结束,else之后要执行的代码。 非正常结束,其else中的代码是不会执行的。&#xf…

GienTech动态|入选软件和信息技术服务名牌企业;荣获城市数字化转型优秀案例;参加第四届深圳国际人工智能展

中电金信入选“2023第二届软件和信息技术服务名牌企业” 近日,中国电子信息行业联合会发布了“2023第二届软件和信息技术服务名牌企业”名单,中电金信入选。此名单发布原则,重点突出技术创新力。突出市场影响力,品牌建设良好&…

Leetcode刷题笔记--Hot81--90

1--打家劫舍III 主要思路: 基于从下到上的 dp 回溯法,每一个节点只有两种状态,dp[0]表示被打劫,dp[1]表示不被打劫; 当前节点被打劫时,其孩子只能都不被打劫;dp[0] left[1] right[1] cur->…

redis集群理论和搭建

目录 环境 一,安装和部署redis 1,安装 2,部署 ​编辑 3,允许非本机连接redis 二、主从模式 主从模式搭建: 三,哨兵模式 哨兵模式搭建 四,集群模式 架构细节: 心跳机制 集群模式搭建&#xff1a…

【NLP】word复制指定内容到新的word文档

目录 1.python代码 2.结果 需求: 复制word文档里的两个关键字(例如“起始位置”到“结束位置”)之间的内容到新的word文档。 前提:安装win32包,通过pip install pywin32命令直接安装。话不多说,直接上代码…

底层全部重构,小米澎湃OS完整系统架构公布

上周,雷军发文称小米全新操作系统澎湃 OS 正式版已完成封包,将逐步接替 MIUI。而后,又有网友曝光小米澎湃 OS 界面。 今日,雷军再度发表长文预热小米澎湃 OS,正式公布了完整系统架构。 据介绍,从架构设计之…

CSS基础入门03

目录 1.圆角矩形 1.1基本用法 1.2生成圆形 1.3生成圆角矩形 1.4展开写法 2.Chrome 调试工具--查看 CSS 属性 2.1打开浏览器 2.2标签页含义 2.3elements 标签页使用 3.元素的显示模式 3.1块级元素 3.2行内元素/内联元素 3.3行内元素和块级元素的区别 3.4改变显示模…

Leetcode刷题详解——寻找峰值

1. 题目链接:162. 寻找峰值 2. 题目描述: 峰值元素是指其值严格大于左右相邻值的元素。 给你一个整数数组 nums,找到峰值元素并返回其索引。数组可能包含多个峰值,在这种情况下,返回 任何一个峰值 所在位置即可。 你可…

Zabbix监控IP地址是否畅通

一、fping安装 1.下载fping安装包 wget http://www.fping.org/dist/fping-4.0.tar.gz下载失败的,请看 https://download.csdn.net/download/qq_45748758/88477979 资源包已上传,免费 2.解压安装包 tar -xf fping-4.0.tar.gz3.安装 cd fping-4.0 ./c…

在HTML当中引入Vue控件,以element-ui为例

前情:需要实现一个同时满足按天、按周、按月选择的时间选择器,但是以HTML为基础写的都不太满足我的要求,要么只能按天选择,要么就是想选择久远的时间得点很久,除非自己写捷径,所以就看上了element-ui的这个…

【开源】基于SpringBoot的计算机机房作业管理系统的设计和实现

目录 一、摘要1.1 项目介绍1.2 项目录屏 二、功能模块2.1 登录注册模块2.2 课程管理模块2.3 课时管理模块2.4 学生作业模块 三、系统设计3.1 用例设计3.2 数据库设计3.2.1 课程表3.2.2 课时表3.2.3 学生作业表 四、系统展示五、核心代码5.1 查询课程数据5.2 新增课时5.3 提交作…

Linux中shell的执行流控制

目录 一、for语句 1、for语句的基本格式 2、示例 二、条件语句 1、while…do语句 2、until…do语句 3、if …then语句 4、示例 三、case语句 四、expect应答语句 1、固定答案 2、将expect与bash环境结合 3、示例 五、终止语句 一、for语句 作用:为…

论文-分布式-并发控制-并发控制问题的解决方案

目录 参考文献 问题 解法与证明 易读版本 参考文献 Dijkstra于1965年发表文章Solution of a Problem in Concurrent Programming Control,引出并发系统下的互斥(mutual exclusion)问题,自此开辟了分布式计算领域Dijkstra在文中给出了基于共享存储原子…