Skip to content

Instantly share code, notes, and snippets.

@tridevgurung
Last active August 29, 2015 14:03
Show Gist options
  • Save tridevgurung/568b84a306813d472a31 to your computer and use it in GitHub Desktop.
Save tridevgurung/568b84a306813d472a31 to your computer and use it in GitHub Desktop.
ASSIGN AWS ELASTIC IP (EIP) WITH WINDOWS POWERSHELL
# User modifyable items: #################################################
# Update to the AWS SDK Path on your system, if not default
Add-Type -Path "C:\Program Files (x86)\AWS SDK for .NET\bin\AWSSDK.dll"
# Update the following lines, as needed:
$accessKeyID="your access key ID"
$secretAccessKey="your secret access key"
$instanceID="i-your instance id"
$instanceEIP="x.x.x.x"
# Uncomment ONE of the following, which applies to your region
# US-West N. California:
$ServiceURL="https://ec2.us-west-1.amazonaws.com"
# US-West Oregon
#$ServiceURL="https://ec2.us-west-2.amazonaws.com"
# US-East (Standard)
#$ServiceURL="https://ec2.us-east-1.amazonaws.com"
# END User configurable options ##########################################
$config=New-Object Amazon.EC2.AmazonEC2Config
$config.ServiceURL = $ServiceURL
$client=[Amazon.AWSClientFactory]::CreateAmazonEC2Client($accessKeyID,$secretAccessKey,$config)
# See if the IP is already assigned somewhere
$request = New-Object -TypeName Amazon.EC2.Model.DescribeAddressesRequest
[void]$request.WithPublicIp($instanceEIP)
$result = New-Object -TypeName Amazon.EC2.Model.DescribeAddressesResponse
try {
$result = $client.DescribeAddresses($request)
}
catch {
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=[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 $instanceEIP 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
[void]$request.WithInstanceId($instanceID)
[void]$request.WithPublicIp($instanceEIP)
$result = $client.AssociateAddress($request)
if ($result) {
echo "Address $instanceEIP assigned to $instanceID successfully."
exit 0
}
else {
echo "Failed to assign $instanceEIP to $instanceID."
exit 3
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment