AWS Developer Blog

Using Elastic IP Addresses

by Norm Johanson | on | in .NET | Permalink | Comments |  Share

Elastic IP addresses are great for keeping a consistent public IP address. They can also be transferred to other EC2 instances, which is useful if you need to replace an instance but don’t want your public IP address to change. The Amazon EC2 User Guide has information on IP addresses for EC2 instances that can give you a better understanding of how and when they are assigned. You can use the AWS Toolkit for Visual Studio or the AWS Management Console to manage your Elastic IP addresses, but what if you want to assign them from code?

To allocate Elastic IP addresses and associate them using the AWS SDK for .NET is very simple, but it differs slightly between EC2-Classic instances and instances launched into a VPC. This snippet shows how to allocate and associate an Elastic IP address for an instance launched into EC2-Classic.

// Create a new Elastic IP
var allocateRequest = new AllocateAddressRequest() { Domain = DomainType.Standard };
var allocateResponse = ec2Client.AllocateAddress(allocateRequest);

// Assign the IP to an EC2 instance
var associateRequest = new AssociateAddressRequest
{
    PublicIp = allocateResponse.PublicIp,
    InstanceId = "i-XXXXXXXX"
};
ec2Client.AssociateAddress(associateRequest);

And the following snippet is for an EC2 instance launched into a VPC.

// Create a new Elastic IP
var allocateRequest = new AllocateAddressRequest() { Domain = DomainType.Vpc };
var allocateResponse = ec2Client.AllocateAddress(allocateRequest);

// Assign the IP to an EC2 instance
var associateRequest = new AssociateAddressRequest
{
    AllocationId = allocateResponse.AllocationId,
    InstanceId = "i-XXXXXXXX"
};
ec2Client.AssociateAddress(associateRequest);

The difference between the two pieces of code is that the Domain property on AllocateAddressRequest is changed from DomainType.Standard to DomainType.Vpc. The other difference is that the address associated with the PublicIp property is used for EC2-Classic, whereas AllocationId is used for EC2-VPC.

Later, if the Elastic IP address needs to be changed to a different instance, the ReleaseAddress API can be called, and then AssociateAddress can be called again on the new instance.

Note, I was using Version 2 of the SDK for this blog. If you are using Version 1 of the SDK, the enumerations DomainType.Standard and DomainType.Vpc would be replaced with the string literals "standard" and "vpc".

Using Windows PowerShell

This is also a great use for the AWS Tools for Windows PowerShell. Here’s how you can do the same as above for EC2-Classic in PowerShell.

$address = New-EC2Address -Domain "standard"
Register-EC2Address -InstanceId "i-XXXXXXXX" -PublicIp $address.PublicIp