Search code examples
azureazure-active-directoryazure-cli

Renew JSON authentication key of Service Principal


I have created a Service Principal to access resources in CI before using the az ad sp create-for-rbac command:

az ad sp create-for-rbac --name "my-ci-sp" --role contributor \
  --scopes /subscriptions/<subscription-id>/resourceGroups/<group-name> \
  --json-auth

This command yields a JSON object with the secret, a few IDs, and a few endpoint URL.

Now that secret is close to expiring. I know that I can renew the secret using az ad app credential reset --id <my-sp-id>. However, that command outputs a different JSON schema.

How do I obtain a drop-in replacement for the --json-auth token that az ad sp create-for-rbac generated?


Solution

  • Initially, I ran same CLI command in my environment and got below JSON response:

    az ad sp create-for-rbac --name "my-ci-sp" --role contributor \
      --scopes /subscriptions/subID/resourceGroups/rgName \
      --json-auth
    

    Response:

    enter image description here

    When you reset the client secret with below CLI command, you will get only few values in response as the remaining will stay same:

    az ad app credential reset --id <my_sp_id>
    

    enter image description here

    Note that, there is no direct CLI command to get similar JSON response while resetting client secret. Alternatively, you can make use of below script that adds remaining values manually in response:

    SUBSCRIPTION_ID="sub_id"
    SP_ID="sp_id"
    
    JSON_OUTPUT=$(az ad app credential reset --id $SP_ID --query "{
        clientId: appId,
        clientSecret: password,
        tenantId: tenant,
        subscriptionId: '$SUBSCRIPTION_ID',
        activeDirectoryEndpointUrl: 'https://login.microsoftonline.com',
        resourceManagerEndpointUrl: 'https://management.azure.com/',
        activeDirectoryGraphResourceId: 'https://graph.windows.net/',
        sqlManagementEndpointUrl: 'https://management.core.windows.net:8443/',
        galleryEndpointUrl: 'https://gallery.azure.com/',
        managementEndpointUrl: 'https://management.core.windows.net/'
    }" --output json)
    
    echo $JSON_OUTPUT | jq .
    

    Response:

    enter image description here