File: new-version-quickstart.md

package info (click to toggle)
golang-github-azure-azure-sdk-for-go 68.0.0-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 556,256 kB
  • sloc: javascript: 196; sh: 96; makefile: 7
file content (344 lines) | stat: -rw-r--r-- 16,193 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344

# Getting Started - New Azure Go SDK

We 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.

You can find the full list of those new libraries [here](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk).

In 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.

## Migration from older versions of Azure management libraries for Go

If 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.

## Prerequisites

You will need Go 1.18 and latest version of resource management modules.

You will need to authenticate to Azure either by using Azure CLI to sign in or setting environment variables.

### Using Azure CLI to Sign In

You 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).

### Setting Environment Variables

You will need the following values to authenticate to Azure

-   **Subscription ID**
-   **Client ID**
-   **Client Secret**
-   **Tenant ID**

These values can be obtained from the portal, here's the instructions:

- Get Subscription ID

    1.  Login into your Azure account
    2.  Select Subscriptions in the left sidebar
    3.  Select whichever subscription is needed
    4.  Click on Overview
    5.  Copy the Subscription ID

- Get Client ID / Client Secret / Tenant ID

    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)

- Setting Environment Variables

    After you obtained the values, you need to set the following values as your environment variables

    -   `AZURE_CLIENT_ID`
    -   `AZURE_CLIENT_SECRET`
    -   `AZURE_TENANT_ID`
    -   `AZURE_SUBSCRIPTION_ID`

    To set the following environment variables on your development system:

    Windows (Note: Administrator access is required)

    1.  Open the Control Panel
    2.  Click System Security, then System
    3.  Click Advanced system settings on the left
    4.  Inside the System Properties window, click the `Environment Variables…` button.
    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.

    Linux-based OS :

        export AZURE_CLIENT_ID="__CLIENT_ID__"
        export AZURE_CLIENT_SECRET="__CLIENT_SECRET__"
        export AZURE_TENANT_ID="__TENANT_ID__"
        export AZURE_SUBSCRIPTION_ID="__SUBSCRIPTION_ID__"

## Install the package

The new SDK uses Go modules for versioning and dependency management.

As an example, to install the Azure Compute module, you would run :

```sh
go get github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute
```

We also recommend installing other packages for authentication and core functionalities :

```sh
go get github.com/Azure/azure-sdk-for-go/sdk/azcore
go get github.com/Azure/azure-sdk-for-go/sdk/azidentity
```

## Authentication

Before 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.

Our default option is to use **DefaultAzureCredential**. It combines common production credentials with development credentials.

```go
import "github.com/Azure/azure-sdk-for-go/sdk/azidentity"
```

```go
cred, err := azidentity.NewDefaultAzureCredential(nil)
```

For 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).


## Creating a Resource Management Client

Once 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`.

To show an example, we will create a client to manage Virtual Machines. The code to achieve this task would be:

```go
import "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute"
```

```go
client, err := armcompute.NewVirtualMachinesClient("<subscription ID>", credential, nil)
```
You 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:

```go
import "github.com/Azure/azure-sdk-for-go/sdk/azidentity"
import "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork"
```

```go
client, err := armnetwork.NewVirtualNetworksClient("<subscription ID>", credential, nil)
```

## Interacting with Azure Resources

Now 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.

To 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:

- [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.

To 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.

Let'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

- **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).
- **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. 
- **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.

Let's show what final code looks like.

## Example: Creating a Resource Group

***Import the packages***
```go
import (
    "context"
    "log"
    "os"
    "time"

    "github.com/Azure/azure-sdk-for-go/sdk/azcore"
    "github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
    "github.com/Azure/azure-sdk-for-go/sdk/azidentity"
    "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/resources/armresources"
)
```

***Define some global variables***
```go
var (
    ctx                 = context.TODO()
    subscriptionId      = os.Getenv("AZURE_SUBSCRIPTION_ID")
    location            = "westus2"
    resourceGroupName   = "resourceGroupName"
    interval            = 5 * time.Second
)
```

***Write a function to create a resource group***
```go
func createResourceGroup(ctx context.Context, credential azcore.TokenCredential) (*armresources.ResourceGroupsClientCreateOrUpdateResponse, error) {
    rgClient, err := armresources.NewResourceGroupsClient(subscriptionId, credential, nil)
    if err != nil {
        return nil, err
    }

    param := armresources.ResourceGroup{
        Location: to.Ptr(location),
    }

    resp, err := rgClient.CreateOrUpdate(ctx, resourceGroupName, param, nil)

    return &resp, err
}
```

***Invoking the `createResourceGroup` function in main***
```go
func main() {
    cred, err := azidentity.NewDefaultAzureCredential(nil)
    if err != nil {
        log.Fatalf("authentication failure: %+v", err)
    }
    
    resourceGroup, err := createResourceGroup(ctx, cred)
    if err != nil {
        log.Fatalf("cannot create resource group: %+v", err)
    }
    log.Printf("Resource Group %s created", *resourceGroup.ResourceGroup.ID)
}
```

Let's demonstrate management client's usage by showing additional samples.

## Example: Managing Resource Groups

***Update a resource group***

```go
func updateResourceGroup(ctx context.Context, credential azcore.TokenCredential) (*armresources.ResourceGroupsClientUpdateResponse, error) {
    rgClient, err := armresources.NewResourceGroupsClient(subscriptionId, credential, nil)
    if err != nil {
        return nil, err
    }

    update := armresources.ResourceGroupPatchable{
        Tags: map[string]*string{
            "new": to.Ptr("tag"),
        },
    }

    resp,err :=rgClient.Update(ctx, resourceGroupName, update, nil)
    
    return  &resp, err
}
```

***List all resource groups***

```go
func listResourceGroups(ctx context.Context, credential azcore.TokenCredential) ([]*armresources.ResourceGroup, error) {
    rgClient, err := armresources.NewResourceGroupsClient(subscriptionId, credential, nil)
    if err != nil {
        return nil, err
    }

    pager := rgClient.NewListPager(nil)

    var resourceGroups []*armresources.ResourceGroup
    for pager.More() {
        nextResult, err := pager.NextPage(ctx)
        if err != nil {
            return nil, err
        }
        if nextResult.ResourceGroupListResult.Value != nil {
            resourceGroups = append(resourceGroups, nextResult.ResourceGroupListResult.Value...)
        }
    }

    return resourceGroups, nil
}
```
You 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).

***Delete a resource group***

```go
func deleteResourceGroup(ctx context.Context, credential azcore.TokenCredential) error {
    rgClient, err := armresources.NewResourceGroupsClient(subscriptionId, credential, nil)
    if err != nil {
        return err
    }

    poller, err := rgClient.BeginDelete(ctx, resourceGroupName, nil)
    if err != nil {
        return err
    }
    _, err = poller.PollUntilDone(ctx, nil)
    return err
}
```
You 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).

***Invoking the update, list and delete of resource group in the main function***
```go
func main() {
    cred, err := azidentity.NewDefaultAzureCredential(nil)
    if err != nil {
        log.Fatalf("authentication failure: %+v", err)
    }

    resourceGroup, err := createResourceGroup(ctx, cred)
    if err != nil {
        log.Fatalf("cannot create resource group: %+v", err)
    }
    log.Printf("Resource Group %s created", *resourceGroup.ResourceGroup.ID)

    updatedRG, err := updateResourceGroup(ctx, cred)
    if err != nil {
        log.Fatalf("cannot update resource group: %+v", err)
    }
    log.Printf("Resource Group %s updated", *updatedRG.ResourceGroup.ID)

    rgList, err := listResourceGroups(ctx, cred)
    if err != nil {
        log.Fatalf("cannot list resource group: %+v", err)
    }
    log.Printf("We totally have %d resource groups", len(rgList))

    if err := deleteResourceGroup(ctx, cred); err != nil {
        log.Fatalf("cannot delete resource group: %+v", err)
    }
    log.Printf("Resource Group deleted")
}
```

## Example: Managing Virtual Machines

In 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)

Due 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.

## Code Samples

More code samples for using the management library for Go SDK can be found in the following locations
- [Go SDK Code Samples](https://aka.ms/azsdk/go/mgmt/samples)
- 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)

## Further Infomation

For 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).

## Need help?

- File an issue via [Github Issues](https://github.com/Azure/azure-sdk-for-go/issues)
- Check [previous questions](https://stackoverflow.com/questions/tagged/azure+go) or ask new ones on StackOverflow using azure and Go tags.

## Contributing

For details on contributing to this repository, see the [contributing guide](https://github.com/Azure/azure-sdk-for-go/blob/main/CONTRIBUTING.md).

This 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.

When 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.

This 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.