packer-cn/builder/scaleway/step_create_server.go

75 lines
1.6 KiB
Go
Raw Normal View History

2017-04-06 05:19:17 -04:00
package scaleway
import (
"fmt"
"strings"
2017-04-06 05:19:17 -04:00
"github.com/hashicorp/packer/packer"
"github.com/mitchellh/multistep"
"github.com/scaleway/scaleway-cli/pkg/api"
)
type stepCreateServer struct {
serverID string
2017-04-06 05:19:17 -04:00
}
func (s *stepCreateServer) Run(state multistep.StateBag) multistep.StepAction {
client := state.Get("client").(*api.ScalewayAPI)
ui := state.Get("ui").(packer.Ui)
c := state.Get("config").(Config)
sshPubKey := state.Get("ssh_pubkey").(string)
tags := []string{}
2017-04-06 05:19:17 -04:00
ui.Say("Creating server...")
if sshPubKey != "" {
tags = []string{fmt.Sprintf("AUTHORIZED_KEY=%s", strings.TrimSpace(sshPubKey))}
}
2017-04-06 05:19:17 -04:00
server, err := client.PostServer(api.ScalewayServerDefinition{
Name: c.ServerName,
Image: &c.Image,
Organization: c.Organization,
CommercialType: c.CommercialType,
Tags: tags,
2017-04-06 05:19:17 -04:00
})
if err != nil {
err := fmt.Errorf("Error creating server: %s", err)
state.Put("error", err)
ui.Error(err.Error())
return multistep.ActionHalt
}
2017-04-06 05:19:17 -04:00
err = client.PostServerAction(server, "poweron")
if err != nil {
err := fmt.Errorf("Error starting server: %s", err)
2017-04-06 05:19:17 -04:00
state.Put("error", err)
ui.Error(err.Error())
return multistep.ActionHalt
}
s.serverID = server
2017-04-06 05:19:17 -04:00
state.Put("server_id", server)
return multistep.ActionContinue
}
func (s *stepCreateServer) Cleanup(state multistep.StateBag) {
if s.serverID == "" {
2017-04-06 05:19:17 -04:00
return
}
client := state.Get("client").(*api.ScalewayAPI)
ui := state.Get("ui").(packer.Ui)
ui.Say("Destroying server...")
err := client.PostServerAction(s.serverID, "terminate")
2017-04-06 05:19:17 -04:00
if err != nil {
ui.Error(fmt.Sprintf(
"Error destroying server. Please destroy it manually: %s", err))
}
}