1、此函数用于将一个不确定长度的路径拆分成一个数组,可接受两个参数:
1.1 arg1: 一个有效的绝对路径字符串[目前未做数据类型有效性检查判断]
1.2 arg2: 一个有效的数字,用于确认哪一部分是需要puppet创建的[[可选]未做逻辑有效性判断,譬如传递数字大与路径的有效层级数是不合理]
2、直接放在模块对应的lib/puppet/parser/functions即可,这里笔者直接放在stdlib的lib/puppet/parser/functions目录下
3、未做数据类型以及逻辑错误判断(譬如arg[2]的取值范围)
4、代码和简单使用说明如下:
Code:
module Puppet::Parser::Functions newfunction(:path_to_array, :type => :rvalue) do |args| res = args[0] array = [] array.push(args[0]) if args.size == 1 while res != ‘/‘ do res = File.dirname(res) array.push(res) if res != ‘/‘ end elsif args.size == 2 e_count = args[1] - 1 e_count.times do res = File.dirname(res) array.push(res) if res != ‘/‘ end end return array end end # vim: set ts=2 sw=2 et :
Usage:
1、vim test.pp
$aaa=[‘/aaa/bbb/ccc/ddd‘, 2] $bbb=path_to_array($aaa[0]) $ccc=path_to_array($aaa[0], $aaa[1]) notify{ ‘result_$bbb‘: message => [ $bbb ] } notify{ ‘result_$ccc‘: message => [ $ccc ] }
2、puppet apply test.pp
Notice: Compiled catalog for puppet.mos.com in environment production in 1.03 seconds Notice: /aaa/bbb/ccc/ddd /aaa/bbb/ccc /aaa/bbb /aaa Notice: /Stage[main]/Main/Notify[result_$bbb]/message: defined ‘message‘ as ‘/aaa/bbb/ccc/ddd /aaa/bbb/ccc /aaa/bbb /aaa‘ Notice: /aaa/bbb/ccc/ddd /aaa/bbb/ccc Notice: /Stage[main]/Main/Notify[result_$ccc]/message: defined ‘message‘ as ‘/aaa/bbb/ccc/ddd /aaa/bbb/ccc‘ Notice: Finished catalog run in 0.60 seconds
本文出自 “自强不息” 博客,谢绝转载!
原文地址:http://mos1989.blog.51cto.com/4226977/1691291