AWS CLI, network-interfaces, and associate-public-ip-address

The AWS CLI run-instances documentation isn’t great on how to assign a public IP Address in a VPC when you create a new instance, so this is a quick note on how to do it.

There’s a bug report on Unable to use –associate-public-ip-address but the fix mentioned isn’t very clear on the formatting, but this command line works:

aws ec2 run-instances --image-id ami-f0b11187 --key-name your-ssh-key-name --instance-type t2.micro --network-interfaces '[ { "DeviceIndex": 0, "Groups": ["sg-123456"], "SubnetId": "subnet-123456", "DeleteOnTermination": true, "AssociatePublicIpAddress": true } ]'

You obviously need to change the “Groups” value to a valid security group in your own VPC, and SubnetID to a subnet-id in your VPC (plus pick the right AMI for image-id), but after that you will be able to create an instance with a public IP!