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

amazon ec2amazon-elastic-ipamazon-web-servicessecurity-groups

I have two instances in a VPC distinct security groups, each with their own public IP. I would like instance one to be able to connect to instance two on it's Public IP. I discovered that granting access to the security group, only allows access to the private IP, not the Public IP.

I have now defined my Security Group to allow access to the Public IP of the instance which resides in the other Security Group. However, this is inconvenient, as I can't easily automate this (think Ansible), since I will first need to perform a lookup of the DNS name, before I can add it to the group.

Does anyone know of a simpler way of doing this?

To summarize:

  • Instance 1 -> 1.2.3.4
  • Instance 2 -> 5.6.7.8

Instance 1 is required to access Instance 2 on it's Public IP.
I currenty end up having to manually lookup what the IP of instance 1 is and in turn add that to the security group of Instance 2.

Best Answer

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 :)