Make it compile again

This commit is contained in:
Paul Meyer 2018-04-06 01:12:58 -07:00
parent 69c2d551d0
commit 09ce3c9803
19 changed files with 261 additions and 243 deletions

View File

@ -1,6 +1,7 @@
package arm
import (
"context"
"encoding/json"
"fmt"
"math"
@ -9,11 +10,10 @@ import (
"os"
"strconv"
"github.com/Azure/azure-sdk-for-go/arm/compute"
"github.com/Azure/azure-sdk-for-go/arm/disk"
"github.com/Azure/azure-sdk-for-go/arm/network"
"github.com/Azure/azure-sdk-for-go/arm/resources/resources"
armStorage "github.com/Azure/azure-sdk-for-go/arm/storage"
"github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2018-04-01/compute"
"github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-01-01/network"
"github.com/Azure/azure-sdk-for-go/services/resources/mgmt/2018-02-01/resources"
armStorage "github.com/Azure/azure-sdk-for-go/services/storage/mgmt/2017-10-01/storage"
"github.com/Azure/azure-sdk-for-go/storage"
"github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/adal"
@ -39,7 +39,7 @@ type AzureClient struct {
compute.VirtualMachinesClient
common.VaultClient
armStorage.AccountsClient
disk.DisksClient
compute.DisksClient
InspectorMaxLength int
Template *CaptureTemplate
@ -141,7 +141,7 @@ func NewAzureClient(subscriptionID, resourceGroupName, storageAccountName string
azureClient.DeploymentOperationsClient.ResponseInspector = byConcatDecorators(byInspecting(maxlen), errorCapture(azureClient))
azureClient.DeploymentOperationsClient.UserAgent = fmt.Sprintf("%s %s", useragent.String(), azureClient.DeploymentOperationsClient.UserAgent)
azureClient.DisksClient = disk.NewDisksClientWithBaseURI(cloud.ResourceManagerEndpoint, subscriptionID)
azureClient.DisksClient = compute.NewDisksClientWithBaseURI(cloud.ResourceManagerEndpoint, subscriptionID)
azureClient.DisksClient.Authorizer = autorest.NewBearerAuthorizer(servicePrincipalToken)
azureClient.DisksClient.RequestInspector = withInspection(maxlen)
azureClient.DisksClient.ResponseInspector = byConcatDecorators(byInspecting(maxlen), errorCapture(azureClient))
@ -222,7 +222,7 @@ func NewAzureClient(subscriptionID, resourceGroupName, storageAccountName string
// If this is a managed disk build, this should be ignored.
if resourceGroupName != "" && storageAccountName != "" {
accountKeys, err := azureClient.AccountsClient.ListKeys(resourceGroupName, storageAccountName)
accountKeys, err := azureClient.AccountsClient.ListKeys(context.TODO(), resourceGroupName, storageAccountName)
if err != nil {
return nil, err
}

View File

@ -1,6 +1,7 @@
package arm
import (
"context"
"errors"
"fmt"
"log"
@ -11,11 +12,11 @@ import (
packerAzureCommon "github.com/hashicorp/packer/builder/azure/common"
armstorage "github.com/Azure/azure-sdk-for-go/services/storage/mgmt/2017-10-01/storage"
"github.com/Azure/azure-sdk-for-go/storage"
"github.com/Azure/go-autorest/autorest/adal"
"github.com/hashicorp/packer/builder/azure/common/constants"
"github.com/hashicorp/packer/builder/azure/common/lin"
"github.com/Azure/azure-sdk-for-go/arm/storage"
"github.com/Azure/go-autorest/autorest/adal"
packerCommon "github.com/hashicorp/packer/common"
"github.com/hashicorp/packer/helper/communicator"
"github.com/hashicorp/packer/helper/multistep"
@ -29,9 +30,8 @@ type Builder struct {
}
const (
DefaultSasBlobContainer = "system/Microsoft.Compute"
DefaultSasBlobPermission = "r"
DefaultSecretName = "packerKeyVaultSecret"
DefaultSasBlobContainer = "system/Microsoft.Compute"
DefaultSecretName = "packerKeyVaultSecret"
)
func (b *Builder) Prepare(raws ...interface{}) ([]string, error) {
@ -87,7 +87,7 @@ func (b *Builder) Run(ui packer.Ui, hook packer.Hook, cache packer.Cache) (packe
}
if b.config.isManagedImage() {
group, err := azureClient.GroupsClient.Get(b.config.ManagedImageResourceGroupName)
group, err := azureClient.GroupsClient.Get(context.TODO(), b.config.ManagedImageResourceGroupName)
if err != nil {
return nil, fmt.Errorf("Cannot locate the managed image resource group %s.", b.config.ManagedImageResourceGroupName)
}
@ -95,12 +95,14 @@ func (b *Builder) Run(ui packer.Ui, hook packer.Hook, cache packer.Cache) (packe
b.config.manageImageLocation = *group.Location
// If a managed image already exists it cannot be overwritten.
_, err = azureClient.ImagesClient.Get(b.config.ManagedImageResourceGroupName, b.config.ManagedImageName, "")
_, err = azureClient.ImagesClient.Get(context.TODO(), b.config.ManagedImageResourceGroupName, b.config.ManagedImageName, "")
if err == nil {
if b.config.PackerForce {
_, errChan := azureClient.ImagesClient.Delete(b.config.ManagedImageResourceGroupName, b.config.ManagedImageName, nil)
ui.Say(fmt.Sprintf("the managed image named %s already exists, but deleting it due to -force flag", b.config.ManagedImageName))
err = <-errChan
f, err := azureClient.ImagesClient.Delete(context.TODO(), b.config.ManagedImageResourceGroupName, b.config.ManagedImageName)
if err == nil {
err = f.WaitForCompletion(context.TODO(), azureClient.ImagesClient.Client)
}
if err != nil {
return nil, fmt.Errorf("failed to delete the managed image named %s : %s", b.config.ManagedImageName, azureClient.LastError.Error())
}
@ -111,7 +113,7 @@ func (b *Builder) Run(ui packer.Ui, hook packer.Hook, cache packer.Cache) (packe
}
if b.config.BuildResourceGroupName != "" {
group, err := azureClient.GroupsClient.Get(b.config.BuildResourceGroupName)
group, err := azureClient.GroupsClient.Get(context.TODO(), b.config.BuildResourceGroupName)
if err != nil {
return nil, fmt.Errorf("Cannot locate the existing build resource resource group %s.", b.config.BuildResourceGroupName)
}
@ -240,9 +242,11 @@ func (b *Builder) Run(ui packer.Ui, hook packer.Hook, cache packer.Cache) (packe
return NewArtifact(
template.(*CaptureTemplate),
func(name string) string {
month := time.Now().AddDate(0, 1, 0).UTC()
blob := azureClient.BlobStorageClient.GetContainerReference(DefaultSasBlobContainer).GetBlobReference(name)
sasUrl, _ := blob.GetSASURI(month, DefaultSasBlobPermission)
options := storage.BlobSASOptions{}
options.BlobServiceSASPermissions.Read = true
options.Expiry = time.Now().AddDate(0, 1, 0).UTC() // one month
sasUrl, _ := blob.GetSASURI(options)
return sasUrl
})
}
@ -294,8 +298,8 @@ func canonicalizeLocation(location string) string {
return strings.Replace(location, " ", "", -1)
}
func (b *Builder) getBlobAccount(client *AzureClient, resourceGroupName string, storageAccountName string) (*storage.Account, error) {
account, err := client.AccountsClient.GetProperties(resourceGroupName, storageAccountName)
func (b *Builder) getBlobAccount(client *AzureClient, resourceGroupName string, storageAccountName string) (*armstorage.Account, error) {
account, err := client.AccountsClient.GetProperties(context.TODO(), resourceGroupName, storageAccountName)
if err != nil {
return nil, err
}

View File

@ -14,7 +14,7 @@ import (
"strings"
"time"
"github.com/Azure/azure-sdk-for-go/arm/compute"
"github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2018-04-01/compute"
"github.com/Azure/go-autorest/autorest/azure"
"github.com/Azure/go-autorest/autorest/to"
"github.com/masterzen/winrm"
@ -189,7 +189,7 @@ func (c *Config) toImageParameters() *compute.Image {
},
},
Location: to.StringPtr(c.Location),
Tags: &c.AzureTags,
Tags: c.AzureTags,
}
}
@ -450,7 +450,7 @@ func provideDefaultValues(c *Config) {
}
if c.ManagedImageStorageAccountType == "" {
c.managedImageStorageAccountType = compute.StandardLRS
c.managedImageStorageAccountType = compute.StorageAccountTypesStandardLRS
}
if c.ImagePublisher != "" && c.ImageVersion == "" {
@ -697,10 +697,10 @@ func assertRequiredParametersSet(c *Config, errs *packer.MultiError) {
}
switch c.ManagedImageStorageAccountType {
case "", string(compute.StandardLRS):
c.managedImageStorageAccountType = compute.StandardLRS
case string(compute.PremiumLRS):
c.managedImageStorageAccountType = compute.PremiumLRS
case "", string(compute.StorageAccountTypesStandardLRS):
c.managedImageStorageAccountType = compute.StorageAccountTypesStandardLRS
case string(compute.StorageAccountTypesPremiumLRS):
c.managedImageStorageAccountType = compute.StorageAccountTypesPremiumLRS
default:
errs = packer.MultiErrorAppend(errs, fmt.Errorf("The managed_image_storage_account_type %q is invalid", c.ManagedImageStorageAccountType))
}

View File

@ -9,10 +9,11 @@ package arm
// used to determine values without use of a client.
import (
"context"
"fmt"
"strings"
"github.com/Azure/azure-sdk-for-go/arm/compute"
"github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2018-04-01/compute"
)
type resourceResolver struct {
@ -72,33 +73,40 @@ func getResourceGroupNameFromId(id string) string {
}
func findManagedImageByName(client *AzureClient, name, resourceGroupName string) (*compute.Image, error) {
images, err := client.ImagesClient.ListByResourceGroup(resourceGroupName)
images, err := client.ImagesClient.ListByResourceGroupComplete(context.TODO(), resourceGroupName)
if err != nil {
return nil, err
}
for _, image := range *images.Value {
for images.NotDone() {
image := images.Value()
if strings.EqualFold(name, *image.Name) {
return &image, nil
}
if err = images.Next(); err != nil {
return nil, err
}
}
return nil, fmt.Errorf("Cannot find an image named '%s' in the resource group '%s'", name, resourceGroupName)
}
func findVirtualNetworkResourceGroup(client *AzureClient, name string) (string, error) {
virtualNetworks, err := client.VirtualNetworksClient.ListAll()
virtualNetworks, err := client.VirtualNetworksClient.ListAllComplete(context.TODO())
if err != nil {
return "", err
}
resourceGroupNames := make([]string, 0)
for _, virtualNetwork := range *virtualNetworks.Value {
for virtualNetworks.NotDone() {
virtualNetwork := virtualNetworks.Value()
if strings.EqualFold(name, *virtualNetwork.Name) {
rgn := getResourceGroupNameFromId(*virtualNetwork.ID)
resourceGroupNames = append(resourceGroupNames, rgn)
}
if err = virtualNetworks.Next(); err != nil {
return "", err
}
}
if len(resourceGroupNames) == 0 {
@ -113,19 +121,21 @@ func findVirtualNetworkResourceGroup(client *AzureClient, name string) (string,
}
func findVirtualNetworkSubnet(client *AzureClient, resourceGroupName string, name string) (string, error) {
subnets, err := client.SubnetsClient.List(resourceGroupName, name)
subnets, err := client.SubnetsClient.List(context.TODO(), resourceGroupName, name)
if err != nil {
return "", err
}
if len(*subnets.Value) == 0 {
subnetList := subnets.Values() // only first page of subnets, but only interested in ==0 or >1
if len(subnetList) == 0 {
return "", fmt.Errorf("Cannot find a subnet in the resource group %q associated with the virtual network called %q", resourceGroupName, name)
}
if len(*subnets.Value) > 1 {
return "", fmt.Errorf("Found multiple subnets in the resource group %q associated with the virtual network called %q, please use virtual_network_subnet_name and virtual_network_resource_group_name to disambiguate", resourceGroupName, name)
if len(subnetList) > 1 {
return "", fmt.Errorf("Found multiple subnets in the resource group %q associated with the virtual network called %q, please use virtual_network_subnet_name and virtual_network_resource_group_name to disambiguate", resourceGroupName, name)
}
subnet := (*subnets.Value)[0]
subnet := subnetList[0]
return *subnet.Name, nil
}

View File

@ -4,8 +4,7 @@ import (
"context"
"fmt"
"github.com/Azure/azure-sdk-for-go/arm/compute"
"github.com/hashicorp/packer/builder/azure/common"
"github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2018-04-01/compute"
"github.com/hashicorp/packer/builder/azure/common/constants"
"github.com/hashicorp/packer/helper/multistep"
"github.com/hashicorp/packer/packer"
@ -14,8 +13,8 @@ import (
type StepCaptureImage struct {
client *AzureClient
generalizeVM func(resourceGroupName, computeName string) error
captureVhd func(resourceGroupName string, computeName string, parameters *compute.VirtualMachineCaptureParameters, cancelCh <-chan struct{}) error
captureManagedImage func(resourceGroupName string, computeName string, parameters *compute.Image, cancelCh <-chan struct{}) error
captureVhd func(ctx context.Context, resourceGroupName string, computeName string, parameters *compute.VirtualMachineCaptureParameters) error
captureManagedImage func(ctx context.Context, resourceGroupName string, computeName string, parameters *compute.Image) error
get func(client *AzureClient) *CaptureTemplate
say func(message string)
error func(e error)
@ -43,32 +42,30 @@ func NewStepCaptureImage(client *AzureClient, ui packer.Ui) *StepCaptureImage {
}
func (s *StepCaptureImage) generalize(resourceGroupName string, computeName string) error {
_, err := s.client.Generalize(resourceGroupName, computeName)
_, err := s.client.Generalize(context.TODO(), resourceGroupName, computeName)
if err != nil {
s.say(s.client.LastError.Error())
}
return err
}
func (s *StepCaptureImage) captureImageFromVM(resourceGroupName string, imageName string, image *compute.Image, cancelCh <-chan struct{}) error {
_, errChan := s.client.ImagesClient.CreateOrUpdate(resourceGroupName, imageName, *image, cancelCh)
err := <-errChan
func (s *StepCaptureImage) captureImageFromVM(ctx context.Context, resourceGroupName string, imageName string, image *compute.Image) error {
f, err := s.client.ImagesClient.CreateOrUpdate(ctx, resourceGroupName, imageName, *image)
if err != nil {
s.say(s.client.LastError.Error())
}
return <-errChan
return f.WaitForCompletion(ctx, s.client.ImagesClient.Client)
}
func (s *StepCaptureImage) captureImage(resourceGroupName string, computeName string, parameters *compute.VirtualMachineCaptureParameters, cancelCh <-chan struct{}) error {
_, errChan := s.client.Capture(resourceGroupName, computeName, *parameters, cancelCh)
err := <-errChan
func (s *StepCaptureImage) captureImage(ctx context.Context, resourceGroupName string, computeName string, parameters *compute.VirtualMachineCaptureParameters) error {
f, err := s.client.VirtualMachinesClient.Capture(ctx, resourceGroupName, computeName, *parameters)
if err != nil {
s.say(s.client.LastError.Error())
}
return <-errChan
return f.WaitForCompletion(ctx, s.client.VirtualMachinesClient.Client)
}
func (s *StepCaptureImage) Run(_ context.Context, state multistep.StateBag) multistep.StepAction {
func (s *StepCaptureImage) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction {
s.say("Capturing image ...")
var computeName = state.Get(constants.ArmComputeName).(string)
@ -86,25 +83,24 @@ func (s *StepCaptureImage) Run(_ context.Context, state multistep.StateBag) mult
s.say(fmt.Sprintf(" -> Compute Name : '%s'", computeName))
s.say(fmt.Sprintf(" -> Compute Location : '%s'", location))
result := common.StartInterruptibleTask(
func() bool {
return common.IsStateCancelled(state)
},
func(cancelCh <-chan struct{}) error {
err := s.generalizeVM(resourceGroupName, computeName)
if err != nil {
return err
}
err := s.generalizeVM(resourceGroupName, computeName)
if isManagedImage {
s.say(fmt.Sprintf(" -> Image ResourceGroupName : '%s'", targetManagedImageResourceGroupName))
s.say(fmt.Sprintf(" -> Image Name : '%s'", targetManagedImageName))
s.say(fmt.Sprintf(" -> Image Location : '%s'", targetManagedImageLocation))
return s.captureManagedImage(targetManagedImageResourceGroupName, targetManagedImageName, imageParameters, cancelCh)
} else {
return s.captureVhd(resourceGroupName, computeName, vmCaptureParameters, cancelCh)
}
})
if err == nil {
if isManagedImage {
s.say(fmt.Sprintf(" -> Image ResourceGroupName : '%s'", targetManagedImageResourceGroupName))
s.say(fmt.Sprintf(" -> Image Name : '%s'", targetManagedImageName))
s.say(fmt.Sprintf(" -> Image Location : '%s'", targetManagedImageLocation))
err = s.captureManagedImage(ctx, targetManagedImageResourceGroupName, targetManagedImageName, imageParameters)
} else {
err = s.captureVhd(ctx, resourceGroupName, computeName, vmCaptureParameters)
}
}
if err != nil {
state.Put(constants.Error, err)
s.error(err)
return multistep.ActionHalt
}
// HACK(chrboum): I do not like this. The capture method should be returning this value
// instead having to pass in another lambda. I'm in this pickle because I am using
@ -114,10 +110,12 @@ func (s *StepCaptureImage) Run(_ context.Context, state multistep.StateBag) mult
// Having to resort to capturing the template via an inspector is hack, and once I can
// resolve that I can cleanup this code too. See the comments in azure_client.go for more
// details.
// [paulmey]: autorest.Future now has access to the last http.Response, but I'm not sure if
// the body is still accessible.
template := s.get(s.client)
state.Put(constants.ArmCaptureTemplate, template)
return processInterruptibleResult(result, s.error, state)
return multistep.ActionContinue
}
func (*StepCaptureImage) Cleanup(multistep.StateBag) {

View File

@ -5,7 +5,7 @@ import (
"errors"
"fmt"
"github.com/Azure/azure-sdk-for-go/arm/resources/resources"
"github.com/Azure/azure-sdk-for-go/services/resources/mgmt/2018-02-01/resources"
"github.com/hashicorp/packer/builder/azure/common/constants"
"github.com/hashicorp/packer/helper/multistep"
"github.com/hashicorp/packer/packer"
@ -13,10 +13,10 @@ import (
type StepCreateResourceGroup struct {
client *AzureClient
create func(resourceGroupName string, location string, tags *map[string]*string) error
create func(ctx context.Context, resourceGroupName string, location string, tags map[string]*string) error
say func(message string)
error func(e error)
exists func(resourceGroupName string) (bool, error)
exists func(ctx context.Context, resourceGroupName string) (bool, error)
}
func NewStepCreateResourceGroup(client *AzureClient, ui packer.Ui) *StepCreateResourceGroup {
@ -31,8 +31,8 @@ func NewStepCreateResourceGroup(client *AzureClient, ui packer.Ui) *StepCreateRe
return step
}
func (s *StepCreateResourceGroup) createResourceGroup(resourceGroupName string, location string, tags *map[string]*string) error {
_, err := s.client.GroupsClient.CreateOrUpdate(resourceGroupName, resources.Group{
func (s *StepCreateResourceGroup) createResourceGroup(ctx context.Context, resourceGroupName string, location string, tags map[string]*string) error {
_, err := s.client.GroupsClient.CreateOrUpdate(ctx, resourceGroupName, resources.Group{
Location: &location,
Tags: tags,
})
@ -43,8 +43,8 @@ func (s *StepCreateResourceGroup) createResourceGroup(resourceGroupName string,
return err
}
func (s *StepCreateResourceGroup) doesResourceGroupExist(resourceGroupName string) (bool, error) {
exists, err := s.client.GroupsClient.CheckExistence(resourceGroupName)
func (s *StepCreateResourceGroup) doesResourceGroupExist(ctx context.Context, resourceGroupName string) (bool, error) {
exists, err := s.client.GroupsClient.CheckExistence(ctx, resourceGroupName)
if err != nil {
s.say(s.client.LastError.Error())
}
@ -52,7 +52,7 @@ func (s *StepCreateResourceGroup) doesResourceGroupExist(resourceGroupName strin
return exists.Response.StatusCode != 404, err
}
func (s *StepCreateResourceGroup) Run(_ context.Context, state multistep.StateBag) multistep.StepAction {
func (s *StepCreateResourceGroup) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction {
var doubleResource, ok = state.GetOk(constants.ArmDoubleResourceGroupNameSet)
if ok && doubleResource.(bool) {
err := errors.New("You have filled in both temp_resource_group_name and build_resource_group_name. Please choose one.")
@ -61,9 +61,9 @@ func (s *StepCreateResourceGroup) Run(_ context.Context, state multistep.StateBa
var resourceGroupName = state.Get(constants.ArmResourceGroupName).(string)
var location = state.Get(constants.ArmLocation).(string)
var tags = state.Get(constants.ArmTags).(*map[string]*string)
var tags = *state.Get(constants.ArmTags).(*map[string]*string)
exists, err := s.exists(resourceGroupName)
exists, err := s.exists(ctx, resourceGroupName)
if err != nil {
return processStepResult(err, s.error, state)
}
@ -84,10 +84,10 @@ func (s *StepCreateResourceGroup) Run(_ context.Context, state multistep.StateBa
s.say(fmt.Sprintf(" -> ResourceGroupName : '%s'", resourceGroupName))
s.say(fmt.Sprintf(" -> Location : '%s'", location))
s.say(fmt.Sprintf(" -> Tags :"))
for k, v := range *tags {
for k, v := range tags {
s.say(fmt.Sprintf(" ->> %s : %s", k, *v))
}
err = s.create(resourceGroupName, location, tags)
err = s.create(ctx, resourceGroupName, location, tags)
if err == nil {
state.Put(constants.ArmIsResourceGroupCreated, true)
}
@ -115,9 +115,11 @@ func (s *StepCreateResourceGroup) Cleanup(state multistep.StateBag) {
ui.Say("\nCleanup requested, deleting resource group ...")
var resourceGroupName = state.Get(constants.ArmResourceGroupName).(string)
_, errChan := s.client.GroupsClient.Delete(resourceGroupName, nil)
err := <-errChan
ctx := context.TODO()
f, err := s.client.GroupsClient.Delete(ctx, resourceGroupName)
if err == nil {
err = f.WaitForCompletion(ctx, s.client.GroupsClient.Client)
}
if err != nil {
ui.Error(fmt.Sprintf("Error deleting resource group. Please delete it manually.\n\n"+
"Name: %s\n"+

View File

@ -16,7 +16,7 @@ import (
type StepDeleteAdditionalDisk struct {
client *AzureClient
delete func(string, string) error
deleteManaged func(string, string) error
deleteManaged func(context.Context, string, string) error
say func(message string)
error func(e error)
}
@ -43,15 +43,18 @@ func (s *StepDeleteAdditionalDisk) deleteBlob(storageContainerName string, blobN
return err
}
func (s *StepDeleteAdditionalDisk) deleteManagedDisk(resourceGroupName string, imageName string) error {
func (s *StepDeleteAdditionalDisk) deleteManagedDisk(ctx context.Context, resourceGroupName string, imageName string) error {
xs := strings.Split(imageName, "/")
// TODO(paulmey): verify if this is right, imagename is passed in, *disk* is deleted... is this a copy/paste error?
diskName := xs[len(xs)-1]
_, errChan := s.client.DisksClient.Delete(resourceGroupName, diskName, nil)
err := <-errChan
f, err := s.client.DisksClient.Delete(ctx, resourceGroupName, diskName)
if err == nil {
err = f.WaitForCompletion(ctx, s.client.DisksClient.Client)
}
return err
}
func (s *StepDeleteAdditionalDisk) Run(_ context.Context, state multistep.StateBag) multistep.StepAction {
func (s *StepDeleteAdditionalDisk) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction {
s.say("Deleting the temporary Additional disk ...")
var dataDisks = state.Get(constants.ArmAdditionalDiskVhds).([]string)
@ -73,7 +76,7 @@ func (s *StepDeleteAdditionalDisk) Run(_ context.Context, state multistep.StateB
s.say(fmt.Sprintf(" -> Additional Disk %d: '%s'", i+1, additionaldisk))
var err error
if isManagedDisk {
err = s.deleteManaged(resourceGroupName, additionaldisk)
err = s.deleteManaged(ctx, resourceGroupName, additionaldisk)
if err != nil {
s.say("Failed to delete the managed Additional Disk!")
return processStepResult(err, s.error, state)

View File

@ -16,7 +16,7 @@ import (
type StepDeleteOSDisk struct {
client *AzureClient
delete func(string, string) error
deleteManaged func(string, string) error
deleteManaged func(context.Context, string, string) error
say func(message string)
error func(e error)
}
@ -43,15 +43,17 @@ func (s *StepDeleteOSDisk) deleteBlob(storageContainerName string, blobName stri
return err
}
func (s *StepDeleteOSDisk) deleteManagedDisk(resourceGroupName string, imageName string) error {
func (s *StepDeleteOSDisk) deleteManagedDisk(ctx context.Context, resourceGroupName string, imageName string) error {
xs := strings.Split(imageName, "/")
diskName := xs[len(xs)-1]
_, errChan := s.client.DisksClient.Delete(resourceGroupName, diskName, nil)
err := <-errChan
f, err := s.client.DisksClient.Delete(ctx, resourceGroupName, diskName)
if err == nil {
err = f.WaitForCompletion(ctx, s.client.DisksClient.Client)
}
return err
}
func (s *StepDeleteOSDisk) Run(_ context.Context, state multistep.StateBag) multistep.StepAction {
func (s *StepDeleteOSDisk) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction {
s.say("Deleting the temporary OS disk ...")
var osDisk = state.Get(constants.ArmOSDiskVhd).(string)
@ -68,7 +70,7 @@ func (s *StepDeleteOSDisk) Run(_ context.Context, state multistep.StateBag) mult
var err error
if isManagedDisk {
err = s.deleteManaged(resourceGroupName, osDisk)
err = s.deleteManaged(ctx, resourceGroupName, osDisk)
if err != nil {
s.say("Failed to delete the managed OS Disk!")
return processStepResult(err, s.error, state)

View File

@ -4,8 +4,6 @@ import (
"context"
"fmt"
"github.com/Azure/go-autorest/autorest"
"github.com/hashicorp/packer/builder/azure/common"
"github.com/hashicorp/packer/builder/azure/common/constants"
"github.com/hashicorp/packer/helper/multistep"
"github.com/hashicorp/packer/packer"
@ -17,7 +15,7 @@ const (
type StepDeleteResourceGroup struct {
client *AzureClient
delete func(state multistep.StateBag, resourceGroupName string, cancelCh <-chan struct{}) error
delete func(ctx context.Context, state multistep.StateBag, resourceGroupName string) error
say func(message string)
error func(e error)
}
@ -33,18 +31,18 @@ func NewStepDeleteResourceGroup(client *AzureClient, ui packer.Ui) *StepDeleteRe
return step
}
func (s *StepDeleteResourceGroup) deleteResourceGroup(state multistep.StateBag, resourceGroupName string, cancelCh <-chan struct{}) error {
func (s *StepDeleteResourceGroup) deleteResourceGroup(ctx context.Context, state multistep.StateBag, resourceGroupName string) error {
var err error
if state.Get(constants.ArmIsExistingResourceGroup).(bool) {
s.say("\nThe resource group was not created by Packer, only deleting individual resources ...")
var deploymentName = state.Get(constants.ArmDeploymentName).(string)
err = s.deleteDeploymentResources(deploymentName, resourceGroupName)
err = s.deleteDeploymentResources(ctx, deploymentName, resourceGroupName)
if err != nil {
return err
}
if keyVaultDeploymentName, ok := state.GetOk(constants.ArmKeyVaultDeploymentName); ok {
err = s.deleteDeploymentResources(keyVaultDeploymentName.(string), resourceGroupName)
err = s.deleteDeploymentResources(ctx, keyVaultDeploymentName.(string), resourceGroupName)
if err != nil {
return err
}
@ -53,8 +51,10 @@ func (s *StepDeleteResourceGroup) deleteResourceGroup(state multistep.StateBag,
return nil
} else {
s.say("\nThe resource group was created by Packer, deleting ...")
_, errChan := s.client.GroupsClient.Delete(resourceGroupName, cancelCh)
err = <-errChan
f, err := s.client.GroupsClient.Delete(ctx, resourceGroupName)
if err == nil {
f.WaitForCompletion(ctx, s.client.GroupsClient.Client)
}
if err != nil {
s.say(s.client.LastError.Error())
@ -63,46 +63,36 @@ func (s *StepDeleteResourceGroup) deleteResourceGroup(state multistep.StateBag,
}
}
func (s *StepDeleteResourceGroup) deleteDeploymentResources(deploymentName, resourceGroupName string) error {
func (s *StepDeleteResourceGroup) deleteDeploymentResources(ctx context.Context, deploymentName, resourceGroupName string) error {
maxResources := int32(maxResourcesToDelete)
deploymentOperations, err := s.client.DeploymentOperationsClient.List(resourceGroupName, deploymentName, &maxResources)
deploymentOperations, err := s.client.DeploymentOperationsClient.ListComplete(ctx, resourceGroupName, deploymentName, &maxResources)
if err != nil {
s.reportIfError(err, resourceGroupName)
return err
}
for _, deploymentOperation := range *deploymentOperations.Value {
for deploymentOperations.NotDone() {
deploymentOperation := deploymentOperations.Value()
// Sometimes an empty operation is added to the list by Azure
if deploymentOperation.Properties.TargetResource == nil {
continue
}
s.say(fmt.Sprintf(" -> %s : '%s'",
*deploymentOperation.Properties.TargetResource.ResourceType,
*deploymentOperation.Properties.TargetResource.ResourceName))
var networkDeleteFunction func(string, string, <-chan struct{}) (<-chan autorest.Response, <-chan error)
resourceName := *deploymentOperation.Properties.TargetResource.ResourceName
resourceType := *deploymentOperation.Properties.TargetResource.ResourceType
switch *deploymentOperation.Properties.TargetResource.ResourceType {
case "Microsoft.Compute/virtualMachines":
_, errChan := s.client.VirtualMachinesClient.Delete(resourceGroupName, resourceName, nil)
err := <-errChan
s.reportIfError(err, resourceName)
case "Microsoft.KeyVault/vaults":
_, err := s.client.VaultClientDelete.Delete(resourceGroupName, resourceName)
s.reportIfError(err, resourceName)
case "Microsoft.Network/networkInterfaces":
networkDeleteFunction = s.client.InterfacesClient.Delete
case "Microsoft.Network/virtualNetworks":
networkDeleteFunction = s.client.VirtualNetworksClient.Delete
case "Microsoft.Network/publicIPAddresses":
networkDeleteFunction = s.client.PublicIPAddressesClient.Delete
}
if networkDeleteFunction != nil {
_, errChan := networkDeleteFunction(resourceGroupName, resourceName, nil)
err := <-errChan
s.reportIfError(err, resourceName)
s.say(fmt.Sprintf(" -> %s : '%s'",
resourceType,
resourceName))
err := deleteResource(ctx, s.client,
resourceType,
resourceName,
resourceGroupName)
s.reportIfError(err, resourceName)
if err = deploymentOperations.Next(); err != nil {
return err
}
}
@ -118,19 +108,23 @@ func (s *StepDeleteResourceGroup) reportIfError(err error, resourceName string)
}
}
func (s *StepDeleteResourceGroup) Run(_ context.Context, state multistep.StateBag) multistep.StepAction {
func (s *StepDeleteResourceGroup) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction {
s.say("Deleting resource group ...")
var resourceGroupName = state.Get(constants.ArmResourceGroupName).(string)
s.say(fmt.Sprintf(" -> ResourceGroupName : '%s'", resourceGroupName))
result := common.StartInterruptibleTask(
func() bool { return common.IsStateCancelled(state) },
func(cancelCh <-chan struct{}) error { return s.delete(state, resourceGroupName, cancelCh) })
stepAction := processInterruptibleResult(result, s.error, state)
err := s.delete(ctx, state, resourceGroupName)
if err != nil {
state.Put(constants.Error, err)
s.error(err)
return multistep.ActionHalt
}
state.Put(constants.ArmIsResourceGroupCreated, false)
return stepAction
return multistep.ActionContinue
}
func (*StepDeleteResourceGroup) Cleanup(multistep.StateBag) {

View File

@ -7,8 +7,6 @@ import (
"net/url"
"strings"
"github.com/Azure/go-autorest/autorest"
"github.com/hashicorp/packer/builder/azure/common"
"github.com/hashicorp/packer/builder/azure/common/constants"
"github.com/hashicorp/packer/helper/multistep"
"github.com/hashicorp/packer/packer"
@ -16,10 +14,10 @@ import (
type StepDeployTemplate struct {
client *AzureClient
deploy func(resourceGroupName string, deploymentName string, cancelCh <-chan struct{}) error
delete func(resourceType string, resourceName string, resourceGroupName string) error
disk func(resourceGroupName string, computeName string) (string, string, error)
deleteDisk func(imageType string, imageName string, resourceGroupName string) error
deploy func(ctx context.Context, resourceGroupName string, deploymentName string) error
delete func(ctx context.Context, client *AzureClient, resourceType string, resourceName string, resourceGroupName string) error
disk func(ctx context.Context, resourceGroupName string, computeName string) (string, string, error)
deleteDisk func(ctx context.Context, imageType string, imageName string, resourceGroupName string) error
say func(message string)
error func(e error)
config *Config
@ -38,28 +36,29 @@ func NewStepDeployTemplate(client *AzureClient, ui packer.Ui, config *Config, de
}
step.deploy = step.deployTemplate
step.delete = step.deleteOperationResource
step.delete = deleteResource
step.disk = step.getImageDetails
step.deleteDisk = step.deleteImage
return step
}
func (s *StepDeployTemplate) deployTemplate(resourceGroupName string, deploymentName string, cancelCh <-chan struct{}) error {
func (s *StepDeployTemplate) deployTemplate(ctx context.Context, resourceGroupName string, deploymentName string) error {
deployment, err := s.factory(s.config)
if err != nil {
return err
}
_, errChan := s.client.DeploymentsClient.CreateOrUpdate(resourceGroupName, deploymentName, *deployment, cancelCh)
err = <-errChan
f, err := s.client.DeploymentsClient.CreateOrUpdate(ctx, resourceGroupName, deploymentName, *deployment)
if err == nil {
err = f.WaitForCompletion(ctx, s.client.DeploymentsClient.Client)
}
if err != nil {
s.say(s.client.LastError.Error())
}
return err
}
func (s *StepDeployTemplate) Run(_ context.Context, state multistep.StateBag) multistep.StepAction {
func (s *StepDeployTemplate) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction {
s.say("Deploying deployment template ...")
var resourceGroupName = state.Get(constants.ArmResourceGroupName).(string)
@ -67,21 +66,16 @@ func (s *StepDeployTemplate) Run(_ context.Context, state multistep.StateBag) mu
s.say(fmt.Sprintf(" -> ResourceGroupName : '%s'", resourceGroupName))
s.say(fmt.Sprintf(" -> DeploymentName : '%s'", s.name))
result := common.StartInterruptibleTask(
func() bool { return common.IsStateCancelled(state) },
func(cancelCh <-chan struct{}) error {
return s.deploy(resourceGroupName, s.name, cancelCh)
},
)
return processInterruptibleResult(result, s.error, state)
return processStepResult(
s.deploy(ctx, resourceGroupName, s.name),
s.error, state)
}
func (s *StepDeployTemplate) getImageDetails(resourceGroupName string, computeName string) (string, string, error) {
func (s *StepDeployTemplate) getImageDetails(ctx context.Context, resourceGroupName string, computeName string) (string, string, error) {
//We can't depend on constants.ArmOSDiskVhd being set
var imageName string
var imageType string
vm, err := s.client.VirtualMachinesClient.Get(resourceGroupName, computeName, "")
vm, err := s.client.VirtualMachinesClient.Get(ctx, resourceGroupName, computeName, "")
if err != nil {
return imageName, imageType, err
} else {
@ -96,44 +90,50 @@ func (s *StepDeployTemplate) getImageDetails(resourceGroupName string, computeNa
return imageType, imageName, nil
}
func (s *StepDeployTemplate) deleteOperationResource(resourceType string, resourceName string, resourceGroupName string) error {
var networkDeleteFunction func(string, string, <-chan struct{}) (<-chan autorest.Response, <-chan error)
//TODO(paulmey): move to helpers file
func deleteResource(ctx context.Context, client *AzureClient, resourceType string, resourceName string, resourceGroupName string) error {
switch resourceType {
case "Microsoft.Compute/virtualMachines":
_, errChan := s.client.VirtualMachinesClient.Delete(resourceGroupName,
resourceName, nil)
err := <-errChan
if err != nil {
return err
f, err := client.VirtualMachinesClient.Delete(ctx, resourceGroupName, resourceName)
if err == nil {
err = f.WaitForCompletion(ctx, client.VirtualMachinesClient.Client)
}
return err
case "Microsoft.KeyVault/vaults":
_, err := s.client.VaultClientDelete.Delete(resourceGroupName, resourceName)
// TODO(paulmey): not sure why VaultClient doesn't do cancellation
_, err := client.VaultClientDelete.Delete(resourceGroupName, resourceName)
return err
case "Microsoft.Network/networkInterfaces":
networkDeleteFunction = s.client.InterfacesClient.Delete
case "Microsoft.Network/virtualNetworks":
networkDeleteFunction = s.client.VirtualNetworksClient.Delete
case "Microsoft.Network/publicIPAddresses":
networkDeleteFunction = s.client.PublicIPAddressesClient.Delete
}
if networkDeleteFunction != nil {
_, errChan := networkDeleteFunction(resourceGroupName, resourceName, nil)
err := <-errChan
if err != nil {
return err
f, err := client.InterfacesClient.Delete(ctx, resourceGroupName, resourceName)
if err == nil {
err = f.WaitForCompletion(ctx, client.InterfacesClient.Client)
}
return err
case "Microsoft.Network/virtualNetworks":
f, err := client.VirtualNetworksClient.Delete(ctx, resourceGroupName, resourceName)
if err == nil {
err = f.WaitForCompletion(ctx, client.VirtualNetworksClient.Client)
}
return err
case "Microsoft.Network/publicIPAddresses":
f, err := client.PublicIPAddressesClient.Delete(ctx, resourceGroupName, resourceName)
if err == nil {
err = f.WaitForCompletion(ctx, client.PublicIPAddressesClient.Client)
}
return err
}
return nil
}
func (s *StepDeployTemplate) deleteImage(imageType string, imageName string, resourceGroupName string) error {
func (s *StepDeployTemplate) deleteImage(ctx context.Context, imageType string, imageName string, resourceGroupName string) error {
// Managed disk
if imageType == "Microsoft.Compute/disks" {
xs := strings.Split(imageName, "/")
diskName := xs[len(xs)-1]
_, errChan := s.client.DisksClient.Delete(resourceGroupName, diskName, nil)
err := <-errChan
f, err := s.client.DisksClient.Delete(ctx, resourceGroupName, diskName)
if err == nil {
err = f.WaitForCompletion(ctx, s.client.DisksClient.Client)
}
return err
}
// VHD image
@ -167,7 +167,7 @@ func (s *StepDeployTemplate) Cleanup(state multistep.StateBag) {
var resourceGroupName = state.Get(constants.ArmResourceGroupName).(string)
var computeName = state.Get(constants.ArmComputeName).(string)
var deploymentName = s.name
imageType, imageName, err := s.disk(resourceGroupName, computeName)
imageType, imageName, err := s.disk(context.TODO(), resourceGroupName, computeName)
if err != nil {
ui.Error("Could not retrieve OS Image details")
}
@ -175,13 +175,14 @@ func (s *StepDeployTemplate) Cleanup(state multistep.StateBag) {
ui.Say(" -> Deployment: " + deploymentName)
if deploymentName != "" {
maxResources := int32(50)
deploymentOperations, err := s.client.DeploymentOperationsClient.List(resourceGroupName, deploymentName, &maxResources)
deploymentOperations, err := s.client.DeploymentOperationsClient.ListComplete(context.TODO(), resourceGroupName, deploymentName, &maxResources)
if err != nil {
ui.Error(fmt.Sprintf("Error deleting resources. Please delete them manually.\n\n"+
"Name: %s\n"+
"Error: %s", resourceGroupName, err))
}
for _, deploymentOperation := range *deploymentOperations.Value {
for deploymentOperations.NotDone() {
deploymentOperation := deploymentOperations.Value()
// Sometimes an empty operation is added to the list by Azure
if deploymentOperation.Properties.TargetResource == nil {
continue
@ -189,7 +190,8 @@ func (s *StepDeployTemplate) Cleanup(state multistep.StateBag) {
ui.Say(fmt.Sprintf(" -> %s : '%s'",
*deploymentOperation.Properties.TargetResource.ResourceType,
*deploymentOperation.Properties.TargetResource.ResourceName))
err = s.delete(*deploymentOperation.Properties.TargetResource.ResourceType,
err = s.delete(context.TODO(), s.client,
*deploymentOperation.Properties.TargetResource.ResourceType,
*deploymentOperation.Properties.TargetResource.ResourceName,
resourceGroupName)
if err != nil {
@ -197,12 +199,18 @@ func (s *StepDeployTemplate) Cleanup(state multistep.StateBag) {
"Name: %s\n"+
"Error: %s", *deploymentOperation.Properties.TargetResource.ResourceName, err))
}
if err = deploymentOperations.Next(); err != nil {
ui.Error(fmt.Sprintf("Error deleting resources. Please delete them manually.\n\n"+
"Name: %s\n"+
"Error: %s", resourceGroupName, err))
break
}
}
// The disk is not defined as an operation in the template so has to be
// deleted separately
ui.Say(fmt.Sprintf(" -> %s : '%s'", imageType, imageName))
err = s.deleteDisk(imageType, imageName, resourceGroupName)
err = s.deleteDisk(context.TODO(), imageType, imageName, resourceGroupName)
if err != nil {
ui.Error(fmt.Sprintf("Error deleting resource. Please delete manually.\n\n"+
"Name: %s\n"+

View File

@ -4,7 +4,7 @@ import (
"context"
"fmt"
"github.com/Azure/azure-sdk-for-go/arm/compute"
"github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2018-04-01/compute"
"github.com/hashicorp/packer/builder/azure/common/constants"
@ -14,7 +14,7 @@ import (
type StepGetDataDisk struct {
client *AzureClient
query func(resourceGroupName string, computeName string) (compute.VirtualMachine, error)
query func(ctx context.Context, resourceGroupName string, computeName string) (compute.VirtualMachine, error)
say func(message string)
error func(e error)
}
@ -30,15 +30,15 @@ func NewStepGetAdditionalDisks(client *AzureClient, ui packer.Ui) *StepGetDataDi
return step
}
func (s *StepGetDataDisk) queryCompute(resourceGroupName string, computeName string) (compute.VirtualMachine, error) {
vm, err := s.client.VirtualMachinesClient.Get(resourceGroupName, computeName, "")
func (s *StepGetDataDisk) queryCompute(ctx context.Context, resourceGroupName string, computeName string) (compute.VirtualMachine, error) {
vm, err := s.client.VirtualMachinesClient.Get(ctx, resourceGroupName, computeName, "")
if err != nil {
s.say(s.client.LastError.Error())
}
return vm, err
}
func (s *StepGetDataDisk) Run(_ context.Context, state multistep.StateBag) multistep.StepAction {
func (s *StepGetDataDisk) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction {
s.say("Querying the machine's additional disks properties ...")
var resourceGroupName = state.Get(constants.ArmResourceGroupName).(string)
@ -47,7 +47,7 @@ func (s *StepGetDataDisk) Run(_ context.Context, state multistep.StateBag) multi
s.say(fmt.Sprintf(" -> ResourceGroupName : '%s'", resourceGroupName))
s.say(fmt.Sprintf(" -> ComputeName : '%s'", computeName))
vm, err := s.query(resourceGroupName, computeName)
vm, err := s.query(ctx, resourceGroupName, computeName)
if err != nil {
state.Put(constants.Error, err)
s.error(err)

View File

@ -28,7 +28,7 @@ var (
type StepGetIPAddress struct {
client *AzureClient
endpoint EndpointType
get func(resourceGroupName string, ipAddressName string, interfaceName string) (string, error)
get func(ctx context.Context, resourceGroupName string, ipAddressName string, interfaceName string) (string, error)
say func(message string)
error func(e error)
}
@ -53,8 +53,8 @@ func NewStepGetIPAddress(client *AzureClient, ui packer.Ui, endpoint EndpointTyp
return step
}
func (s *StepGetIPAddress) getPrivateIP(resourceGroupName string, ipAddressName string, interfaceName string) (string, error) {
resp, err := s.client.InterfacesClient.Get(resourceGroupName, interfaceName, "")
func (s *StepGetIPAddress) getPrivateIP(ctx context.Context, resourceGroupName string, ipAddressName string, interfaceName string) (string, error) {
resp, err := s.client.InterfacesClient.Get(ctx, resourceGroupName, interfaceName, "")
if err != nil {
s.say(s.client.LastError.Error())
return "", err
@ -63,8 +63,8 @@ func (s *StepGetIPAddress) getPrivateIP(resourceGroupName string, ipAddressName
return *(*resp.IPConfigurations)[0].PrivateIPAddress, nil
}
func (s *StepGetIPAddress) getPublicIP(resourceGroupName string, ipAddressName string, interfaceName string) (string, error) {
resp, err := s.client.PublicIPAddressesClient.Get(resourceGroupName, ipAddressName, "")
func (s *StepGetIPAddress) getPublicIP(ctx context.Context, resourceGroupName string, ipAddressName string, interfaceName string) (string, error) {
resp, err := s.client.PublicIPAddressesClient.Get(ctx, resourceGroupName, ipAddressName, "")
if err != nil {
return "", err
}
@ -72,12 +72,12 @@ func (s *StepGetIPAddress) getPublicIP(resourceGroupName string, ipAddressName s
return *resp.IPAddress, nil
}
func (s *StepGetIPAddress) getPublicIPInPrivateNetwork(resourceGroupName string, ipAddressName string, interfaceName string) (string, error) {
s.getPrivateIP(resourceGroupName, ipAddressName, interfaceName)
return s.getPublicIP(resourceGroupName, ipAddressName, interfaceName)
func (s *StepGetIPAddress) getPublicIPInPrivateNetwork(ctx context.Context, resourceGroupName string, ipAddressName string, interfaceName string) (string, error) {
s.getPrivateIP(ctx, resourceGroupName, ipAddressName, interfaceName)
return s.getPublicIP(ctx, resourceGroupName, ipAddressName, interfaceName)
}
func (s *StepGetIPAddress) Run(_ context.Context, state multistep.StateBag) multistep.StepAction {
func (s *StepGetIPAddress) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction {
s.say("Getting the VM's IP address ...")
var resourceGroupName = state.Get(constants.ArmResourceGroupName).(string)
@ -89,7 +89,7 @@ func (s *StepGetIPAddress) Run(_ context.Context, state multistep.StateBag) mult
s.say(fmt.Sprintf(" -> NicName : '%s'", nicName))
s.say(fmt.Sprintf(" -> Network Connection : '%s'", EndpointCommunicationText[s.endpoint]))
address, err := s.get(resourceGroupName, ipAddressName, nicName)
address, err := s.get(ctx, resourceGroupName, ipAddressName, nicName)
if err != nil {
state.Put(constants.Error, err)
s.error(err)

View File

@ -4,7 +4,7 @@ import (
"context"
"fmt"
"github.com/Azure/azure-sdk-for-go/arm/compute"
"github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2018-04-01/compute"
"github.com/hashicorp/packer/builder/azure/common/constants"
@ -14,7 +14,7 @@ import (
type StepGetOSDisk struct {
client *AzureClient
query func(resourceGroupName string, computeName string) (compute.VirtualMachine, error)
query func(ctx context.Context, resourceGroupName string, computeName string) (compute.VirtualMachine, error)
say func(message string)
error func(e error)
}
@ -30,15 +30,15 @@ func NewStepGetOSDisk(client *AzureClient, ui packer.Ui) *StepGetOSDisk {
return step
}
func (s *StepGetOSDisk) queryCompute(resourceGroupName string, computeName string) (compute.VirtualMachine, error) {
vm, err := s.client.VirtualMachinesClient.Get(resourceGroupName, computeName, "")
func (s *StepGetOSDisk) queryCompute(ctx context.Context, resourceGroupName string, computeName string) (compute.VirtualMachine, error) {
vm, err := s.client.VirtualMachinesClient.Get(ctx, resourceGroupName, computeName, "")
if err != nil {
s.say(s.client.LastError.Error())
}
return vm, err
}
func (s *StepGetOSDisk) Run(_ context.Context, state multistep.StateBag) multistep.StepAction {
func (s *StepGetOSDisk) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction {
s.say("Querying the machine's properties ...")
var resourceGroupName = state.Get(constants.ArmResourceGroupName).(string)
@ -47,7 +47,7 @@ func (s *StepGetOSDisk) Run(_ context.Context, state multistep.StateBag) multist
s.say(fmt.Sprintf(" -> ResourceGroupName : '%s'", resourceGroupName))
s.say(fmt.Sprintf(" -> ComputeName : '%s'", computeName))
vm, err := s.query(resourceGroupName, computeName)
vm, err := s.query(ctx, resourceGroupName, computeName)
if err != nil {
state.Put(constants.Error, err)
s.error(err)

View File

@ -12,7 +12,7 @@ import (
type StepPowerOffCompute struct {
client *AzureClient
powerOff func(resourceGroupName string, computeName string, cancelCh <-chan struct{}) error
powerOff func(ctx context.Context, resourceGroupName string, computeName string, cancelCh <-chan struct{}) error
say func(message string)
error func(e error)
}
@ -28,17 +28,18 @@ func NewStepPowerOffCompute(client *AzureClient, ui packer.Ui) *StepPowerOffComp
return step
}
func (s *StepPowerOffCompute) powerOffCompute(resourceGroupName string, computeName string, cancelCh <-chan struct{}) error {
_, errChan := s.client.PowerOff(resourceGroupName, computeName, cancelCh)
err := <-errChan
func (s *StepPowerOffCompute) powerOffCompute(ctx context.Context, resourceGroupName string, computeName string, cancelCh <-chan struct{}) error {
f, err := s.client.VirtualMachinesClient.PowerOff(ctx, resourceGroupName, computeName)
if err == nil {
err = f.WaitForCompletion(ctx, s.client.VirtualMachinesClient.Client)
}
if err != nil {
s.say(s.client.LastError.Error())
}
return err
}
func (s *StepPowerOffCompute) Run(_ context.Context, state multistep.StateBag) multistep.StepAction {
func (s *StepPowerOffCompute) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction {
s.say("Powering off machine ...")
var resourceGroupName = state.Get(constants.ArmResourceGroupName).(string)
@ -49,7 +50,7 @@ func (s *StepPowerOffCompute) Run(_ context.Context, state multistep.StateBag) m
result := common.StartInterruptibleTask(
func() bool { return common.IsStateCancelled(state) },
func(cancelCh <-chan struct{}) error { return s.powerOff(resourceGroupName, computeName, cancelCh) })
func(cancelCh <-chan struct{}) error { return s.powerOff(ctx, resourceGroupName, computeName, cancelCh) })
return processInterruptibleResult(result, s.error, state)
}

View File

@ -11,7 +11,7 @@ import (
type StepValidateTemplate struct {
client *AzureClient
validate func(resourceGroupName string, deploymentName string) error
validate func(ctx context.Context, resourceGroupName string, deploymentName string) error
say func(message string)
error func(e error)
config *Config
@ -31,20 +31,20 @@ func NewStepValidateTemplate(client *AzureClient, ui packer.Ui, config *Config,
return step
}
func (s *StepValidateTemplate) validateTemplate(resourceGroupName string, deploymentName string) error {
func (s *StepValidateTemplate) validateTemplate(ctx context.Context, resourceGroupName string, deploymentName string) error {
deployment, err := s.factory(s.config)
if err != nil {
return err
}
_, err = s.client.Validate(resourceGroupName, deploymentName, *deployment)
_, err = s.client.DeploymentsClient.Validate(ctx, resourceGroupName, deploymentName, *deployment)
if err != nil {
s.say(s.client.LastError.Error())
}
return err
}
func (s *StepValidateTemplate) Run(_ context.Context, state multistep.StateBag) multistep.StepAction {
func (s *StepValidateTemplate) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction {
s.say("Validating deployment template ...")
var resourceGroupName = state.Get(constants.ArmResourceGroupName).(string)
@ -53,7 +53,7 @@ func (s *StepValidateTemplate) Run(_ context.Context, state multistep.StateBag)
s.say(fmt.Sprintf(" -> ResourceGroupName : '%s'", resourceGroupName))
s.say(fmt.Sprintf(" -> DeploymentName : '%s'", deploymentName))
err := s.validate(resourceGroupName, deploymentName)
err := s.validate(ctx, resourceGroupName, deploymentName)
return processStepResult(err, s.error, state)
}

View File

@ -3,8 +3,8 @@ package arm
import (
"encoding/json"
"github.com/Azure/azure-sdk-for-go/arm/compute"
"github.com/Azure/azure-sdk-for-go/arm/resources/resources"
"github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2018-04-01/compute"
"github.com/Azure/azure-sdk-for-go/services/resources/mgmt/2018-02-01/resources"
"fmt"

View File

@ -1,13 +1,14 @@
package common
import (
"context"
"fmt"
"net/http"
"os"
"path/filepath"
"regexp"
"github.com/Azure/azure-sdk-for-go/arm/resources/subscriptions"
"github.com/Azure/azure-sdk-for-go/services/resources/mgmt/2016-06-01/subscriptions"
"github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/adal"
"github.com/Azure/go-autorest/autorest/azure"
@ -100,7 +101,7 @@ func Authenticate(env azure.Environment, tenantID string, say func(string)) (*ad
return nil, err
}
say("Obtained service principal token.")
if err := saveToken(spt.Token); err != nil {
if err := saveToken(spt.Token()); err != nil {
say("Error occurred saving token to cache file.")
return nil, err
}
@ -186,9 +187,9 @@ func mkTokenCallback(path string) adal.TokenRefreshCallback {
// automatically refresh the token using refresh_token (which might have
// expired). This check is essentially to make sure refresh_token is good.
func validateToken(env azure.Environment, token *adal.ServicePrincipalToken) error {
c := subscriptionsClient(env.ResourceManagerEndpoint)
c := subscriptions.NewClientWithBaseURI(env.ResourceManagerEndpoint)
c.Authorizer = autorest.NewBearerAuthorizer(token)
_, err := c.List()
_, err := c.List(context.TODO())
if err != nil {
return fmt.Errorf("Token validity check failed: %v", err)
}
@ -200,12 +201,12 @@ func validateToken(env azure.Environment, token *adal.ServicePrincipalToken) err
// the value from WWW-Authenticate header.
func FindTenantID(env azure.Environment, subscriptionID string) (string, error) {
const hdrKey = "WWW-Authenticate"
c := subscriptionsClient(env.ResourceManagerEndpoint)
c := subscriptions.NewClientWithBaseURI(env.ResourceManagerEndpoint)
// we expect this request to fail (err != nil), but we are only interested
// in headers, so surface the error if the Response is not present (i.e.
// network error etc)
subs, err := c.Get(subscriptionID)
subs, err := c.Get(context.TODO(), subscriptionID)
if subs.Response.Response == nil {
return "", fmt.Errorf("Request failed: %v", err)
}
@ -228,8 +229,3 @@ func FindTenantID(env azure.Environment, subscriptionID string) (string, error)
}
return m[1], nil
}
func subscriptionsClient(baseURI string) subscriptions.GroupClient {
client := subscriptions.NewGroupClientWithBaseURI(baseURI)
return client
}

View File

@ -1,8 +1,8 @@
package template
import (
"github.com/Azure/azure-sdk-for-go/arm/compute"
"github.com/Azure/azure-sdk-for-go/arm/network"
"github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2018-04-01/compute"
"github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-01-01/network"
)
/////////////////////////////////////////////////

View File

@ -5,7 +5,7 @@ import (
"fmt"
"strings"
"github.com/Azure/azure-sdk-for-go/arm/compute"
"github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2018-04-01/compute"
"github.com/Azure/go-autorest/autorest/to"
)
@ -113,7 +113,7 @@ func (s *TemplateBuilder) SetManagedDiskUrl(managedImageId string, storageAccoun
}
profile.OsDisk.Name = to.StringPtr("osdisk")
profile.OsDisk.OsType = s.osType
profile.OsDisk.CreateOption = compute.FromImage
profile.OsDisk.CreateOption = compute.DiskCreateOptionTypesFromImage
profile.OsDisk.Vhd = nil
profile.OsDisk.ManagedDisk = &compute.ManagedDiskParameters{
StorageAccountType: storageAccountType,
@ -138,7 +138,7 @@ func (s *TemplateBuilder) SetManagedMarketplaceImage(location, publisher, offer,
}
profile.OsDisk.Name = to.StringPtr("osdisk")
profile.OsDisk.OsType = s.osType
profile.OsDisk.CreateOption = compute.FromImage
profile.OsDisk.CreateOption = compute.DiskCreateOptionTypesFromImage
profile.OsDisk.Vhd = nil
profile.OsDisk.ManagedDisk = &compute.ManagedDiskParameters{
StorageAccountType: storageAccountType,