Ryan Grush
Ryan Grush

Reputation: 2128

Ansible EC2 with security groups across VPC peering connections

I have 3 separate VPCs on aws and am using ansible to handle deploys. My problem is that a few of my environments use security groups from another VPC.

Here is my EC2 module -

- name: Create instance
  ec2:
    image: "{{ image }}"
    instance_type: "{{ instance_type }}"
    aws_access_key: "{{ aws_access_key_id }}"
    aws_secret_key: "{{ aws_secret_access_key }}"
    key_name: "{{ key_name }}"
    instance_tags:
      Name: "{{ name }}"
      Environment: "{{ env }}"
      Product: "{{ product }}"
      Service: "{{ service }}"
    region: "{{ region }}"
    volumes:
      - device_name: "{{ disk_name }}"
        volume_type: "{{ disk_type }}"
        volume_size: "{{ disk_size }}"
        delete_on_termination: "{{ delete_on_termination }}"
    # group: "{{ security_group_name }}"
    group_id: "{{ security_group_id }}"
    wait: true
    vpc_subnet_id: "{{ vpc_subnet_id }}"
    count: "{{ instance_count }}"
    monitoring: "{{ detailed_monitoring }}"
    instance_profile_name: "{{ iam_role }}"
    assign_public_ip: "{{ assign_public_ip }}"
    termination_protection: "{{ termination_protection }}"
  register: ec2

When I pass in a security group id from another VPC, I get this -

"msg": "Instance creation failed => InvalidParameter: Security group sg-e7284493 and subnet subnet-19d97e50 belong to different networks."

Is there a workaround in Ansible for this?

Upvotes: 0

Views: 435

Answers (1)

Chris Pollard
Chris Pollard

Reputation: 1780

You can't assign a foreign security group to an EC2 in a different VPC. Meaning, the security groups assigned to an EC2 must be associated with the security groups in that VPC.

The way to do this would be to create a security group in the VPC where your EC2 lives that allows the foreign security group access, then apply the created security group to your EC2.

Upvotes: 2

Related Questions