Replace unencrypted EBS snapshots with encrypted

To ensure that groups and users attributes are added to the encrypted
snapshots.
This commit is contained in:
Rickard von Essen 2016-12-04 20:18:27 +01:00
parent c3a352955e
commit 4ce3b8712a
No known key found for this signature in database
GPG Key ID: E0C0327388876CBA
3 changed files with 32 additions and 11 deletions

View File

@ -64,6 +64,10 @@ func (c *AMIConfig) Prepare(ctx *interpolate.Context) []error {
errs = append(errs, fmt.Errorf("Cannot share AMI with encrypted boot volume"))
}
if len(c.SnapshotUsers) > 0 && len(c.AMIKmsKeyId) == 0 && c.AMIEncryptBootVolume {
errs = append(errs, fmt.Errorf("Cannot share snapshot encrypted with default KMS key"))
}
if len(errs) > 0 {
return errs
}

View File

@ -77,6 +77,22 @@ func (s *stepCreateEncryptedAMICopy) Run(state multistep.StateBag) multistep.Ste
return multistep.ActionHalt
}
// Get the encrypted AMI image, we need the new snapshot id's
encImagesResp, err := ec2conn.DescribeImages(&ec2.DescribeImagesInput{ImageIds: []*string{aws.String(*copyResp.ImageId)}})
if err != nil {
err := fmt.Errorf("Error searching for AMI: %s", err)
state.Put("error", err)
ui.Error(err.Error())
return multistep.ActionHalt
}
encImage := encImagesResp.Images[0]
var encSnapshots []string
for _, blockDevice := range encImage.BlockDeviceMappings {
if blockDevice.Ebs != nil && blockDevice.Ebs.SnapshotId != nil {
encSnapshots = append(encSnapshots, *blockDevice.Ebs.SnapshotId)
}
}
// Get the unencrypted AMI image
unencImagesResp, err := ec2conn.DescribeImages(&ec2.DescribeImagesInput{ImageIds: []*string{aws.String(id)}})
if err != nil {
@ -97,10 +113,10 @@ func (s *stepCreateEncryptedAMICopy) Run(state multistep.StateBag) multistep.Ste
// Remove associated unencrypted snapshot(s)
ui.Say("Deleting unencrypted snapshots")
snapshots := state.Get("snapshots").(map[string][]string)
for _, blockDevice := range unencImage.BlockDeviceMappings {
if blockDevice.Ebs != nil {
if blockDevice.Ebs.SnapshotId != nil {
if blockDevice.Ebs != nil && blockDevice.Ebs.SnapshotId != nil {
ui.Message(fmt.Sprintf("Snapshot ID: %s", *blockDevice.Ebs.SnapshotId))
deleteSnapOpts := &ec2.DeleteSnapshotInput{
SnapshotId: aws.String(*blockDevice.Ebs.SnapshotId),
@ -111,11 +127,12 @@ func (s *stepCreateEncryptedAMICopy) Run(state multistep.StateBag) multistep.Ste
}
}
}
}
// Replace original AMI ID with Encrypted ID in state
amis[region] = *copyResp.ImageId
snapshots[region] = encSnapshots
state.Put("amis", amis)
state.Put("snapshots", snapshots)
imagesResp, err := ec2conn.DescribeImages(&ec2.DescribeImagesInput{ImageIds: []*string{copyResp.ImageId}})
if err != nil {

View File

@ -129,7 +129,7 @@ Packer to work:
"ec2:GetPasswordData",
"ec2:ModifyImageAttribute",
"ec2:ModifyInstanceAttribute",
"ec2:ModifySnapshotAttribute"
"ec2:ModifySnapshotAttribute",
"ec2:RegisterImage",
"ec2:RunInstances",
"ec2:StopInstances",