How to change the tenancy of multiple EC2 instances from ‘dedicated’ to ‘default’ using PowerShell (and also how to encrypt the EBS volumes)

I was recently asked to change the tenancy of several EC2 instances from ‘dedicated’ to ‘default’, which basically means that these instances will not use dedicated hardware to run, instead, they will run on hardware shared with other tenants (it is less expensive).

AWS won’t let you change the tenancy of an instance once it has been started. So, what you have to do is to create an AMI (Amazon Machine Image), recreate the instance using that AMI as a template, and copy the instance details by hand (such as IP address, tags, UserData, etc.), which makes this process prone to human error.

Also many EBS volumes of these instances were encrypted using a wrong Key, so I had to re-encrypt them using the right one.

In order to avoid errors and lots of work, I created the next script, which hopefully, might help you too!



Notes:

-You have to install AWS PowerShell Tools first.
-Then you have to configure AWS CLI Credentials.
-Make sure the script migrates all of the attributes your instances use, we migrated most of them, but not all.
-Once the process is finished, make sure the instances were migrated correctly, then you will have to manually delete the created AMIs and its snapshots from the AWS EC2 console.
-You can always go to the log file to get the instance information in order to rebuild it manually from the AMI, if the creation of the new instance fails after the original instance is terminated.


See you around!