Pawan Verma
Pawan Verma

Reputation: 149

Is there any policy variable available for AWS S3 bucket name?

I have multiple s3 buckets and I want to maintain a common bucket policy across all my bucket. My bucket policy contains the bucket name as part of resource name and hence I am not able to maintain a single policy file for all my bucket. Is there any way to fetch the bucket name in the policy using any variable?

{
    "Version": "2012-10-17",
    "Id": "Policy1610615475618",
    "Statement": [
        {
            "Sid": "Stmt1610615465140",
            "Effect": "Deny",
            "Principal": {
                "AWS": "arn:aws:iam::<acc_name>:user/<user_name>"
            },
            "Action": "s3:PutObject",
            "NotResource": [
                "arn:aws:s3:::<bucket-name>/*.PNG",
                "arn:aws:s3:::<bucket-name>/*.JPG",
                "arn:aws:s3:::<bucket-name>/*.txt",
                "arn:aws:s3:::<bucket-name>/*.mp3",
                "arn:aws:s3:::<bucket-name>/*.Docx"
            ]
        }
    ]
}

Upvotes: 7

Views: 2045

Answers (3)

Duru Cynthia Udoka
Duru Cynthia Udoka

Reputation: 787

You can use jq to pipe and modify the bucket arn as a variable

Upvotes: 0

Nick
Nick

Reputation: 1273

You haven't mentioned how do you create the policy. But if you use IaC this is possible in both terraform and CloudFormation (I would assume that it's possible with other tools like cdk as well)

In CloudFormation you can use Ref and Fn:GetAtt.

And this is how it looks like in practice. Take a look at the examples section.

With terraform you can do something similar:

    {
        "Sid": "AllowSSLRequestsOnly",
        "Action": "s3:*",
        "Effect": "Deny",
        "Resource": [
            "arn:aws:s3:::${s3-bucket-name}",
            "arn:aws:s3:::${s3-bucket-name}/*"
        ],
        "Condition": {
            "Bool": {
                 "aws:SecureTransport": "false"
            }
        },
       "Principal": "*"
    }

And then pass the account_id (or in your case $bucket_name) from outside during the policy creation:

data "template_file" "s3-bucket-policy" {
  template = file("${path.module}/policies/bucket.json")

  vars = {
    s3-bucket-name   = aws_s3_bucket.my-bucket.bucket
  }
}

Upvotes: 2

Marcin
Marcin

Reputation: 238507

Sadly there is no such variable. Usually in a situation like this you would create and manage your buckets and their policies using Infrastructure as Code tools such as AWS CloudFormation or Terraform.

This would allow you to programmatically parametrize and generate the buckets and their policies in a reproducible and easy to manage manner.

Upvotes: 2

Related Questions