For EC2's that are started up infrequently it can be time consuming to go through the AWS Management login with MFA just to start them up, this powershell script uses the AWSPowerShell module along with API keys to startup the specified EC2 instance.
Within the AWS Management Console > EC2, note the Instance ID(s) you would like to start up on an ad-hoc basis
Create the IAM policy
Within IAM > Policies create a new policy, select the JSON tab and paste the code below replacing <instance id 1> and <instance id 2> with your instance ID's.
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "VisualEditor0",
"Effect": "Allow",
"Action": [
"ec2:StartInstances"
],
"Resource": [
"arn:aws:ec2:*:*:instance/<instance id 1>",
"arn:aws:ec2:*:*:instance/<instance id 2>"
]
},
{
"Sid": "VisualEditor1",
"Effect": "Allow",
"Action": [
"ec2:DescribeInstances"
],
"Resource": "*"
}
]
}
Click review
On the Next page give it a logical name, description and create the policy
Create the Access Keys
Within IAM > Users > Add User create a new user with a logical name and set the access type has programmatic access, i.e.
On the permissions page, select "Attach existing policies directly" then search and select the policy created earlier, add any tags, review and a new user should be created with an access key and secret key ID for use in the powershell script, download these for later use as .csv
Install the AWSPowerShell module
Run powershell as administrator and install the AWS Powershell module with the following command,
Install-Module -Name AWSPowerShell
Create the Powershell script
Copy the script below into notepad, update the access key, secret key, region and instance id then save this file with a .ps1 extension
# A powershell script to power up EC2's as required
# Set API Keys
Set-AWSCredentials -AccessKey <Access Key> -SecretKey <Secret Key>
# Set AWS Region, for example eu-west-1
Set-DefaultAWSRegion <region>
# Power on EC2, to add more EC2's just copy and paste replacing the instance id
Get-EC2Instance -InstanceId <Instance ID> | Start-EC2Instance
Providing the AWS Powershell module is installed, your IAM policy is correct and your powershell values are correct, it should now be a case of running the script and after a minute or so your EC2 should be ready to work with. You can monitor this within your EC2 management page refreshing as you go.
A similar script could easily be created to power down your EC2's to keep your on-demand costs to a minimum.