Skip to content

Instantly share code, notes, and snippets.

@lavoiesl
Last active December 4, 2022 10:27
Show Gist options
  • Save lavoiesl/4539865 to your computer and use it in GitHub Desktop.
Save lavoiesl/4539865 to your computer and use it in GitHub Desktop.
Puppet: Generate a unique integer id base on the hostname
#
# Generate a unique integer id base on the hostname
# It works by stripping $domain from the $::fqdn,
# removing all characters except alphanumeric and converting to base 10
# $domain is provided if you have complex domains like *.hosting.example.com
#
class uniqueid (
$domain = $::domain,
) {
$node_id = inline_template("<%= '$::fqdn'.gsub('$domain','').gsub(/[^a-z0-9]/i,'').to_i(36) %>")
}
@t-pascal
Copy link

Nice code, I've used it myself. Two things I noticed. You use //i (case insensitive match). So there is a possibility that capital letters might appear (but this is a minor issue with fqdn). I would recommend '$::fqdn'..(...).downcase.gsub(...) instead.

Second issue I ran into was that I needed to modulus to get 32-bit integers. It may be tempting to use %232 or 231. DO NOT DO THIS :) I have run into many instances where host1.example.com and host2.example.com have the same remainder. Use a large prime Mersenne like 2**31-1 instead. :)

@ybrock
Copy link

ybrock commented Feb 25, 2019

Exactly what I was looking for.

Excellent !

Thank you for this inline_template ! I wanted to use a integer derivated from a node node in order to "modulo" it, in order to use different puppetmaster, spreading the load of pupetmasters depending on ::fqdn.

Perfect !

@CoolCold
Copy link

CoolCold commented Dec 4, 2022

for server_id in MySQL, used extra modulo % operator on top, giving range from 0 to 255

    $_server_id = Integer(inline_template("<%= '$::fqdn'.gsub('$::domain','').gsub(/[^a-z0-9]/i,'').to_i(36) % 256 %>"))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment