Weekend Learning: Day 1 – Deploy in AWS using PowerShell

Today’s post I will start by setting up PowerShell and use it to deploy a EC2 Instance, stopping, starting and finally terminating it. Yes all using PowerShell.
You need to have an AWS Account and would need the AccessKey & SecretKey of the account that you would like to use.
To get your access key ID and secret access key, Login to your AWS Account. Open the IAM console from the navigation menu, click Users. Select your IAM user name Click User Actions, and then click Manage Access Keys. Click Create Access Key.
You would also need AWS Tool for Windows PowerShell, you could google for it download and install it on a machine with PowerShell version 2 or higher (I am using version 5).
Ok, So lets get started !!
First Step is to Import AWS PowerShell Module and we can do that by running the following command
# Import AWS PowerShell Module
Import-Module AWSPowerShell
Lets check to see if the AWS Powershell Module is imported and working, I like to do this by run the below command to get the AWS Regions.
# Get AWS Region
Get-AWSRegion

get-awsregion

AWS Powershell Module provide a way to store access key ID and secret access key into the credential store and assign it a profile name, here it is called DMPSH. Command takes 3 Mandatory Parameters, -StoreAs this is the profile name, -AccessKey which is your access key ID and -SecretKey this is the secret key for your access key ID.
I have saved my access key ID and secret access key into variable $AccessKey and $SecretKey so that I can avoid showing you my keys in plain text here.
#Setup Profile with AWS Credentials
Set-AWSCredentials -StoreAs DMPSH -AccessKey $AccessKey -SecretKey $SecretKey
By setting up a profile, you can use the profilename parameter instead of passing the Accesskey and SecretKey  as parameters for the AWS commands.
Next we need to find the available AMI in my region, the region that is closest to where I am is Mumbai which is ap-south-1. We can do that by running the below command with the -Region parameter.
#Get Windows AMI by name in Mumbai
Get-EC2ImageByName -Region ap-south-1
get-ec2imagebyname
You can see that this will list only Windows AMI, to get RHEL AMI we will need to use the below command and filter the Name with RHEL , we will also need to pass the -Profilename Parameter to authenticate to AWS and – Region.
#Get RHEL AMI by name in Mumbai
Get-EC2Image -Filter @{Name="name";Values="RHEL-*"} -ProfileName DMPSH -Region ap-south-1 | Select-Object -Property Name

get-ec2imagerhel

Before we can deploy an EC2 Instance we need a couple more things, One is an Keypair that will be used to encrypt the Administrator password and the AMI ID.
I will first create the keypair and then store the Key to a file using the below command, so that I can use them in a future post.
#create a KeyPair, this is used to encrypt the Administrator password.
$mumbaikey = New-EC2KeyPair -KeyName mumbai-key -ProfileName DMPSH -Region ap-south-1

# Save the KeyPair to a File
$folder = "G:\AWS Powershell"
"$($mumbaikey.KeyMaterial)" | out-file -encoding ascii -filepath $folder\mumbaikey.pem
"KeyName: $($mumbaikey.KeyName)" | out-file -encoding ascii -filepath $folder\mumbaikey.pem -Append
"KeyFingerprint: $($mumbaikey.KeyFingerprint)" | out-file -encoding ascii -filepath $folder\mumbaikey.pem -Append
Next I need the AMI Id, I want to deploy an Windows Server 2012 R2 Server. Running the below command and assigning it to a variable will save the AMI Id into a variable called $ami
#Get AMI Id for Windows Server 2012 R2
$ami = Get-EC2ImageByName WINDOWS_2012R2_BASE -ProfileName DMPSH -Region ap-south-1 | Select-Object -First 1 -ExpandProperty ImageId
$ami

amiid

One last thing, we need to have a way to know what is the Status of the deployment. For that I have written the below function that takes 4 parameters the instanceid, ProfileName, AWS Region and Desired State of the Instance like running, stopped etc.
# Wait until desired state of an instance
function Wait-DMAWSState ($instanceId, $DMProfileName, $DMRegion, $desiredstate)
{
    while ($true)
    {
        # Get the Instance
        $a = Get-EC2Instance -Filter @{Name = "instance-id"; Values = $instanceId} -ProfileName $DMProfileName -Region $DMRegion
        # Get the Current State of the Instance
        $currentstate = $a.Instances[0].State.Name
        #Check if the Instance is in the desired State
        if ($currentstate -eq $desiredstate)
        {
            Write-Output "$(Get-Date) Instance $instanceId is $currentstate"
            break;
        }
        Write-Output "$(Get-Date) Current State of Instance $instanceId is $currentstate, Waiting to be $desiredstate"
        Sleep -Seconds 5
    }
}
Now that we have everything that we need, Lets go ahead and deploy an Windows EC2 Instance
# Deploy EC2 Instance and Pass the Instances Property into variable
$newinst = New-EC2Instance -ImageId $ami -InstanceType t2.micro -KeyName mumbai-key -ProfileName DMPSH -Region ap-south-1 | Select-Object -ExpandProperty Instances
$newinst.InstanceId
Here is the instance id of the EC2 Instance we just deployed

instanceid

Lets quickly run the Function to check the desired status of the EC2 Instance, We need the Instance in running status
#Verify the Instance is Running
Wait-DMAWSState -instanceId $newinst.InstanceId -DMProfileName "DMPSH" -DMRegion "ap-south-1" -desiredstate "running"
You can see here that it is pending and then the state becomes running

initialstate

Here is a screen shot of AWS Console..

awsconsole

Now Lets Stop the EC2 Instance and also run the function to check the desired status of stopped at once.
#Stop the EC2 Instance
Stop-EC2Instance -InstanceId $newinst.InstanceId -ProfileName DMPSH -Region ap-south-1
#Verify the Instance is Stopped
Wait-DMAWSState -instanceId $newinst.InstanceId -DMProfileName "DMPSH" -DMRegion "ap-south-1" -desiredstate "stopped"

stopinstance

stopconsole

Lets Start the Instance back up..
#Start the EC2 Instance
Start-EC2Instance -InstanceId $newinst.InstanceId -ProfileName DMPSH -Region ap-south-1
#Verify the Instance is Running
Wait-DMAWSState -instanceId $newinst.InstanceId -DMProfileName "DMPSH" -DMRegion "ap-south-1" -desiredstate "running"

startinstance

Finally lets Terminate the EC2 Instance..
#Terminate the EC2 Instance
Remove-EC2Instance -InstanceId $newinst.InstanceId -ProfileName DMPSH -Region ap-south-1 -Confirm:$false
#Verify the Instance is terminated
Wait-DMAWSState -instanceId $newinst.InstanceId -DMProfileName "DMPSH" -DMRegion "ap-south-1" -desiredstate "terminated"

terminateinstance

terminateconsole

That brings us to the end of today’s blog Post. In the upcoming blog post we will do more advance tasks in AWS using PowerShell..

!! Preenesh

Advertisements
This entry was posted in Powershell and tagged , . Bookmark the permalink.

One Response to Weekend Learning: Day 1 – Deploy in AWS using PowerShell

  1. Pingback: Weekend Learning: Day 2 – Resume Windows Server Configuration after Restart using userdata in AWS using PowerShell | Deployment Mechanic

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s