Create Terraform Service Principle

1 minute read

Description

Before using Terraform to create resources in Azure, you need to first create an Azure AD Application and give it rights to your subscription to deploy resources. Here are the steps to follow. It is recommended to follow the official source as well, but this is just my notes on what I did.

To Resolve:

  1. Create the application as a service principle:

    1
    2
    3
    4
    
    $password = 'somePassword'
    $securePassword = ConvertTo-SecureString -Force -AsPlainText -String $password
    $azTerraformapp = New-AzADApplication -DisplayName 'az-terraform' -HomePage 'http://az-terraform' -IdentifierUris 'http://az-terraform' -Password $securePassword
    New-AzADServicePrincipal -ApplicationId $azTerraformapp.ApplicationId.Guid -SkipAssignment
    
  2. Grab the client ID from output

    1
    2
    
    app id
    bb581ce9-xxx
    
  3. Get object id:

    1
    2
    
    (Get-AzADApplication -ApplicationId "bb581ce9-xxx").ObjectId
    ae9f0a7a-xxx
    
  4. Get the client secret

    1
    2
    
    $SecureStringPassword = ConvertTo-SecureString -String "someSecret" -AsPlainText -Force
    New-AzADAppCredential -ObjectId "ae9f0a7a-xxx" -Password $SecureStringPassword
    
  5. Get your tenant info

    1
    2
    3
    4
    5
    6
    
    (Get-AzSubscription).TenantId
    b525d9fd-xxx
    
    subscription-id
    (Get-AzSubscription).Id
    700b8c1a-xxx
    
  6. Assign them to the bashrc profile for later deployments from cloudshell:

    1
    2
    3
    4
    5
    6
    
    vi ~/.bashrc
    # add the following
    export TF_VAR_ARM_SUBSCRIPTION_ID="700b8c1a-xxx"
    export TF_VAR_ARM_TENANT_ID="b525d9fd-xxx"
    export TF_VAR_ARM_CLIENT_ID="bb581ce9-xxx"
    export TF_VAR_ARM_CLIENT_SECRET="someSecret"
    
  7. Assign the service principle contributor at subscription level.

    • IAM blade, add contributor role for the Service Principle.
  8. In preparation for modifying .tf files, inside VSCode, install the two following extensions:

    1
    2
    
    code --install-extension 4ops.terraform
    code --install-extension hashicorp.terraform
    
  9. Feel free to try this using Bash instead of Powershell by following the above article. I switch between the two for now.

Tags:

Updated:

Comments