I am trying to launch an EC2 instance with an Elastic IP attached to it via cloudformation. I have a YAML file that launches the EC2 instance and runs code after launch via UserData property (AWS::EC2::Instance). It then associates an IP via AWS::EC2::EIPAssociation. However, this order does not fit my requirements. I want to first associate and then run the script, because my script actually depends on the IP associated with it.
Does anybody know how to first associate IP and then run script via YAML? Is there an option of defining the Elastic IP within AWS::EC2::Instance?
You can use the option to create a ENI first > Associate the EIP to it > Use this ENI as primary interface of your Instance during launch. This way your EC2 will come up with the EIP associated and thus have internet access to proceed with User-Data. In the example below, I am also doing an EIP allocation. If this is not needed in your case, do make changes to the
EC2EIPsection.This lets you select a VPC, Subnet as parameters. Then it pulls an EIP from Amazon pool and associate with an ENI. Next, launches an EC2 with this ENI mentioned. In this order, the
User-Datawill be triggered after EIP is associated.