I want to check whether the content of a variable is an odd number. But I need an integer for it.

$ip_array = split($ipaddress, '.')
$odd_ip = $ip_array[3] % 2

if $odd_ip == 1 {
  notice("is odd")

Is there an easy way to convert a string to integer?


You can do this:

$n_timeout = 0 + $timeout

  • This breaks with stings with leading zeros, e.g. "04" – Gary van der Merwe Apr 6 '16 at 7:17
  • With puppet 4 this will cause a warning: Warning: The string '1' was automatically coerced to the numerical value 1 at ... – Slaven Rezic Nov 20 '18 at 12:46

I've taken to using the scanf function in stdlib.

An example of this:

$ram = scanf("${::memorysize_mb}", "%i")

This requires puppet >= 3.7.5

  • 1
    Note that this will return an array, where the first element is the wished value. In puppet 4 it is possible to write something like scanf(...)[0], in puppet 3 it seems to be required to split this in two statements: first assign to an array variable, then get the first element. – Slaven Rezic Nov 20 '18 at 12:53

Your code will work exactly as defined; Puppet implicitly converts strings and integers as appropriate for the comparison operator being used.

  • I got the following error: Could not match % at /etc/puppet/modules/my/manifests/target.pp:23 on node mynode.domain.de – MMore May 14 '12 at 17:16
  • If I replace '%' with '*' (testing) -> left operand of * is not a number at /etc/puppet/modules/my/manifests/target.pp:25 on node mynode.domain.de – MMore May 14 '12 at 17:20
  • 1
    Ah. You have found a genuine bug in Puppet. You should file a ticket at projects.puppetlabs.com/projects/puppet/issues/new so that we can fix it. – Daniel Pittman May 14 '12 at 18:15
  • 2
    Puppet doesn't do that when the value comes from hiera. You get a "Error 400 on SERVER: comparison of Fixnum with String failed" error. – Rob Feb 14 '14 at 15:42

Puppet 4: $odd_ip = Integer($ip_array[3]) % 2

Taken from https://github.com/puppetlabs/puppetlabs-apt/pull/743/files

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.