Resourcegroepen beheren met de Azure SDK voor Go

In dit artikel leert u hoe u een resourcegroep maakt met de Azure SDK voor Go-beheerbibliotheek.

1. Uw omgeving configureren

Belangrijk

De pakketten voor de huidige versie van de Azure-resourcebeheerbibliotheken bevinden zich in sdk/**/arm** . De pakketten voor de vorige versie van de beheerbibliotheken bevinden zich onder /services . Als u de oudere versie gebruikt, bekijkt u de Azure SDK voor Go Migration Guide.

2. Verifiëren bij Azure

Stel met behulp van uw Azure-verificatiegegevens de juiste omgevingsvariabelen in, zodat uw code kan worden geverifieerd bij Azure.

  1. Bewerk het ~/.bashrc bestand door de volgende omgevingsvariabelen toe te voegen. Vervang de tijdelijke aanduidingen door de juiste waarden uit de vorige sectie.

    export AZURE_SUBSCRIPTION_ID="<azure_subscription_id>"
    export AZURE_TENANT_ID="<active_directory_tenant_id"
    export AZURE_CLIENT_ID="<service_principal_appid>"
    export AZURE_CLIENT_SECRET="<service_principal_password>"
    
  2. Voer uit (of het verkorte equivalent ervan) om het ~/.bashrcsource ~/.bashrc script uit te . ~/.bashrc voeren.

    . ~/.bashrc
    
  3. Zodra de omgevingsvariabelen zijn ingesteld, kunt u de waarden ervan als volgt controleren:

    printenv | grep ^AZURE*
    

3. Een resourcegroep maken

  1. Maak een map waarin u de Go-voorbeeldcode wilt testen en uitvoeren en van deze de huidige map wilt maken.

  2. Voer go mod init uit om een module te maken in de huidige map.

    go mod init <module_path>
    

    Belangrijkste punten:

    • De <module_path> parameter is doorgaans een locatie in een GitHub-repo, zoals github.com/<your_github_account_name>/<directory> .
    • Wanneer u als test een opdrachtregel-app maakt en de app niet publiceert, hoeft deze <module_path> niet te bestaan.
  3. Voer get uit om de benodigde modules te downloaden, te bouwen Azure SDK voor Go installeren.

    go get github.com/Azure/azure-sdk-for-go/sdk/compute/armcompute
    go get github.com/Azure/azure-sdk-for-go/sdk/armcore
    go get github.com/Azure/azure-sdk-for-go/sdk/azcore
    go get github.com/Azure/azure-sdk-for-go/sdk/azidentity
    go get github.com/Azure/azure-sdk-for-go/sdk/resources/armresources
    go get github.com/Azure/azure-sdk-for-go/sdk/to
    
  4. Maak een bestand met de main.go naam en voeg de volgende code in. Elke sectie met code wordt becommentreerd om het doel ervan uit te leggen.

    package main
    
    // Import key modules.
    import (
    	"context"
    	"log"
    	"os"
    
    	"github.com/Azure/azure-sdk-for-go/sdk/armcore"
    	"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/resources/armresources"
    	"github.com/Azure/azure-sdk-for-go/sdk/to"
    )
    
    // Define key global variables.
    var (
    	subscriptionId    = os.Getenv("ARM_SUBSCRIPTION_ID")
    	location          = "eastus"
    	resourceGroupName = "myResourceGroup" // !! IMPORTANT: Change this to a unique name in your subscription.
        interval          = 5 * time.Second
    )
    
    // Define the function to create a resource group.
    func createResourceGroup(connection *armcore.Connection) (armresources.ResourceGroupResponse, error) {
    	rgClient := armresources.NewResourceGroupsClient(connection, subscriptionId)
    
    	param := armresources.ResourceGroup{
    		Location: to.StringPtr(location),
    	}
    
    	return rgClient.CreateOrUpdate(context.Background(), resourceGroupName, param, nil)
    }
    
    // Define the standard 'main' function for an app that is called from the command line.
    func main() {
    
    	// Create a credentials object.
    	cred, err := azidentity.NewDefaultAzureCredential(nil)
    	if err != nil {
    		log.Fatalf("Authentication failure: %+v", err)
    	}
    
    	// Establish a connection with the Azure subscription.
    	conn := armcore.NewDefaultConnection(cred, &armcore.ConnectionOptions{
    		Logging: azcore.LogOptions{
    			IncludeBody: true,
    		},
    	})
    
    	// Call your function to create an Azure resource group.
    	resourceGroup, err := createResourceGroup(ctx, conn)
    	if err != nil {
    		log.Fatalf("Creation of resource group failed: %+v", err)
    	}
    
    	// Print the name of the new resource group.
    	log.Printf("Resource group %s created", *resourceGroup.ResourceGroup.ID)
    }
    

    Belangrijkste punten:

    • De subscriptionId waarde wordt opgehaald uit de ARM_SUBSCRIPTION_ID omgevingsvariabele.
    • De locationresourceGroupName tekenreeksen en hebben testwaarden gekregen. Wijzig indien nodig deze waarden in iets dat geschikt is voor uw omgeving.
  5. Voer go mod tidy uit om de afhankelijkheden in het bestand op te schonen op basis van uw broncode.

    go mod tidy
    
  6. Voer go run uit om de app te bouwen en uit te voeren.

    go run .
    

4. De resultaten controleren

  1. Blader naar Azure Portal.

  2. Meld u aan en selecteer uw Azure-abonnement.

  3. Selecteer Resourcegroepen in het linkermenu.

  4. De nieuwe resourcegroep wordt vermeld in de resourcegroepen van uw Azure-abonnement.

5. Een resourcegroep bijwerken

  1. Ga terug naar uw main.go bestand.

  2. Voeg de volgende code net boven de main functie in.

    // Update the resource group by adding a tag to it.
    func updateResourceGroup(ctx context.Context, connection *armcore.Connection) (armresources.ResourceGroupResponse, error) {
        rgClient := armresources.NewResourceGroupsClient(connection, subscriptionId)
    
        update := armresources.ResourceGroupPatchable{
            Tags: map[string]*string{
                "new": to.StringPtr("tag"),
            },
        }
        return rgClient.Update(ctx, resourceGroupName, update, nil)
    }
    

6. Een lijst met resourcegroepen van een Azure-abonnement maken

  1. Ga terug naar uw main.go bestand.

  2. Voeg de volgende code net boven de main functie in.

    // List all the resource groups of an Azure subscription.
    func listResourceGroups(ctx context.Context, connection *armcore.Connection) ([]*armresources.ResourceGroup, error) {
        rgClient := armresources.NewResourceGroupsClient(connection, subscriptionId)
    
        pager := rgClient.List(nil)
    
        var resourceGroups []*armresources.ResourceGroup
        for pager.NextPage(ctx) {
            resp := pager.PageResponse()
            if resp.ResourceGroupListResult != nil {
                resourceGroups = append(resourceGroups, resp.ResourceGroupListResult.Value...)
            }
        }
        return resourceGroups, pager.Err()
    }
    

7. Een resourcegroep verwijderen

  1. Ga terug naar uw main.go bestand.

  2. Voeg de volgende code net boven de main functie in.

    // Delete a resource group.
    func deleteResourceGroup(ctx context.Context, connection *armcore.Connection) error {
        rgClient := armresources.NewResourceGroupsClient(connection, subscriptionId)
    
        poller, err := rgClient.BeginDelete(ctx, resourceGroupName, nil)
        if err != nil {
            return err
        }
        if _, err := poller.PollUntilDone(ctx, interval); err != nil {
            return err
        }
        return nil
    }
    

8. De hoofdfunctie bijwerken

In dit artikel hebt u gezien hoe u een resourcegroep kunt maken, bijwerken en verwijderen. U hebt ook gezien hoe u een lijst maakt met alle resourcegroepen van een Azure-abonnement. Als u al deze functies opeenvolgend wilt uitvoeren, vervangt u de main functie door de volgende code:

func main() {

    // Create a credentials object.
    cred, err := azidentity.NewDefaultAzureCredential(nil)
    if err != nil {
        log.Fatalf("Authentication failure: %+v", err)
    }

    // Establish a connection with the Azure subscription.
    conn := armcore.NewDefaultConnection(cred, &armcore.ConnectionOptions{
        Logging: azcore.LogOptions{
            IncludeBody: true,
        },
    })

    // Call your function to create an Azure resource group.
    resourceGroup, err := createResourceGroup(ctx, conn)
    if err != nil {
        log.Fatalf("Creation of resource group failed: %+v", err)
    }
    // Print the name of the new resource group.
    log.Printf("Resource group %s created", *resourceGroup.ResourceGroup.ID)

    // Call your function to add a tag to your new resource group.
    updatedRG, err := updateResourceGroup(ctx, conn)
    if err != nil {
        log.Fatalf("Update of resource group failed: %+v", err)
    }
    log.Printf("Resource Group %s updated", *updatedRG.ResourceGroup.ID)

    // Call your function to list all the resource groups.
    rgList, err := listResourceGroups(ctx, conn)
    if err != nil {
        log.Fatalf("Listing of resource groups failed: %+v", err)
    }
    log.Printf("Your Azure subscription has a total of %d resource groups", len(rgList))

    // Call your function to delete the resource group you created.
    if err := deleteResourceGroup(ctx, conn); err != nil {
        log.Fatalf("Deletion of resource group failed: %+v", err)
    }
    log.Printf("Resource group deleted")
}

Problemen oplossen

Volgende stappen