Search code examples
azureazure-virtual-machineazure-identity

Azure Portal - How to setup a Client ID and Client Secret


I want to programmatically start and stop a VM instance, if possible can someone give me the step-by-step guide to how to obtain these two values:

AZURE_CLIENT_ID
AZURE_CLIENT_SECRET

Either creation via the azure cli or Azure dev ops portal is fine, I just can not understand why this process is not documented or somewhat intuitive.

I can not reference the process to do this anywhere.

I have seen this:

Attempted credentials:
        EnvironmentCredential: invalid tenantID. You can locate your tenantID by following the instructions listed here: https://learn.microsoft.com/partner-center/find-ids-and-domain-names
        WorkloadIdentityCredential: no token file specified. Check pod configuration or set TokenFilePath in the options
        ManagedIdentityCredential: managed identity timed out. See https://aka.ms/azsdk/go/identity/troubleshoot#dac for more information
        AzureCLICredential: Azure CLI not found on path
        AzureDeveloperCLICredential: Azure Developer CLI not found on path
exit status 1

Yet as far as I can reference, I have supplied the correct TenantId from my Azure portal subscription?

The best I can get to is this:

RESPONSE 403: 403 Forbidden
ERROR CODE: AuthorizationFailed
--------------------------------------------------------------------------------
{
  "error": {
    "code": "AuthorizationFailed",
    "message": "The client '...' with object id '...' does not have authorization to perform action 'Microsoft.Compute/virtualMachines/start/action' over scope '/subscriptions/.../resourceGroups/.../providers/Microsoft.Compute/virtualMachines...' or the scope is invalid. If access was recently granted, please refresh your credentials."
  }
}

enter image description here

enter image description here

The code for reproduction is here:

package main

import (
    "context"
    "fmt"
    "log"
    "os"

    "github.com/Azure/azure-sdk-for-go/sdk/azcore"
    "github.com/Azure/azure-sdk-for-go/sdk/azidentity"
    "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v5"
)

func connectionAzure() (azcore.TokenCredential, error) {
    cred, err := azidentity.NewDefaultAzureCredential(nil)

    if err != nil {
        return nil, err
    }
    return cred, nil
}

func main() {
    subscriptionId := os.Getenv("AZURE_SUBSCRIPTION_ID")

    if len(subscriptionId) == 0 {
        log.Fatal("AZURE_SUBSCRIPTION_ID is not set.")
    }

    // Set your Azure resource group name and VM name
    resourceGroupName := "<RESOURCE_GROUP_NAME>"
    virtualMachineName := "<VIRTUAL_MACHINE_NAME>"

    cred, err := connectionAzure()

    if err != nil {
        log.Fatalf("cannot connect to Azure:%+v", err)
    }

    ctx := context.Background()

    client, err := armcompute.NewVirtualMachinesClient(subscriptionId, cred, nil)

    if err != nil {
        log.Fatalf("cannot create Azure Virtual Machines client:%+v", err)
    }

    poller, err := client.BeginStart(ctx, resourceGroupName, virtualMachineName, &armcompute.VirtualMachinesClientBeginStartOptions{})

    if err != nil {
        log.Fatalf("cannot start Azure Virtual Machine:%+v", err)
    }

    // Call the poller object's PollUntilDone function that will block until the poller object
    // has been updated to indicate the task has completed.
    res, err := poller.PollUntilDone(ctx, nil)

    if err != nil {
        log.Fatalf("cannot poll Azure Virtual Machine:%+v", err)
    }

    // Print the fact that the LRO completed.
    fmt.Printf("LRO done")

    // Print the response
    fmt.Printf("Response: %v\n", res)
}

Solution

  • In order to obtain AZURE_CLIENT_ID and AZURE_CLIENT_SECRET basically you will need to follow these steps:

    Create an Azure Active Directory Application in Microsoft Entra ID:

    • In Azure portal navigate to MS EntraID.
    • Click on App registrations and then New registration.
    • Once the application is created, note down the Application (client) ID. This is your AZURE_CLIENT_ID.

    Generate a Client Secret:

    • In the application settings, go to Certificates & secrets.
    • Under the Client secrets section, click new client secret.

    Generated client secret is your AZURE_CLIENT_SECRET

    The error message you're receiving, AuthorizationFailed, indicates that the App Registration you're using doesn't have the necessary permissions to perform the action you're trying to execute. In this case, it's trying to start a virtual machine, but lacks authorization. To resolve this issue, you'll need to ensure that the App Registration has the appropriate permissions. By assigning the Contributor role you're granting the App Registration the ability to start/stop your VM.