Skip to content

Commit

Permalink
feat: add mongodb resource for creating db users
Browse files Browse the repository at this point in the history
  • Loading branch information
limwa committed Jul 1, 2024
1 parent 7293d08 commit 9bad573
Show file tree
Hide file tree
Showing 7 changed files with 232 additions and 121 deletions.
104 changes: 0 additions & 104 deletions dev/wireguard/01-wireguard.yaml

This file was deleted.

11 changes: 0 additions & 11 deletions dev/wireguard/add-vpn.sh

This file was deleted.

5 changes: 4 additions & 1 deletion services/pulumi/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,10 @@
"@pulumi/pulumi": "^3.113.0"
},
"imports": {
"#crds": "./crds/nodejs/index.ts"
"#crds": "./crds/nodejs/index.ts",
"#resources/": "./resources/",
"#services/": "./services/",
"#utils/": "./utils/"
},
"packageManager": "[email protected]+sha512.67f5879916a9293e5cf059c23853d571beaf4f753c707f40cb22bed5fb1578c6aad3b6c4107ccb3ba0b35be003eb621a16471ac836c87beb53f9d54bb4612724"
}
202 changes: 202 additions & 0 deletions services/pulumi/resources/mongodb.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,202 @@
import { PulumiInputify } from "#utils/pulumi.js";
import * as pulumi from "@pulumi/pulumi";
import * as k8s from "@pulumi/kubernetes";
import * as crds from "#crds";
import { resolve } from "path";

type Role =
// Database user roles
| "read"
| "readWrite"
// Database administration roles
| "dbAdmin"
| "dbOwner"
| "userAdmin"
// Cluster administration roles
| "clusterAdmin"
| "clusterManager"
| "clusterMonitor"
| "enableSharding"
| "hostManager"
// Backup and restoration roles
| "backup"
| "restore"
// All database roles
| "readAnyDatabase"
| "readWriteAnyDatabase"
| "userAdminAnyDatabase"
| "dbAdminAnyDatabase"
// Superuser roles
| "root";
// User-defined roles
// | (string & {});

type User<Databases extends string> = {
db: Databases;
password: string;
connectionStringSecretMetadata?: {
namespace?: string;
name?: string;
};
roles: {
name: Role;
db: Databases;
}[];
};

type Args<Databases extends string> = {
readonly dbs: Databases[];
metadata?: Omit<k8s.types.input.meta.v1.ObjectMeta, "name">;
spec?: Omit<
crds.types.input.mongodbcommunity.v1.MongoDBCommunitySpecArgs,
"users"
>;
};

export class MongoDBCommunity<
const Databases extends string
> extends pulumi.ComponentResource<{}> {
private name: string;
private namespace: pulumi.Output<string | undefined>;
private users: pulumi.Output<crds.types.input.mongodbcommunity.v1.MongoDBCommunitySpecUsersArgs>[];
private secrets: k8s.core.v1.Secret[];

private resourcePromise: Promise<void>;
private resolveResourcePromise: () => void;

constructor(
name: string,
args: Args<Databases>,
opts?: pulumi.ComponentResourceOptions
) {
super("niployments:mongodb:MongoDBCommunity", name, {}, opts);

this.name = name;
this.users = [];
this.secrets = [];

this.resolveResourcePromise = () => { throw new Error("resolveResourcePromise not set") };
this.resourcePromise = new Promise((resolve) => {
this.resolveResourcePromise = resolve;
});

this.namespace = pulumi.output(args.metadata?.namespace);

const operatorName = `${this.name}-operator`;
new crds.mongodbcommunity.v1.MongoDBCommunity(
operatorName,
{
metadata: {
...args.metadata,
name: operatorName,
},
spec: args.spec && {
...args.spec,
users: pulumi.output(this.resourcePromise.then(() => this.users)),
},
},
{ parent: this }
);
}

protected async initialize(args: pulumi.Inputs): Promise<{}> {
await this.resourcePromise;
pulumi.log.error("MongoDBCommunity initialized");
return {};
}

public addUser(name: string, user: PulumiInputify<User<Databases>>) {
const resolvedUser = pulumi.output(user);

const credentialsSecretName = `${this.name}-${name}-credentials-secret`;
const credentialsSecret = new k8s.core.v1.Secret(
credentialsSecretName,
{
metadata: this.namespace.apply((namespace) => ({
namespace,
name: credentialsSecretName,
})),
stringData: {
password: resolvedUser.password,
},
},
{ parent: this }
);

this.secrets.push(credentialsSecret);

this.users.push(
pulumi.all([resolvedUser, credentialsSecret.metadata]).apply(([user, credentialsSecretMetadata]) => ({
connectionStringSecretName: user.connectionStringSecretMetadata?.name,
connectionStringSecretNamespace:
user.connectionStringSecretMetadata?.namespace,
db: user.db,
name,
passwordSecretRef: {
name: credentialsSecretMetadata.name,
},
roles: user.roles,
scramCredentialsSecretName: `${this.name}-${name}-scram-credentials-secret`,
}))
);
}

public finish() {
pulumi.log.error("MongoDBCommunity finishing");
this.resolveResourcePromise();
}
}


const db = new MongoDBCommunity("mongodb", {
dbs: ["admin", "nimentas", "fkjkhgkdjf"],
metadata: {
namespace: "mongodb",
},
spec: {
type: "ReplicaSet",
members: 3,
version: "6.0.5",
security: {
authentication: {
modes: ["SCRAM"],
},
},
additionalMongodConfig: {
"storage.wiredTiger.engineConfig.journalCompressor": "zlib",
},
statefulSet: {
spec: {
volumeClaimTemplates: [
{
metadata: {
name: "data-volume",
},
spec: {
accessModes: ["ReadWriteOnce"],
resources: {
requests: {
storage: "5Gi",
},
},
},
},
],
},
},
},
});

db.addUser("ni", {
db: "fkjkhgkdjf",
password: "pass",
roles: [
{
db: "admin",
name: "root",
},
],
})
;

db.finish();
13 changes: 9 additions & 4 deletions services/pulumi/services/ementas/deployments.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,12 +34,17 @@ export const website = new k8s.apps.v1.Deployment("ementas-website", {
containerPort,
},
],
envFrom: [
env: [
{
secretRef: {
name: secrets.metadata.name,
name: "DATABASE_URL",
valueFrom: {
secretKeyRef: {
name: secrets.metadata.name,
key: "connectionString.standard",
optional: false,
},
},
},
}
],
},
],
Expand Down
2 changes: 1 addition & 1 deletion services/pulumi/sync-crds.sh
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ function download_crds {
local chart_id="$(echo "$helm_crd" | yq '.chart')"
local chart_version="$(echo "$helm_crd" | yq '.version // "*"')"

echo "[Helm CRDs] Downloading CRDs for $chart_id:chart_version" 1>&2
echo "[Helm CRDs] Downloading CRDs for $chart_id:$chart_version" 1>&2
crds+=("$(download_crds_from_helm "$chart_id" "$chart_version" "$dir")")
done

Expand Down
16 changes: 16 additions & 0 deletions services/pulumi/utils/pulumi.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import * as pulumi from "@pulumi/pulumi";

type RecursivePulumiInput<T> =
T extends object
? pulumi.Input<{ [K in keyof T]: RecursivePulumiInput<T[K]> }>
: T extends undefined
? undefined
: pulumi.Input<T>;

type X = RecursivePulumiInput<string | undefined>;

export type PulumiInputify<T> = RecursivePulumiInput<pulumi.Unwrap<T>>;

export function applyInDeployment<Input, Output>(value: pulumi.Output<Input>, inDryRun: pulumi.Input<Output>, inDeployment: (value: Input) => pulumi.Input<Output>) {
return value.apply((value) => pulumi.output(pulumi.runtime.isDryRun() ? inDryRun : inDeployment(value)));
}

0 comments on commit 9bad573

Please sign in to comment.