Skip to content

Instantly share code, notes, and snippets.

@OneCricketeer
Created May 24, 2017 16:16
Show Gist options
  • Save OneCricketeer/92cd8b2f0085f9beb734163b534fc3a9 to your computer and use it in GitHub Desktop.
Save OneCricketeer/92cd8b2f0085f9beb734163b534fc3a9 to your computer and use it in GitHub Desktop.
Sync LDAP Active Directory with Ambari Server
#!/usr/bin/env bash
set -euf -o pipefail
logMsg() {
echo "[$(date +'%Y %b %d %T')]" ${*}
}
## Just in case we are run from cron with no path set...
export PATH=/bin:/usr/bin:/usr/sbin:/sbin:/usr/local/bin
LDAP_URI=ldap://ldapserver:389
BASE_DN="DC=example,DC=com"
LDAP_PASSFILE=/etc/ambari-server/conf/ldap-password.dat
## Groups we want to look for, in this case any group name that starts with Ambari
GROUP_FILTER="(&(ObjectClass=Group)(CN=Ambari*))"
SEARCH_USER=CN=Ambari,OU=Services,${BASE_DN}
## Base ldapsearch command
LDAPSEARCH="ldapsearch -LLL -x \
-H ${LDAP_URI} \
-s sub \
-b ${BASE_DN} \
-D ${SEARCH_USER} -y ${LDAP_PASSFILE}"
LDAPGROUPS=`${LDAPSEARCH} "${GROUP_FILTER}" cn \
| grep ^dn: \
| cut -d' ' -f2- \
| sed -e "s/\(.*\)/(memberOf=\1)/" \
| tr '\n' ':' \
| sed -e "s/://g"`
## Filter for users with a "valid" flag set who have a first name, last name and email.
SEARCH_FILTER="(&(objectClass=user)(mail=*example.com)(givenName=*)(sn=*)(!(msexchuserAccountControl:1.2.840.113556.1.4.803:=2))(|$LDAPGROUPS))"
USERLIST=`${LDAPSEARCH} "${SEARCH_FILTER}" sAMAccountName \
| grep -i sAMAccountName \
| grep -v '^#' \
| sort -u \
| awk '{print $2}' \
| tr '\n' , | tr '[:upper:]' '[:lower:]' \
| sed -e "s/,$//"`
GROUPLIST=`${LDAPSEARCH} "${SEARCH_FILTER}" memberOf \
| grep memberOf \
| grep -v '^#' \
| grep Ambari \
| sort -u \
| cut -d: -f2 | cut -d= -f2 | cut -d, -f1 \
| awk '{print $1}' \
| tr '\n' , \
| sed -e "s/,$//"`
## Can use credentials for an ambari admin, but a ~/.netrc file for cURL is more secure
## Change below commands to use 'curl -u $AMBARI_ADMIN_USER -d ... ' instead
# AMBARI_ADMIN_USER='admin:admin'
AMBARI_SERVER=localhost:8080 # Ambari Server location
## Sync new users and groups
curl -s -H "X-Requested-By: ambari" --netrc -d '{"Event": {"specs": [{"principal_type": "users", "sync_type": "specific", "names": "'$USERLIST'"}, {"principal_type": "groups", "sync_type": "specific", "names": "'$GROUPLIST'"}]}}' http://$AMBARI_SERVER/api/v1/ldap_sync_events >/dev/null
sleep 30
## Sync existing users and groups
curl -s -H "X-Requested-By: ambari" --netrc -d '{"Event": { "specs": [{"principal_type": "users", "sync_type": "existing"}, {"principal_type": "groups", "sync_type": "existing"}]}}' http://$AMBARI_SERVER/api/v1/ldap_sync_events >/dev/null
logMsg "AmbariLdapSync completed"
exit 0
15 0,6,12,18 * * * root sudo -u ambari-qa '/home/ambari-qa/ambari_ldap_usersync.sh' >> /var/log/ambari_ldap_usersync.log 2>&1
machine localhost login admin password admin
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment