Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 44 additions & 18 deletions aws/resource_aws_instance.go
Original file line number Diff line number Diff line change
Expand Up @@ -336,6 +336,12 @@ func resourceAwsInstance() *schema.Resource {
ForceNew: true,
},

"kms_key_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},

"iops": {
Type: schema.TypeInt,
Optional: true,
Expand Down Expand Up @@ -432,6 +438,19 @@ func resourceAwsInstance() *schema.Resource {
ForceNew: true,
},

"encrypted": {
Type: schema.TypeBool,
Optional: true,
Computed: true,
ForceNew: true,
},

"kms_key_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},

"iops": {
Type: schema.TypeInt,
Optional: true,
Expand Down Expand Up @@ -1321,16 +1340,19 @@ func readBlockDevicesFromInstance(instance *ec2.Instance, conn *ec2.EC2) (map[st
if vol.Iops != nil {
bd["iops"] = *vol.Iops
}
if vol.Encrypted != nil {
bd["encrypted"] = *vol.Encrypted
}
if vol.KmsKeyId != nil {
bd["kms_key_id"] = *vol.KmsKeyId
}

if blockDeviceIsRoot(instanceBd, instance) {
blockDevices["root"] = bd
} else {
if instanceBd.DeviceName != nil {
bd["device_name"] = *instanceBd.DeviceName
}
if vol.Encrypted != nil {
bd["encrypted"] = *vol.Encrypted
}
if vol.SnapshotId != nil {
bd["snapshot_id"] = *vol.SnapshotId
}
Expand Down Expand Up @@ -1363,15 +1385,15 @@ func fetchRootDeviceName(ami string, conn *ec2.EC2) (*string, error) {

// For a bad image, we just return nil so we don't block a refresh
if len(res.Images) == 0 {
return nil, nil
return nil, fmt.Errorf("No images found for AMI %s", ami)
}

image := res.Images[0]
rootDeviceName := image.RootDeviceName

// Instance store backed AMIs do not provide a root device name.
if *image.RootDeviceType == ec2.DeviceTypeInstanceStore {
return nil, nil
return nil, fmt.Errorf("Instance store backed AMIs do not provide a root device name - Use an EBS AMI")
}

// Some AMIs have a RootDeviceName like "/dev/sda1" that does not appear as a
Expand Down Expand Up @@ -1491,6 +1513,10 @@ func readBlockDeviceMappingsFromConfig(
ebs.Encrypted = aws.Bool(v)
}

if v, ok := bd["kms_key_id"].(string); ok && v != "" {
ebs.KmsKeyId = aws.String(v)
}

if v, ok := bd["volume_size"].(int); ok && v != 0 {
ebs.VolumeSize = aws.Int64(int64(v))
}
Expand Down Expand Up @@ -1546,6 +1572,11 @@ func readBlockDeviceMappingsFromConfig(
bd := v.(map[string]interface{})
ebs := &ec2.EbsBlockDevice{
DeleteOnTermination: aws.Bool(bd["delete_on_termination"].(bool)),
Encrypted: aws.Bool(bd["encrypted"].(bool)),
}

if v, ok := bd["kms_key_id"].(int); ok && v != 0 {
ebs.KmsKeyId = aws.String(bd["kms_key_id"].(string))
}

if v, ok := bd["volume_size"].(int); ok && v != 0 {
Expand All @@ -1568,20 +1599,15 @@ func readBlockDeviceMappingsFromConfig(
log.Print("[WARN] IOPs is only valid for storate type io1 for EBS Volumes")
}

if dn, err := fetchRootDeviceName(d.Get("ami").(string), conn); err == nil {
if dn == nil {
return nil, fmt.Errorf(
"Expected 1 AMI for ID: %s, got none",
d.Get("ami").(string))
}

blockDevices = append(blockDevices, &ec2.BlockDeviceMapping{
DeviceName: dn,
Ebs: ebs,
})
} else {
return nil, err
dn, err := fetchRootDeviceName(d.Get("ami").(string), conn)
if err != nil {
return nil, fmt.Errorf("Expected 1 AMI for ID: %s (%s)", d.Get("ami").(string), err)
}

blockDevices = append(blockDevices, &ec2.BlockDeviceMapping{
DeviceName: dn,
Ebs: ebs,
})
}
}

Expand Down
95 changes: 89 additions & 6 deletions aws/resource_aws_instance_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -120,10 +120,7 @@ func TestFetchRootDevice(t *testing.T) {
data := r.Data.(*ec2.DescribeImagesOutput)
data.Images = tc.images
})
name, err := fetchRootDeviceName("ami-123", conn)
if err != nil {
t.Errorf("Error fetching device name: %s", err)
}
name, _ := fetchRootDeviceName("ami-123", conn)
if tc.name != aws.StringValue(name) {
t.Errorf("Expected name %s, got %s", tc.name, aws.StringValue(name))
}
Expand Down Expand Up @@ -320,6 +317,32 @@ func TestAccAWSInstance_basic(t *testing.T) {
})
}

func TestAccAWSInstance_encryptedRootVolume(t *testing.T) {
var v ec2.Instance

resource.ParallelTest(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
IDRefreshName: "aws_instance.foo",
Providers: testAccProviders,
CheckDestroy: testAccCheckInstanceDestroy,
Steps: []resource.TestStep{
{
Config: testAccCheckInstanceEncryptedRootVolume,
Check: resource.ComposeTestCheckFunc(
testAccCheckInstanceExists(
"aws_instance.foo", &v),
resource.TestCheckResourceAttr(
"aws_instance.foo", "root_block_device.#", "1"),
resource.TestCheckResourceAttr(
"aws_instance.foo", "root_block_device.0.encrypted", "true"),
resource.TestCheckResourceAttrSet(
"aws_instance.foo", "root_block_device.0.kms_key_id"),
),
},
},
})
}

func TestAccAWSInstance_userDataBase64(t *testing.T) {
var v ec2.Instance

Expand Down Expand Up @@ -497,6 +520,8 @@ func TestAccAWSInstance_blockDevices(t *testing.T) {
"aws_instance.foo", "ebs_block_device.2634515331.device_name", "/dev/sdd"),
resource.TestCheckResourceAttr(
"aws_instance.foo", "ebs_block_device.2634515331.encrypted", "true"),
resource.TestCheckResourceAttrSet(
"aws_instance.foo", "ebs_block_device.2634515331.kms_key_id"),
resource.TestCheckResourceAttr(
"aws_instance.foo", "ebs_block_device.2634515331.volume_size", "12"),
resource.TestCheckResourceAttr(
Expand Down Expand Up @@ -2423,9 +2448,30 @@ resource "aws_instance" "foo" {
`

const testAccInstanceConfigBlockDevices = `
resource "aws_vpc" "foo" {
cidr_block = "10.1.0.0/16"

tags {
Name = "terraform-testacc-instance-source-dest-enable"
}
}

resource "aws_subnet" "foo" {
cidr_block = "10.1.1.0/24"
vpc_id = "${aws_vpc.foo.id}"
availability_zone = "us-west-2a"

tags {
Name = "tf-acc-instance-source-dest-enable"
}
}

resource "aws_kms_key" "foo" {}

resource "aws_instance" "foo" {
# us-west-2
ami = "ami-55a7ea65"
ami = "ami-55a7ea65"
subnet_id = "${aws_subnet.foo.id}"

# In order to attach an encrypted volume to an instance you need to have an
# m3.medium or larger. See "Supported Instance Types" in:
Expand All @@ -2436,10 +2482,12 @@ resource "aws_instance" "foo" {
volume_type = "gp2"
volume_size = 11
}

ebs_block_device {
device_name = "/dev/sdb"
volume_size = 9
}

ebs_block_device {
device_name = "/dev/sdc"
volume_size = 10
Expand All @@ -2451,7 +2499,8 @@ resource "aws_instance" "foo" {
ebs_block_device {
device_name = "/dev/sdd"
volume_size = 12
encrypted = true
encrypted = true
kms_key_id = "${aws_kms_key.foo.arn}"
}

ephemeral_block_device {
Expand Down Expand Up @@ -2731,6 +2780,40 @@ resource "aws_instance" "foo" {
}
`

const testAccCheckInstanceEncryptedRootVolume = `
resource "aws_vpc" "foo" {
cidr_block = "10.1.0.0/16"

tags {
Name = "terraform-testacc-instance-source-dest-enable"
}
}

resource "aws_subnet" "foo" {
cidr_block = "10.1.1.0/24"
vpc_id = "${aws_vpc.foo.id}"
availability_zone = "us-west-2a"

tags {
Name = "tf-acc-instance-source-dest-enable"
}
}

resource "aws_kms_key" "foo" {}

resource "aws_instance" "foo" {
ami = "ami-08692d171e3cf02d6"
instance_type = "t3.nano"
subnet_id = "${aws_subnet.foo.id}"

root_block_device {
delete_on_termination = true
encrypted = true
kms_key_id = "${aws_kms_key.foo.arn}"
}
}
`

const testAccCheckInstanceConfigWithAttachedVolume = `
data "aws_ami" "debian_jessie_latest" {
most_recent = true
Expand Down
3 changes: 3 additions & 0 deletions website/docs/r/instance.html.markdown
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,8 @@ The `root_block_device` mapping supports the following:
using that type
* `delete_on_termination` - (Optional) Whether the volume should be destroyed
on instance termination (Default: `true`).
* `encrypted` - (Optional) Enable volume encryption. (Default: `false`).
* `kms_key_id` - (Optional) The KMS key to use when encrypting the volume.

Modifying any of the `root_block_device` settings requires resource
replacement.
Expand All @@ -150,6 +152,7 @@ Each `ebs_block_device` supports the following:
* `encrypted` - (Optional) Enables [EBS
encryption](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html)
on the volume (Default: `false`). Cannot be used with `snapshot_id`.
* `kms_key_id` - (Optional) The KMS key to use when encrypting the volume.

Modifying any `ebs_block_device` currently requires resource replacement.

Expand Down