New-AwsVM.ps1


<#PSScriptInfo
 
.VERSION 1.1
 
.GUID 854b9a68-5718-4836-b04d-077e81d93d63
 
.AUTHOR Tiander Turpijn
 
.COMPANYNAME
 
.COPYRIGHT
 
.TAGS
 
.LICENSEURI
 
.PROJECTURI
 
.ICONURI
 
.EXTERNALMODULEDEPENDENCIES
 
.REQUIREDSCRIPTS
 
.EXTERNALSCRIPTDEPENDENCIES
 
#ToDO
#Change the default values for the following parameters if they do not match with yours:
#AWSRegion, EC2ImageName, MinCount, MaxCount,InstanceType
#Create an Azure Automation Asset called "AwsCred"
#Turn on Log verbose records and optionally Log progress records under the runbook settings to see verbose messages and progress
 
 
#>


<#
 
.DESCRIPTION
 Provisions a new Amazon Web Services (AWS) Virtual Machine
 
#>
 


param (
    [Parameter(Mandatory=$true)]
    [string]$VMname,
    [ValidateNotNullOrEmpty()]
    [string]$AWSRegion = "us-west-2",
    [ValidateNotNullOrEmpty()]
    [string]$EC2ImageName = "WINDOWS_2012R2_BASE",
    [ValidateNotNullOrEmpty()]
    [string]$MinCount = 1,
    [ValidateNotNullOrEmpty()]
    [string]$MaxCount = 1,
    [ValidateNotNullOrEmpty()]
    [string]$InstanceType = "t2.micro"
    )

# Get credentials to authenticate against AWS
$AwsCred = Get-AutomationPSCredential -Name "AwsCred"
$AwsAccessKeyId = $AwsCred.UserName
$AwsSecretKey = $AwsCred.GetNetworkCredential().Password

# Set up the AWS environment
Write-Verbose "Authenticating against AWS..."
Set-AWSCredentials -AccessKey $AwsAccessKeyId -SecretKey $AwsSecretKey -StoreAs AWSProfile
Set-DefaultAWSRegion -Region $AWSRegion

Write-Verbose "Getting AWS Image..."
$ami = Get-EC2ImageByName $EC2ImageName -ProfileName AWSProfile -ErrorAction Stop

#Check if our AWS image is valid
If([string]::IsNullOrEmpty($ami)) {            
    throw "No Image has been found!"            
} else {            
    Write-Verbose ("The following image has been found: " + $ami.Name)            
}

#Creating new VM
Write-Verbose "Creating new AWS Instance..."
$NewVM = New-EC2Instance `
    -ImageId $ami.ImageId `
    -MinCount $MinCount `
    -MaxCount $MaxCount `
    -InstanceType $InstanceType `
    -ProfileName AWSProfile `
    -ErrorAction Stop
 $InstanceID = $NewVM.Instances.InstanceID
 $NewVM

#Applying VMName - also known as an AWS Tag
Write-Verbose "Applying new VM Name...."
New-EC2Tag -Resource $InstanceID -Tag @( @{ Key = "Name" ; Value = $VMname}) -ProfileName AWSProfile
Write-Verbose ("Successfully created AWS VM: " + $VMname)