How to Associate Elastic IP with EC2 Instance using CloudFormation

How to Associate Elastic IP with EC2 Instance using CloudFormation
Sharing is Caring:

How to Associate Elastic IP with EC2 Instance using CloudFormation

Dear Reader, hope you are doing good. In my previous post, we talked about Elastic IP and it’s significance with respect to EC2 Instance.

We also allocated an elastic IP to our account and then associated that to one of our running instance. In this post, we will do the same thing but instead of doing it manually, we will do it using CloudFormation.

Basic Overview

When you launch an EC2 instance in a default VPC, a public IP gets automatically assigned to your instance at launch. You can use that public IP to connect to(SSH) your instance or to access it over internet via public IP or pubic DNS.

So far so good 🙂

However, usually when you stop your instance and start it again, due to the dynamic nature of pubic IP ,your instance’s public IP changes and you no more can access your instance using previous pubic IP.

It becomes even more difficult when you have A records in route 53 mapping to your instance’s public IP. It simply doesn’t make sense to update the A record every time your instance change the IP.

One of the solution in such cases is to assign an elastic IP which is a static public IP and will not change. Read my previous post to understand it in even more details(Link below).

Suggested Read: How to Assign an Elastic IP to your EC2 Instance in AWS

Steps to Associate Elastic IP with EC2 Instance using CloudFormation

Let’s see the step by step instruction to associate Elastic IP with EC2 Instance using CloudFormation

Step 1: Permission

If you are not an admin user, you should at least provide below mentioned permissions explicitly to your user/role that will create the CloudFormation Stack.

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "Stmt1634732138851",
      "Action": [
        "ec2:AllocateAddress",
        "ec2:AssociateAddress",
        "ec2:ReleaseAddress",
        "ec2:StartInstances",
        "ec2:StopInstances",
        "ec2:TerminateInstances",
        "ec2:DisassociateAddress",
        "ec2:RunInstances"
      ]

    }
  ]
}

Note: You will also needs cloudformation:* to do CloudFormation stack operations. Also for creating this stack if you face permission issue, you can try ec2:*

Step 2: Prepare a template

You can use YAML or JSON for your template. I prefer YAML for writing my templates. But don’t worry, If you want it in JSON, I will provide JSON template as well.

As you might already know, before we can associate an elastic IP to EC2 instance, we need to allocate an elastic IP to our account. Once allocated, you can associate with any of your instance.

Allocate Elastic IP to Your Account

To allocate an elastic IP to your account, all you need is a AWS::EC2::EIP resource.

  DemoElasticIP:
    Type: AWS::EC2::EIP

Okay, so we know how to allocate an EIP but what about associating them with an actual instance?

Well, the simplest way to associate an Elastic IP to an EC2 instance is using the InstanceId property of AWS::EC2::EIP resource.

That means, while allocating an elastic IP to your AWS account using CloudFormation, you have an option to specify AWS EC2 instance Id to which you would like to associate this EIP with. for example-

  DemoElasticIP:
    Type: AWS::EC2::EIP
    Properties:
      Domain: vpc
      InstanceId: !Ref DemoInstance 

Few things to note there –

  • Domain is used to specify whether the elastic IP is to be used with an instance in VPC or in EC2-Classic
    • VPC: vpc
    • EC2-Classic: standard 
  • If your region supports EC2-Classic, default value of this property is standard otherwise vpc
  • InstanceId property is available to you to associate this newly created EIP with an EC2 instance.
  • I have used !Ref: DemoInstance in InstanceId property because I am creating EC2 in the same template and using !Ref on the logical Id of an EC2 resource returns it’s InstanceId.
  • For other available properties for this resources, check official documentation

Template to Associate Elastic IP with EC2 Instance using CloudFormation : YAML

In this template, we are launching an EC2 instance, allocating an elastic IP and associating that IP with our EC2 instance.

AWSTemplateFormatVersion: '2010-09-09'
Description: Template to Create an EC2 instance, EIP and associate with instance
   
Parameters:

  ImageId:
    Type: String
    Description: 'Linux 2 AMI for Ireland eu-west1 Region'
    Default: 'ami-0fc970315c2d38f01'
  InstanceType:
    Type: String
    Description: Choosing  t2 micro because it is free
    Default: t2.micro
  KeyName:
    Description: SSH Keypair to login to the instance
    Type: AWS::EC2::KeyPair::KeyName
    Default: demokeypair

Resources:
  DemoInstance:
    Type: 'AWS::EC2::Instance'
    Properties: 
      ImageId: !Ref ImageId
      InstanceType: !Ref InstanceType
      KeyName: !Ref KeyName
  
  #Allocate an Elastic IP in your Account
  DemoElasticIP:
    Type: AWS::EC2::EIP
    Properties:
      Domain: vpc
      InstanceId: !Ref DemoInstance 

Outputs:
  DemoInstanceId:
    Description: Instance Id 
    Value: !Ref DemoInstance

Template to Associate Elastic IP with EC2 Instance using CloudFormation : JSON

{
    "AWSTemplateFormatVersion": "2010-09-09",
    "Description": "Template to Create an EC2 instance, EIP and associate with instance",
    "Parameters": {
        "ImageId": {
            "Type": "String",
            "Description": "Linux 2 AMI for Ireland eu-west1 Region",
            "Default": "ami-0fc970315c2d38f01"
        },
        "InstanceType": {
            "Type": "String",
            "Description": "Choosing  t2 micro because it is free",
            "Default": "t2.micro"
        },
        "KeyName": {
            "Description": "SSH Keypair to login to the instance",
            "Type": "AWS::EC2::KeyPair::KeyName",
            "Default": "demokeypair"
        }
    },
    "Resources": {
        "DemoInstance": {
            "Type": "AWS::EC2::Instance",
            "Properties": {
                "ImageId": {
                    "Ref": "ImageId"
                },
                "InstanceType": {
                    "Ref": "InstanceType"
                },
                "KeyName": {
                    "Ref": "KeyName"
                }
            }
        },
        "DemoElasticIP": {
            "Type": "AWS::EC2::EIP",
            "Properties": {
                "Domain": "vpc",
                "InstanceId": {
                    "Ref": "DemoInstance"
                }
            }
        }
    },
    "Outputs": {
        "DemoInstanceId": {
            "Description": "Instance Id",
            "Value": {
                "Ref": "DemoInstance"
            }
        }
    }
}

Step3: Create a Stack using prepared template

Now, we know the basics and we have the template so let’s go and create the stack.

  1. Grab the YAML or JSON template from above as per your convenience.
  2. Change parameters like ImageId, InstanceType and KeyName with your own AMI Id, instance type and name of keypair respectivey
  3. Save the template with .yml or .json as per the choice of template and follow below steps.
  4. Login to AWS Management Console, navigate to CloudFormation and click on Create stack
  5. Click on “Upload a template file”, upload your saved .yml  or .json file and click Next
  6. Enter the stack name and click on Next. In configuration, keep everything as default and click on Next.
  7. In the events tab of stack, you can view the status.
  8. Once stack is successfully created, you can check “Resources” tab to see all that’s created by this template.
  9. Navigate to EC2 instance and verify that EIP is created and associated with your instance.

Resources Created:

As you can see in Resources tab of created stack, two resource have been created. An EC2 instance and an Elastic IP. You can view details by clicking on the physical ID as underlined in below screenshot

How to Associate Elastic IP with EC2 Instance using CloudFormation 1

Verifying EIP Association with EC2:

Click on instance ID to see EC2 instance details. In the details screen you will see that Elastic IP and public IP is same. And , the good news is that now if you stop your instance and start it again, it is not going to change 🙂

How to Associate Elastic IP with EC2 Instance using CloudFormation 2

Clean Up

If you are creating this EC2 and EIP just for learning purpose. Don’t forget to delete your CloudFormation stack so that your instance and elastic IP is deleted and you don’t bear any cost.

Happy Learning !!!

Conclusion:

In this post, we learnt how to associate elastic IP with EC2 instance using CloudFormation .

We learnt-

  • A bit about Elastic IP and it’s need
  • How to allocate an elastic IP using CloudFormtion
  • Associating the created EIP with EC2 instance using CloudFormation

I hope you found this post helpful. If you find any issue, please fee free to reach me in comment section. I would be more than happy to reply to your comment.

Enjoyed the content?

Subscribe to our newsletter below to get awesome AWS learning materials delivered straight to your inbox.

Don’t forget to motivate me by-

Suggested Read:

Sharing is Caring:

Leave a Reply

Your email address will not be published. Required fields are marked *