Skip to content

Instantly share code, notes, and snippets.

@acidprime
Created December 7, 2016 23:12
Show Gist options
  • Save acidprime/eccd1c50bff1efa67eec2d218bfd1a69 to your computer and use it in GitHub Desktop.
Save acidprime/eccd1c50bff1efa67eec2d218bfd1a69 to your computer and use it in GitHub Desktop.
require 'net/ldap'
require 'facter'
# This code is only ever loaded in newer versions of puppet and ruby
# https://github.com/puppetlabs/puppet-specifications/blob/master/language/func-api.md
Puppet::Functions.create_function(:get_ldap_group) do
dispatch :get_ldap_group do
param 'Variant[Array[String],String]', :groups
optional_param 'Variant[Array[String],String]', :attrs
optional_param 'Boolean', :single_attr
end
def get_ldap_group( groups, attrs, single_attr)
if ! groups.kind_of?(Array)
groups = [groups]
end
single_attr = (single_attr == nil ? false : single_attr)
ret_array = []
basedn = 'dc=foo,dc=bar'
binddn = 'uid=root,cn=users,dc=foo,dc=bar'
bindpw = 'password'
ldap_server = 'ldap.foo.bar'
ldap_port = 389
conn = nil
groups.each { |group|
group_found = false
# Not found in memcache
if conn.nil?
# Defer LDAP connection until we actually need it
conn = Net::LDAP::Connection.new(:host => ldap_server, :port => ldap_port)
conn.bind(
method: :simple,
username: binddn,
password: bindpw
)
end
group_entries = []
conn.search(:base => basedn, :scope => Net::LDAP::SearchScope_WholeSubtree, :filter => "(&(objectClass=posixGroup)(cn=#{group}))", :attributes => ['memberUid']) { |entry|
group_found = true
members = []
members = entry.memberUid if entry.respond_to?(:memberUid)
members.each { |member|
conn.search(:base => basedn, :scope => Net::LDAP::SearchScope_WholeSubtree, :filter => "(&(objectClass=posixAccount)(uid=#{member}))", :attributes => attrs) { |entry2|
if single_attr
group_entries.push(entry2[((attrs.kind_of?(Array) ? attrs.first : attrs))])
else
hash = Hash.new
entry2.each do |k,v|
hash[k] = v.length > 1 ? v : v.first
end
group_entries.push(hash)
end
}
}
}
if ! group_found
raise(Puppet::ParseError, "get_ldap_group(): cannot find group #{group}...this is probably wrong, so we're bailing to prevent weird issues")
end
# Add entries to the return array
group_entries.each { |entry| ret_array.push(entry) }
}
# Unbind from LDAP if we are connected
if ! conn.nil?
conn.close
end
ret_array.flatten.uniq
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment