Search code examples
amazon-s3aws-codepipelineaws-codebuild

How to get S3 objects from a codebuild buildspec ? (AccessDenied)


I have a CodePipeline Pipeline with a CodeBuild stage

Here is my buildspec :

{
  "version": "0.2",
  "phases": {
    "build": {
      "commands": [
        "echo \"Hello, CodeBuild!\"",
        "echo \"ca marche\" > test.txt",
        "mkdir site-content",
        "aws s3 sync s3://my-super-bucket-name site-content",
        "ls - al"
      ]
    }
  },
  "artifacts": {
    "files": [
      "test.txt"
    ]
  }
}

The build project Service Role is defined with a default cdk generated policy, plus this one :

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Action": "s3:*",
            "Resource": [
                "arn:aws:s3:::my-super-bucket-name",
                "arn:aws:s3:::my-super-bucket-name/* "
            ],
            "Effect": "Allow"
        }
    ]
}

And codebuild.amazonaws.com is a trusted entities for the Role

On the bucket side, I have this bucket policy :

{
    "Version": "2012-10-17",
    "Id": "PolicyXXXXXXXXXXXXX",
    "Statement": [
        {
            "Sid": "StmtYYYYYYYYYYYYY",
            "Effect": "Allow",
            "Principal": {
                "AWS": "arn:aws:iam::12345678910:user/a-user-for-another-process"
            },
            "Action": "s3:*",
            "Resource": "arn:aws:s3:::my-super-bucket-name"
        }
    ]
}

But the build project fail with this :

[Container] 2021/02/03 09:57:43 Running command aws s3 sync s3://my-super-bucket-name site-content
download failed: s3://my-super-bucket-name/test.txt to site-content/test.txt An error occurred (AccessDenied) when calling the GetObject operation: Access Denied
Completed 4 Bytes/13.7 KiB (0 Bytes/s) with 4 file(s) remaining

Help !

EDIT : I just add this statement to the bucket policy :

        {
            "Effect": "Allow",
            "Principal": {
                "AWS": "arn:aws:iam::XXXXXXXXXXXXX:role/my-role"
            },
            "Action": "s3:*",
            "Resource": "arn:aws:s3:::my-super-bucket-name"
        }

But I have the same error :(

EDIT 2 : Silly me ! It was :

"Resource": "arn:aws:s3:::my-super-bucket-name*"

Now it work !


Solution

  • You should modify the bucket policy to grant explicit access to you code build role, as the privileges are checked first based on bucket policy if there was no bucket policy attached to bucket then they way how you are trying would have worked.