fdgg888 发表于 2015-9-6 14:59:04

puppet函数 多层路径转换数组

1、此函数用于将一个不确定长度的路径拆分成一个数组,可接受两个参数:
1.1 arg1: 一个有效的绝对路径字符串[目前未做数据类型有效性检查判断]
1.2 arg2: 一个有效的数字,用于确认哪一部分是需要puppet创建的[[可选]未做逻辑有效性判断,譬如传递数字大与路径的有效层级数是不合理]
2、直接放在模块对应的lib/puppet/parser/functions即可,这里笔者直接放在stdlib的lib/puppet/parser/functions目录下
3、未做数据类型以及逻辑错误判断(譬如arg的取值范围)
4、代码和简单使用说明如下:

Code:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
module Puppet::Parser::Functions
newfunction(:path_to_array, :type => :rvalue) do |args|

    res = args
   
    array = []
    array.push(args)

    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
      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

1
2
3
4
5
6
7
$aaa=['/aaa/bbb/ccc/ddd', 2]

$bbb=path_to_array($aaa)
$ccc=path_to_array($aaa, $aaa)

notify{ 'result_$bbb': message => [ $bbb ] }
notify{ 'result_$ccc': message => [ $ccc ] }




2、puppet apply test.pp

1
2
3
4
5
6
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/Notify/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/Notify/message: defined 'message' as '/aaa/bbb/ccc/ddd /aaa/bbb/ccc'
Notice: Finished catalog run in 0.60 seconds






页: [1]
查看完整版本: puppet函数 多层路径转换数组