This repository has been archived by the owner on Nov 16, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
Updated to v7.0.1 and code looks better now #3
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,2 @@ | ||
/vendor | ||
your-azure-sample-group-template.json |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -4,7 +4,7 @@ platforms: go | |
author: mcardosos | ||
--- | ||
|
||
#Manage Azure resources and resource groups with Go | ||
# Manage Azure resources and resource groups with Go | ||
|
||
This package demonstrates how to manage [resources and resource groups](bhttps://azure.microsoft.com/documentation/articles/resource-group-overview/#resource-groups) using Azure SDK for Go. | ||
|
||
|
@@ -13,154 +13,162 @@ If you don't have a Microsoft Azure subscription you can get a FREE trial accoun | |
**On this page** | ||
|
||
- [Run this sample](#run) | ||
- [What does resourceSample.go do?](#sample) | ||
- [What does example.go do?](#sample) | ||
- [More information](#info) | ||
|
||
<a id="run"></a> | ||
|
||
## Run this sample | ||
|
||
1. Create a [service principal](https://azure.microsoft.com/documentation/articles/resource-group-authenticate-service-principal-cli/). You will need the Tenant ID, Client ID and Client Secret for [authentication](https://github.com/Azure/azure-sdk-for-go/tree/master/arm#first-a-sidenote-authentication-and-the-azure-resource-manager), so keep them as soon as you get them. | ||
2. Get your Azure Subscription ID using either of the methods mentioned below: | ||
- Get it through the [portal](portal.azure.com) in the subscriptions section. | ||
- Get it using the [Azure CLI](https://azure.microsoft.com/documentation/articles/xplat-cli-install/) with command `azure account show`. | ||
- Get it using [Azure Powershell](https://azure.microsoft.com/documentation/articles/powershell-install-configure/) whit cmdlet `Get-AzureRmSubscription`. | ||
3. Set environment variables `AZURE_TENANT_ID = <TENANT_ID>`, `AZURE_CLIENT_ID = <CLIENT_ID>`, `AZURE_CLIENT_SECRET = <CLIENT_SECRET>` and `AZURE_SUBSCRIPTION_ID = <SUBSCRIPTION_ID>`. | ||
4. Get this sample using command `go get -u github.com/Azure-Samples/resource-manager-go-resources-and-groups`. | ||
5. Get the [Azure SDK for Go](https://github.com/Azure/azure-sdk-for-go) using command `go get -u github.com/Azure/azure-sdk-for-go`. Or in case that you want to vendor your dependencies using [glide](https://github.com/Masterminds/glide), navigate to this sample's directory and use command `glide install`. | ||
6. Compile and run the sample. | ||
1. If you don't already have it, [install Go 1.7](https://golang.org/dl/). | ||
|
||
<a id="sample"></a> | ||
## What does resourceSample.go do? | ||
1. Get the sample. You can use either | ||
|
||
The sample gets an authorization token, creates a new resource group, updates it, lists the resource groups, creates a resource using a generic template, updates the resource, lists the resources inside the resource group, exports all resources into a json template, deletes a resource, and deletes the resource group. | ||
``` | ||
go get github.com/Azure-Samples/resource-manager-go-resources-and-groups | ||
``` | ||
|
||
### Get credentials and token | ||
or | ||
|
||
The sample starts by getting an authorization token from the service principal using your credentials. This token should be included in clients. | ||
``` | ||
git clone https://github.com:Azure-Samples/virtual-machines-go-manage.git | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Thoughts on offering There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Fixed |
||
``` | ||
|
||
``` | ||
credentials := map[string]string{ | ||
"AZURE_CLIENT_ID": os.Getenv("AZURE_CLIENT_ID"), | ||
"AZURE_CLIENT_SECRET": os.Getenv("AZURE_CLIENT_SECRET"), | ||
"AZURE_SUBSCRIPTION_ID": os.Getenv("AZURE_SUBSCRIPTION_ID"), | ||
"AZURE_TENANT_ID": os.Getenv("AZURE_TENANT_ID")} | ||
if err := checkEnvVar(&credentials); err != nil { | ||
return err | ||
} | ||
oauthConfig, err := azure.PublicCloud.OAuthConfigForTenant(credentials["AZURE_TENANT_ID"]) | ||
if err != nil { | ||
return err | ||
} | ||
token, err := azure.NewServicePrincipalToken(*oauthConfig, credentials["AZURE_CLIENT_ID"], credentials["AZURE_CLIENT_SECRET"], azure.PublicCloud.ResourceManagerEndpoint) | ||
if err != nil { | ||
return err | ||
} | ||
``` | ||
1. Install the dependencies using [glide](https://github.com/Masterminds/glide). | ||
|
||
### Create resource group | ||
``` | ||
cd virtual-machines-go-manage | ||
glide install | ||
``` | ||
Then, the sample creates a GroupsClient, which creates a resource group. | ||
1. Create an Azure service principal either through | ||
[Azure CLI](https://azure.microsoft.com/documentation/articles/resource-group-authenticate-service-principal-cli/), | ||
[PowerShell](https://azure.microsoft.com/documentation/articles/resource-group-authenticate-service-principal/) | ||
or [the portal](https://azure.microsoft.com/documentation/articles/resource-group-create-service-principal-portal/). | ||
``` | ||
groupClient := resources.NewGroupsClient(credentials["AZURE_SUBSCRIPTION_ID"]) | ||
groupClient.Authorizer = token | ||
location := "westus" | ||
resourceGroupName := "azure-sample-group" resourceGroupParameters := resources.ResourceGroup{ | ||
Location: &location} | ||
if _, err := groupClient.CreateOrUpdate(resourceGroupName, resourceGroupParameters); err != nil { | ||
return err | ||
} | ||
1. Set the following environment variables using the information from the service principle that you created. | ||
``` | ||
export AZURE_TENANT_ID={your tenant id} | ||
export AZURE_CLIENT_ID={your client id} | ||
export AZURE_CLIENT_SECRET={your client secret} | ||
export AZURE_SUBSCRIPTION_ID={your subscription id} | ||
``` | ||
> [AZURE.NOTE] On Windows, use `set` instead of `export`. | ||
1. Run the sample. | ||
``` | ||
go run example.go | ||
``` | ||
<a id="sample"></a> | ||
## What does example.go do? | ||
### Create resource group | ||
```go | ||
rg := resources.ResourceGroup{ | ||
Location: to.StringPtr(location), | ||
} | ||
_, err := groupsClient.CreateOrUpdate(groupName, rg) | ||
``` | ||
|
||
### Update the resource group | ||
|
||
The sample updates the resource group with tags. | ||
|
||
``` | ||
tags := map[string]*string{ | ||
```go | ||
rg.Tags = &map[string]*string{ | ||
"who rocks": to.StringPtr("golang"), | ||
"where": to.StringPtr("on azure")} | ||
resourceGroupParameters.Tags = &tags | ||
_, err = groupClient.CreateOrUpdate(resourceGroupName, resourceGroupParameters) | ||
"where": to.StringPtr("on azure"), | ||
} | ||
_, err := groupsClient.CreateOrUpdate(groupName, rg) | ||
``` | ||
|
||
### List resource groups in subscription | ||
|
||
``` | ||
```go | ||
groupsList, err := groupClient.List("", nil) | ||
``` | ||
|
||
### Create a generic resource | ||
|
||
In this sample, a Key Vault is created, but it can be any resource. | ||
|
||
``` | ||
resourceClient := resources.NewClient(credentials["AZURE_SUBSCRIPTION_ID"]) | ||
resourceClient.Authorizer = token | ||
resourceClient.APIVersion = "2015-06-01" | ||
namespace, resourceType, vaultName := "Microsoft.KeyVault", "vaults", "azureSampleVault" | ||
keyVaultParameters := resources.GenericResource{ | ||
Location: &location, | ||
Properties: &map[string]interface{}{ | ||
"sku": map[string]string{ | ||
"Family": "A", | ||
"Name": "standard"}, | ||
"tenantID": credentials["AZURE_TENANT_ID"], | ||
"accessPolicies": []string{}, | ||
"enabledForDeployment": true}} | ||
if _, err = resourceClient.CreateOrUpdate(resourceGroupName, namespace, "", resourceType, vaultName, keyVaultParameters); err != nil { | ||
return err | ||
} | ||
```go | ||
genericResource := resources.GenericResource{ | ||
Location: to.StringPtr(location), | ||
Properties: &map[string]interface{}{ | ||
"sku": map[string]string{ | ||
"Family": "A", | ||
"Name": "standard", | ||
}, | ||
"tenantID": tenantID, | ||
"accessPolicies": []string{}, | ||
"enabledForDeployment": true, | ||
}, | ||
} | ||
_, err := resourcesClient.CreateOrUpdate(groupName, namespace, "", resourceType, resourceName, genericResource, nil) | ||
``` | ||
|
||
### Update the resource with tags | ||
|
||
``` | ||
keyVaultParameters.Tags = &tags | ||
_, err = resourceClient.CreateOrUpdate(resourceGroupName, namespace, "", resourceType, vaultName, keyVaultParameters) | ||
```go | ||
gr.Tags = &map[string]*string{ | ||
"who rocks": to.StringPtr("golang"), | ||
"where": to.StringPtr("on azure"), | ||
} | ||
_, err := resourcesClient.CreateOrUpdate(groupName, namespace, "", resourceType, resourceName, gr, nil) | ||
``` | ||
|
||
### List resources inside the resource group | ||
|
||
``` | ||
resourcesList, err := groupClient.ListResources(resourceGroupName, "", nil) | ||
```go | ||
resourcesList, err := groupsClient.ListResources(groupName, "", "", nil) | ||
``` | ||
|
||
###Export resource group template to a json file | ||
### Export resource group template to a json file | ||
|
||
Resources can be exported into a json file. The asterisk * indicates all resources should be exported. Later, the json file can be used for [template deployment](https://github.com/Azure-Samples/resource-manager-go-template-deployment). | ||
|
||
``` | ||
expReq := resources.ExportTemplateRequest{ | ||
Resources: &[]string{"*"}} | ||
template, err := groupClient.ExportTemplate(resourceGroupName, expReq) | ||
if err != nil { | ||
return err | ||
} | ||
exported, err := json.MarshalIndent(template, "", " ") | ||
if err != nil { | ||
return err | ||
} | ||
fileName := fmt.Sprintf("%v-template.json", resourceGroupName) | ||
if _, err := os.Stat(fileName); err == nil { | ||
return fmt.Errorf("File '%v' already exists", fileName) | ||
} | ||
return ioutil.WriteFile(fileName, exported, 0666) | ||
``` | ||
```go | ||
// The asterisk * indicates all resources should be exported. | ||
expReq := resources.ExportTemplateRequest{ | ||
Resources: &[]string{"*"}, | ||
} | ||
template, err := groupsClient.ExportTemplate(groupName, expReq) | ||
onErrorFail(err, "ExportTemplate failed") | ||
|
||
###Delete a generic resource | ||
prefix, indent := "", " " | ||
exported, err := json.MarshalIndent(template, prefix, indent) | ||
onErrorFail(err, "MarshalIndent failed") | ||
|
||
``` | ||
_, err = resourceClient.Delete(resourceGroupName, namespace, "", resourceType, vaultName) | ||
fileTemplate := "%s-template.json" | ||
fileName := fmt.Sprintf(fileTemplate, groupName) | ||
if _, err := os.Stat(fileName); err == nil { | ||
onErrorFail(fmt.Errorf("File '%s' already exists", fileName), "Saving JSON file failed") | ||
} | ||
ioutil.WriteFile(fileName, exported, 0666) | ||
``` | ||
|
||
###Delete the resource group | ||
### Delete a generic resource | ||
|
||
```go | ||
_, err := resourcesClient.Delete(groupName, namespace, "", resourceType, resourceName, nil) | ||
``` | ||
_, err = groupClient.Delete(resourceGroupName, nil) | ||
|
||
### Delete the resource group | ||
|
||
```go | ||
_, err := groupsClient.Delete(groupName, nil) | ||
``` | ||
|
||
<a id="info"></a> | ||
|
||
## More information | ||
|
||
- [First a Sidenote: Authentication and the Azure Resource Manager](https://github.com/Azure/azure-sdk-for-go/tree/master/arm#first-a-sidenote-authentication-and-the-azure-resource-manager) | ||
|
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I'd remove the version number here, I don't think there's anything in particular tying us to Go v1.7 instead of Go v1.6 or Go v1.8
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The SDK does not work with anything below 1.7
History time :D