从不同的木偶模块扩展一类

  • 本文关键字:一类 扩展 模块 puppet
  • 更新时间 :
  • 英文 :


我需要从其他木偶模块扩展一类。是否有可能做到这一点?如果是,语法是什么?

在Puppet中,A类A :: B可以通过inherits关键字继承A类。这允许A级:: B"扩展" A类A。

请注意,Puppet建议您很少需要这样做。特别是,也可以通过使用Include函数将基础类包括在内,也可以通过继承实现的大部分。有关更多信息,请参见此处的文档。

如果您选择使用继承,则首先自动声明A类;A类成为A类的父范围,因此它收到了所有变量和资源默认值的副本;A类A :: B中的代码有权覆盖A。

中设置的资源属性

使用此模式,A类A :: B也可以使用A类的变量作为其类参数之一的默认值。这导致了"参数模式",其中params.pp文件用于设置类默认。

以下简单代码示例说明了所有这些功能:

class a {
  File {
    mode => '0755',
  }
  file { '/tmp/foo':
    ensure => absent,
  }
  $x = 'I, Foo'
}
class a::b (
  $y = $a::x  # default from class a.
) inherits a {
  # Override /tmp/foo's ensure
  # and content attributes.
  File['/tmp/foo'] {
    ensure  => file,
    content => $y,
  }
  # Both /tmp/foo and /tmp/bar
  # will receive the default file
  # mode of 0755.
  file { '/tmp/bar':
    ensure => file,
  }
}

并使用RSPEC表达目录的预期最终状态:

describe 'a::b' do
  it 'overrides ensure attribute' do
    is_expected.to contain_file('/tmp/foo').with({
      'ensure'  => 'file',
    })
  end
  it 'inherits content from $x' do
    is_expected.to contain_file('/tmp/foo').with({
      'content' => "I, Foo",
    })
  end
  it 'file defaults inherited' do
    is_expected.to contain_file('/tmp/foo').with({
      'mode' => '0755',
    })
    is_expected.to contain_file('/tmp/bar').with({
      'mode' => '0755',
    })
  end
end

测试通过:

a::b
  overrides ensure attribute
  inherits content from $x
  file defaults inherited
Finished in 0.15328 seconds (files took 1.2 seconds to load)
3 examples, 0 failures

关于"加签名"的注释。

也是文档中所述的,当覆盖数组的资源属性时,可能会添加到该数组中,而不是使用+>" Plusignment"操作员替换。这是一个很少使用的功能,但应在此上下文中提及。有关代码示例,请参见上面的链接。

最新更新