forked from martinbaillie/packer-plugin-ami-copy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
post-processor.go
239 lines (212 loc) · 6.36 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
package main
import (
"errors"
"fmt"
"strconv"
"strings"
"sync"
"sync/atomic"
"github.com/martinbaillie/packer-post-processor-ami-copy/amicopy"
"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/builder/amazon/chroot"
"github.com/hashicorp/packer/builder/amazon/ebs"
"github.com/hashicorp/packer/builder/amazon/ebssurrogate"
"github.com/hashicorp/packer/builder/amazon/ebsvolume"
"github.com/hashicorp/packer/builder/amazon/instance"
"github.com/hashicorp/packer/common"
"github.com/hashicorp/packer/helper/config"
"github.com/hashicorp/packer/packer"
"github.com/hashicorp/packer/template/interpolate"
awscommon "github.com/hashicorp/packer/builder/amazon/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"`
ctx interpolate.Context
}
// PostProcessor implements Packer's PostProcessor interface.
type PostProcessor struct {
config Config
}
// Configure interpolates and validates requisite vars for the PostProcessor.
func (p *PostProcessor) Configure(raws ...interface{}) error {
p.config.ctx.Funcs = awscommon.TemplateFuncs
err := config.Decode(&p.config, &config.DecodeOpts{
Interpolate: true,
InterpolateContext: &p.config.ctx,
InterpolateFilter: &interpolate.RenderFilter{
Exclude: []string{},
},
}, raws...)
if 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(
ui packer.Ui, artifact packer.Artifact) (packer.Artifact, bool, error) {
keepArtifactBool, err := strconv.ParseBool(p.config.KeepArtifact)
if err != nil {
return artifact, keepArtifactBool, 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,
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, 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, 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
}
}
copies = append(copies, &amicopy.AmiCopy{
EC2: conn,
SourceImage: source,
TargetAccountID: user,
Input: &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),
},
EnsureAvailable: p.config.EnsureAvailable,
})
}
}
// Copy execution loop
var (
copyCount = len(copies)
copyTasks = make(chan *amicopy.AmiCopy, copyCount)
copyErrs int32
wg sync.WaitGroup
)
var workers int
{
if workers = p.config.CopyConcurrency; workers == 0 {
workers = copyCount
}
}
for i := 0; i < workers; i++ {
wg.Add(1)
go func() {
defer wg.Done()
for c := range copyTasks {
ui.Say(fmt.Sprintf("[%s] Copying %s to account %s (encrypted: %t)",
*c.Input.SourceRegion,
*c.Input.SourceImageId,
c.TargetAccountID,
*c.Input.Encrypted),
)
if err = c.Copy(&ui); err != nil {
ui.Say(err.Error())
atomic.AddInt32(©Errs, 1)
continue
}
ui.Say(fmt.Sprintf("[%s] Finished copying %s to %s (copied id: %s)",
*c.Input.SourceRegion,
*c.Input.SourceImageId,
c.TargetAccountID,
*c.Output.ImageId),
)
}
}()
}
// Copy task submission
for _, copy := range copies {
copyTasks <- copy
}
close(copyTasks)
wg.Wait()
if copyErrs > 0 {
return artifact, true, fmt.Errorf(
"%d/%d AMI copies failed, manual reconciliation may be required", copyErrs, copyCount)
}
return artifact, keepArtifactBool, nil
}
// 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
}