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?

MMore
  • 543
  • 2
  • 6
  • 12

4 Answers4

5

You can do this:

$n_timeout = 0 + $timeout

Barry
  • 159
  • 1
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

Andrew
  • 484
  • 2
  • 9
  • 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
  • This is acceptable too based on puppet documentation https://puppet.com/docs/puppet/latest/lang_data_number.html#reference-5590. Both the @barry above and answers here are allowed by puppetlabs. – cgseller Nov 22 '19 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.

Daniel Pittman
  • 5,842
  • 1
  • 23
  • 20
  • 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
1

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

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

jonhattan
  • 111
  • 4