📩 Note: This Project is a part of 13 week long DevOps Micro Intership(DMI). If you want to learn DevOps with hands-on practice and live projects for free, you can follow the YouTube Playlist by Pravin Mishra.
Prerequisites #
- Active Azure subscription (Azure Free)
- Azure CLI installed and able to az login (only to create the SP)
- Terraform installed (v1.5+ recommended)
- macOS/Linux shell or Windows PowerShell
Solutions #
Step 1 : Setup Azure CLI with Service Principal. #
- Open Terminal in MacOS/Linux or Powershell in Windows and enter the command :
az login --use-device-code
- Copy the Link and Visit your Favourite Browser and Enter the code provided in the terminal.
- Select the Azure account you want to use for Project and confirm to use Azure CLI.
- Check the Terminal, you will see the Subscription details if you are logged in.
- Select the subscription or press ‘Enter’ to select by default.
- Enter the command :
az account show
in the terminal to check the account info and copy the subscription id .
Step 2 : Create a Service Principal with RBAC. #
- Copy the Subscription id and prepare a command to create a service principal with RBAC (Role Based Access Control).
SUBSCRIPTION_ID="<your-subscription-id>"
az ad sp create-for-rbac \
--name "sp-terraform-epicbook" \
--role "Contributor" \
--scopes "/subscriptions/$SUBSCRIPTION_ID" \
--years 1 \
--query "{appId:appId,password:password,tenant:tenant}" -o json
- Using the above command will generate the appId, tenant Id and Password.
Step 3 : Save the credentials as an environment variable. #
- If you are using Linux, add the below content with real credentials to ~/.bashrc file. Command :
nano ~/.bashrc
export ARM_CLIENT_ID="<appId>"
export ARM_CLIENT_SECRET="<password>"
export ARM_TENANT_ID="<tenant>"
export ARM_SUBSCRIPTION_ID="$SUBSCRIPTION_ID"
- Run the command :
source ~/.bashrc
Step 4 : Log out Azure CLI (to prove Terraform uses SP) #
Command : az logout
Step 5 : Test if the service principal is working or not. #
Create a Terraform script with .tf extension.
#writing provider block
provider "azurerm" {
features{}
}
#create a resource group
resource "azurerm_resource_group" "example" {
name = "terraform-rg"
location = "East US"
}
#output the resource group name after creation
output "resource_group_name" {
value = azurerm_resource_group.example.name
}
- Initialize a new Terraform directory by using command :
terraform init
- Create an execution plan by using the command :
terraform plan
- Apply the changes defined in plan by using the command :
terraform apply -auto-approve
. - Check in Azure Portal if you want,
Step 6 : Rotate / show / delete secret (reference) #
- Rotate secret (create a new password) :
Command :
az ad sp credential reset –name “<appId>” –years 1
- Delete SP (cleanup when done with labs):
Command :
az ad sp delete –id “<appId>”