如何在Puppet或Ruby中遍历嵌套dict实现Python示例的取值效果?
注:原Python示例中存在语法笔误,
'appuser'2'应为'appuser2',否则代码无法正常运行,以下方案均基于修正后的结构实现。
Ruby 环境实现
完全对齐原Python逻辑,先遍历一级键,再提取对应字段的值:
# 定义与原Python结构完全匹配的嵌套哈希 account_data = { 'account1' => { 'uid' => ['123456'], 'user' => ['appuser1'], 'appname' => ['myapp1'] }, 'account2' => { 'uid' => ['567878'], 'user' => ['appuser2'], 'appname' => ['myapp2'] } } # 遍历所有一级键,和原Python的 dict.keys() 遍历逻辑完全一致 account_data.keys.each do |account| # 若需要直接输出原数组(匹配原Python直接print数组的效果),去掉后面的 .first current_user = account_data[account]['user'].first current_uid = account_data[account]['uid'].first # 对应原Python的print输出 puts "#{current_user} #{current_uid}" end
执行后输出结果和Python版本一致:
appuser1 123456 appuser2 567878
如果原数据结构中user、uid是直接存储标量、没有包数组的话,删除对应行的.first即可正常取值。
Puppet 环境实现
原生Puppet语法(兼容Puppet 5+)
不需要嵌入自定义Ruby代码,直接用Puppet原生语法实现遍历:
# 定义和原结构一致的嵌套哈希 $account_data = { 'account1' => { 'uid' => ['123456'], 'user' => ['appuser1'], 'appname' => ['myapp1'] }, 'account2' => { 'uid' => ['567878'], 'user' => ['appuser2'], 'appname' => ['myapp2'] } } # 遍历所有一级键 $account_data.keys.each |$account| { # 若需要直接输出原数组,去掉后面的 [0] $current_user = $account_data[$account]['user'][0] $current_uid = $account_data[$account]['uid'][0] # 用notice输出到执行日志,对应Python的print notice("${current_user} ${current_uid}") }
执行Puppet代码时,日志里会输出和Python版本一致的结果。
旧版Puppet(Puppet 3及以前)兼容说明
旧版Puppet没有内置的each遍历方法,需要依赖puppetlabs-stdlib模块提供的函数实现,写法调整为:
# 基于stdlib的兼容写法 each(keys($account_data)) |$account| { $current_user = $account_data[$account]['user'][0] $current_uid = $account_data[$account]['uid'][0] notice("${current_user} ${current_uid}") }
实用扩展
实际运维场景中,提取到的user、uid值可以直接用来声明系统资源,不需要单纯打印,比如批量创建系统用户:
$account_data.keys.each |$account| { $user_name = $account_data[$account]['user'][0] $user_uid = Integer($account_data[$account]['uid'][0]) # 直接声明用户资源,Puppet会自动同步到目标节点 user { $user_name: uid => $user_uid, ensure => present, } }
内容的提问来源于stack exchange,提问作者chetan honnavile
相关产品推荐
相关产品推荐

