AWS Security Group - how to allow Public IP from another Security Group

Solution 1:

I'm afraid that as soon as you go out to the Public IPs you no longer can use the Security Group ID as the Source in the target SG. That only works for Private IPs.

However if you create the Instance 1 through Ansible you can then use the Ansible facts for the instance to obtain its Public IP and set it as a source in the Instance 2 SG. Something like this should do:

- name: Create Instance 1
  ec2:
    key_name: mykey
    instance_type: t2.micro
    image: ami-123456
    wait: yes
    assign_public_ip: yes             <<< Assign Public IP
  register: ec2

And then you can add it as a source to the Instance 2 Security Group:

- name: Instance 2 SG
  ec2_group:
    name: ...
    rules:
    - proto: tcp
      ports:
      - 80
      cidr_ip: "{{ ec2.instances.public_ip }}"   <<< Use it here

Something along these lines should let you do the automation with Ansible.

Hope that helps :)

Solution 2:

Requests from an instance's public IP address are not treated as if they are coming from the instance's Security Groups. That only works from requests using private IP addresses.

I recommend that the source instance use a DNS address for the target instance that resolves to the target instance's private IP. For example: you create a CNAME record my-service.example.com that points to the target instance's public DNS name that is provided by AWS. The public DNS name will look something like ec2-public-ipv4-address.compute-1.amazonaws.com.

AWS provides split-horizon DNS resolution. When my-service.example.com is resolved on the public internet, the public IP is returned. When my-service.example.com is resolved in your VPC, the private IP is returned. Therefore your source instance will connect to the target instance using a private IP and your Security Group rules will work as expected.

This sort of DNS configuration isn't always possible or practical, so you may need to whitelist the source instance's public IP address. In this case, make sure that it is an Elastic IP Address - otherwise the public IP will change if the server shuts down.

Solution 3:

Typically you'd create a named security group, attach it to those instances, and add a rule which references this security group as a source and allow the needed destination ports.

Final picture:

  • All instances needed to communicate with each other have the created security group attached.
  • The created security group contains rules which state inbound from created security group to destination port you need
  • Often there are no outbound rules included, as secutity groups are stateful. But feel free to add what is needed.

So basically not even a single ip is needed, and allow/deny can be controlled by attaching the security group to resources where access is needed. This method also works nicely with dynamic environments (e.g. autoscaled).