blob: df68d318c83145fec52ff5e2f5b7230d114ba345 (
plain) (
blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
|
apiVersion: v1
kind: ConfigMap
metadata:
name: mongodb-standalone
data:
ensure-users.js: |
const targetDbStr = 'training';
const rootUser = cat('/etc/k8-training/admin/MONGO_ROOT_USERNAME');
const rootPass = cat('/etc/k8-training/admin/MONGO_ROOT_PASSWORD');
const usersStr = cat('/etc/k8-training/MONGO_USERS_LIST');
// auth against admin
const adminDb = db.getSiblingDB('admin');
adminDb.auth(rootUser, rootPass);
print('Successfully authenticated admin user');
// we'll create the users here
const targetDb = db.getSiblingDB(targetDbStr);
// user-defined roles should be stored in the admin db
const customRoles = adminDb
.getRoles({rolesInfo: 1, showBuiltinRoles: false})
.map(role => role.role)
.filter(Boolean);
// parse the list of users, and create each user as needed
usersStr
.trim()
.split(';')
.map(s => s.split(':'))
.forEach(user => {
const username = user[0];
const rolesStr = user[1];
const password = user[2];
if (!rolesStr || !password) {
return;
}
const roles = rolesStr.split(',');
const userDoc = {
user: username,
pwd: password,
};
userDoc.roles = roles.map(role => {
if (!~customRoles.indexOf(role)) {
// is this a user defined role?
return role; // no, it is built-in, just use the role name
}
return {role: role, db: 'admin'}; // yes, user-defined, specify the long format
});
try {
targetDb.createUser(userDoc);
} catch (err) {
if (!~err.message.toLowerCase().indexOf('duplicate')) {
// if not a duplicate user
throw err; // rethrow
}
}
});
|