将键附加到数组的顶部

问题描述

我有一些与以下不同的 hiera(我知道这是带有两个键的无效 hiera……我不知道):

an::example::rule_files:
  my_rules:
    groups:
    - name: my_rules
      rules:
      - alert: highcpu
        expr: cpu > 90
        for: 5m
        annotations:
          summary: "cpu is too high"
          description: "cpu should be less than 90"
  someone_elses_rules:
    groups:
    - name: someone_elses_rules
      rules:
      - alert: highcpu
        expr: cpu > 70
        for: 5m
        annotations:
          summary: "cpu is too high"
          description: "cpu should be less than 70 on someone else's system"

我正在尝试将其转换为 yaml 文件(关键是文件名)。现在我知道这是无效的 hiera,我可以删除组键以使其正常工作(正是我所做的),但是当我尝试将其重新插入数组时,我无法正确设置格式。这是我正在使用的木偶代码

  $alert_files = hiera('an::example::rule_files'),$alert_files.each | String $alerts_file_name,Array $alert_config_pre | {
    $prefix = [ "groups:" ]
    $alert_config = $prefix + $alert_config_pre
    file { "/etc/prometheus/${alerts_file_name}.rules":
      ensure  => file,content => $alert_config.to_yaml,}
  }

这是我想要的:

cat /etc/prometheus/my_rules.rules
---
groups:
  - name: my_rules
    rules:
    - alert: highcpu
      expr: cpu > 90
      for: 5m
      annotations:
        summary: cpu is too high
        description: cpu should be less than 90

这是我得到的:

---
- 'groups:'
- name: my_rules
  rules:
  - alert: highcpu
    expr: cpu > 90
    for: 5m
    annotations:
      summary: cpu is too high
      description: cpu should be less than 90

任何帮助将不胜感激。我觉得这应该很简单,但我并没有真正取得任何进展(我什至无法从单词组中删除引号)。如果这在 hiera 或 puppet 中都是可能的(也许我已经定义了 hiera 错误),那就太好了;我能以任何方式取得的任何进展都将不胜感激。

解决方法

这...

  $alert_files = hiera('an::example::rule_files'),$alert_files.each | String $alerts_file_name,Array $alert_config_pre | {

... 取决于与键 an::example::rule_files 关联的数据是具有字符串键和数组值的哈希。在问题顶部显示的 YAML 中,该项目是一个带有 String 键和 Hash 值的散列。由于数据似乎与想要的文件内容匹配,问题似乎不在于 YAML(除了不一致的缩进),而在于 Puppet 代码。

为了使用您想要的数据按照您想要的方式工作,Puppet 代码可能看起来更像这样:

  $alert_files = lookup('an::example::rule_files'),$alert_files.each |String $alerts_file_name,Hash $alert_config| {
    file { "/etc/prometheus/${alerts_file_name}.rules":
      ensure  => 'file',content => $alert_config.to_yaml,}
  }

请注意,我已从弃用的 hiera() 函数切换到其替代函数 lookup()