packer-cn/builder/azure/chroot/step_attach_disk.go

84 lines
2.2 KiB
Go
Raw Normal View History

2019-05-29 14:00:04 -04:00
package chroot
import (
"context"
"fmt"
2019-05-31 16:02:25 -04:00
"log"
"time"
2019-05-29 14:00:04 -04:00
"github.com/hashicorp/packer/builder/azure/common/client"
"github.com/hashicorp/packer/helper/multistep"
"github.com/hashicorp/packer/packer"
)
var _ multistep.Step = &StepAttachDisk{}
type StepAttachDisk struct {
2019-06-03 01:27:33 -04:00
attached bool
2019-05-29 14:00:04 -04:00
}
2019-06-03 01:27:33 -04:00
func (s *StepAttachDisk) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction {
2019-05-29 14:00:04 -04:00
azcli := state.Get("azureclient").(client.AzureClientSet)
ui := state.Get("ui").(packer.Ui)
2019-05-31 16:02:25 -04:00
diskResourceID := state.Get("os_disk_resource_id").(string)
2019-05-29 14:00:04 -04:00
ui.Say(fmt.Sprintf("Attaching disk '%s'", diskResourceID))
da := NewDiskAttacher(azcli)
lun, err := da.AttachDisk(ctx, diskResourceID)
if err != nil {
log.Printf("StepAttachDisk.Run: error: %+v", err)
err := fmt.Errorf(
"error attaching disk '%s': %v", diskResourceID, err)
state.Put("error", err)
ui.Error(err.Error())
return multistep.ActionHalt
}
ui.Say("Disk attached, waiting for device to show up")
ctx, cancel := context.WithTimeout(ctx, time.Minute*3) // in case is not configured correctly
defer cancel()
device, err := da.WaitForDevice(ctx, lun)
2019-06-03 01:27:33 -04:00
if err != nil {
log.Printf("StepAttachDisk.Run: error: %+v", err)
err := fmt.Errorf(
"error attaching disk '%s': %v", diskResourceID, err)
state.Put("error", err)
ui.Error(err.Error())
return multistep.ActionHalt
}
2019-05-29 14:00:04 -04:00
ui.Say(fmt.Sprintf("Disk available at %q", device))
2019-06-03 01:27:33 -04:00
s.attached = true
2019-05-29 14:00:04 -04:00
state.Put("device", device)
2019-05-31 15:01:47 -04:00
state.Put("attach_cleanup", s)
2019-05-29 14:00:04 -04:00
return multistep.ActionContinue
}
2019-06-03 01:27:33 -04:00
func (s *StepAttachDisk) Cleanup(state multistep.StateBag) {
2019-05-31 15:01:47 -04:00
ui := state.Get("ui").(packer.Ui)
if err := s.CleanupFunc(state); err != nil {
ui.Error(err.Error())
}
}
func (s *StepAttachDisk) CleanupFunc(state multistep.StateBag) error {
2019-05-29 14:00:04 -04:00
2019-06-03 01:27:33 -04:00
if s.attached {
azcli := state.Get("azureclient").(client.AzureClientSet)
ui := state.Get("ui").(packer.Ui)
diskResourceID := state.Get("os_disk_resource_id").(string)
2019-05-29 14:00:04 -04:00
2019-06-03 01:27:33 -04:00
ui.Say(fmt.Sprintf("Detaching disk '%s'", diskResourceID))
da := NewDiskAttacher(azcli)
err := da.DetachDisk(context.Background(), diskResourceID)
if err != nil {
return fmt.Errorf("error detaching %q: %v", diskResourceID, err)
}
s.attached = false
2019-05-29 14:00:04 -04:00
}
2019-06-03 01:27:33 -04:00
2019-05-31 15:01:47 -04:00
return nil
2019-05-29 14:00:04 -04:00
}