Fargate service not respecting security groups

773 views Asked by At

I am unable to connect from a Fargate container to an RDS instance when its ingress is limited through security groups. I can connect with lambdas though.

The container has no issue hitting SQS, or the internet. Only has issues hitting the RDS endpoint.

Here is an excerpt from the template, where the database ingress is open. Fargate can connect without issue.

  Service:
    Type: AWS::ECS::Service
    Properties:
      ServiceName: !Ref ServiceName
      Cluster: !Ref Cluster
      TaskDefinition: !Ref TaskDefinition
      PlatformVersion: 1.3.0
      DeploymentConfiguration:
        MinimumHealthyPercent: 100
        MaximumPercent: 200
      DesiredCount: 0
      LaunchType: FARGATE
      NetworkConfiguration:
        AwsvpcConfiguration:
          AssignPublicIp: DISABLED
          Subnets:
            - !Ref PrivateSubnet1
          SecurityGroups:
            - !Ref DatabaseAccessSecurityGroup

  DatabaseInstance:
    Type: AWS::RDS::DBInstance
    Properties:
      Engine: mysql
      EngineVersion: 8.0.16
      AvailabilityZone: !GetAtt PrivateSubnet1.AvailabilityZone
      PubliclyAccessible: false
      ...
      VPCSecurityGroups:
        - !Ref DatabaseSecurityGroup

  DatabaseSubnetGroup:
    Type: AWS::RDS::DBSubnetGroup
    Properties:
      DBSubnetGroupDescription: Cloudformation managed Db subnet group
      SubnetIds:
        - !Ref PrivateSubnet1
        - !Ref PrivateSubnet2

  DatabaseSecurityGroup:
    Type: AWS::EC2::SecurityGroup
    Properties:
      VpcId: !Ref VPC
      GroupName: database-sg
      GroupDescription: Database security group
      SecurityGroupIngress:
        - Description: Access to RDS
          # allowing all works with Fargate
          CidrIp: 0.0.0.0/0
          FromPort: 3306
          ToPort: 3306
          IpProtocol: tcp

  DatabaseAccessSecurityGroup:
    Type: AWS::EC2::SecurityGroup
    Properties:
      GroupName: database-access-sg
      GroupDescription: Security group for accessing db
      VpcId: !Ref VPC



But if I change the DatabaseSecurityGroup Group ingress to only allow ingress through DatabaseAccessSecurityGroup I get errors when trying to connect through Fargate. Lambdas using the same security group have no issue.

   SecurityGroupIngress:
     - Description: Access to RDS
       CidrIp: 0.0.0.0/0
       SourceSecurityGroupId: !GetAtt DatabaseAccessSecurityGroup.GroupId
       FromPort: 3306
       ToPort: 3306
       IpProtocol: tcp

Is there any way to get the Fargate Service to respect security group rules?

1

There are 1 answers

0
Elliot On BEST ANSWER

This issue was occurring because I was using a Service in the Cloudformation template, but spinning up the tasks via ecs.runTask, which overrode the security groups in the Service.