ERB介绍

全称是Embedded RuBy,意思是嵌入式的Ruby,是一种文本模板技术,用过JSP的话,会发现两者语法很像。

我们项目中一般用ERB来产生各模块的配置文件。ERB模板也可以用来产生Web页面(之前搞过一段时间ROR开发,模板用的haml),也可以用来产生其他文件。

<% %>与<%= %>

<%Ruby脚本%>,一般是Ruby的逻辑脚本,但是不会写入到目标文件中。

<%= Ruby脚本%> ,脚本的执行结果会写入到目标文件中。

举例如下(代码来源):

这段代码是从Hash中读取信息创建sql语句保存到文件中。

  1. require "erb"
  2. domains = {...}
  3. sqlTemplate = ERB.new %q{
  4. <%for organization in domains.keys%>
  5. insert into org_domain(Domain, organization) values('<%=domains[organization]%>','<%=organization%>');
  6. <%end%>
  7. }
  8. sqlFile = File.new("./sql.sql", "w")
  9. sqlFile.puts sqlTemplate.result

使输出紧凑

<%= -%>

You can trim line breaks after expression-printing tags by adding a hyphen to the closing tag delimiter.

  • -%> — If the tag ends a line, trim the following line break.

意思是如果<%= -%>表达式中,-%>是一行的结尾,会忽略后面的换行。

<%- -%>

You can trim whitespace surrounding a non-printing tag by adding hyphens (-) to the tag delimiters.

  • <%- — If the tag is indented, trim the indentation.
  • -%> — If the tag ends a line, trim the following line break.

意思是<%-前面是空白符时,会删除这些空白符;-%> 含义同上。

puppet中一般怎么使用erb

举例如下:

目录结构

  1. ~/tmp# tree -L 2 puppet
  2. puppet
  3. ├── manifests
  4. ├── nodes
  5. └── site.pp
  6. └── modules
  7. ├── xxx
  8. └── nginx

这里是大的目录结构。


manifests的内容如下:

  1. ~/tmp/puppet# tree -L 2 manifests
  2. manifests
  3. ├── nodes
  4.    ├── controller-192-41-1-185.pp
  5.    ├── controller-192-41-1-186.pp
  6.    ├── controller-192-41-1-187.pp
  7.    ├── controller-192-41-1-191.pp
  8.    └── controller-192-41-1-202.pp
  9. └── site.pp

这里每个.pp文件是对应每个agent节点的定义,具体内容见下一节。


每个模块下的内容类似,现在只以nginx举例。

  1. ~/tmp/puppet/modules# tree -L 3 nginx/
  2. nginx/
  3. ├── files
  4.    ├── xxxClientCert.jks
  5.    ├──xxxServerCert.jks
  6.    ├── README.md
  7.    ├── server.crt
  8.    └── server.key
  9. ├── manifests
  10.    ├── config.pp
  11.    ├── init.pp
  12.    ├── params.pp
  13.    └── service.pp
  14. └── templates
  15. └── conf.d
  16. ├── nginx.conf.erb
  17. ├── ssl_restart_oms.sh.erb
  18. ├── web-hedex.xml.erb
  19. └── web.xml.erb

具体模块的manifests目录下是各个类的定义,templates定义了各个模板,模板会在manifests下的类中被引用。

类的定义


  1. ~/tmp/puppet/manifests# cat site.pp
  2. import 'nodes/*.pp'
  3. $puppetserver='controller-192-41-1-191'

下面是一个node的定义:

  1. ~/tmp/puppet/manifests/nodes# cat controller-192-41-1-191.pp
  2. node 'controller-192-41-1-191' {
  3. $xxx = "true"
  4. #这里是各种变量的定义
  5. Class['aaa']->Class['bbb']->Class['ccc']->Class['nginx']->Class['ddd']
  6. include aaa,bbb,ccc,nginx,ddd
  7. }

模板中使用的变量就是来自这里的定义。


总结如下

nginx/manifests下的各个pp文件是各个类的定义,类的定义中使用了nginx/templates中定义的模板,这些类被controller-192-41-1-191.pp 文件引用,controller-192-41-1-191.pp 文件中定义了模板中使用的变量。

访问puppet 变量

模板可以访问puppet的变量,这是模板的主要数据来源。

一个ERB模板有自己的本地作用域,它的父作用域是引用该模板的类。这意味着,模板可以使用短名称访问父类中的变量,但是不能向父类中添加新的变量。

在ERB模板中,有两种方式访问变量。

  • @variable
  • scope['variable'] (旧的形式为:scope.lookupvar('variable'))

@variable

原文:

All variables in the current scope (including global variables) are passed to templates as Ruby instance variables, which begin with “at” signs (@). If you can access a variable by its short name in the surrounding manifest, you can access it in the template by replacing its $ sign with an @. So $os becomes @os, $trusted becomes @trusted, etc.

当前作用域的所有变量(包括全局变量)都会以Ruby实例变量的形式传给模板。如果你在模板中可以使用短名称访问一个变量,你就可以使用"@"代替"$"。所以,$os就变成了@os,$trusted就变成了@trusted。

这是访问变量最直接清晰的方式,但是这种方式不能访问其他作用域的变量,需要访问其他作用域的变量时,你需要使用下面的方式。

scope['variable'] or scope.lookupvar('variable')

Puppet可以使用对象scope来以散列表的方式访问变量。例如,访问$ntp::tinker你可以使用scope['ntp::tinker']这种形式。

还有另一种方式使用scope对象,就是通过它的lookupvar方法来访问变量,该方法需要传入要访问的变量名,例如,scope.lookupvar('ntp::tinker')。这和上面的方式效果是一样的,但是使用起来没有scope['ntp::tinker']更简洁直观。

puppet类型和Ruby类型的对应关系

这部分表格,就不翻译了,直接贴图。

未定义变量

如果一个puppet变量没有定义的话,它的值是undef,意思是,在模板中它的值是nil。

含义是Puppet变量值为undef,对应Ruby变量值为nil。

在模板中使用puppet函数

  • 所有的函数都以scope对象的方法调用;
  • 函数名的开头都必须加上前缀"function_";
  • 函数的参数必须以数组的形式传递,即使只有一个参数。

    例如,在一个模板中引用另一个模板:

<%= scope.function_template(["my_module/template2.erb"]) %>

模板示例

  1. # ntp.conf: Managed by puppet.
  2. #
  3. <% if @tinker == true and (@panic or @stepout) -%>
  4. # Enable next tinker options:
  5. # panic - keep ntpd from panicking in the event of a large clock skew
  6. # when a VM guest is suspended and resumed;
  7. # stepout - allow ntpd change offset faster
  8. tinker<% if @panic -%> panic <%= @panic %><% end %><% if @stepout -%> stepout <%= @stepout %><% end %>
  9. <% end -%>
  10. <% if @disable_monitor == true -%>
  11. disable monitor
  12. <% end -%>
  13. <% if @disable_auth == true -%>
  14. disable auth
  15. <% end -%>
  16. <% if @restrict != [] -%>
  17. # Permit time synchronization with our time source, but do not
  18. # permit the source to query or modify the service on this system.
  19. <% @restrict.flatten.each do |restrict| -%>
  20. restrict <%= restrict %>
  21. <% end -%>
  22. <% end -%>
  23. <% if @interfaces != [] -%>
  24. # Ignore wildcard interface and only listen on the following specified
  25. # interfaces
  26. interface ignore wildcard
  27. <% @interfaces.flatten.each do |interface| -%>
  28. interface listen <%= interface %>
  29. <% end -%>
  30. <% end -%>
  31. <% if @broadcastclient == true -%>
  32. broadcastclient
  33. <% end -%>
  34. # Set up servers for ntpd with next options:
  35. # server - IP address or DNS name of upstream NTP server
  36. # iburst - allow send sync packages faster if upstream unavailable
  37. # prefer - select preferrable server
  38. # minpoll - set minimal update frequency
  39. # maxpoll - set maximal update frequency
  40. <% [@servers].flatten.each do |server| -%>
  41. server <%= server %><% if @iburst_enable == true -%> iburst<% end %><% if @preferred_servers.include?(server) -%> prefer<% end %><% if @minpoll -%> minpoll <%= @minpoll %><% end %><% if @maxpoll -%> maxpoll <%= @maxpoll %><% end %>
  42. <% end -%>
  43. <% if @udlc -%>
  44. # Undisciplined Local Clock. This is a fake driver intended for backup
  45. # and when no outside source of synchronized time is available.
  46. server 127.127.1.0
  47. fudge 127.127.1.0 stratum <%= @udlc_stratum %>
  48. restrict 127.127.1.0
  49. <% end -%>
  50. # Driftfile.
  51. driftfile <%= @driftfile %>
  52. <% unless @logfile.nil? -%>
  53. # Logfile
  54. logfile <%= @logfile %>
  55. <% end -%>
  56. <% unless @peers.empty? -%>
  57. # Peers
  58. <% [@peers].flatten.each do |peer| -%>
  59. peer <%= peer %>
  60. <% end -%>
  61. <% end -%>
  62. <% if @keys_enable -%>
  63. keys <%= @keys_file %>
  64. <% unless @keys_trusted.empty? -%>
  65. trustedkey <%= @keys_trusted.join(' ') %>
  66. <% end -%>
  67. <% if @keys_requestkey != '' -%>
  68. requestkey <%= @keys_requestkey %>
  69. <% end -%>
  70. <% if @keys_controlkey != '' -%>
  71. controlkey <%= @keys_controlkey %>
  72. <% end -%>
  73. <% end -%>
  74. <% [@fudge].flatten.each do |entry| -%>
  75. fudge <%= entry %>
  76. <% end -%>
  77. <% unless @leapfile.nil? -%>
  78. # Leapfile
  79. leapfile <%= @leapfile %>
  80. <% end -%>
  81. > ```
  82. **参考**
  83. [Language: Embedded Ruby (ERB) template syntax](https://docs.puppet.com/puppet/latest/reference/lang_template_erb.html)

puppet的使用:ERB模板的更多相关文章

  1. puppet的使用:ERB模板介绍

    ERB介绍 全称是Embedded RuBy,意思是嵌入式的Ruby,是一种文本模板技术,用过JSP的话,会发现两者语法很像. 我们项目中一般用ERB来产生各模块的配置文件.ERB模板也可以用来产生W ...

  2. 从入门到精通Puppet的实践之路

    本文有感于<精通Puppet配置管理工具>在豆瓣上的某些差评而顺手写的书评. 半路出家   故事要从12年初说起.  某天,部门老大让我所在team的老大调研一下当下业界的配置管理工具.于 ...

  3. puppet之模板和类

    puppet之模板和类 不同节点布置资源 vim /etc/puppet/manifests/site.pp 1 import "nodes/*.pp" 建立节点文件 mkdir ...

  4. 自动化运维工具之Puppet变量、正则表达式、流程控制、类和模板

    前文我们了解了puppet的file.exec.cron.notify这四种核心资源类型的使用以及资源见定义通知/订阅关系,回顾请参考https://www.cnblogs.com/qiuhom-18 ...

  5. CentOS7:Puppet推送Zabbix Agent

    创建zabbix模块目录: $ mkdir -p /etc/puppet/modules/zabbix/{manifests,templates} 创建init.pp清单: $ cat /etc/pu ...

  6. Puppet权威指南

    <Puppet权威指南>基本信息作者: 王冬生 丛书名: Linux/Unix技术丛书出版社:机械工业出版社ISBN:9787111485988上架时间:2014-12-25出版日期:20 ...

  7. puppet组织架构

    树结构如下: |-- puppet.conf #主配置配置文件 |-- fileserver.conf #文件服务器配置文件 |-- auth.conf #认证配置文件 |-- autosign.co ...

  8. puppet运维配置实列

    aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAABQkAAAGBCAIAAABKMKAEAAAgAElEQVR4nOydeXwU9cH/t2o9WutR+7

  9. puppet的配置清单书写

    puppet的配置清单书写 1使用数组,合并同类的 例如你想安装很多软件,如果分开来写的话,很麻烦,不简洁,这时我们可以使用数组来完成 以前我们这样来写 class packages{ package ...

随机推荐

  1. python 求最大子序列

     动态规划的本质,是对问题状态的定义和状态转移方程的定义.dynamic programming is a method for solving a complex problem by breaki ...

  2. The First Android App----Adding the Action Bar

    In its most basic form, the action bar displays the title for the activity and the app icon on the l ...

  3. OKHttp概览

    1,整体思路 从使用方法出发,首先是怎么使用,其次是我们使用的功能在内部是如何实现的,实现方案上有什么技巧,有什么范式.全文基本上是对 OkHttp 源码的一个分析与导读,非常建议大家下载 OkHtt ...

  4. 查看sql server数据库连接数的三种方法

    怎样才能查看sql server数据库连接数呢?下面就将为您介绍三种查看的方法,供您参考,希望能够帮助到您. 1.通过系统的“性能”来查看:开始->管理工具->性能(或者是运行里面输入 m ...

  5. [LeetCode] Binary Tree Maximum Path Sum(最大路径和)

    Given a binary tree, find the maximum path sum. The path may start and end at any node in the tree. ...

  6. (转)(WinForm)FormBorderStyle属性

    原地址

  7. abp+angular+bootstrap-table的使用

    问题 materialize与bootstrap框架样式冲突 问题描述 在abp模板项目中引入bootstrap-table,列设置为checkbox,checkbox无法显示. 使用firefox浏 ...

  8. SQL Server 维护计划(数据库备份)

    公司的项目都需要定期备份,程序备份关掉iis站点复制文件就可以了,难受的地方就是数据库的备份了.服务器上装的大都是英文版,一看见英文,操作都变得小心翼翼起来,生怕哪里搞错,第二天就要被安排写辞职申请了 ...

  9. SignalR 设计理念(二)

    SignalR 设计理念(二) 实现客户端和服务器端的实时通讯. 前言: 客户端方法忽略大小写,主要原因基于是URL对大小写不敏感的问题,开发者之间为了更好的协同开发,定下的开发者协议. 问题阐述 客 ...

  10. ASP.NET MVC Ajax 伪造请求

    1.前言 CSRF(Cross-site request forgery)跨站请求伪造,ASP.NET MVC 应用通过使用AJAX请求来提升用户体验,浏览器开发者工具可以一览众山小,就很容易伪造了请 ...