簡體   English   中英

在 puppet erb 模板中迭代 hash 的數組

[英]iterate over array of hash in puppet erb template

我在 puppet 的 hieradata 中定義了以下值

globals::myservers:
  - fqdn: "host1.example.com"
    port: 22
    protocol: "ssh"
  - fqdn: "host2.example.com"
    port: 22
    protocol: "ssh"

我希望它用上述數據打印以下值

my_servers = host1.example.com host2.example.com

您的 hiera 數據看起來像您有一個名為 myservers 的數組,其中每個元素都包含一個 hash。

# Build a =data structure the same as you have in hiera.
$myservers = [ {fqdn => 'host1', port => '22' }, {fqdn => 'host2', port => '22' } ]

# Use the map function to extract all the values for fqdn into an array.
$fqdnarray = $myservers.map |$item| { $item[fqdn] }

# use the join function to turn the array into a string.
$fqdnstring = join($fqdnarray,',')

# Print the output
notify { 'Hosts message':
  message => "my_servers = ${fqdnstring}"
}

您應該能夠將上述代碼直接放入文件中,我們將其命名為 test.pp,然后在裝有 Puppet 代理的機器上運行puppet apply test.pp以查看它的作用。

首先要做的是將數據加載到 Puppet 中。 Hiera 鍵適用於自動將數據綁定到名為globals的 class 的參數$myservers

class globals(
  Array[Hash[String, String]] $myservers
) {
  # ... do something with $myservers ...
}

但是,如果您還沒有這樣的 class,那么您也可以從任何其他 class 或任何定義的類型中查找數據:

class mymodule::any_class {
  $myservers = lookup('globals::myservers', Array[Hash[String, String]])
  # ... do something with $myservers ...
}

獲得數據后,問題是如何編寫一個 ERB 模板來迭代它並根據需要對其進行格式化。 這並不難,只要您知道一些 Ruby(畢竟這就是 ERB 中的“R”代表)。 想要的模板可能是這樣的......

my_servers = <%= @myservers.map { |server| server['fqdn'] } .join(' ') %>

在模板內部,Ruby @myservers變量綁定到來自評估模板的本地 scope 的$myservers Puppet 變量。 該腳本提取所有數組元素的“fqdn”成員,並將它們的字符串表示形式與空格分隔符連接在一起。

至於調用模板評估,您可以選擇將模板放入單獨的文件並使用template() function,或者將其直接放入清單並使用inline_template() 例如,

  $formatted_server_list = inline_template(
      "my_servers = <%= @myservers.map { |server| server['fqdn'] } .join(' ') %>")
  notify { "${formatted_server_list}": }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM