This is an example project that uses packer and terraform to manage virtual machines and docker containers in Azure cloud.
To get through with all the operations these requirements should be met:
- Azure account obtained
- terraform installed locally
- packer installed locally
- azure cli installed locally
- jq installed
- ansible and docker for debug
Install on Linux (Ubuntu):
sudo apt-get install -y azure-cli terraform packer jq ansible
With the use of Azure free account the actions could be performed without an additional cost. However free Azure account registration requires use of a banking card.
Run command to obtain device code:
az login --use-device-code
Expected result:
To sign in, use a web browser to open the page [https://microsoft.com/devicelogin] and enter the code YOUR DEVICE CODE
to authenticate.
Go to the page and input obtained code.
Create azure resource group:
az group create -n packergroup -l eastus
Expected output:
{
"id": "/subscriptions/{YOUR SUBSCRIPTION ID}/resourceGroups/packergroup",
"location": "eastus",
"managedBy": null,
"name": "packergroup",
"properties": {
"provisioningState": "Succeeded"
},
"tags": null,
"type": "Microsoft.Resources/resourceGroups"
}
Get Azure subscription id:
az account show --query "{ subscription_id: id }"
Expected output:
{
"subscription_id": "{YOUR SUBSCRIPTION ID}"
}
Create service principal (app registration):
az ad sp create-for-rbac --role Owner --name api://packer001 \
--query "{ client_id: appId, client_secret: password, tenant_id: tenant }" \
--scopes /subscriptions/{YOUR SUBSCRIPTION ID}
Expected output: Creating a role assignment under the scope of "/subscriptions/{YOUR SUBSCRIPTION ID}" Retrying role assignment creation: 1/36 Retrying role assignment creation: 2/36
{
"client_id": "{YOUR CLIENT ID}",
"client_secret": "{YOUR CLIENT SECRECT}",
"tenant_id": "{YOUR TENANT ID}"
}
Update the client and tenant info in packer variables files - [packer/variables.json]
Build packer image:
cd packer/
packer build -var-file variables.json azure-ubuntu.json
Create VM in Azure using built packer image:
az vm create --resource-group packergroup --name packedVm --image packerimage --public-ip-sku Standard --admin-username packerazuser --generate-ssh-keys
Allow access through port 80:
az vm open-port --resource-group packergroup --name packedVm --port 80
Convert pakcer json file to hcl:
packer hcl2_upgrade -with-annotations azure-ubuntu.json
Useful scripts:
- scripts/init.sh - installs ansible galaxy roles, then creates azure resource group for packer images, app registration (packer app) and packer image, and then launches terraform
- scripts/remove.sh - removes ansible roles, sensitive info, app registration and resource groups
The scripts use variables from variables.json.