How to assign EIP to Autoscaling Group of VPC in Cloudformation template

muzafarow picture muzafarow · Jan 18, 2016 · Viewed 15.5k times · Source

I want to assign one of my reserved Elastic IP's(ec2 classic ip) to Autoscaling group in VPC. Using AWS Cli I moved ip to vpc:

$ aws ec2 move-address-to-vpc --public-ip 23.23.23.23

And saw in aws concole, that this IP passed to VPC. And Assigned in tags of AutoscalingGroup in Cloudformation template in Resources:

"Process": {
        "Type" : "AWS::AutoScaling::AutoScalingGroup",
        "Properties": {
            "LaunchConfigurationName": {"Ref": "PreprocessorLC"},
            "LoadBalancerNames": [{"Ref": "ProcessELB"}],
            "VPCZoneIdentifier" : [{ "Fn::Join" : [",", [ { "Ref" : "PublicSubnet1"}, { "Ref" : "PublicSubnet2"} ]]}],
            "AvailabilityZones": {"Ref": "AZs"},
            "MinSize" : "1",
            "MaxSize" : "1",
            "HealthCheckGracePeriod": 300,
            "Tags" : [
                {"Key": "Name", "Value": {"Fn::Join": ["", [{"Ref": "Env"}, "-Process"]]}, "PropagateAtLaunch": true},
                {"Key": "WorkersScalingGroup", "Value": {"Fn::Join": ["", ["Offering-", {"Ref": "Env"},  "-Process-Worker"]]}, "PropagateAtLaunch": true},
                {"Key": "EIP", "Value": {"Ref": "ProcessIP"}, "PropagateAtLaunch": true},
                {"Key": "Environment", "Value": {"Ref": "Env"}, "PropagateAtLaunch": true}
            ]
        }
    }

And added value of "ProcessIP" in Parameters:

"ProcessIP":{
            "Description": "DEV: 23.23.23.23",
            "Type": "String",
            "Default": "23.23.23.23",
            "AllowedValues": ["23.23.23.23"]
}

And it doesn't worked. Still get random IP. If someone can tell where I'm wrong or what should to add for make it work?

Thanks!

Answer

Steve Robbins picture Steve Robbins · Nov 13, 2018

In my case, I needed to keep a bank of unassigned EIPs and randomly assign them to the EC2 when they boot. That way I always know my servers will be using a specific list of IPs that I can whitelist in other places.

If you create several EIPs named "prod-pool" you can then use this script.

apt install -y jq awscli
ALLOCATION_ID=`aws ec2 describe-addresses --filters="Name=tag:Name,Values=prod-pool" | jq -r '.Addresses[] | "\(.InstanceId) \(.AllocationId)"' | grep null | awk '{print $2}' | xargs shuf -n1 -e`

if [ ! -z $ALLOCATION_ID ]; then
    aws ec2 associate-address --instance-id $INSTANCE_ID --allocation-id $ALLOCATION_ID --allow-reassociation
fi

You can attached this policy to your IAM user

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "AllowEIPAttachment",
      "Effect": "Allow",
      "Resource": [
        "*"
      ],
      "Action": [
        "ec2:AssociateAddress",
        "ec2:DisassociateAddress"
      ]
    }
  ]
}