1

I (AWS noob) am playing around with the aws cdk. I want to build a simple Spring service running in fargate with a dynamodb as a database. It seems like my service cannot access the dynamo because of some missing permissions. In the Cloudwatch Logs I see this error message:

com.amazonaws.services.dynamodbv2.model.AmazonDynamoDBException: User: arn:aws:sts::xxxxxxxxxx:assumed-role/MyCdkAppStack-TaskDefTaskRole1EDB4A67-xxxxxxxx/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx is not authorized to perform: dynamodb:UpdateItem on resource: arn:aws:dynamodb:eu-central-1:xxxxxxxxxxx:table/MyDynamoDbTable (Service: AmazonDynamoDBv2; Status Code: 400; Error Code: AccessDeniedException; Request ID: XXXXX)

For permissions for the table, I thought it should suffice to grant the necessary permissions to the task role of the fargate service:

props.dependencies.dynamoDb.grantReadWriteData(taskDefinition.taskRole);

In the AWS console, it looks like the permissions should be there: When I go to the corresponding task, the corresponding role seems to have all permissions.

It is not working though, so obviously I am missing something or doing something wrong. Any hints on how I can connect a fargate service with a dynamo db table in a cdk app?

Thanks, some tips would be greatly appreciated :)

Edit: Sorry for the delay... Stack:

export class MyCdkAppStack extends cdk.Stack {
constructor(scope: cdk.Construct, id: string, props: MyCdkAppStackProps) {
    super(scope, id, props);

    const appId = 'myService';

    const table = new Table(this, 'MyDynamoDbTable', {
        tableName: 'MyDynamoDbTable',
        partitionKey: {name: 'Id', type: AttributeType.STRING},
        billingMode: BillingMode.PAY_PER_REQUEST,
        removalPolicy: RemovalPolicy.DESTROY
    });

    let logDriver = new AwsLogDriver({
        logRetention: RetentionDays.ONE_WEEK,
        streamPrefix: "test-stream-prefix",
    });

    const vpc = new Vpc(this, 'cdk-my-vpc', {maxAzs: 2});

    new cdk.CfnOutput(this, "MyVpc", {value: vpc.vpcId});

    const cluster = new Cluster(this, "MyCluster", {
        vpc: vpc,
        clusterName: appId
    });

    const appImage = ContainerImage.fromEcrRepository(props.dependencies.appRepo, 'latest');

    const applicationLoadBalancedFargateService = new ApplicationLoadBalancedFargateService(this, "FargateService", {
        cluster: cluster,
        taskImageOptions: {
            image: appImage,
            containerPort: 8080,
            logDriver: logDriver
        },
    });

    table.grantReadWriteData(applicationLoadBalancedFargateService.taskDefinition.taskRole);
}

}

Task Role Policy after cdk synth:

"FargateServiceTaskDefTaskRoleDefaultPolicy63F83D6F": {
  "Type": "AWS::IAM::Policy",
  "Properties": {
    "PolicyDocument": {
      "Statement": [
        {
          "Action": [
            "dynamodb:BatchGetItem",
            "dynamodb:GetRecords",
            "dynamodb:GetShardIterator",
            "dynamodb:Query",
            "dynamodb:GetItem",
            "dynamodb:Scan",
            "dynamodb:BatchWriteItem",
            "dynamodb:PutItem",
            "dynamodb:UpdateItem",
            "dynamodb:DeleteItem"
          ],
          "Effect": "Allow",
          "Resource": [
            {
              "Fn::GetAtt": [
                "MyDynamoDbTableC81ED735",
                "Arn"
              ]
            },
            {
              "Ref": "AWS::NoValue"
            }
          ]
        }
      ],
      "Version": "2012-10-17"
    },
    "PolicyName": "FargateServiceTaskDefTaskRoleDefaultPolicy63F83D6F",
    "Roles": [
      {
        "Ref": "FargateServiceTaskDefTaskRole8CDCF85E"
      }
    ]
  }
3
  • Can you add the task role policy definition here (json) after obscuring the necessary sections? Please also add corresponding CDK code here in question to get a better visibility. Commented May 29, 2020 at 21:54
  • Can you please share the relevant stack code as well. Commented Jun 1, 2020 at 5:41
  • I had a simmilar problem - in my case the issue was caused by wrong table name in my application Commented Apr 4, 2024 at 0:09

1 Answer 1

0

This should help https://greenchapel.dev/2022/02/18/aws-cdk-fargate-schedular-write-to-dynamodb/ https://serverlessland.com/patterns/cdk-fargate-dynamodb

const dynamoGatewayEndpoint = vpc.addGatewayEndpoint('dynamoGatewayEndpoint', {
  service: GatewayVpcEndpointAwsService.DYNAMODB
});

// Allow PutItem action from the Fargate Task Definition only
dynamoGatewayEndpoint.addToPolicy(
  new PolicyStatement({
    effect: Effect.ALLOW,
    principals: [new AnyPrincipal()],
    actions: [
      'dynamodb:PutItem',
    ],
    resources: [
      `${dynamoTable.tableArn}`
    ],
    conditions: {
      'ArnEquals': {
        'aws:PrincipalArn': `${fargate.taskDefinition.taskRole.roleArn}`
      }
    }
  })
);

// Write permissions for Fargate
dynamoTable.grantWriteData(fargate.taskDefinition.taskRole);

// Outputs
new CfnOutput(this, 'DynamoDbTableName', { value: dynamoTable.tableName });

} }

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.