ruby puppet applly和deferred函数:错误:未知的函数“MyModule::myupcase”

unguejic  于 2023-08-04  发布在  Ruby
关注(0)|答案(1)|浏览(91)

我正在按照this puppet doc测试延迟函数,下面我重复了这些步骤。

cd ~/dev/src/local/puppet_tests
pdk new module mymodule
cd mymodule
pdk new class mymodule
mkdir -p lib/puppet/functions/mymodule

字符串

  • 接下来,您应该将以下代码粘贴到manifest/init.pp文件中:
class mymodule {
  $d = Deferred("mymodule::myupcase", ["mysecret"])

  notify { example :
    message => $d
  }
}

class { 'mymodule': }

  • 接下来,在lib/puppet/functions/mymodule目录下创建一个名为myupcase.rb的文件,并粘贴以下代码:
Puppet::Functions.create_function(:'mymodule::myupcase') do
  dispatch :up do
    param 'String', :some_string
  end

  def up(some_string)
    Puppet::Pops::Types::PSensitiveType::Sensitive.new(some_string.upcase)
  end
end

  • 现在,您应该运行puppet apply manifest/init.pp
~/dev/src/local/puppet_tests/mymodule main*
❯ puppet apply manifests/init.pp
Notice: Compiled catalog for localhost.localdomain in environment production in 0.04 seconds
Error: Unknown function 'mymodule::myupcase'


删除init.pp文件中的以下部分代码,它可以工作,但只是因为您删除了对$d变量的引用:

notify { example :
    message => $d,
  }


我错过了什么?
我的S.O.是MacOX 13.4.1,puppet 8.1.0。使用brew安装了puppet-agent和pdk:

brew install --cask puppetlabs/puppet/puppet-agent
brew install --cask puppetlabs/puppet/pdk

已编辑:

我做了一个额外的测试,现在使用pdk new function创建函数,但错误仍然存在:

cd ~/dev/src/local/puppet_tests
pdk new module mymodule
cd mymodule
pdk new class mymodule
pdk new function myupcase --type=v4


它创建了一些名为spec/的附加目录,其中包含一些附加文件。最后的myupcase.rb是:

# frozen_string_literal: true

# https://github.com/puppetlabs/puppet-specifications/blob/master/language/func-api.md#the-4x-api
Puppet::Functions.create_function(:"mymodule::myupcase") do
  dispatch :myupcase do
    param 'String', :a
    return_type 'String'
  end
  # the function below is called by puppet and and must match
  # the name of the puppet function above. You can set your
  # required parameters below and puppet will enforce these
  # so change x to suit your needs although only one parameter is required
  # as defined in the dispatch method.
  def myupcase(x)
    x.upcase
  end

  # you can define other helper methods in this code block as well
end


init.pp文件保持不变。

au9on6nz

au9on6nz1#

函数本身看起来很好,您似乎已经将其正确地放置在模块中。puppet apply找不到它可能是因为您的模块不在其模块路径中(您已经确认了这一点)。如果主类试图使用模块的任何其他内容,也会出现类似的错误:其他类、已定义类型、模块数据 * 等 *。
总的来说,文档的最后一步,其中您通过applymanifests/init.pp测试函数似乎非常不明智,当它确实可以测试函数时,这只是因为模块的init.pp在顶部范围包含class { 'mymodule': },这是另一个层次的错误。
你应该这样做:

  • 从模块的init.pp中删除类声明class { 'mymodule': }。它根本不应该在那里。
  • 确保模块目录的父目录(~/dev/src/local/puppet_tests)在Puppet的modulepath中。
  • 如果你想测试puppet apply,那么在任何地方创建一个单独的清单:
    test.pp
include mymodule

字符串
注意:一般来说,我们更喜欢像include-like这样的类声明,而不是像我们从init.pp中删除的资源类声明。
使用命令/path/to/puppet apply path/to/test.pp运行测试。

相关问题