-
Notifications
You must be signed in to change notification settings - Fork 1
/
step_create_instance.go
80 lines (64 loc) · 1.96 KB
/
step_create_instance.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package civo
import (
"context"
"fmt"
"log"
"github.com/civo/civogo"
"github.com/hashicorp/packer/helper/multistep"
"github.com/hashicorp/packer/packer"
)
type stepCreateInstance struct {
instanceID string
}
// Run function to run create a instance
func (s *stepCreateInstance) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction {
client := state.Get("client").(*civogo.Client)
ui := state.Get("ui").(packer.Ui)
c := state.Get("config").(*Config)
sshKeyID := state.Get("ssh_key_id").(string)
// Create the instance based on configuration
ui.Say("Creating instance...")
template, err := client.FindTemplate(c.Template)
if err != nil {
ui.Error(err.Error())
}
network, _ := client.GetDefaultNetwork()
InstanceConfig := &civogo.InstanceConfig{
Hostname: c.InstanceName,
PublicIPRequired: c.PublicNetworking,
Region: c.Region,
NetworkID: network.ID,
InitialUser: c.Comm.SSHUsername,
Size: c.Size,
TemplateID: template.ID,
SSHKeyID: sshKeyID,
}
log.Printf("[DEBUG] Instance create paramaters: %+v", InstanceConfig)
instance, err := client.CreateInstance(InstanceConfig)
if err != nil {
err := fmt.Errorf("Error creating instance: %s", err)
state.Put("error", err)
ui.Error(err.Error())
return multistep.ActionHalt
}
// We use this in cleanup
s.instanceID = instance.ID
// Store the instance id for later
state.Put("instance_id", instance.ID)
return multistep.ActionContinue
}
func (s *stepCreateInstance) Cleanup(state multistep.StateBag) {
// If the instanceid isn't there, we probably never created it
if s.instanceID == "" {
return
}
client := state.Get("client").(*civogo.Client)
ui := state.Get("ui").(packer.Ui)
// Destroy the instance we just created
ui.Say("Destroying instance...")
_, err := client.DeleteInstance(s.instanceID)
if err != nil {
ui.Error(fmt.Sprintf(
"Error destroying instance. Please destroy it manually: %s", err))
}
}