Skip to content

Instantly share code, notes, and snippets.

@purplexa
Last active May 13, 2017 06:00
Show Gist options
  • Save purplexa/59140e5979807f68b0e5c8427102bfad to your computer and use it in GitHub Desktop.
Save purplexa/59140e5979807f68b0e5c8427102bfad to your computer and use it in GitHub Desktop.
create_resources in native puppet that works with metaparameters
function create_resources_with_metaparameters (
Variant[String, Type[Resource]] $type,
Hash[String, Hash[String, Any]] $resources,
Optional[Hash[String, Any]] $defaults = undef,
) {
$resources.each |$resource, $attributes| {
Resource[$type] {
$resource: * => $attributes.prepare_attributes();
default: * => $defaults.prepare_attributes();
}
}
}
function prepare_attributes (Optional[Hash[String, Any]] $attributes) {
$attributes.lest || { {} }.filter |$items| { $items[1] != undef }.reduce({})
|Hash $memo,
Variant[Tuple[Enum[before, consume, export, notify, require, subscribe],
Array[Variant[Type[Resource], Pattern[/\A[A-Z][a-z]*(?:::[A-Z][a-z]*)*\[[^\[\]]+\]\Z/]]]],
Tuple[String, Data]] $items| {
if $items =~ Tuple[String, Data] {
$memo + Hash.new($items)
}
else {
$resources = $items[1].map |$item| {
case $item {
Resource: {
$item
}
/\A([A-Z][a-z]*(?:::[A-Z][a-z]*)*)\[([^\[\]]+)\]\Z/: {
Resource[$1][$2]
}
}
}
$memo + { $items[0] => $resources }
}
}
}
$foo = {
'notify' => {
'one' => {
'message' => 'hydrogen',
},
'two' => {
'message' => 'helium',
'before' => [Notify[one]],
},
'three' => {
'message' => 'lithium',
'subscribe' => [Notify[one]],
},
},
File => {
'/tmp/puppet-foo' => {
'ensure' => 'file',
'mode' => '0640',
'require' => ['Notify[two]'],
'notify' => ['Notify[one]', Notify[three]],
},
},
}
$foo.each |$type, $resources| {
create_resources_with_metaparameters($type, $resources)
}
> puppet apply create_resources_with_metaparameters.pp
Notice: Compiled catalog for node.example.com in environment production in 0.10 seconds
Notice: helium
Notice: /Stage[main]/Main/Notify[two]/message: defined 'message' as 'helium'
Notice: lithium
Notice: /Stage[main]/Main/Notify[three]/message: defined 'message' as 'lithium'
Notice: hydrogen
Notice: /Stage[main]/Main/Notify[one]/message: defined 'message' as 'hydrogen'
Notice: Applied catalog in 0.05 seconds
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment