-
-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathpost-processor.go
305 lines (267 loc) · 8.07 KB
/
post-processor.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
//go:generate mapstructure-to-hcl2 -type Config
package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"strconv"
"strings"
"sync"
"sync/atomic"
"github.com/hashicorp/hcl/v2/hcldec"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/credentials/stscreds"
"github.com/aws/aws-sdk-go/service/ec2"
"github.com/hashicorp/packer-plugin-amazon/builder/chroot"
"github.com/hashicorp/packer-plugin-amazon/builder/ebs"
"github.com/hashicorp/packer-plugin-amazon/builder/ebssurrogate"
"github.com/hashicorp/packer-plugin-amazon/builder/ebsvolume"
"github.com/hashicorp/packer-plugin-amazon/builder/instance"
"github.com/hashicorp/packer-plugin-sdk/common"
"github.com/hashicorp/packer-plugin-sdk/packer"
"github.com/hashicorp/packer-plugin-sdk/template/config"
"github.com/hashicorp/packer-plugin-sdk/template/interpolate"
"github.com/martinbaillie/packer-plugin-ami-copy/amicopy"
awscommon "github.com/hashicorp/packer-plugin-amazon/builder/common"
)
// BuilderId is the ID of this post processor.
// nolint: golint
const BuilderId = "packer.post-processor.ami-copy"
// Config is the post-processor configuration with interpolation supported.
// See https://www.packer.io/docs/builders/amazon.html for details.
type Config struct {
common.PackerConfig `mapstructure:",squash"`
awscommon.AccessConfig `mapstructure:",squash"`
awscommon.AMIConfig `mapstructure:",squash"`
// Variables specific to this post-processor
RoleName string `mapstructure:"role_name"`
CopyConcurrency int `mapstructure:"copy_concurrency"`
EnsureAvailable bool `mapstructure:"ensure_available"`
KeepArtifact string `mapstructure:"keep_artifact"`
ManifestOutput string `mapstructure:"manifest_output"`
TagsOnly bool `mapstructure:"tags_only"`
ctx interpolate.Context
}
// PostProcessor implements Packer's PostProcessor interface.
type PostProcessor struct {
config Config
}
func (p *PostProcessor) ConfigSpec() hcldec.ObjectSpec {
return p.config.FlatMapstructure().HCL2Spec()
}
// Configure interpolates and validates requisite vars for the PostProcessor.
func (p *PostProcessor) Configure(raws ...interface{}) error {
p.config.ctx.Funcs = awscommon.TemplateFuncs
if err := config.Decode(&p.config, &config.DecodeOpts{
PluginType: BuilderId,
Interpolate: true,
InterpolateContext: &p.config.ctx,
InterpolateFilter: &interpolate.RenderFilter{
Exclude: []string{},
},
}, raws...); err != nil {
return err
}
if len(p.config.AMIUsers) == 0 {
return errors.New("ami_users must be set")
}
if len(p.config.KeepArtifact) == 0 {
p.config.KeepArtifact = "true"
}
return nil
}
// PostProcess will copy the source AMI to each of the target accounts as
// designated by the mandatory `ami_users` variable. It will optionally
// encrypt the copied AMIs (`encrypt_boot`) with `kms_key_id` if set, or the
// default EBS KMS key if unset. Tags will be copied with the image.
//
// Copies are executed concurrently. This concurrency is unlimited unless
// controller by `copy_concurrency`.
func (p *PostProcessor) PostProcess(
ctx context.Context, ui packer.Ui, artifact packer.Artifact) (packer.Artifact, bool, bool, error) {
keepArtifactBool, err := strconv.ParseBool(p.config.KeepArtifact)
if err != nil {
return artifact, keepArtifactBool, false, err
}
// Ensure we're being called from a supported builder
switch artifact.BuilderId() {
case ebs.BuilderId,
ebssurrogate.BuilderId,
ebsvolume.BuilderId,
chroot.BuilderId,
instance.BuilderId:
break
default:
return artifact, keepArtifactBool, false,
fmt.Errorf("Unexpected artifact type: %s\nCan only export from Amazon builders",
artifact.BuilderId())
}
// Current AWS session
currSession, err := p.config.AccessConfig.Session()
if err != nil {
return artifact, keepArtifactBool, false, err
}
// Copy futures
var (
amis = amisFromArtifactID(artifact.Id())
users = p.config.AMIUsers
copies []amicopy.AmiCopy
)
for _, ami := range amis {
var source *ec2.Image
if source, err = amicopy.LocateSingleAMI(
ami.id,
ec2.New(currSession, aws.NewConfig().WithRegion(ami.region)),
); err != nil || source == nil {
return artifact, keepArtifactBool, false, err
}
for _, user := range users {
var conn *ec2.EC2
{
if p.config.RoleName != "" {
var (
role = fmt.Sprintf("arn:aws:iam::%s:role/%s", user, p.config.RoleName)
sess = currSession.Copy(&aws.Config{Region: aws.String(ami.region)})
)
conn = ec2.New(sess, &aws.Config{
Credentials: stscreds.NewCredentials(sess, role),
})
} else {
conn = ec2.New(currSession.Copy(&aws.Config{Region: aws.String(ami.region)}))
}
}
var name, description string
{
if source.Name != nil {
name = *source.Name
}
if source.Description != nil {
description = *source.Description
}
}
amiCopy := &amicopy.AmiCopyImpl{
EC2: conn,
SourceImage: source,
EnsureAvailable: p.config.EnsureAvailable,
TagsOnly: p.config.TagsOnly,
}
amiCopy.SetTargetAccountID(user)
amiCopy.SetInput(&ec2.CopyImageInput{
Name: aws.String(name),
Description: aws.String(description),
SourceImageId: aws.String(ami.id),
SourceRegion: aws.String(ami.region),
KmsKeyId: aws.String(p.config.AMIKmsKeyId),
Encrypted: aws.Bool(p.config.AMIEncryptBootVolume.True()),
})
copies = append(copies, amiCopy)
}
}
copyErrs := copyAMIs(copies, ui, p.config.ManifestOutput, p.config.CopyConcurrency)
if copyErrs > 0 {
return artifact, true, false, fmt.Errorf(
"%d/%d AMI copies failed, manual reconciliation may be required", copyErrs, len(copies))
}
return artifact, keepArtifactBool, false, nil
}
func copyAMIs(copies []amicopy.AmiCopy, ui packer.Ui, manifestOutput string, concurrencyCount int) int32 {
// Copy execution loop
var (
copyCount = len(copies)
copyTasks = make(chan amicopy.AmiCopy, copyCount)
amiManifests = make(chan *amicopy.AmiManifest, copyCount)
copyErrs int32
wg sync.WaitGroup
)
var workers int
{
if workers = concurrencyCount; workers == 0 {
workers = copyCount
}
}
for i := 0; i < workers; i++ {
wg.Add(1)
go func() {
defer wg.Done()
for c := range copyTasks {
input := c.Input()
ui.Say(
fmt.Sprintf(
"[%s] Copying %s to account %s (encrypted: %t)",
*input.SourceRegion,
*input.SourceImageId,
c.TargetAccountID(),
*input.Encrypted,
),
)
if err := c.Copy(&ui); err != nil {
ui.Say(err.Error())
atomic.AddInt32(©Errs, 1)
continue
}
output := c.Output()
manifest := &amicopy.AmiManifest{
AccountID: c.TargetAccountID(),
Region: *input.SourceRegion,
ImageID: *output.ImageId,
}
amiManifests <- manifest
ui.Say(
fmt.Sprintf(
"[%s] Finished copying %s to %s (copied id: %s)",
*input.SourceRegion,
*input.SourceImageId,
c.TargetAccountID(),
*output.ImageId,
),
)
}
}()
}
// Copy task submission
for _, copy := range copies {
copyTasks <- copy
}
close(copyTasks)
wg.Wait()
if manifestOutput != "" {
manifests := []*amicopy.AmiManifest{}
LOOP:
for {
select {
case m := <-amiManifests:
manifests = append(manifests, m)
default:
break LOOP
}
}
err := writeManifests(manifestOutput, manifests)
if err != nil {
ui.Say(fmt.Sprintf("Unable to write out manifest to %s: %s", manifestOutput, err))
}
}
close(amiManifests)
return copyErrs
}
// ami encapsulates simplistic details about an AMI.
type ami struct {
id string
region string
}
// amisFromArtifactID returns an AMI slice from a Packer artifact id.
func amisFromArtifactID(artifactID string) (amis []*ami) {
for _, amiStr := range strings.Split(artifactID, ",") {
pair := strings.SplitN(amiStr, ":", 2)
amis = append(amis, &ami{region: pair[0], id: pair[1]})
}
return amis
}
func writeManifests(output string, manifests []*amicopy.AmiManifest) error {
rawManifest, err := json.Marshal(manifests)
if err != nil {
return err
}
return ioutil.WriteFile(output, rawManifest, 0644)
}