Manage resource groups with the Azure SDK for Go
In this article, you learn how to create a resource group with the Azure SDK for Go management library.
1. Configure your environment
Azure subscription: If you don't have an Azure subscription, create a free account before you begin.
Create a service principal. Note the service principal's application (client) ID and secret.
Important
The packages for the current version of the Azure resource management libraries are located in sdk/**/arm**. The packages for the previous version of the management libraries are located under /services. If you're using the older version, see the this Azure SDK for Go Migration Guide.
2. Authenticate to Azure
Using your Azure authentication information, set the appropriate environment variables so that your code can authenticate to Azure.
Edit the
~/.bashrcfile by adding the following environment variables. Replace the placeholders with the appropriate values from the previous section.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>"To execute the
~/.bashrcscript, runsource ~/.bashrc(or its abbreviated equivalent. ~/.bashrc).. ~/.bashrcOnce the environment variables have been set, you can verify their values as follows:
printenv | grep ^AZURE*
3. Create a resource group
Create a directory in which to test and run the sample Go code and make it the current directory.
Run go mod init to create a module in the current directory.
go mod init <module_path>Key points:
- The
<module_path>parameter is generally a location in a GitHub repo - such asgithub.com/<your_github_account_name>/<directory>. - When you're creating a command-line app as a test and won't publish the app, the
<module_path>doesn't have to exist.
- The
Run go get to download, build, and install the necessary Azure SDK for Go modules.
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/toCreate a file named
main.goand insert the following code. Each section of code is commented to explain its purpose.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) }Key points:
- The
subscriptionIdvalue is retrieved from theARM_SUBSCRIPTION_IDenvironment variable. - The
locationandresourceGroupNamestrings have been given test values. If necessary, change those values to something appropriate for your environment.
- The
Run go mod tidy to clean up the dependencies in the
go.modfile based on your source code.go mod tidyRun
go runto build and run the app.go run .
4. Verify the results
Browse to the Azure portal.
Sign in and select your Azure subscription.
In the left menu, select Resource groups.
The new resource group will be listed among your Azure subscription's resource groups.
5. Update a resource group
Return to your
main.gofile.Insert the following code just above the
mainfunction.// 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. List an Azure subscription's resource groups
Return to your
main.gofile.Insert the following code just above the
mainfunction.// 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. Delete a resource group
Return to your
main.gofile.Insert the following code just above the
mainfunction.// 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. Update the main function
In this article, you've seen how to create, update, and delete a resource group. You've also seen how to list all the resource groups of an Azure subscription. To run all these functions sequentially, replace the main function with the following 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")
}
Troubleshooting
- Check previous questions posted to Stack Overflow or ask new questions using the
AzureandGotags. - For any errors you come across, file a GitHub Issue