Friday, April 15, 2022

[SOLVED] Restrict access to DynamoDB from EC2 instance

Issue

I have a service where I have long running jobs. Each job has a GUID. I store information about that job in dynamodb and use the job GUID as the partition key. There's an EC2 instance associated with each job (and some extremely untrustworthy code running on the EC2 instance). I want to make it so that the EC2 instance associated with a particular job can only have access to the entry in dynamodb associated with that job.

What I was trying before was to tag an EC2 instance with the job GUID then use something like whats below to compare dynamodb leading keys with EC2 tags.

{
    "Sid": "UpdateDynamo",
    "Effect": "Allow",
    "Action": "dynamodb:UpdateItem",
    "Resource": "arn:aws:dynamodb:us-east-1:720911909616:table/test",
    "Condition": {
        "ForAllValues:StringEquals": {
            "dynamodb:LeadingKeys": [
                "${aws:PrincipalTag/job_guid}"
            ]
        }
    }
}

This didn't work because "PrincipalTag" refers to the IAM role and not the EC2 instance.

What is a good solution to this?


Solution

You will not be able to achieve this with a single policy/role, because there is no AWS-wide condition key that will evaluate to the tag of the EC2 instance that you can use to compare to dynamodb:LeadingKeys.

Given your use case, I would therefore suggest setting up a serverless solution (probably a Lambda function) that, for each job:

  • Creates a role
  • Creates a policy that will allow the dynamodb:UpdateItem only for the GUID of that particular job
  • Assigns the role to the appropriate EC2 instance


Answered By - Paolo
Answer Checked By - Gilberto Lyons (WPSolving Admin)