optionally passing a parameter to puppet resource

时光总嘲笑我的痴心妄想 提交于 2019-12-13 17:19:31

问题


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

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?


回答1:


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

or using automatic Hiera lookups similar to:

example::id:
  uid: 1000
  gid: 1000

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.

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.



来源:https://stackoverflow.com/questions/40530656/optionally-passing-a-parameter-to-puppet-resource

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!