Deploy MongoDB on Ubuntu using Bicep

9 mins read

Quickly deploy your MongoDB in Azure using Infrastructure-As-Code

đŸ’ȘDeploy MongoDB on Ubuntu using Bicep

This article will review how you can deploy MongoDB on an Ubuntu virtual machine using Bicep, the new Domain Specific Language (DSL) for deploying Azure resources declaratively.

The solution consists of the following files:

main.bicep: This is our Bicep template to deploy the solutionazuredeploy.parameters.json: The parameters file contains the values passed on during deployment time.mongo-install-ubuntu.sh: This is a script that installs MongoDB on the Ubuntu virtual machine. This script will be executed once the virtual machine is deployed using “Custom Scripts”.

Pre-requisites:

Azure Bicep installedAn active Azure subscriptionA resource group created in your subscription

Now let’s start working on the Bicep template.

We will define the following parameters:

@description(‘DNS Name for Public IP’)
param dnsNameForPublicIP string@description(‘Admin Username’)
param adminUsername string@description(‘Image Publisher’)
param imagePublisher string = ‘Canonical’@description(‘Image Offer’)
param imageOffer string = ‘UbuntuServer’@description(‘Image SKU’)
param imageSKU string = ‘18.04-LTS’@description(‘VM Size’)
param vmSize string = ‘Standard_A1_v2’@description(‘Public IP Address Name’)
param publicIPAddressName string = ‘myPublicIP’@description(‘Vm Name’)
param vmName string = ‘myLinuxVM’@description(‘Virtual Network Name’)
param virtualNetworkName string = ‘myVNET’@description(‘NIC Name’)
param nicName string = ‘myNIC’@description(‘Location for all resources.’)
param location string = resourceGroup().location@allowed([
‘sshPublicKey’
‘password’
])
@description(‘Type of authentication to use on the Virtual Machine. SSH key is recommended.’)
param authenticationType string = ‘password’@description(‘SSH Key or password for the Virtual Machine. SSH key is recommended.’)
@secure()
param adminPasswordOrKey string@description(‘The base URI where artifacts required by this template are located. For example, if stored on a public GitHub repo, you’d use the following URI: https://raw.githubusercontent.com/Azure/azure-quickstart-templates/master/mongodb-on-ubuntu/.’)
param artifactsLocation string = ‘https://raw.githubusercontent.com/daveRendon/azinsider/main/application-workloads/mongodb-on-ubuntu/mongo-install-ubuntu.sh’@description(‘The sasToken required to access _artifactsLocation. If your artifacts are stored on a public repo or public storage account you can leave this blank.’)
@secure()
param artifactsLocationSasToken string = ”

Note that we allow Password or SSH Keys to deploy the Ubuntu VM, in this example, we will pass on a value for the Password. You can opt to use SSH Keys.

Now we will define the variables as shown below:

var addressPrefix = ‘10.0.0.0/16’
var subnet1Name = ‘Subnet-1’
var subnet1Prefix = ‘10.0.0.0/24’
var publicIPAddressType = ‘Dynamic’
var linuxConfiguration = {
disablePasswordAuthentication: true
ssh: {
publicKeys: [
{
path: ‘/home/${adminUsername}/.ssh/authorized_keys’
keyData: adminPasswordOrKey
}
]
}
}
var networkSecurityGroupName_var = ‘default-NSG’

Next, we will define the resources, including the components for the virtual machine and a resource type ‘Extensions’, which will execute the script to install MongoDB:

resource publicIPAddressName_resource ‘Microsoft.Network/publicIPAddresses@2020-05-01’ = {
name: publicIPAddressName
location: location
properties: {
publicIPAllocationMethod: publicIPAddressType
dnsSettings: {
domainNameLabel: dnsNameForPublicIP
}
}
}resource networkSecurityGroupName ‘Microsoft.Network/networkSecurityGroups@2020-05-01’ = {
name: networkSecurityGroupName_var
location: location
properties: {
securityRules: [
{
name: ‘default-allow-22’
properties: {
priority: 1000
access: ‘Allow’
direction: ‘Inbound’
destinationPortRange: ’22’
protocol: ‘Tcp’
sourceAddressPrefix: ‘*’
sourcePortRange: ‘*’
destinationAddressPrefix: ‘*’
}
}
]
}
}resource virtualNetworkName_resource ‘Microsoft.Network/virtualNetworks@2020-05-01’ = {
name: virtualNetworkName
location: location
properties: {
addressSpace: {
addressPrefixes: [
addressPrefix
]
}
subnets: [
{
name: subnet1Name
properties: {
addressPrefix: subnet1Prefix
networkSecurityGroup: {
id: networkSecurityGroupName.id
}
}
}
]
}
}resource nicName_resource ‘Microsoft.Network/networkInterfaces@2020-05-01’ = {
name: nicName
location: location
properties: {
ipConfigurations: [
{
name: ‘ipconfig1’
properties: {
privateIPAllocationMethod: ‘Dynamic’
publicIPAddress: {
id: publicIPAddressName_resource.id
}
subnet: {
id: resourceId(‘Microsoft.Network/virtualNetworks/subnets’, virtualNetworkName, subnet1Name)
}
}
}
]
}
dependsOn: [
virtualNetworkName_resource
]
}resource vmName_resource ‘Microsoft.Compute/virtualMachines@2019-12-01’ = {
name: vmName
location: location
properties: {
hardwareProfile: {
vmSize: vmSize
}
osProfile: {
computerName: vmName
adminUsername: adminUsername
adminPassword: adminPasswordOrKey
linuxConfiguration: ((authenticationType == ‘password’) ? json(‘null’) : linuxConfiguration)
}
storageProfile: {
imageReference: {
publisher: imagePublisher
offer: imageOffer
sku: imageSKU
version: ‘latest’
}
osDisk: {
name: ‘${vmName}_OSDisk’
caching: ‘ReadWrite’
createOption: ‘FromImage’
}
}
networkProfile: {
networkInterfaces: [
{
id: nicName_resource.id
}
]
}
}
}resource vmName_installmongo ‘Microsoft.Compute/virtualMachines/extensions@2019-12-01’ = {
parent: vmName_resource
name: ‘installmongo’
location: location
properties: {
publisher: ‘Microsoft.Azure.Extensions’
type: ‘CustomScript’
typeHandlerVersion: ‘2.0’
autoUpgradeMinorVersion: true
settings: {
fileUris: [
uri(artifactsLocation, ‘mongo-install-ubuntu.sh${artifactsLocationSasToken}’)
]
commandToExecute: ‘sh mongo-install-ubuntu.sh’
}
}
}

Azure Bicep template to deploy MongoDB on an Ubuntu VM

The code below shows the complete template to deploy MongoDB on an Ubuntu VM using Bicep:

https://medium.com/media/b279c5f3e0d12970451175eb629ac241/href

Now that we have our Bicep template let’s review the parameters file.

Parameters file.

In the parameters file, we will pass on the admin username for the virtual machine, the password or SSH key value, and the DNS name:

{
“$schema”: “https://schema.management.azure.com/schemas/2019-04-01/deploymentParameters.json#”,
“contentVersion”: “1.0.0.0”,
“parameters”: {
“adminUsername”: {
“value”: “Your-Username”
},
“dnsNameForPublicIP”: {
“value”: “Your-DNS-Name-For-PublicIP”
},
“adminPasswordOrKey”: {
“value”: “Your-password-or-Key”
}
}
}

Lastly, we will reference the code below to install MongoDB:

# Configure mongodb.list file with the correct location
sudo apt-key adv –keyserver hkp://keyserver.ubuntu.com:80 –recv 9DA31620334BD75D9DCB49F368818C72E52529D4
echo “deb http://repo.mongodb.org/apt/ubuntu “$(lsb_release -sc)”/mongodb-org/4.0 multiverse” | sudo tee /etc/apt/sources.list.d/mongodb-org-4.0.list# Disable THP
sudo echo never > /sys/kernel/mm/transparent_hugepage/enabled
sudo echo never > /sys/kernel/mm/transparent_hugepage/defrag
sudo grep -q -F ‘transparent_hugepage=never’ /etc/default/grub || echo ‘transparent_hugepage=never’ >> /etc/default/grub# Install updates
sudo apt-get -y update# Modified tcp keepalive according to https://docs.mongodb.org/ecosystem/platforms/windows-azure/
sudo bash -c “sudo echo net.ipv4.tcp_keepalive_time = 120 >> /etc/sysctl.conf”#Install Mongo DB
sudo apt-get install -y mongodb-org# Uncomment this to bind to all ip addresses
sudo sed -i -e ‘s/bindIp: 127.0.0.1/bindIp: 0.0.0.0/g’ /etc/mongod.conf
sudo service mongod restart

Feel free to grab the complete code of this solution from the following URL:

azinsider/application-workloads/mongodb-on-ubuntu at main · daveRendon/azinsider

Now, let’s deploy this solution.

We will use the command to deploy our Bicep template:

$date = Get-Date -Format “MM-dd-yyyy”
$deploymentName = “AzInsiderDeployment”+”$date”New-AzResourceGroupDeployment -Name $deploymentName -ResourceGroupName azinsider-mongodb -TemplateFile .main.bicep -TemplateParameterFile .azuredeploy.parameters.json -c

Note we previously created a resource group called ‘azinsider-mongodb’.

The above command will provide a preview of the deployment as shown below:

MongoDB on Ubuntu using Bicep — Deployment Preview

Once the deployment is valid, we will execute it. The figure below shows the output from the deployment.

MongoDB on an Ubuntu VM using Bicep — deployment output

Verify the MongoDB installation.

Now we can SSH into the virtual machine with the command below:

ssh your-admin-username@your-vm-ip

Then we will verify that MongoDB is running using the command ‘mongo’:

Verify the MongoDB installation

Hope this provides you with a better understanding of how you can execute custom scripts on Linux virtual machines using Bicep.

👉 Join the AzInsider email list here.

-Dave R.

đŸ’ȘDeploy MongoDB on Ubuntu using Bicep was originally published in CodeX on Medium, where people are continuing the conversation by highlighting and responding to this story.

Leave a Reply

Your email address will not be published.

Follow Us