You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Puppet中通过Hiera访问嵌套哈希及Puppet 3兼容问题解决

Puppet嵌套哈希迁移Hiera及兼容3.8.7的问题解决

初始代码与迁移需求

原本在Puppet类中直接定义嵌套哈希$config用于后续深度合并:

$config = {
    'foo'       => {
      'fvar1'   => 'fvar1-string',
      'fvar2'   => 'fvar2-string',
    },
    'bar'  => {
      'bvar1'  => 'bvar1-string',
      'bvar2'  => 'bvar2-string',
    },
}

需求是将这些数据迁移至Hiera管理,且对foo和bar两个子哈希各自仅执行一次Hiera查找。

初始尝试与问题

配置Hiera数据如下:

role::fb:
  foo:
    fvar1: 'fvar1-string'
    fvar2: 'fvar2-string'
  bar:
    bvar1: 'bvar1-string'
    bvar2: 'bvar2-string'

对应的Puppet代码:

class test {
  $config = {
    'foo'  => hiera('role::fb::foo', undef),
    'bar'  => hiera('role::fb::bar', undef),
  }
  notify { "Config: ${config}": }
}

include test

执行后foo和bar均为空:

[root@puppetclient1 ~]# puppet agent -t
Info: Using configured environment 'production'
Info: Retrieving pluginfacts
Info: Retrieving plugin
Info: Retrieving locales
Info: Caching catalog for puppetclient1.home.arpa
Info: Applying configuration version '1684256670'
Notice: Config: {foo => , bar => }
Notice: /Stage[main]/Test/Notify[Config: {foo => , bar => }]/message: defined 'message' as 'Config: {foo => , bar => }'
Notice: Applied catalog in 0.01 seconds
[root@puppetclient1 ~]#

问题根源:Hiera中不存在role::fb::foo和role::fb::bar这两个顶级键,它们是role::fb哈希下的子键,直接通过hiera()查找子键路径无法匹配数据。

Puppet 5兼容方案与3.8.7语法冲突

在Puppet 5中,可通过先获取整个role::fb哈希再提取子键的方式解决:

class fb {
  $config = {
    'foo'  => hiera('role::fb', undef)['foo'],
    'bar'  => hiera('role::fb', undef)['bar'],
  }
  notify { "Config: ${config}": }
}

include fb

但该写法在Puppet 3.8.7中会触发语法错误:

Error: Could not retrieve catalog from remote server: Error 400 on SERVER: Syntax error at '['; expected ']' at /etc/puppet/environments/production/modules/A/manifests/fb.pp:3 on node puppetclient1.home.arpa
Warning: Not using cache on failed catalog
Error: Could not retrieve catalog; skipping run

原因:Puppet 3.x不支持直接对函数返回值进行哈希索引(即hiera(...)['key']语法),必须先将哈希赋值给变量再提取子键。

最终解决方案

将foo和bar提升为Hiera的顶级键,修改Hiera配置:

role::fb::foo:
  fvar1: 'fvar1-string'
  fvar2: 'fvar2-string'
role::fb::bar:
  bvar1: 'bvar1-string'
  bvar2: 'bvar2-string'

保持最初的Puppet代码即可正常获取数据,同时满足每个子哈希仅一次Hiera查找的需求,且完全兼容Puppet 3.8.7版本。

内容的提问来源于stack exchange,提问作者JG7

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 14:12:55