从不同的人偶模块扩展 class

Extend a class from different puppet module

我需要从不同的 Puppet 模块扩展 class。是否有可能做到这一点?如果是,语法是什么?

在 Puppet 中,class a::b 可以通过 inherits 关键字继承 class a 。这允许 class a::b 到 "extend" class a.

请注意,Puppet 建议您在需要时尽量不要这样做。特别是,大多数可以通过继承实现的功能也可以通过使用 include 函数 仅包含基 class 来实现。有关更多信息,请参阅文档 here.

如果您确实选择使用继承,class a 会自动首先声明; class a 成为 class a::b 的父作用域,因此它接收所有变量和资源默认值的副本; class a::b 中的代码有权覆盖 class a.

中设置的资源属性

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

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

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" 的注释。

如文档中所述,在覆盖作为数组的资源属性时,可以添加到该数组而不是使用 +> "plusignment" 运算符进行替换。这是一个很少使用的功能,但应该在这种情况下提及。有关代码示例,请参见上面的 link。