/
provisioner.go
384 lines (331 loc) · 10.5 KB
/
provisioner.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
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
//go:generate packer-sdc mapstructure-to-hcl2 -type Config
// NB this code was based on https://github.com/hashicorp/packer/blob/81522dced0b25084a824e79efda02483b12dc7cd/provisioner/windows-restart/provisioner.go
package update
import (
"bytes"
"context"
_ "embed" // this is needed for using the go:embed directive
"encoding/base64"
"errors"
"fmt"
"strings"
"time"
"unicode/utf16"
"github.com/hashicorp/hcl/v2/hcldec"
"github.com/hashicorp/packer-plugin-sdk/common"
"github.com/hashicorp/packer-plugin-sdk/packer"
"github.com/hashicorp/packer-plugin-sdk/retry"
"github.com/hashicorp/packer-plugin-sdk/template/config"
"github.com/hashicorp/packer-plugin-sdk/template/interpolate"
"github.com/hashicorp/packer-plugin-sdk/uuid"
)
const (
elevatedPath = "C:/Windows/Temp/packer-windows-update-elevated.ps1"
elevatedCommand = "PowerShell -ExecutionPolicy Bypass -OutputFormat Text -File C:/Windows/Temp/packer-windows-update-elevated.ps1"
windowsUpdatePath = "C:/Windows/Temp/packer-windows-update.ps1"
pendingRebootElevatedPath = "C:/Windows/Temp/packer-windows-update-pending-reboot-elevated.ps1"
pendingRebootElevatedCommand = "PowerShell -ExecutionPolicy Bypass -OutputFormat Text -File C:/Windows/Temp/packer-windows-update-pending-reboot-elevated.ps1"
restartCommand = "shutdown.exe -f -r -t 0 -c \"packer restart\""
testRestartCommand = "shutdown.exe -f -r -t 60 -c \"packer restart test\""
abortTestRestartCommand = "shutdown.exe -a"
retryableDelay = 5 * time.Second
uploadTimeout = 5 * time.Minute
)
//go:embed windows-update.ps1
var windowsUpdatePs1 []byte
type Config struct {
common.PackerConfig `mapstructure:",squash"`
// The timeout for waiting for the machine to restart
RestartTimeout time.Duration `mapstructure:"restart_timeout"`
// Instructs the communicator to run the remote script as a
// Windows scheduled task, effectively elevating the remote
// user by impersonating a logged-in user.
Username string `mapstructure:"username"`
Password string `mapstructure:"password"`
// The updates search criteria.
// See the IUpdateSearcher::Search method at https://docs.microsoft.com/en-us/windows/desktop/api/wuapi/nf-wuapi-iupdatesearcher-search.
SearchCriteria string `mapstructure:"search_criteria"`
// Filters the installed Windows updates. If no filter is
// matched the update is NOT installed.
Filters []string `mapstructure:"filters"`
// Adds a limit to how many updates are installed at a time
UpdateLimit int `mapstructure:"update_limit"`
// Max times the provisioner will try install the updates
// in case of failure.
UpdateMaxRetries int `mapstructure:"update_max_retries"`
ctx interpolate.Context
}
type Provisioner struct {
config Config
}
func (b *Provisioner) ConfigSpec() hcldec.ObjectSpec {
return b.config.FlatMapstructure().HCL2Spec()
}
func (p *Provisioner) Prepare(raws ...interface{}) error {
err := config.Decode(&p.config, &config.DecodeOpts{
Interpolate: true,
InterpolateContext: &p.config.ctx,
InterpolateFilter: &interpolate.RenderFilter{
Exclude: []string{
"execute_command",
},
},
}, raws...)
if err != nil {
return err
}
if p.config.RestartTimeout == 0 {
p.config.RestartTimeout = 4 * time.Hour
}
if p.config.Username == "" {
p.config.Username = "SYSTEM"
}
var errs error
if p.config.Username == "" {
errs = packer.MultiErrorAppend(errs,
errors.New("Must supply an 'username'"))
}
if p.config.UpdateLimit == 0 {
p.config.UpdateLimit = 1000
}
if p.config.UpdateMaxRetries == 0 {
p.config.UpdateMaxRetries = 5
}
return errs
}
func (p *Provisioner) Provision(ctx context.Context, ui packer.Ui, comm packer.Communicator, _ map[string]interface{}) error {
ui.Say("Uploading the Windows update elevated script...")
var buffer bytes.Buffer
err := elevatedTemplate.Execute(&buffer, elevatedOptions{
Username: p.config.Username,
Password: p.config.Password,
TaskDescription: "Packer Windows update elevated task",
TaskName: fmt.Sprintf("packer-windows-update-%s", uuid.TimeOrderedUUID()),
Command: p.windowsUpdateCommand(),
})
if err != nil {
fmt.Printf("Error creating elevated template: %s", err)
return err
}
err = retry.Config{StartTimeout: uploadTimeout}.Run(ctx, func(context.Context) error {
if err := comm.Upload(
elevatedPath,
bytes.NewReader(buffer.Bytes()),
nil); err != nil {
return fmt.Errorf("Error uploading the Windows update elevated script: %s", err)
}
return nil
})
if err != nil {
return err
}
ui.Say("Uploading the Windows update check for reboot required elevated script...")
buffer.Reset()
err = elevatedTemplate.Execute(&buffer, elevatedOptions{
Username: p.config.Username,
Password: p.config.Password,
TaskDescription: "Packer Windows update pending reboot elevated task",
TaskName: fmt.Sprintf("packer-windows-update-pending-reboot-%s", uuid.TimeOrderedUUID()),
Command: p.windowsUpdateCheckForRebootRequiredCommand(),
})
if err != nil {
fmt.Printf("Error creating elevated template: %s", err)
return err
}
err = retry.Config{StartTimeout: uploadTimeout}.Run(ctx, func(context.Context) error {
if err := comm.Upload(
pendingRebootElevatedPath,
bytes.NewReader(buffer.Bytes()),
nil); err != nil {
return fmt.Errorf("Error uploading the Windows update check for reboot required elevated script: %s", err)
}
return nil
})
if err != nil {
return err
}
ui.Say("Uploading the Windows update script...")
err = comm.Upload(
windowsUpdatePath,
bytes.NewReader(windowsUpdatePs1),
nil)
if err != nil {
return err
}
for {
restartPending, err := p.update(ctx, ui, comm)
if err != nil {
return err
}
if !restartPending {
return nil
}
err = p.restart(ctx, ui, comm)
if err != nil {
return err
}
}
}
func (p *Provisioner) update(ctx context.Context, ui packer.Ui, comm packer.Communicator) (bool, error) {
ui.Say("Running Windows update...")
var restartPending bool
err := retry.Config{
RetryDelay: func() time.Duration { return retryableDelay },
Tries: p.config.UpdateMaxRetries,
}.Run(ctx, func(ctx context.Context) error {
cmd := &packer.RemoteCmd{Command: elevatedCommand}
err := cmd.RunWithUi(ctx, comm, ui)
if err != nil {
return err
}
var exitStatus = cmd.ExitStatus()
switch exitStatus {
case 0:
return nil
case 101:
restartPending = true
return nil
case 2147942501: //windows 2012
restartPending = true
return nil
default:
return fmt.Errorf("Windows update script exited with non-zero exit status: %d", exitStatus)
}
})
return restartPending, err
}
func (p *Provisioner) restart(ctx context.Context, ui packer.Ui, comm packer.Communicator) error {
restartPending := true
for restartPending {
ui.Say("Restarting the machine...")
err := p.retryable(ctx, func(ctx context.Context) error {
cmd := &packer.RemoteCmd{Command: restartCommand}
err := cmd.RunWithUi(ctx, comm, ui)
if err != nil {
return err
}
exitStatus := cmd.ExitStatus()
if exitStatus != 0 {
return fmt.Errorf("Failed to restart the machine with exit status: %d", exitStatus)
}
return err
})
if err != nil {
return err
}
ui.Say("Waiting for machine to become available...")
err = p.retryable(ctx, func(ctx context.Context) error {
// wait for the machine to reboot.
cmd := &packer.RemoteCmd{Command: testRestartCommand}
err := cmd.RunWithUi(ctx, comm, ui)
if err != nil {
return err
}
exitStatus := cmd.ExitStatus()
if exitStatus != 0 {
return fmt.Errorf("Machine not yet available (exit status %d)", exitStatus)
}
cmd = &packer.RemoteCmd{Command: abortTestRestartCommand}
err = cmd.RunWithUi(ctx, comm, ui)
return err
})
if err != nil {
return err
}
ui.Say("Checking for pending restart...")
err = p.retryable(ctx, func(ctx context.Context) error {
cmd := &packer.RemoteCmd{Command: pendingRebootElevatedCommand}
err = cmd.RunWithUi(ctx, comm, ui)
if err != nil {
return err
}
exitStatus := cmd.ExitStatus()
switch {
case exitStatus == 0:
restartPending = false
case exitStatus == 101:
restartPending = true
case exitStatus == 2147942501: //windows 2012
restartPending = true
default:
return fmt.Errorf("Machine not yet available (exit status %d)", exitStatus)
}
return err
})
if err != nil {
return err
}
if restartPending {
ui.Say("Restart is still pending...")
} else {
ui.Say("Restart complete")
}
}
return nil
}
// retryable will retry the given function over and over until a
// non-error is returned, RestartTimeout expires, or ctx is
// cancelled.
func (p *Provisioner) retryable(ctx context.Context, f func(ctx context.Context) error) error {
return retry.Config{
RetryDelay: func() time.Duration { return retryableDelay },
StartTimeout: p.config.RestartTimeout,
}.Run(ctx, f)
}
func (p *Provisioner) windowsUpdateCommand() string {
return fmt.Sprintf(
"PowerShell -ExecutionPolicy Bypass -OutputFormat Text -EncodedCommand %s",
base64.StdEncoding.EncodeToString(
encodeUtf16Le(fmt.Sprintf(
"%s%s%s -UpdateLimit %d",
windowsUpdatePath,
searchCriteriaArgument(p.config.SearchCriteria),
filtersArgument(p.config.Filters),
p.config.UpdateLimit))))
}
func (p *Provisioner) windowsUpdateCheckForRebootRequiredCommand() string {
return fmt.Sprintf(
"PowerShell -ExecutionPolicy Bypass -OutputFormat Text -EncodedCommand %s",
base64.StdEncoding.EncodeToString(
encodeUtf16Le(fmt.Sprintf(
"%s -OnlyCheckForRebootRequired",
windowsUpdatePath))))
}
func encodeUtf16Le(s string) []byte {
d := utf16.Encode([]rune(s))
b := make([]byte, len(d)*2)
for i, r := range d {
b[i*2] = byte(r)
b[i*2+1] = byte(r >> 8)
}
return b
}
func searchCriteriaArgument(searchCriteria string) string {
if searchCriteria == "" {
return ""
}
var buffer bytes.Buffer
buffer.WriteString(" -SearchCriteria ")
buffer.WriteString(escapePowerShellString(searchCriteria))
return buffer.String()
}
func filtersArgument(filters []string) string {
if filters == nil {
return ""
}
var buffer bytes.Buffer
buffer.WriteString(" -Filters ")
for i, filter := range filters {
if i > 0 {
buffer.WriteString(",")
}
buffer.WriteString(escapePowerShellString(filter))
}
return buffer.String()
}
func escapePowerShellString(value string) string {
return fmt.Sprintf(
"'%s'",
// escape single quotes with another single quote.
strings.Replace(value, "'", "''", -1))
}