PageRenderTime 45ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/puppet/util/network_device/cisco/interface.rb

https://gitlab.com/gutocarvalho/puppet
Ruby | 82 lines | 64 code | 12 blank | 6 comment | 6 complexity | cc2e920224a891a822eaa10be328cf5c MD5 | raw file
  1. require 'puppet/util/network_device/cisco'
  2. require 'puppet/util/network_device/ipcalc'
  3. # this manages setting properties to an interface in a cisco switch or router
  4. class Puppet::Util::NetworkDevice::Cisco::Interface
  5. include Puppet::Util::NetworkDevice::IPCalc
  6. extend Puppet::Util::NetworkDevice::IPCalc
  7. attr_reader :transport, :name
  8. def initialize(name, transport)
  9. @name = name
  10. @transport = transport
  11. end
  12. COMMANDS = {
  13. # property => order, ios command/block/array
  14. :description => [1, "description %s"],
  15. :speed => [2, "speed %s"],
  16. :duplex => [3, "duplex %s"],
  17. :native_vlan => [4, "switchport access vlan %s"],
  18. :encapsulation => [5, "switchport trunk encapsulation %s"],
  19. :mode => [6, "switchport mode %s"],
  20. :allowed_trunk_vlans => [7, "switchport trunk allowed vlan %s"],
  21. :etherchannel => [8, ["channel-group %s", "port group %s"]],
  22. :ipaddress => [9,
  23. lambda do |prefix,ip,option|
  24. ip.ipv6? ? "ipv6 address #{ip.to_s}/#{prefix} #{option}" :
  25. "ip address #{ip.to_s} #{netmask(Socket::AF_INET,prefix)}"
  26. end],
  27. :ensure => [10, lambda { |value| value == :present ? "no shutdown" : "shutdown" } ]
  28. }
  29. def update(is={}, should={})
  30. Puppet.debug("Updating interface #{name}")
  31. command("conf t")
  32. command("interface #{name}")
  33. # apply changes in a defined orders for cisco IOS devices
  34. [is.keys, should.keys].flatten.uniq.sort {|a,b| COMMANDS[a][0] <=> COMMANDS[b][0] }.each do |property|
  35. # They're equal, so do nothing.
  36. next if is[property] == should[property]
  37. # We're deleting it
  38. if should[property] == :absent or should[property].nil?
  39. execute(property, is[property], "no ")
  40. next
  41. end
  42. # We're replacing an existing value or creating a new one
  43. execute(property, should[property])
  44. end
  45. command("exit")
  46. command("exit")
  47. end
  48. def execute(property, value, prefix='')
  49. case COMMANDS[property][1]
  50. when Array
  51. COMMANDS[property][1].each do |command|
  52. transport.command(prefix + command % value) do |out|
  53. break unless out =~ /^%/
  54. end
  55. end
  56. when String
  57. command(prefix + COMMANDS[property][1] % value)
  58. when Proc
  59. value = [value] unless value.is_a?(Array)
  60. value.each do |v|
  61. command(prefix + COMMANDS[property][1].call(*v))
  62. end
  63. end
  64. end
  65. def command(command)
  66. transport.command(command) do |out|
  67. Puppet.err "Error while executing #{command}, device returned #{out}" if out =~ /^%/mo
  68. end
  69. end
  70. end