github.com/raghuse92/packer@v1.3.2/builder/ncloud/step_create_login_key.go (about)

     1  package ncloud
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"time"
     7  
     8  	ncloud "github.com/NaverCloudPlatform/ncloud-sdk-go/sdk"
     9  	"github.com/hashicorp/packer/helper/multistep"
    10  	"github.com/hashicorp/packer/packer"
    11  )
    12  
    13  type LoginKey struct {
    14  	KeyName    string
    15  	PrivateKey string
    16  }
    17  
    18  type StepCreateLoginKey struct {
    19  	Conn           *ncloud.Conn
    20  	CreateLoginKey func() (*LoginKey, error)
    21  	Say            func(message string)
    22  	Error          func(e error)
    23  }
    24  
    25  func NewStepCreateLoginKey(conn *ncloud.Conn, ui packer.Ui) *StepCreateLoginKey {
    26  	var step = &StepCreateLoginKey{
    27  		Conn:  conn,
    28  		Say:   func(message string) { ui.Say(message) },
    29  		Error: func(e error) { ui.Error(e.Error()) },
    30  	}
    31  
    32  	step.CreateLoginKey = step.createLoginKey
    33  
    34  	return step
    35  }
    36  
    37  func (s *StepCreateLoginKey) createLoginKey() (*LoginKey, error) {
    38  	KeyName := fmt.Sprintf("packer-%d", time.Now().Unix())
    39  
    40  	privateKey, err := s.Conn.CreateLoginKey(KeyName)
    41  	if err != nil {
    42  		return nil, err
    43  	}
    44  
    45  	return &LoginKey{KeyName, privateKey.PrivateKey}, nil
    46  }
    47  
    48  func (s *StepCreateLoginKey) Run(_ context.Context, state multistep.StateBag) multistep.StepAction {
    49  	s.Say("Create Login Key")
    50  
    51  	loginKey, err := s.CreateLoginKey()
    52  	if err == nil {
    53  		state.Put("LoginKey", loginKey)
    54  		s.Say(fmt.Sprintf("Login Key[%s] is created", loginKey.KeyName))
    55  	}
    56  
    57  	return processStepResult(err, s.Error, state)
    58  }
    59  
    60  func (s *StepCreateLoginKey) Cleanup(state multistep.StateBag) {
    61  	if loginKey, ok := state.GetOk("LoginKey"); ok {
    62  		s.Say("Clean up login key")
    63  		s.Conn.DeleteLoginKey(loginKey.(*LoginKey).KeyName)
    64  	}
    65  }