0

I'm new to ruby and I'm writing a puppet module to be accessed via Foreman.

I writing it to be used by Foreman's Smart Class Parameter so it can be configured from the Foreman web console.

I was trying to see how I could create a parameter for 48 possible ports a device might have. Instead of manually entering the ports I was wondering if it is possible to do this dynamically.

For example instead of this:

class ciscobaseconfig (
  $interface_description_lan = 'A LAN interface'
) {
  interface {
   'FastEthernet 0/1':
      description => $interface_description_lan
  }
  interface {
   'FastEthernet 0/2':
      description => $interface_description_lan
  }
}

I want to do this:

class ciscobaseconfig (
  $interface_description_lan = 'A LAN interface',
) {
  interface {
    (0..48).each do |i|
    "FastEthernet 0/#{i}":
      description => $interface_description_lan
    end
  }
}

Following a commenter's suggestion I tried this, but it doesn't not work:

class ciscobaseconfig (
  $interface_description_lan = 'A LAN interface',
) {

  arrInterfaces = Array(1..48)

  arrInterfaces.each{
    interface {
      |intNum| puts "FastEthernet 0/#{intNum}":
        description => $interface_description_lan
    }
  }
}
4

1 回答 1

3

As I understand the question, you want to declare 48 resources, using titles based on the resource index, and all with the same parameter values. This must be implemented in Puppet DSL, of course, and though that has some similarities to Ruby, it is not Ruby. It appears that that has contributed some confusion.

It is useful for this purpose to install the puppetlabs-stdlib module, which provides a wide variety of useful extension functions. The one that will help us out here is range(). Given stdlib installed, something like this should do the trick:

class ciscobaseconfig (
    $interface_description_lan = 'A LAN interface',
  ) {

  each(range('1', '48')) |portnum| {
    interface { "FastEthernet 0/${portnum}":
      description => $interface_description_lan
    }
  }
}

That does assume you are using Puppet 4, or else Puppet 3 with the future parser. It can be done with the standard Puppet 3 parser, too, but not as cleanly:

class ciscobaseconfig (
    $interface_description_lan = 'A LAN interface',
  ) {

  $portnums = split(inline_template("<%= (1..48).to_a.join(',') %>"), ',')
  $ifc_names = regsubst($portnums, '.*', 'FastEthernet 0/\0')

  interface { $ifc_names:
      description => $interface_description_lan
  }
}

Note in particular that when an array is given as a resource title, it means you are declaring one resource for each element of the array, all with identical parameters.

于 2015-12-17T20:58:06.760 回答