Search code examples
puppet

optionally passing a parameter to puppet resource


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?


Solution

  • 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.