Start Instance & Assign ElasticIP on AWS with Powershell

Here’s a script to start an EC2 instance and assign an elastic ip to said instance.  I knocked this together from a couple of other scripts, to which I don’t have the link to anymore. 

	[string]$instanceID = "InstanceID",  
	[string]$keyID = "KeyID",
	[string]$accessKeyID = "SecretAccessKeyID",
	[string]$EIP = "xx.xx.xx.xx",


Add-Type -Path "C:\Program Files (x86)\AWS SDK for .NET\bin\AWSSDK.dll"

$config=New-Object Amazon.EC2.AmazonEC2Config
$config.ServiceURL = $ServiceURL

$ec2 = [Amazon.AWSClientFactory]::CreateAmazonEC2Client($keyID,$accessKeyID, $config)
$startReq = New-Object amazon.EC2.Model.StartInstancesRequest
$startResponse = $ec2.StartInstances($startReq)
$startResult = $startResponse.StartInstancesResult;

$request = New-Object -TypeName Amazon.EC2.Model.DescribeAddressesRequest
$result = New-Object -TypeName Amazon.EC2.Model.DescribeAddressesResponse
    $result = $client.DescribeAddresses($request)
    echo "Failed to validate EIP $instanceEIP, ensure that it is allocated and associated with your account.  Aborting."
    exit 2

# See if an instanceID is already assigned to this EIP
$xml = $result.ToXML()
$assignedInstanceID = [string]($xml.DescribeAddressesResponse.DescribeAddressesResult.Address.InstanceId)

# Run this block if an Instance already has this EIP associated to it... just in case changes would
# result in downtime (i.e. if we are launching a test system from a cloned production one).
if ($assignedInstanceID) 
  echo "Address $EIP already assigned to: $assignedInstanceID, aborting."
  exit 1

# If we get here, the IP is free and clear, go ahead and associate it.
$request = New-Object -TypeName Amazon.EC2.Model.AssociateAddressRequest

$result = $client.AssociateAddress($request)
if ($result) 
  echo "Address $EIP assigned to $instanceID successfully."
  exit 0
  echo "Failed to assign $EIP to $instanceID."
  exit 3

Here is the code to stop an instance.

	[string]$instanceID = "InstanceID",
	[string]$keyID = "KeyID",
	[string]$accessKeyID = "AccessKeyID"

Add-Type -Path "C:\Program Files (x86)\AWS SDK for .NET\bin\AWSSDK.dll"

$ec2 = [Amazon.AWSClientFactory]::CreateAmazonEC2Client($keyID,$accessKeyID)

$stopReq = New-Object amazon.EC2.Model.StopInstancesRequest
$stopResponse = $ec2.StopInstances($stopReq)
$stopResult = $stopResponse.StopInstancesResult;

Leave a Reply

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

You are commenting using your 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 )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.