openldap.rb 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122
  1. require 'tempfile'
  2. # Base provider class for OpenLDAP defined types
  3. class Puppet::Provider::Openldap < Puppet::Provider
  4. # Initialize provider structure
  5. initvars
  6. # Declare binaries that we use
  7. commands cmd_ldapadd: 'ldapadd',
  8. cmd_ldapmodify: 'ldapmodify',
  9. cmd_slapcat: 'slapcat'
  10. # Class-level wrapper methods for ldap binaries
  11. def self.ldapadd(path)
  12. cmd_ldapadd('-cQY', 'EXTERNAL', '-H', 'ldapi:///', '-f', path)
  13. end
  14. def self.ldapmodify(path)
  15. cmd_ldapmodify('-Y', 'EXTERNAL', '-H', 'ldapi:///', '-f', path)
  16. end
  17. def self.slapcat(filter, dn = '', base = 'cn=config')
  18. arguments = [
  19. '-b', base,
  20. '-o', 'ldif-wrap=no',
  21. '-H', "ldap:///#{dn}???#{filter}"
  22. ]
  23. cmd_slapcat(*arguments)
  24. end
  25. # Instance-level wrapper methods
  26. def ldapadd(*args)
  27. self.class.ldapadd(*args)
  28. end
  29. def ldapmodify(*args)
  30. self.class.ldapmodify(*args)
  31. end
  32. def slapcat(*args)
  33. self.class.slapcat(*args)
  34. end
  35. # Create temporary LDIF file
  36. def self.temp_ldif(name = 'openldap_ldif')
  37. Tempfile.new(name)
  38. end
  39. def temp_ldif(*args)
  40. self.class.temp_ldif(*args)
  41. end
  42. # Methods to generate LDIF fragments
  43. def delimit
  44. "-\n"
  45. end
  46. def cn_config
  47. dn('cn=config')
  48. end
  49. def dn(dn)
  50. "dn: #{dn}\n"
  51. end
  52. def changetype(t)
  53. "changetype: #{t}\n"
  54. end
  55. def add(key)
  56. "add: olc#{key}\n"
  57. end
  58. def del(key)
  59. "delete: olc#{key}\n"
  60. end
  61. def replace(key)
  62. "replace: olc#{key}\n"
  63. end
  64. def key_with_value(key, value)
  65. "olc#{key}: #{value}\n"
  66. end
  67. # Turn LDIF output into an array of olc attributes
  68. def self.get_lines(items)
  69. items.strip
  70. .gsub("\n ", '')
  71. .split("\n")
  72. .select { |e| e =~ %r{^olc} }
  73. .map { |e| e.gsub(%r{^olc}, '') }
  74. end
  75. def get_lines(*args)
  76. self.class.get_lines(*args)
  77. end
  78. # Turn LDIF output into a 2D array of entries
  79. def self.get_entries(items)
  80. items.strip
  81. .split("\n\n")
  82. .map do |p|
  83. p.gsub("\n ", '')
  84. .split("\n")
  85. end
  86. end
  87. def get_entries(*args)
  88. self.class.get_entries(*args)
  89. end
  90. # Split a line and get the last part
  91. def self.last_of_split(line, by = ' ')
  92. line.split(by, 2).last
  93. end
  94. def last_of_split(*args)
  95. self.class.last_of_split(*args)
  96. end
  97. end