可选地将参数传递给 puppet 资源 [英] optionally passing a parameter to puppet resource
问题描述
有没有办法仅在设置参数时将参数传递给 puppet 资源?例如,假设我有一个创建新用户的清单,我可能想也可能不想手动设置 uid 和 gid.我能想到的最好方法是这样的:
Is there a way to pass a parameter to a puppet resource only if it's been set? For example, say I have a manifest that creates a new user, and I may or may not want to set the uid and gid manually. Best way I can think to do is like this:
class example (
$uid = undef,
$gid = undef,
$username = 'default'
) {
user { $username:
ensure => present,
# etc
}
if $uid != undef {
user { "uid-${username}":
name => $username,
uid => $uid,
require => User[$username]
}
}
if $gid != undef {
user { "gid-${username}":
name => $username,
gid => $gid,
require => User[$username]
}
}
}
但那是很多代码只是为了确定是否发送 uid 和/或 gid.有没有更好的办法?
But that is a lot of code just to determine whether or not to send the uid and/or gid. Is there a better way?
推荐答案
我认为由于多个声明,您的示例将无法编译,因为 user
资源上的 name
是正在检查唯一性的内容.话虽如此,在我看来,有几种方法可以使这个稍微好一点.
I think your example would fail to compile due to multiple declarations, because name
on the user
resource is what is being checked for uniqueness. That being said, there are a couple ways to make this slightly better in my opinion.
第一种方式涉及属性修改:
The first way involves attribute amending:
...
user { $username:
ensure => present,
# etc
}
if $uid != undef {
User[$username] { uid => $uid }
}
if $gid != undef {
User[$username] { gid => $gid }
}
第二个涉及从哈希设置属性:
The second involves setting attributes from a Hash:
class example (
Hash $id = {},
String $username = 'default'
) {
user { $username:
ensure => present,
* => $id,
# etc
}
}
然后通过声明传递额外的参数:
and then either passing the additional parameters in via declaration:
class example { 'foo':
username => 'bar',
id => { uid => 1000, gid => 1000 }
}
或使用类似于以下内容的自动 Hiera 查找:
or using automatic Hiera lookups similar to:
example::id:
uid: 1000
gid: 1000
请注意,在任何一种情况下(声明或 Hiera)都不指定 id
仍会导致 user
资源在没有 uid的情况下出现正确和预期的行为code> 或
gid
已更改.
Note that not specifying id
in either case (declaration or Hiera) will still result in the correct and expected behavior of a user
resource without uid
or gid
altered.
您可以在 https://docs.puppet 中找到这两种方法.com/puppet/latest/reference/lang_resources_advanced.html,您甚至可以从该文档中找出另一种或两种方法.
You can find both methods documented at https://docs.puppet.com/puppet/latest/reference/lang_resources_advanced.html, and you may even be able to figure out another method or two from that document.
这篇关于可选地将参数传递给 puppet 资源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!