2019-04-04 09:17:51 -04:00
|
|
|
package yandex
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"fmt"
|
|
|
|
|
2020-12-17 16:29:25 -05:00
|
|
|
"github.com/hashicorp/packer-plugin-sdk/multistep"
|
|
|
|
packersdk "github.com/hashicorp/packer-plugin-sdk/packer"
|
2019-04-04 09:17:51 -04:00
|
|
|
|
|
|
|
"github.com/yandex-cloud/go-genproto/yandex/cloud/compute/v1"
|
|
|
|
ycsdk "github.com/yandex-cloud/go-sdk"
|
|
|
|
)
|
|
|
|
|
2020-11-30 05:27:45 -05:00
|
|
|
type StepTeardownInstance struct {
|
|
|
|
SerialLogFile string
|
|
|
|
}
|
2019-04-04 09:17:51 -04:00
|
|
|
|
2020-04-26 19:19:08 -04:00
|
|
|
func (s *StepTeardownInstance) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction {
|
2019-04-04 09:17:51 -04:00
|
|
|
sdk := state.Get("sdk").(*ycsdk.SDK)
|
2020-11-19 14:54:31 -05:00
|
|
|
ui := state.Get("ui").(packersdk.Ui)
|
2019-04-04 09:17:51 -04:00
|
|
|
c := state.Get("config").(*Config)
|
|
|
|
|
|
|
|
instanceID := state.Get("instance_id").(string)
|
|
|
|
|
2019-06-06 09:41:58 -04:00
|
|
|
ui.Say("Stopping instance...")
|
2019-04-04 09:17:51 -04:00
|
|
|
ctx, cancel := context.WithTimeout(ctx, c.StateTimeout)
|
|
|
|
defer cancel()
|
2020-11-30 05:27:45 -05:00
|
|
|
|
|
|
|
if s.SerialLogFile != "" {
|
|
|
|
err := writeSerialLogFile(ctx, state, s.SerialLogFile)
|
|
|
|
if err != nil {
|
|
|
|
ui.Error(err.Error())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-06-06 09:41:58 -04:00
|
|
|
op, err := sdk.WrapOperation(sdk.Compute().Instance().Stop(ctx, &compute.StopInstanceRequest{
|
|
|
|
InstanceId: instanceID,
|
|
|
|
}))
|
|
|
|
if err != nil {
|
2020-12-09 10:51:34 -05:00
|
|
|
return StepHaltWithError(state, fmt.Errorf("Error stopping instance: %s", err))
|
2019-06-06 09:41:58 -04:00
|
|
|
}
|
|
|
|
err = op.Wait(ctx)
|
|
|
|
if err != nil {
|
2020-12-09 10:51:34 -05:00
|
|
|
return StepHaltWithError(state, fmt.Errorf("Error stopping instance: %s", err))
|
2019-06-06 09:41:58 -04:00
|
|
|
}
|
2019-04-04 09:17:51 -04:00
|
|
|
|
2019-06-06 09:41:58 -04:00
|
|
|
ui.Say("Deleting instance...")
|
|
|
|
op, err = sdk.WrapOperation(sdk.Compute().Instance().Delete(ctx, &compute.DeleteInstanceRequest{
|
2019-04-04 09:17:51 -04:00
|
|
|
InstanceId: instanceID,
|
|
|
|
}))
|
|
|
|
if err != nil {
|
2020-12-09 10:51:34 -05:00
|
|
|
return StepHaltWithError(state, fmt.Errorf("Error deleting instance: %s", err))
|
2019-04-04 09:17:51 -04:00
|
|
|
}
|
|
|
|
err = op.Wait(ctx)
|
|
|
|
if err != nil {
|
2020-12-09 10:51:34 -05:00
|
|
|
return StepHaltWithError(state, fmt.Errorf("Error deleting instance: %s", err))
|
2019-04-04 09:17:51 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
ui.Message("Instance has been deleted!")
|
|
|
|
state.Put("instance_id", "")
|
|
|
|
|
|
|
|
return multistep.ActionContinue
|
|
|
|
}
|
|
|
|
|
2020-04-26 19:19:08 -04:00
|
|
|
func (s *StepTeardownInstance) Cleanup(state multistep.StateBag) {
|
2019-04-04 09:17:51 -04:00
|
|
|
// no cleanup
|
|
|
|
}
|