BASH: скрипт добавления нового DIT в LDAP

Автор: | 12/29/2014
 

terminalРазработчикам часто требуется добавить новые базы в LDAP.

LDAP настроен через OLC (cn=config).

Что бы не отвлекаться — на скорую руку был написан такой скрипт:

#!/usr/bin/env bash

DB_DIR="/var/lib/ldap"
M_ROOT="cn=root,cn=config"
M_ROOT_PW="p@ssw0rd"

TM_LDIF="/tmp/tmldif.ldif"
TM_LDIF_TOP="/tmp/toptemp.ldif"

answer ()
{
while read response; do
echo
case $response in
    [yY][eE][sS]|[yY])
        return 0
        break
        ;;
    [nN][oO]|[nN])
        return 1
        break
        ;;
        *)
        printf "Please, enter Y(yes) or N(no)! "
esac
done
}

printf "n"
read -p "Please, enter new database name (example: autodev1): " db_name
read -s -p "Please, enter this database root password: " root_pw

create_pw () {
    h_root_pw=$(slappasswd -s $1 -h {MD5} | base64)
}

create_pw $root_pw

text="dn: olcDatabase=bdb,cn=config
objectClass: olcBdbConfig
olcDatabase: bdb
olcDbDirectory: $DB_DIR/$db_name
olcSuffix: dc=$db_name
olcRootDN: cn=root,dc=$db_name
olcRootPW:: $h_root_pw"

printf "nnNew database will be created with data:nn$textnnIs it OK? [y/n] "
answer && printf "Starting database creation.n" || { printf "Exit.nn"; exit 0; }
printf "nMkdir $DB_DIR/$db_name... "

if mkdir $DB_DIR/$db_name; then
    cp /var/lib/ldap/autobuild1/DB_CONFIG $DB_DIR/$db_name
    chown -R ldap:ldap $DB_DIR/$db_name
    printf "done.nn"
else
    printf "nERROR! Can't create directory.n.Exit."
    exit 2
fi

printf "Creating temporary lfid file... "
cat > $TM_LDIF <<EOL
$text
EOL

cat > $TM_LDIF_TOP <<EOL
dn: dc=$db_name
objectClass: top
objectClass: dcObject
objectClass: organization
dc: $db_name
o: DevLDAP
description: Testing LDAP DIT for DEV
EOL

printf "done.n"

printf "nAdding new DIT to LDAP... "

ldapadd -x -D "$M_ROOT" -w"$M_ROOT_PW" -f $TM_LDIF
ldapadd -x -D "cn=root,dc=$db_name" -w"$root_pw" -f $TM_LDIF_TOP

/etc/init.d/slapd restart

И его работа:

# ./create_DIT.sh

Please, enter new database name (example: autodev1): autodev8
Please, enter this database root password:

New database will be created with data:

dn: olcDatabase=bdb,cn=config
objectClass: olcBdbConfig
olcDatabase: bdb
olcDbDirectory: /var/lib/ldap/autodev8
olcSuffix: dc=autodev8
olcRootDN: cn=root,dc=autodev8
olcRootPW:: e01ENX1Cc0U5dUsrZll2eEJlOTlrYjBJZk1nPT0K

Is it OK? [y/n] y

Starting database creation.

Mkdir /var/lib/ldap/autodev8... done.

Creating temporary lfid file... done.

Adding new DIT to LDAP... adding new entry "olcDatabase=bdb,cn=config"

adding new entry "dc=autodev8"

Stopping slapd:                                            [  OK  ]
Starting slapd:                                            [  OK  ]