Filtering entry attributes not on a list

Very specific task here: delete all the LDAP attributes in an LDIF dump of an entry that are NOT on a predetermined list. Some example code below.

Obviously the way to do this is to read the raw LDIF and rewrite it, omitting all the attributes you’re not interested in. The perl Net::LDAP::LDIF module is the tool to use for this.

Assume the following array of LDAP attributes as the list of what you’re interested in keeping:

my @attrs = qw(uid cn sn givenname title o mail manager c);

All you need now is to read the LDAP entry, compare the attributes it has with those on the above list, and then delete anything that’s not on the list. You’ll need to load Net::LDAP, Net::LDAP::Entry, Net::LDAP::LDIF and List::Compare for this job.

# Only capture the attributes in our list (so we can feed a raw
# LDIF with all attr values if we want
# Make a list of all the attribute names in the entry
my @eattrs = $entry->attributes;

# Normalize all the attribute names from the entry by forcing them
# to lowercase (the target list is already all lowercase)
my @eattrs = map { lc } @eattrs;

# Compare entry attributes with the target list
my $compared = List::Compare->new(@eattrs, @attrs);

# Make a list of the entry attributes that are not in the target list
my @eonly = $compared->get_unique;

# Delete the attributes not in the target list
foreach my $attr(@eonly) {

That’s really all there is to it. Attention to little details like normalizing the casing of the attribute names will keep you sane, as will learning how to use perl’s “lc” method against a whole array. I was actually really pleased to discover List::Compare and learn how to use it for this small project. Its capabilities are something I’m sure to exploit again in the future.