8

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?

4 Answers 4

5

You can do this:

$n_timeout = 0 + $timeout

3
  • This breaks with stings with leading zeros, e.g. "04" Apr 6, 2016 at 7:17
  • With puppet 4 this will cause a warning: Warning: The string '1' was automatically coerced to the numerical value 1 at ... Nov 20, 2018 at 12:46
  • Puppet documentation suggests this, and offers a scanf method to handle extraction versus peer coercion. puppet.com/docs/puppet/latest/…
    – cgseller
    Nov 22, 2019 at 14:38
3

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

2
  • 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. Nov 20, 2018 at 12:53
  • This is acceptable too based on puppet documentation puppet.com/docs/puppet/latest/…. Both the @barry above and answers here are allowed by puppetlabs.
    – cgseller
    Nov 22, 2019 at 14:39
1

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

4
  • 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, 2012 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, 2012 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. May 14, 2012 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, 2014 at 15:42
1

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

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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .