ERB:遍历数组并输出每个值作为一行字符串的一部分

时间:2016-09-21 08:46:05

标签: ruby iteration puppet erb

我试图通过迭代来自木偶阵列的数组来编写一个sudoers文件。

这是我的傀儡课。它定义了一个数组oracle_homes

1 class oracle_home {
2   $oracle_homes = split($::oracle_homes, ',')
3   file { '/tmp/oracle_homes':
4     ensure  => file,
5     content => template('oracle/oracle.sudoer.erb'),
6   } 
7 }       
8 
9 require oracle_home

这是erb模板。

 1 Defaults    env_keep += "ORACLE_BASE ORACLE_HOME TNS_ADMIN"
 2 
 3 <% @oracle_homes.each do |oracle_home| -%>
 4 Cmnd_Alias SQLPLUS = <%= oracle_home -%>/bin/sqlplus
 5 Cmnd_Alias SRVCTL  = <%= oracle_home -%>/bin/srvctl
 6 Cmnd_Alias VOTEDSK = <%= oracle_home -%>/bin/crsctl query css votedisk
 7 <% end -%>  
 8 
 9 Runas_Alias DB    = oracle, regdb
10 Runas_Alias GRID  = oracle, grid
11 
12 zabbix ALL = (GRID) NOPASSWD: VOTEDSK
13 zabbix ALL = (DB) NOPASSWD: SQLPLUS
14 zabbix ALL = (GRID) NOPASSWD: SRVCTL
15 
16 Defaults:zabbix !authenticate
17 Defaults:zabbix !syslog

从第3行到第6行我试图生成Cmnd_Alias,但输出不是我需要的。

我得到了

 1  Defaults    env_keep += "ORACLE_BASE ORACLE_HOME TNS_ADMIN"
 2  
 3  Cmnd_Alias SQLPLUS = '/opt/oracle/regdb/product/12.1.0.2/dbhome_1'/bin/sqlplus
 4  Cmnd_Alias SRVCTL  = '/opt/oracle/regdb/product/12.1.0.2/dbhome_1'/bin/srvctl
 5  Cmnd_Alias VOTEDSK = '/opt/oracle/regdb/product/12.1.0.2/dbhome_1'/bin/crsctl query css votedisk
 6  Cmnd_Alias SQLPLUS = '/opt/oracle/regdb/product/11.2.0.4/dbhome_1'/bin/sqlplus
 7  Cmnd_Alias SRVCTL  = '/opt/oracle/regdb/product/11.2.0.4/dbhome_1'/bin/srvctl
 8  Cmnd_Alias VOTEDSK = '/opt/oracle/regdb/product/11.2.0.4/dbhome_1'/bin/crsctl query css votedisk
 9  
10  Runas_Alias DB    = oracle, regdb
11  Runas_Alias GRID  = oracle, grid
12  
13  zabbix ALL = (GRID) NOPASSWD: VOTEDSK
14  zabbix ALL = (DB) NOPASSWD: SQLPLUS
15  zabbix ALL = (GRID) NOPASSWD: SRVCTL
16  
17  Defaults:zabbix !authenticate
18  Defaults:zabbix !syslog

如何更改迭代语法以生成{/ 1}}行,如

Cmnd_Alias

2 个答案:

答案 0 :(得分:3)

我会尝试替换

3 <% @oracle_homes.each do |oracle_home| -%>
4 Cmnd_Alias SQLPLUS = <%= oracle_home -%>/bin/sqlplus
5 Cmnd_Alias SRVCTL  = <%= oracle_home -%>/bin/srvctl
6 Cmnd_Alias VOTEDSK = <%= oracle_home -%>/bin/crsctl query css votedisk
7 <% end -%>  

Cmnd_Alias SQLPLUS = <%= @oracle_homes.map { |path| "#{path}/bin/sqlplus" }.join(', ') %>
Cmnd_Alias SRVCTL  = <%= @oracle_homes.map { |path| "#{path}/bin/srvctl" }.join(', ') %>
Cmnd_Alias VOTEDSK = <%= @oracle_homes.map { |path| "#{path}/bin/crsctl query css votedisk" }.join(', ') %>

答案 1 :(得分:0)

sql_plus = []

srv_ctl = []

vote_desk = []

<% @oracle_homes.each do |oracle_home| -%>

    sql_plus << "#{oracle_home}/bin/sqlplus"

    srv_ctl << "#{oracle_home}/bin/srvctl"

    vote_desk << "#{oracle_home}/bin/crsctl query css votedisk"  
<% end -%>

Cmnd_Alias SQLPLUS = sql_plus.join(', ')

Cmnd_Alias SRVCTL  = srv_ctl.join(', ')

Cmnd_Alias VOTEDSK = vote_desk.join(', ')