Skip to content

4. Create Terraform Service Principals

Create the Terraform / IaC Service Principals

Whenever we create or update an environment, either a permanent one, manually, such as prod, or a temporary one, automatically, such as dev (which is created daily, in the morning, and destroyed in the evening), we will be using Terraform / Infrastructure as Code (IaC) which will be accessing Azure APIs to create/update the corresponding resources. To avoid using actual AD users, which might have their credentials or state changed over time, we will use Service Principals as means to authenticate against Azure and use its APIs.

    az ad sp create-for-rbac --name ar-infra-manager-<env>-sp

Where <env> specifies the runtime environment the Service Principal is built for (eg. dev, uat, prod). When the command completes successfully, the credentials / identifiers for the new Service Principal are displayed, as exemplified below:

{
    "appId": "<app-id>",
    "displayName": "ar-infra-manager-prod-sp",
    "password": "<secret>",
    "tenant": "<tenant-id>"
}

Keep the information in a safe temporary location for now. We will need this later.

Warning

Make sure this information is not stored in Git or other repositories. All credentials need to be stored in Azure DevOps Library section, as secrets, or in other password management systems or vaults.

Assign the required roles to the new Service Principal

Once the Service Principal is created, the required roles can be associated and scoped to the corresponding resources. The <app-id> is the identifier of the Service Principal created before.

    az role assignment create \
        --role Contributor \
        --scope /subscriptions/35ddf877-eb02-420f-97e8-81f584388517/ --assignee <app-id>    

Where <app-id> is the identifier of the Service Principal created before.