1
2# Getting Started - New Azure Go SDK
3
4We are excited to announce that a new set of management libraries are now production-ready. Those packages share a number of new features such as Azure Identity support, HTTP pipeline, error-handling.,etc, and they also follow the new Azure SDK guidelines which create easy-to-use APIs that are idiomatic, compatible, and dependable.
5
6You can find the full list of those new libraries [here](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk).
7
8In this basic quickstart guide, we will walk you through how to authenticate to Azure and start interacting with Azure resources. There are several possible approaches to authentication. This document illustrates the most common scenario.
9
10## Migration from older versions of Azure management libraries for Go
11
12If you are an existing user of the older version of Azure management library for Go (packages that are located under [`/services`](https://github.com/Azure/azure-sdk-for-go/tree/main/services)), and you are looking for a migration guide to upgrade to the latest version of the SDK, please refer to [this migration guide](https://aka.ms/azsdk/go/mgmt/migration) for detailed instructions.
13
14## Prerequisites
15
16You will need Go 1.18 and latest version of resource management modules.
17
18You will need to authenticate to Azure either by using Azure CLI to sign in or setting environment variables.
19
20### Using Azure CLI to Sign In
21
22You could easily use `az login` in command line to sign in to Azure via your default browser. Detail instructions can be found in [Sign in with Azure CLI](https://docs.microsoft.com/cli/azure/authenticate-azure-cli).
23
24### Setting Environment Variables
25
26You will need the following values to authenticate to Azure
27
28- **Subscription ID**
29- **Client ID**
30- **Client Secret**
31- **Tenant ID**
32
33These values can be obtained from the portal, here's the instructions:
34
35- Get Subscription ID
36
37 1. Login into your Azure account
38 2. Select Subscriptions in the left sidebar
39 3. Select whichever subscription is needed
40 4. Click on Overview
41 5. Copy the Subscription ID
42
43- Get Client ID / Client Secret / Tenant ID
44
45 For information on how to get Client ID, Client Secret, and Tenant ID, please refer to [this document](https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal)
46
47- Setting Environment Variables
48
49 After you obtained the values, you need to set the following values as your environment variables
50
51 - `AZURE_CLIENT_ID`
52 - `AZURE_CLIENT_SECRET`
53 - `AZURE_TENANT_ID`
54 - `AZURE_SUBSCRIPTION_ID`
55
56 To set the following environment variables on your development system:
57
58 Windows (Note: Administrator access is required)
59
60 1. Open the Control Panel
61 2. Click System Security, then System
62 3. Click Advanced system settings on the left
63 4. Inside the System Properties window, click the `Environment Variables…` button.
64 5. Click on the property you would like to change, then click the `Edit…` button. If the property name is not listed, then click the `New…` button.
65
66 Linux-based OS :
67
68 export AZURE_CLIENT_ID="__CLIENT_ID__"
69 export AZURE_CLIENT_SECRET="__CLIENT_SECRET__"
70 export AZURE_TENANT_ID="__TENANT_ID__"
71 export AZURE_SUBSCRIPTION_ID="__SUBSCRIPTION_ID__"
72
73## Install the package
74
75The new SDK uses Go modules for versioning and dependency management.
76
77As an example, to install the Azure Compute module, you would run :
78
79```sh
80go get github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute
81```
82
83We also recommend installing other packages for authentication and core functionalities :
84
85```sh
86go get github.com/Azure/azure-sdk-for-go/sdk/azcore
87go get github.com/Azure/azure-sdk-for-go/sdk/azidentity
88```
89
90## Authentication
91
92Before creating a client, you will need to provide a credential for authenticating with the Azure service. The `azidentity` module provides facilities for various ways of authenticating with Azure including client/secret, certificate, managed identity, and more.
93
94Our default option is to use **DefaultAzureCredential**. It combines common production credentials with development credentials.
95
96```go
97import "github.com/Azure/azure-sdk-for-go/sdk/azidentity"
98```
99
100```go
101cred, err := azidentity.NewDefaultAzureCredential(nil)
102```
103
104For more details on how authentication works in `azidentity`, please see the documentation for `azidentity` at [pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity).
105
106
107## Creating a Resource Management Client
108
109Once you have a credential, you will need to decide what service to use and create a client to connect to that service. In this section, we will use `Compute` as our target service. The Compute modules consist of one or more clients. A client groups a set of related APIs, providing access to its functionality within the specified subscription. You will need to create one or more clients to access the APIs you require using your `azcore.TokenCredential`.
110
111To show an example, we will create a client to manage Virtual Machines. The code to achieve this task would be:
112
113```go
114import "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute"
115```
116
117```go
118client, err := armcompute.NewVirtualMachinesClient("<subscription ID>", credential, nil)
119```
120You can use the same pattern to connect with other Azure services that you are using. For example, in order to manage Virtual Network resources, you would install the Network package and create a `VirtualNetwork` Client:
121
122```go
123import "github.com/Azure/azure-sdk-for-go/sdk/azidentity"
124import "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork"
125```
126
127```go
128client, err := armnetwork.NewVirtualNetworksClient("<subscription ID>", credential, nil)
129```
130
131## Interacting with Azure Resources
132
133Now that we are authenticated and have created our sub-resource clients, we can use our client to make API calls. For resource management scenarios, most of our cases are centered around creating / updating / reading / deleting Azure resources. Those scenarios correspond to what we call "operations" in Azure. Once you are sure of which operations you want to call, you can then implement the operation call using the management client we just created in previous section.
134
135To write the concrete code for the API call, you might need to look up the information of request parameters, types, and response body for a certain operation. We recommend using the following site for SDK reference:
136
137- [Official Go docs for new Azure Go SDK packages](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk) - This web-site contains the complete SDK references for each released package as well as embedded code snippets for some operation.
138
139To see the reference for a certain package, you can either click into each package on the web-site, or directly add the SDK path to the end of URL. For example, to see the reference for Azure Compute package, you can use [https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute). Certain development tool or IDE has features that allow you to directly look up API definitions as well.
140
141Let's illustrate the SDK usage by a few quick examples. In the following sample. we are going to create a resource group using the SDK. To achieve this scenario, we can take the follow steps
142
143- **Step 1** : Decide which client we want to use, in our case, we know that it's related to Resource Group so our choice is the [ResourceGroupsClient](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/resources/armresources#ResourceGroupsClient).
144- **Step 2** : Find out which operation is responsible for creating a resource group. By locating the client in previous step, we are able to see all the functions under `ResourceGroupsClient`, and we can see [the `CreateOrUpdate` function](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/resources/armresources#ResourceGroupsClient.CreateOrUpdate) is what need.
145- **Step 3** : Using the information about this operation, we can then fill in the required parameters, and implement it using the Go SDK. If we need extra information on what those parameters mean, we can also use the [Azure service documentation](https://docs.microsoft.com/azure/?product=featured) on Microsoft Docs.
146
147Let's show what final code looks like.
148
149## Example: Creating a Resource Group
150
151***Import the packages***
152```go
153import (
154 "context"
155 "log"
156 "os"
157 "time"
158
159 "github.com/Azure/azure-sdk-for-go/sdk/azcore"
160 "github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
161 "github.com/Azure/azure-sdk-for-go/sdk/azidentity"
162 "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/resources/armresources"
163)
164```
165
166***Define some global variables***
167```go
168var (
169 ctx = context.TODO()
170 subscriptionId = os.Getenv("AZURE_SUBSCRIPTION_ID")
171 location = "westus2"
172 resourceGroupName = "resourceGroupName"
173 interval = 5 * time.Second
174)
175```
176
177***Write a function to create a resource group***
178```go
179func createResourceGroup(ctx context.Context, credential azcore.TokenCredential) (*armresources.ResourceGroupsClientCreateOrUpdateResponse, error) {
180 rgClient, err := armresources.NewResourceGroupsClient(subscriptionId, credential, nil)
181 if err != nil {
182 return nil, err
183 }
184
185 param := armresources.ResourceGroup{
186 Location: to.Ptr(location),
187 }
188
189 resp, err := rgClient.CreateOrUpdate(ctx, resourceGroupName, param, nil)
190
191 return &resp, err
192}
193```
194
195***Invoking the `createResourceGroup` function in main***
196```go
197func main() {
198 cred, err := azidentity.NewDefaultAzureCredential(nil)
199 if err != nil {
200 log.Fatalf("authentication failure: %+v", err)
201 }
202
203 resourceGroup, err := createResourceGroup(ctx, cred)
204 if err != nil {
205 log.Fatalf("cannot create resource group: %+v", err)
206 }
207 log.Printf("Resource Group %s created", *resourceGroup.ResourceGroup.ID)
208}
209```
210
211Let's demonstrate management client's usage by showing additional samples.
212
213## Example: Managing Resource Groups
214
215***Update a resource group***
216
217```go
218func updateResourceGroup(ctx context.Context, credential azcore.TokenCredential) (*armresources.ResourceGroupsClientUpdateResponse, error) {
219 rgClient, err := armresources.NewResourceGroupsClient(subscriptionId, credential, nil)
220 if err != nil {
221 return nil, err
222 }
223
224 update := armresources.ResourceGroupPatchable{
225 Tags: map[string]*string{
226 "new": to.Ptr("tag"),
227 },
228 }
229
230 resp,err :=rgClient.Update(ctx, resourceGroupName, update, nil)
231
232 return &resp, err
233}
234```
235
236***List all resource groups***
237
238```go
239func listResourceGroups(ctx context.Context, credential azcore.TokenCredential) ([]*armresources.ResourceGroup, error) {
240 rgClient, err := armresources.NewResourceGroupsClient(subscriptionId, credential, nil)
241 if err != nil {
242 return nil, err
243 }
244
245 pager := rgClient.NewListPager(nil)
246
247 var resourceGroups []*armresources.ResourceGroup
248 for pager.More() {
249 nextResult, err := pager.NextPage(ctx)
250 if err != nil {
251 return nil, err
252 }
253 if nextResult.ResourceGroupListResult.Value != nil {
254 resourceGroups = append(resourceGroups, nextResult.ResourceGroupListResult.Value...)
255 }
256 }
257
258 return resourceGroups, nil
259}
260```
261You could see there is a pattern for pageable operation here. With `NewListPager` you will get an pager helper for fetching pages and determining if there are more pages to fetch. For more details, you could refer to [Azure Go Management SDK Guideline](https://github.com/Azure/azure-sdk-for-go/blob/main/documentation/new-version-guideline.md#pageable-operations).
262
263***Delete a resource group***
264
265```go
266func deleteResourceGroup(ctx context.Context, credential azcore.TokenCredential) error {
267 rgClient, err := armresources.NewResourceGroupsClient(subscriptionId, credential, nil)
268 if err != nil {
269 return err
270 }
271
272 poller, err := rgClient.BeginDelete(ctx, resourceGroupName, nil)
273 if err != nil {
274 return err
275 }
276 _, err = poller.PollUntilDone(ctx, nil)
277 return err
278}
279```
280You could see there is a pattern for LRO (long-running operations) here. With `BeginDelete` the LRO has started and you will get an poller helper for fetching operation result. For more details, you could refer to [Azure Go Management SDK Guideline](https://github.com/Azure/azure-sdk-for-go/blob/main/documentation/new-version-guideline.md#long-running-operations).
281
282***Invoking the update, list and delete of resource group in the main function***
283```go
284func main() {
285 cred, err := azidentity.NewDefaultAzureCredential(nil)
286 if err != nil {
287 log.Fatalf("authentication failure: %+v", err)
288 }
289
290 resourceGroup, err := createResourceGroup(ctx, cred)
291 if err != nil {
292 log.Fatalf("cannot create resource group: %+v", err)
293 }
294 log.Printf("Resource Group %s created", *resourceGroup.ResourceGroup.ID)
295
296 updatedRG, err := updateResourceGroup(ctx, cred)
297 if err != nil {
298 log.Fatalf("cannot update resource group: %+v", err)
299 }
300 log.Printf("Resource Group %s updated", *updatedRG.ResourceGroup.ID)
301
302 rgList, err := listResourceGroups(ctx, cred)
303 if err != nil {
304 log.Fatalf("cannot list resource group: %+v", err)
305 }
306 log.Printf("We totally have %d resource groups", len(rgList))
307
308 if err := deleteResourceGroup(ctx, cred); err != nil {
309 log.Fatalf("cannot delete resource group: %+v", err)
310 }
311 log.Printf("Resource Group deleted")
312}
313```
314
315## Example: Managing Virtual Machines
316
317In addition to resource groups, we will also use Virtual Machine as an example and show how to manage how to create a Virtual Machine which involves three Azure services (Resource Group, Network and Compute)
318
319Due to the complexity of this scenario, please [click here](https://aka.ms/azsdk/go/mgmt/samples?path=sdk/resourcemanager/compute/createVM) for the complete sample.
320
321## Code Samples
322
323More code samples for using the management library for Go SDK can be found in the following locations
324- [Go SDK Code Samples](https://aka.ms/azsdk/go/mgmt/samples)
325- Example files under each package. For example, examples for Network packages can be [found here](https://github.com/Azure/azure-sdk-for-go/blob/main/sdk/resourcemanager/network/armnetwork/ze_generated_example_loadbalancernetworkinterfaces_client_test.go)
326
327## Further Infomation
328
329For further infomation about the new SDK including advanced API usage and trouble shooting, you could refer to [Azure Go Management SDK Guideline](https://github.com/Azure/azure-sdk-for-go/blob/main/documentation/new-version-guideline.md).
330
331## Need help?
332
333- File an issue via [Github Issues](https://github.com/Azure/azure-sdk-for-go/issues)
334- Check [previous questions](https://stackoverflow.com/questions/tagged/azure+go) or ask new ones on StackOverflow using azure and Go tags.
335
336## Contributing
337
338For details on contributing to this repository, see the [contributing guide](https://github.com/Azure/azure-sdk-for-go/blob/main/CONTRIBUTING.md).
339
340This project welcomes contributions and suggestions. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, please visit https://cla.microsoft.com.
341
342When you submit a pull request, a CLA-bot will automatically determine whether you need to provide a CLA and decorate the PR appropriately (e.g., label, comment). Simply follow the instructions provided by the bot. You will only need to do this once across all repositories using our CLA.
343
344This project has adopted the Microsoft Open Source Code of Conduct. For more information see the Code of Conduct FAQ or contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any questions or comments.
View as plain text