generated from hashicorp/packer-plugin-scaffolding
/
step_deploy_template.go
250 lines (218 loc) · 8.41 KB
/
step_deploy_template.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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0
package dtl
import (
"context"
"errors"
"fmt"
"net/url"
"strings"
"time"
"github.com/Azure/azure-sdk-for-go/services/devtestlabs/mgmt/2018-09-15/dtl"
"github.com/hashicorp/packer-plugin-azure/builder/azure/common/constants"
"github.com/hashicorp/packer-plugin-sdk/multistep"
packersdk "github.com/hashicorp/packer-plugin-sdk/packer"
)
type StepDeployTemplate struct {
client *AzureClient
deploy func(ctx context.Context, resourceGroupName string, deploymentName string, state multistep.StateBag) error
delete func(ctx context.Context, client *AzureClient, resourceType string, resourceName string, resourceGroupName string) error
disk func(ctx context.Context, resourceGroupName string, computeName string) (string, string, error)
deleteDisk func(ctx context.Context, imageType string, imageName string, resourceGroupName string) error
say func(message string)
error func(e error)
config *Config
factory templateFactoryFuncDtl
name string
}
func NewStepDeployTemplate(client *AzureClient, ui packersdk.Ui, config *Config, deploymentName string, factory templateFactoryFuncDtl) *StepDeployTemplate {
var step = &StepDeployTemplate{
client: client,
say: func(message string) { ui.Say(message) },
error: func(e error) { ui.Error(e.Error()) },
config: config,
factory: factory,
name: deploymentName,
}
step.deploy = step.deployTemplate
step.delete = deleteResource
step.disk = step.getImageDetails
step.deleteDisk = step.deleteImage
return step
}
func (s *StepDeployTemplate) deployTemplate(ctx context.Context, resourceGroupName string, deploymentName string, state multistep.StateBag) error {
vmlistPage, err := s.client.DtlVirtualMachineClient.List(ctx, s.config.tmpResourceGroupName, s.config.LabName, "", "", nil, "")
if err != nil {
s.say(s.client.LastError.Error())
return err
}
vmList := vmlistPage.Values()
for i := range vmList {
if *vmList[i].Name == s.config.tmpComputeName {
return fmt.Errorf("Error: Virtual Machine %s already exists. Please use another name", s.config.tmpComputeName)
}
}
s.say(fmt.Sprintf("Creating Virtual Machine %s", s.config.tmpComputeName))
labMachine, err := s.factory(s.config)
if err != nil {
return err
}
f, err := s.client.DtlLabsClient.CreateEnvironment(ctx, s.config.tmpResourceGroupName, s.config.LabName, *labMachine)
if err == nil {
err = f.WaitForCompletionRef(ctx, s.client.DtlLabsClient.Client)
}
if err != nil {
s.say(s.client.LastError.Error())
return err
}
expand := "Properties($expand=ComputeVm,Artifacts,NetworkInterface)"
vm, err := s.client.DtlVirtualMachineClient.Get(ctx, s.config.tmpResourceGroupName, s.config.LabName, s.config.tmpComputeName, expand)
if err != nil {
s.say(s.client.LastError.Error())
}
// set tmpFQDN to the PrivateIP or to the real FQDN depending on
// publicIP being allowed or not
if s.config.DisallowPublicIP {
resp, err := s.client.InterfacesClient.Get(ctx, s.config.tmpResourceGroupName, s.config.tmpNicName, "")
if err != nil {
s.say(s.client.LastError.Error())
return err
}
s.config.tmpFQDN = *(*resp.IPConfigurations)[0].PrivateIPAddress
} else {
s.config.tmpFQDN = *vm.Fqdn
}
s.say(fmt.Sprintf(" -> VM FQDN/IP : '%s'", s.config.tmpFQDN))
state.Put(constants.SSHHost, s.config.tmpFQDN)
// In a windows VM, add the winrm artifact. Doing it after the machine has been
// created allows us to use its IP address as FQDN
if strings.ToLower(s.config.OSType) == "windows" {
// Add mandatory Artifact
var winrma = "windows-winrm"
var artifactid = fmt.Sprintf("/subscriptions/%s/resourceGroups/%s/providers/Microsoft.DevTestLab/labs/%s/artifactSources/public repo/artifacts/%s",
s.config.ClientConfig.SubscriptionID,
s.config.tmpResourceGroupName,
s.config.LabName,
winrma)
var hostname = "hostName"
dp := &dtl.ArtifactParameterProperties{}
dp.Name = &hostname
dp.Value = &s.config.tmpFQDN
dparams := []dtl.ArtifactParameterProperties{*dp}
winrmArtifact := &dtl.ArtifactInstallProperties{
ArtifactTitle: &winrma,
ArtifactID: &artifactid,
Parameters: &dparams,
}
dtlArtifacts := []dtl.ArtifactInstallProperties{*winrmArtifact}
dtlArtifactsRequest := dtl.ApplyArtifactsRequest{Artifacts: &dtlArtifacts}
// infinite loop until the artifacts have been applied
for {
f, err := s.client.DtlVirtualMachineClient.ApplyArtifacts(ctx, s.config.tmpResourceGroupName, s.config.LabName, s.config.tmpComputeName, dtlArtifactsRequest)
if err == nil {
s.say("WinRM artifact deployment started, waiting for completion")
err = f.WaitForCompletionRef(ctx, s.client.DtlVirtualMachineClient.Client)
if err != nil {
s.say(s.client.LastError.Error())
return err
}
break
} else {
s.say("WinRM artifact deployment failed, sleeping a minute and retrying")
time.Sleep(60 * time.Second)
}
}
}
xs := strings.Split(*vm.LabVirtualMachineProperties.ComputeID, "/")
s.config.VMCreationResourceGroup = xs[4]
// Resuing the Resource group name from common constants as all steps depend on it.
state.Put(constants.ArmResourceGroupName, s.config.VMCreationResourceGroup)
s.say(fmt.Sprintf(" -> VM ResourceGroupName : '%s'", s.config.VMCreationResourceGroup))
return err
}
func (s *StepDeployTemplate) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction {
s.say("Deploying deployment template ...")
var resourceGroupName = state.Get(constants.ArmResourceGroupName).(string)
s.say(fmt.Sprintf(" -> Lab ResourceGroupName : '%s'", resourceGroupName))
return processStepResult(
s.deploy(ctx, resourceGroupName, s.name, state),
s.error, state)
}
func (s *StepDeployTemplate) getImageDetails(ctx context.Context, resourceGroupName string, computeName string) (string, string, error) {
//We can't depend on constants.ArmOSDiskVhd being set
var imageName string
var imageType string
vm, err := s.client.VirtualMachinesClient.Get(ctx, resourceGroupName, computeName, "")
if err != nil {
return imageName, imageType, err
} else {
if vm.StorageProfile.OsDisk.Vhd != nil {
imageType = "image"
imageName = *vm.StorageProfile.OsDisk.Vhd.URI
} else {
imageType = "Microsoft.Compute/disks"
imageName = *vm.StorageProfile.OsDisk.ManagedDisk.ID
}
}
return imageType, imageName, nil
}
func deleteResource(ctx context.Context, client *AzureClient, resourceType string, resourceName string, resourceGroupName string) error {
switch resourceType {
case "Microsoft.Compute/virtualMachines":
f, err := client.VirtualMachinesClient.Delete(ctx, resourceGroupName, resourceName)
if err == nil {
err = f.WaitForCompletionRef(ctx, client.VirtualMachinesClient.Client)
}
return err
case "Microsoft.Network/networkInterfaces":
f, err := client.InterfacesClient.Delete(ctx, resourceGroupName, resourceName)
if err == nil {
err = f.WaitForCompletionRef(ctx, client.InterfacesClient.Client)
}
return err
case "Microsoft.Network/virtualNetworks":
f, err := client.VirtualNetworksClient.Delete(ctx, resourceGroupName, resourceName)
if err == nil {
err = f.WaitForCompletionRef(ctx, client.VirtualNetworksClient.Client)
}
return err
case "Microsoft.Network/publicIPAddresses":
f, err := client.PublicIPAddressesClient.Delete(ctx, resourceGroupName, resourceName)
if err == nil {
err = f.WaitForCompletionRef(ctx, client.PublicIPAddressesClient.Client)
}
return err
}
return nil
}
func (s *StepDeployTemplate) deleteImage(ctx context.Context, imageType string, imageName string, resourceGroupName string) error {
// Managed disk
if imageType == "Microsoft.Compute/disks" {
xs := strings.Split(imageName, "/")
diskName := xs[len(xs)-1]
f, err := s.client.DisksClient.Delete(ctx, resourceGroupName, diskName)
if err == nil {
err = f.WaitForCompletionRef(ctx, s.client.DisksClient.Client)
}
return err
}
// VHD image
u, err := url.Parse(imageName)
if err != nil {
return err
}
xs := strings.Split(u.Path, "/")
if len(xs) < 3 {
return errors.New("Unable to parse path of image " + imageName)
}
var storageAccountName = xs[1]
var blobName = strings.Join(xs[2:], "/")
blob := s.client.BlobStorageClient.GetContainerReference(storageAccountName).GetBlobReference(blobName)
err = blob.Delete(nil)
return err
}
func (s *StepDeployTemplate) Cleanup(state multistep.StateBag) {
//Only clean up if this was an existing resource group and the resource group
//is marked as created
// Just return now
}