Data Resilience: Self-Managed / Security and Compliance
Code Summary: Security and Compliance
Configuring Zone Sharding with Geographic Data Distribution
These commands configure zone-based sharding to distribute data across geographic regions. The addShardToZone commands assign shards to specific zones (EU and US). The updateZoneKeyRange command defines which data belongs in each zone using the shard key range. Finally, shardCollection enables sharding on the collection using hashed sharding on the _id field. This configuration automatically routes data to appropriate geographic shards based on the defined zones.
> sh.addShardToZone("shard0", "EU")
> sh.addShardToZone("shard1", "US")
> sh.updateZoneKeyRange(
"shardThis.bigData",
{ "_id" : MinKey },
{ "_id" : MaxKey },
"FLASH"
)
> sh.shardCollection(
"shardThis.bigData",
{ region: 1, _id: "hashed" }
)
Starting MongoDB with TLS Encryption
This command starts a mongod instance with TLS encryption enabled. The --tlsMode requireTLS flag forces all connections to use TLS encryption. The --tlsCertificateKeyFile flag specifies the path to the certificate and key file, while --tlsCAFile points to the Certificate Authority's root certificate chain. The --dbpath flag indicates where the database files are stored.
mongod --tlsMode requireTLS \
--tlsCertificateKeyFile /etc/ssl/mongodb.pem \
--tlsCAFile /etc/ssl/ca.pem \
--dbpath /data/db
Enabling Encryption at Rest
This command starts MongoDB with encryption at rest enabled using the --enableEncryption flag. The --encryptionKeyFile flag specifies the path to the encryption key file used to encrypt and decrypt data on disk. This provides an additional layer of security for data stored in MongoDB.
mongod --enableEncryption \
--encryptionKeyFile /etc/mongodb-keyfile \
--dbpath /data/db
Creating Users with Role-Based Access Control
These commands demonstrate MongoDB's Role-Based Access Control by creating three users with different permission levels. The reportingUser has read-only access to the ecommerce database. The dbAdmin user can manage database configurations but cannot access customer data. The superAdmin has root-level permissions across all databases for administrative tasks. Each user is created with the db.createUser() command, specifying username, password, and assigned roles.
test> use admin
switched to db admin
admin> db.createUser({
user: "reportingUser",
pwd: "securePassword123",
roles: [
{ role: "read", db: "ecommerce" }
]
})
admin> db.createUser({
user: "dbAdmin",
pwd: "adminPassword456",
roles: [
{ role: "dbAdmin", db: "ecommerce" }
]
})
admin> db.createUser({
user: "superAdmin",
pwd: "superPassword789",
roles: [
{ role: "root", db: "admin" }
]
})