storage

package
v0.0.0-...-e747c7c Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 5, 2018 License: MIT Imports: 14 Imported by: 0

README


services: storage platforms: go author: mcardosos,joshgav

Manage Azure Storage

This package demonstrates how to manage storage accounts and blobs with the Azure SDK for Go. You can use the SDK to create and update storage accounts, list all accounts in a subscription or resource group, list and regenerate keys, and delete accounts. You can also use the SDK to create and delete containers and the blobs they contain.

If you need it, get an Azure trial here.

On this page

Run this sample

  1. If necessary install Go.
  2. Clone this repository.
export PROJECT=github.com/Azure-Samples/azure-sdk-for-go-samples/storage
go get -u $PROJECT
cd ${GOPATH}/src/${PROJECT}
dep ensure
  1. Create an Azure service principal either through Azure CLI, PowerShell or the portal.

  2. Set the following environment variables based on the properties of this new service principal. Alternatively, fill in the variables in .env.tpl in this directory and rename that to .env.

EnvVar Value
AZURE_TENANT_ID your tenant id
AZURE_SUBSCRIPTION_ID your subscription ID
AZURE_CLIENT_ID service principal/application ID
AZURE_CLIENT_SECRET service principal/application secret
AZURE_RG_NAME name of new resource group
AZURE_LOCATION location for all resources
  1. Run the sample.
go test

What does example.go do?

Check storage account name availability

Check the validity and availability of a string as a storage account name.

result, err := storageAccountsClient.CheckNameAvailability(
  storage.AccountCheckNameAvailabilityParameters{
    Name: to.StringPtr(accountName),
    Type: to.StringPtr("Microsoft.Storage/storageAccounts")})
if err != nil {
  log.Fatalf("%s: %v", "storage account creation failed", err)
}
if *result.NameAvailable != true {
  log.Fatalf("%s: %v", "storage account name not available", err)
}

Create a new storage account

// CreateStorageAccount creates a new storage account.
func CreateStorageAccount() (<-chan storage.Account, <-chan error) {
	storageAccountsClient, _ := getStorageAccountsClient()

	result, err := storageAccountsClient.CheckNameAvailability(
		storage.AccountCheckNameAvailabilityParameters{
			Name: to.StringPtr(accountName),
			Type: to.StringPtr("Microsoft.Storage/storageAccounts")})
	if err != nil {
		log.Fatalf("%s: %v", "storage account creation failed", err)
	}
	if *result.NameAvailable != true {
		log.Fatalf("%s: %v", "storage account name not available", err)
	}

	return storageAccountsClient.Create(
		helpers.ResourceGroupName,
		accountName,
		storage.AccountCreateParameters{
			Sku: &storage.Sku{
				Name: storage.StandardLRS},
			Location: to.StringPtr(helpers.Location),
			AccountPropertiesCreateParameters: &storage.AccountPropertiesCreateParameters{}},
		nil /* cancel <-chan struct{} */)
}

Get the properties of a storage account

account, err := storageClient.GetProperties(groupName, accountName)

List storage accounts by resource group

listGroupAccounts, err := storageClient.ListByResourceGroup(groupName)
onErrorFail(err, "ListByResourceGroup failed")

for _, acc := range *listGroupAccounts.Value {
     fmt.Printf("\t%s\n", *acc.Name)
}

List storage accounts in subscription

listSubAccounts, err := storageClient.List()
onErrorFail(err, "List failed")

for _, acc := range *listSubAccounts.Value {
    fmt.Printf("\t%s\n", *acc.Name)
}

Get the storage account keys

keys, err := storageClient.ListKeys(groupName, accountName)
onErrorFail(err, "ListKeys failed")

fmt.Printf("'%s' storage account keys\n", accountName)
for _, key := range *keys.Keys {
    fmt.Printf("\tKey name: %s\n\tValue: %s...\n\tPermissions: %s\n",
        *key.KeyName,
        (*key.Value)[:5],
        key.Permissions)
    fmt.Println("\t----------------")
}

Regenerate a storage account key

keys, err = storageClient.RegenerateKey(groupName, accountName, storage.AccountRegenerateKeyParameters{
    KeyName: (*keys.Keys)[0].KeyName},
)

Update the storage account

Just like all resources, storage accounts can be updated.

storageClient.Update(groupName, accountName, storage.AccountUpdateParameters{
    Tags: &map[string]*string{
        "who rocks": to.StringPtr("golang"),
        "where":     to.StringPtr("on azure")},
})

List usage

usageList, err := usageClient.List()
onErrorFail(err, "List failed")

for _, usage := range *usageList.Value {
    fmt.Printf("\t%v: %v / %v\n", *usage.Name.Value, *usage.CurrentValue, *usage.Limit)
}

Delete storage account

storageClient.Delete(groupName, accountName)

More information

Please refer to Azure SDK for Go for more information.


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 with any additional questions or comments.

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func AppendToBlob

func AppendToBlob(ctx context.Context, accountName, containerName, blobName, message string) error

AppendToBlob appends new data to the specified append blob

func ClearPage

func ClearPage(ctx context.Context, accountName, containerName, blobName string, page int) error

ClearPage clears the specified page in the page blob

func CommitBlocks

func CommitBlocks(ctx context.Context, accountName, containerName, blobName string) error

CommitBlocks commits the uncommitted blocks to the blob

func CreateAppendBlob

func CreateAppendBlob(ctx context.Context, accountName, containerName, blobName string) (blob.AppendBlobURL, error)

CreateAppendBlob creates an empty append blob

func CreateBlockBlob

func CreateBlockBlob(ctx context.Context, accountName, containerName, blobName string) (blob.BlockBlobURL, error)

CreateBlockBlob creates a new block blob

func CreateContainer

func CreateContainer(ctx context.Context, accountName, containerName string) (blob.ContainerURL, error)

CreateContainer creates a new container with the specified name in the specified account

func CreatePageBlob

func CreatePageBlob(ctx context.Context, accountName, containerName, blobName string, pages int) (blob.PageBlobURL, error)

CreatePageBlob creates a new test blob in the container specified by env var

func CreateStorageAccount

func CreateStorageAccount(ctx context.Context, accountName string) (s storage.Account, err error)

CreateStorageAccount creates a new storage account.

func DeleteContainer

func DeleteContainer(ctx context.Context, accountName, containerName string) error

DeleteContainer deletes the named container.

func DeleteStorageAccount

func DeleteStorageAccount(ctx context.Context, accountName string) (autorest.Response, error)

DeleteStorageAccount deletes an existing storate account

func GetBlob

func GetBlob(ctx context.Context, accountName, containerName, blobName string) (string, error)

GetBlob downloads the specified blob contents

func GetContainer

func GetContainer(ctx context.Context, accountName, containerName string) (blob.ContainerURL, error)

GetContainer gets info about an existing container.

func GetPageRanges

func GetPageRanges(ctx context.Context, accountName, containerName, blobName string, pages int) (*blob.PageList, error)

GetPageRanges gets a list of valid page ranges in the page blob

func GetStorageAccount

func GetStorageAccount(ctx context.Context, accountName string) (storage.Account, error)

GetStorageAccount gets details on the specified storage account

func GetUncommitedBlocks

func GetUncommitedBlocks(ctx context.Context, accountName, containerName, blobName string) (*blob.BlockList, error)

GetUncommitedBlocks gets a list of uncommited blobs

func ListBlobs

func ListBlobs(ctx context.Context, accountName, containerName string) (*blob.ListBlobsResponse, error)

ListBlobs lists blobs on the specified container

Example
accountName = getAccountName()
containerName = strings.ToLower(containerName)

helpers.SetResourceGroupName("ListBlobs")
ctx := context.Background()
defer resources.Cleanup(ctx)
_, err := resources.CreateGroup(ctx, helpers.ResourceGroupName())
if err != nil {
	helpers.PrintAndLog(err.Error())
}

_, err = CreateStorageAccount(ctx, accountName)
if err != nil {
	helpers.PrintAndLog(err.Error())
}
helpers.PrintAndLog("created storage account")

_, err = CreateContainer(ctx, accountName, containerName)
if err != nil {
	helpers.PrintAndLog(err.Error())
}
helpers.PrintAndLog("created container")

for i := 0; i < 3; i++ {
	name := fmt.Sprintf("blob%d", i)
	_, err = CreateBlockBlob(ctx, accountName, containerName, name)
	if err != nil {
		helpers.PrintAndLog(err.Error())
	}
	helpers.PrintAndLog("created blob")
}

list, err := ListBlobs(ctx, accountName, containerName)
if err != nil {
	helpers.PrintAndLog(err.Error())
}
helpers.PrintAndLog(fmt.Sprintf("listed blobs: %d", len(list.Blobs.Blob)))
Output:

created storage account
created container
created blob
created blob
created blob
listed blobs: 3

func PutBlockOnBlob

func PutBlockOnBlob(ctx context.Context, accountName, containerName, blobName, message string, blockNum int) error

PutBlockOnBlob adds a block to a block blob. It does not commit the block.

func PutPage

func PutPage(ctx context.Context, accountName, containerName, blobName, message string, page int) error

PutPage adds a page to the page blob

Types

This section is empty.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL