compute

package
v0.0.0-...-86c76a3 Latest Latest
Warning

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

Go to latest
Published: Feb 19, 2020 License: MIT Imports: 18 Imported by: 0

README


services: compute platforms: go author: joshgav

Azure Compute Samples

This package demonstrates how to manage Azure VMs, their disks and container instances with the Go SDK.

The child package "hybrid" demonstrates how to manage Azure VMs using Azure's Hybrid profile.

Contents

  • How to run all samples
  • Virtual Machines
    • CreateVM - All the steps necessary to create a VM and turn it on and off.
    • CreateVMWithIdentity - Create a VM with a managed identity.
    • CreateVMWithLoadBalancer - Create VMs taking advantage of availability sets and load balancing.
    • CreateVMWithEncryptedDisks - Store a secret in Key Vault and use it to encrypt and decrypt disks.
    • CreateAvailabilitySet
    • AddIdentityToVM
    • DeallocateVM
    • UpdateVM
    • StartVM
    • RestartVM
    • StopVM
  • Container Instances
    • CreateContainerGroup
    • UpdateContainerGroup
    • DeleteContainerGroup
  • Disks
    • CreateDisk
    • CreateVMWithDisk
    • AddDiskEncryptionToVM
    • AttachDataDisk
    • DetachDataDisks
    • UpdateOSDiskSize

How to run all samples

  1. Get this package and all dependencies.
export PROJECT=github.com/Azure-Samples/azure-sdk-for-go-samples/compute
go get -u $PROJECT
cd ${GOPATH}/src/${PROJECT}
dep ensure
  1. Create an Azure service principal with the [Azure CLI][] command az ad sp create-for-rbac --output json and set the following environment variables per that command's output. You can also copy .env.tpl to .env and fill it in; the configuration system will utilize this.
AZURE_CLIENT_ID=
AZURE_CLIENT_SECRET=
AZURE_TENANT_ID=
AZURE_SUBSCRIPTION_ID=
AZURE_BASE_GROUP_NAME=
AZURE_LOCATION_DEFAULT=westus2
  1. TODO(joshgav): grant this principal all-powerful rights to your AAD tenant to faciliate identity-related operations.
  2. Run the tests: go test -v -timeout 12h

The timeout is optional, but some tests take longer than then default 10m to complete.

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 AddDiskEncryptionToVM

func AddDiskEncryptionToVM(ctx context.Context, vmName, vaultName, keyID string) (ext compute.VirtualMachineExtension, err error)

AddDiskEncryptionToVM adds an extension to a VM to enable use of encryption keys from Key Vault to decrypt disks.

func AddIdentityToVM

func AddIdentityToVM(ctx context.Context, vmName string) (ext compute.VirtualMachineExtension, err error)

AddIdentityToVM adds a managed identity to an existing VM by activating the corresponding VM extension.

func AddUserAssignedIDToVM

func AddUserAssignedIDToVM(ctx context.Context, vmName string, id msi.Identity) (*compute.VirtualMachine, error)

AddUserAssignedIDToVM adds the specified user-assigned identity to the specified pre-existing VM.

func AttachDataDisk

func AttachDataDisk(ctx context.Context, vmName string) (vm compute.VirtualMachine, err error)

AttachDataDisk attaches a 1GB data disk to the specified VM.

func CreateAKS

func CreateAKS(ctx context.Context, resourceName, location, resourceGroupName, username, sshPublicKeyPath, clientID, clientSecret string, agentPoolCount int32) (c containerservice.ManagedCluster, err error)

CreateAKS creates a new managed Kubernetes cluster

Example
var groupName = config.GenerateGroupName("CreateAKS")
config.SetGroupName(groupName)

ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(time.Hour*1))
defer cancel()
defer resources.Cleanup(ctx)

_, err := resources.CreateGroup(ctx, config.GroupName())
if err != nil {
	util.PrintAndLog(err.Error())
}

_, err = CreateAKS(ctx, aksClusterName, config.Location(), config.GroupName(), aksUsername, aksSSHPublicKeyPath, config.ClientID(), config.ClientSecret(), aksAgentPoolCount)
if err != nil {
	util.PrintAndLog(err.Error())
}
util.PrintAndLog("created AKS cluster")

_, err = GetAKS(ctx, config.GroupName(), aksClusterName)
if err != nil {
	util.PrintAndLog(err.Error())
}
util.PrintAndLog("retrieved AKS cluster")

_, err = DeleteAKS(ctx, config.GroupName(), aksClusterName)
if err != nil {
	util.PrintAndLog(err.Error())
}

util.PrintAndLog("deleted AKS cluster")
Output:

created AKS cluster
retrieved AKS cluster
deleted AKS cluster

func CreateAvailabilitySet

func CreateAvailabilitySet(ctx context.Context, asName string) (compute.AvailabilitySet, error)

CreateAvailabilitySet creates an availability set

func CreateContainerGroup

func CreateContainerGroup(ctx context.Context, containerGroupName, location, resourceGroupName string) (c containerinstance.ContainerGroup, err error)

CreateContainerGroup creates a new container group given a container group name, location and resoruce group

Example
var groupName = config.GenerateGroupName("CreateContainerGroup")
config.SetGroupName(groupName)

ctx := context.Background()
defer resources.Cleanup(ctx)

_, err := resources.CreateGroup(ctx, groupName)
if err != nil {
	util.PrintAndLog(err.Error())
}

_, err = CreateContainerGroup(ctx, containerGroupName, config.Location(), groupName)
if err != nil {
	log.Fatalf("cannot create container group: %v", err)
}
util.PrintAndLog("created container group")

c, err := GetContainerGroup(ctx, groupName, containerGroupName)
if err != nil {
	log.Fatalf("cannot get container group %v from resource group %v", containerGroupName, groupName)
}

if *c.Name != containerGroupName {
	log.Fatalf("incorrect name of container group: expected %v, got %v", containerGroupName, *c.Name)
}
util.PrintAndLog("retrieved container group")

_, err = UpdateContainerGroup(ctx, groupName, containerGroupName)
if err != nil {
	log.Fatalf("cannot upate container group: %v", err)
}
util.PrintAndLog("updated container group")

_, err = DeleteContainerGroup(ctx, groupName, containerGroupName)
if err != nil {
	log.Fatalf("cannot delete container group %v from resource group %v: %v", containerGroupName, groupName, err)
}
util.PrintAndLog("deleted container group")
Output:

created container group
retrieved container group
updated container group
deleted container group

func CreateDisk

func CreateDisk(ctx context.Context, diskName string) (disk disks.Disk, err error)

CreateDisk creates an empty 64GB disk which can be attached to a VM.

func CreateVM

func CreateVM(ctx context.Context, vmName, nicName, username, password, sshPublicKeyPath string) (vm compute.VirtualMachine, err error)

CreateVM creates a new virtual machine with the specified name using the specified NIC. Username, password, and sshPublicKeyPath determine logon credentials.

Example

ExampleVM creates a group and network artifacts needed for a VM, then creates a VM and tests operations on it.

var groupName = config.GenerateGroupName("VM")
// TODO: remove and use local `groupName` only
config.SetGroupName(groupName)

ctx, cancel := context.WithTimeout(context.Background(), 6000*time.Second)
defer cancel()
defer resources.Cleanup(ctx)

_, err := resources.CreateGroup(ctx, groupName)
if err != nil {
	util.PrintAndLog(err.Error())
}

_, err = network.CreateVirtualNetworkAndSubnets(ctx, virtualNetworkName, subnet1Name, subnet2Name)
if err != nil {
	util.PrintAndLog(err.Error())
}
util.PrintAndLog("created vnet and 2 subnets")

_, err = network.CreateNetworkSecurityGroup(ctx, nsgName)
if err != nil {
	util.PrintAndLog(err.Error())
}
util.PrintAndLog("created network security group")

_, err = network.CreatePublicIP(ctx, ipName)
if err != nil {
	util.PrintAndLog(err.Error())
}
util.PrintAndLog("created public IP")

_, err = network.CreateNIC(ctx, virtualNetworkName, subnet1Name, nsgName, ipName, nicName)
if err != nil {
	util.PrintAndLog(err.Error())
}
util.PrintAndLog("created nic")

_, err = CreateVM(ctx, vmName, nicName, username, password, sshPublicKeyPath)
if err != nil {
	util.PrintAndLog(err.Error())
}
util.PrintAndLog("created VM")

// set or change VM metadata
_, err = UpdateVM(ctx, vmName, map[string]*string{
	"runtime": to.StringPtr("go"),
	"cloud":   to.StringPtr("azure"),
})
if err != nil {
	util.PrintAndLog(err.Error())
}
util.PrintAndLog("updated VM")

// set or change system state
_, err = StartVM(ctx, vmName)
if err != nil {
	util.PrintAndLog(err.Error())
}
util.PrintAndLog("started VM")

_, err = RestartVM(ctx, vmName)
if err != nil {
	util.PrintAndLog(err.Error())
}
util.PrintAndLog("restarted VM")

_, err = StopVM(ctx, vmName)
if err != nil {
	util.PrintAndLog(err.Error())
}
util.PrintAndLog("stopped VM")
Output:

created vnet and 2 subnets
created network security group
created public IP
created nic
created VM
updated VM
started VM
restarted VM
stopped VM

func CreateVMSS

func CreateVMSS(ctx context.Context, vmssName, vnetName, subnetName, username, password, sshPublicKeyPath string) (vmss compute.VirtualMachineScaleSet, err error)

CreateVMSS creates a new virtual machine scale set with the specified name using the specified vnet and subnet. Username, password, and sshPublicKeyPath determine logon credentials.

Example

ExampleCreateVMSS creates a group and network artifacts needed for a VMSS, then creates a VMSS and tests operations on it.

var groupName = config.GenerateGroupName("VMSS")
// TODO: remove and use local `groupName` only
config.SetGroupName(groupName)

ctx, cancel := context.WithTimeout(context.Background(), 6000*time.Second)
defer cancel()
defer resources.Cleanup(ctx)

_, err := resources.CreateGroup(ctx, groupName)
if err != nil {
	util.PrintAndLog(err.Error())
}

_, err = network.CreateVirtualNetworkAndSubnets(ctx, virtualNetworkName, subnet1Name, subnet2Name)
if err != nil {
	util.PrintAndLog(err.Error())
}
util.PrintAndLog("created vnet and 2 subnets")

_, err = CreateVMSS(ctx, vmssName, virtualNetworkName, subnet1Name, username, password, sshPublicKeyPath)
if err != nil {
	util.PrintAndLog(err.Error())
}
util.PrintAndLog("created VMSS")

//set or change VMSS metadata
_, err = UpdateVMSS(ctx, vmssName, map[string]*string{
	"runtime": to.StringPtr("go"),
	"cloud":   to.StringPtr("azure"),
})
if err != nil {
	util.PrintAndLog(err.Error())
}
util.PrintAndLog("updated VMSS")

// set or change system state
_, err = StartVMSS(ctx, vmssName)
if err != nil {
	util.PrintAndLog(err.Error())
}
util.PrintAndLog("started VMSS")

_, err = RestartVMSS(ctx, vmssName)
if err != nil {
	util.PrintAndLog(err.Error())
}
util.PrintAndLog("restarted VMSS")

_, err = StopVMSS(ctx, vmssName)
if err != nil {
	util.PrintAndLog(err.Error())
}
util.PrintAndLog("stopped VMSS")
Output:

created vnet and 2 subnets
created VMSS
updated VMSS
started VMSS
restarted VMSS
stopped VMSS

func CreateVMWithDisk

func CreateVMWithDisk(ctx context.Context, nicName, diskName, vmName, username, password string) (vm compute.VirtualMachine, err error)

CreateVMWithDisk creates a VM, attaching an already existing data disk

func CreateVMWithLoadBalancer

func CreateVMWithLoadBalancer(ctx context.Context, vmName, lbName, vnetName, subnetName, publicipName, availabilitySetName string, natRule int) (vm compute.VirtualMachine, err error)

CreateVMWithLoadBalancer creates a new VM in an availability set. It also creates and configures a load balancer and associates that with the VM's NIC.

func CreateVMWithMSI

func CreateVMWithMSI(ctx context.Context, vmName, nicName, username, password string) (vm compute.VirtualMachine, err error)

CreateVMWithMSI creates a virtual machine with a system-assigned managed identity.

Example
var groupName = config.GenerateGroupName("VMWithMSI")
// TODO: remove and use local `groupName` only
config.SetGroupName(groupName)

ctx, cancel := context.WithTimeout(context.Background(), 6000*time.Second)
defer cancel()
defer resources.Cleanup(ctx)

_, err := resources.CreateGroup(ctx, groupName)
if err != nil {
	util.PrintAndLog(err.Error())
}

_, err = network.CreateVirtualNetworkAndSubnets(ctx, virtualNetworkName, subnet1Name, subnet2Name)
if err != nil {
	util.PrintAndLog(err.Error())
}
util.PrintAndLog("created vnet and 2 subnets")

_, err = network.CreateNetworkSecurityGroup(ctx, nsgName)
if err != nil {
	util.PrintAndLog(err.Error())
}
util.PrintAndLog("created network security group")

_, err = network.CreatePublicIP(ctx, ipName)
if err != nil {
	util.PrintAndLog(err.Error())
}
util.PrintAndLog("created public IP")

_, err = network.CreateNIC(ctx, virtualNetworkName, subnet1Name, nsgName, ipName, nicName)
if err != nil {
	util.PrintAndLog(err.Error())
}
util.PrintAndLog("created nic")

_, err = CreateVMWithMSI(ctx, vmName, nicName, username, password)
if err != nil {
	util.PrintAndLog(err.Error())
}
util.PrintAndLog("created VM")

_, err = AddIdentityToVM(ctx, vmName)
if err != nil {
	util.PrintAndLog(err.Error())
}
util.PrintAndLog("added MSI extension")

vm, err := GetVM(ctx, vmName)
if err != nil {
	util.PrintAndLog(err.Error())
}
util.PrintAndLog("got VM")

list, err := authorization.ListRoleDefinitions(ctx, "roleName eq 'Contributor'")
if err != nil {
	util.PrintAndLog(err.Error())
}
util.PrintAndLog("got role definitions list")

_, err = authorization.AssignRole(ctx, *vm.Identity.PrincipalID, *list.Values()[0].ID)
if err != nil {
	util.PrintAndLog(err.Error())
}
util.PrintAndLog("role assigned")
Output:

created vnet and 2 subnets
created network security group
created public IP
created nic
created VM
added MSI extension
got VM
got role definitions list
role assigned

func CreateVMWithUserAssignedID

func CreateVMWithUserAssignedID(ctx context.Context, vmName, nicName, username, password string, id msi.Identity) (vm compute.VirtualMachine, err error)

CreateVMWithUserAssignedID creates a virtual machine with a user-assigned identity.

func DeallocateVM

func DeallocateVM(ctx context.Context, vmName string) (osr autorest.Response, err error)

DeallocateVM deallocates the selected VM

func DeallocateVMSS

func DeallocateVMSS(ctx context.Context, vmssName string) (osr compute.OperationStatusResponse, err error)

DeallocateVMSS deallocates the selected VMSS

func DeleteAKS

func DeleteAKS(ctx context.Context, resourceGroupName, resourceName string) (c containerservice.ManagedClustersDeleteFuture, err error)

DeleteAKS deletes an existing AKS cluster

func DeleteContainerGroup

func DeleteContainerGroup(ctx context.Context, resourceGroupName, containerGroupName string) (c containerinstance.ContainerGroup, err error)

DeleteContainerGroup deletes an existing container group given a resource group name and container group name

func DetachDataDisks

func DetachDataDisks(ctx context.Context, vmName string) (vm compute.VirtualMachine, err error)

DetachDataDisks detaches all data disks from the selected VM

func GetAKS

func GetAKS(ctx context.Context, resourceGroupName, resourceName string) (c containerservice.ManagedCluster, err error)

GetAKS returns an existing AKS cluster given a resource group name and resource name

func GetAvailabilitySet

func GetAvailabilitySet(ctx context.Context, asName string) (compute.AvailabilitySet, error)

GetAvailabilitySet gets info on an availability set

func GetContainerGroup

func GetContainerGroup(ctx context.Context, resourceGroupName, containerGroupName string) (c containerinstance.ContainerGroup, err error)

GetContainerGroup returns an existing container group given a resource group name and container group name

func GetVM

func GetVM(ctx context.Context, vmName string) (compute.VirtualMachine, error)

GetVM gets the specified VM info

func GetVMSS

func GetVMSS(ctx context.Context, vmssName string) (compute.VirtualMachineScaleSet, error)

GetVMSS gets the specified VMSS info

func RemoveUserAssignedIDFromVM

func RemoveUserAssignedIDFromVM(ctx context.Context, vmName string, id msi.Identity) (*compute.VirtualMachine, error)

RemoveUserAssignedIDFromVM removes the specified user-assigned identity from the specified pre-existing VM.

func RestartVM

func RestartVM(ctx context.Context, vmName string) (osr autorest.Response, err error)

RestartVM restarts the selected VM

func RestartVMSS

func RestartVMSS(ctx context.Context, vmssName string) (osr compute.OperationStatusResponse, err error)

RestartVMSS restarts the selected VMSS

func StartVM

func StartVM(ctx context.Context, vmName string) (osr autorest.Response, err error)

StartVM starts the selected VM

func StartVMSS

func StartVMSS(ctx context.Context, vmssName string) (osr compute.OperationStatusResponse, err error)

StartVMSS starts the selected VMSS

func StopVM

func StopVM(ctx context.Context, vmName string) (osr autorest.Response, err error)

StopVM stops the selected VM

func StopVMSS

func StopVMSS(ctx context.Context, vmssName string) (osr compute.OperationStatusResponse, err error)

StopVMSS stops the selected VMSS

func UpdateContainerGroup

func UpdateContainerGroup(ctx context.Context, resourceGroupName, containerGroupName string) (c containerinstance.ContainerGroup, err error)

UpdateContainerGroup updates the image of the first container of an existing container group given a resrouce group name and container group name

func UpdateOSDiskSize

func UpdateOSDiskSize(ctx context.Context, vmName string) (d disks.Disk, err error)

UpdateOSDiskSize increases the selected VM's OS disk size by 10GB.

func UpdateVM

func UpdateVM(ctx context.Context, vmName string, tags map[string]*string) (vm compute.VirtualMachine, err error)

UpdateVM modifies the VM resource by getting it, updating it locally, and putting it back to the server.

func UpdateVMSS

func UpdateVMSS(ctx context.Context, vmssName string, tags map[string]*string) (vmss compute.VirtualMachineScaleSet, err error)

UpdateVMSS modifies the VMSS resource by getting it, updating it locally, and putting it back to the server.

Types

This section is empty.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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