How do I create an AWS EC2 Instance with an encrypted instance storage EBS volume with Powershell?

Viewed 119

I am attempting to build a script that deploys an EC2 instance with an instance storage volume that is both slightly larger than the default for the AMI selected and encrypted with a KMS key.

When running the below code, the instance is created then immediately shuts down and terminates.

#Build KMS Key
$kms = New-KMSKey

#Build BlockDeviceMapping and EBSBlockDevice
$bdm = New-Object Amazon.EC2.Model.BlockDeviceMapping
$ebs = New-Object Amazon.EC2.Model.EbsBlockDevice
$bdm.VirtualName = "ephemeral0"
$bdm.DeviceName = "/dev/sda1"
$bdm.EBS = $ebs
$ebs.VolumeSize = 60
$ebs.VolumeType = 'standard'
$ebs.Encrypted = $true
$ebs.KmsKeyId = $kms.KeyId

#Create EC2 Instance (with breaks for easy reading on StackOverflow)
New-EC2Instance -ImageId ami-0aad84f764a2bd39a -InstanceType m5.large `
-BlockDeviceMapping $bdm -SubnetId subnet-07edc15b92714e094 `
-SecurityGroupId sg-00e44cd81c970243b

When watching this occur in the console, it looks like there's a problem with the volume not properly creating. If I run the above code without the $ebs.encrypted and $ebs.KmsKeyId values, the instance deploys without a problem.

When reviewing the attributes for $ebs, I can see that the Encrypted and KmsKeyId values are properly populated on the object.

DeleteOnTermination : False
Encrypted           : True
Iops                : 0
KmsKeyId            : 5d08e2fb-59ff-464b-a2ad-3cce90b7bb7f
OutpostArn          :
SnapshotId          :
Throughput          : 0
VolumeSize          : 60
VolumeType          : standard

Is this a syntax problem with my code or is there something that would stop an instance storage volume from being encrypted systematically upon creation?

0 Answers
Related