How to Configure IAM for CodeBuild to Push to ECR?
Configuring IAM for CodeBuild to Push to ECR
In this guide, we will configure AWS IAM roles and policies to allow AWS CodeBuild to push Docker images to Amazon ECR. This involves creating an IAM role for CodeBuild and attaching the necessary policies.
Step-by-Step Explanation
Step 1: Create an IAM Role for CodeBuild
- Define a new IAM role for CodeBuild.
- Attach the
AWSCodeBuildDeveloperAccess
managed policy to the role. - Attach a custom policy to allow pushing to ECR.
Step 2: Create a Custom Policy for ECR Access
- Define a custom policy that grants permissions to push images to ECR.
- Attach this policy to the IAM role created in Step 1.
Summary
By following these steps, you will have configured an IAM role for CodeBuild with the necessary permissions to push Docker images to ECR. This involves creating an IAM role, attaching the AWSCodeBuildDeveloperAccess
managed policy, and adding a custom policy for ECR access.
Full Code Example
import * as aws from "@pulumi/aws";
// Create an IAM role for CodeBuild
const codeBuildRole = new aws.iam.Role("codeBuildRole", {
assumeRolePolicy: JSON.stringify({
Version: "2012-10-17",
Statement: [
{
Action: "sts:AssumeRole",
Principal: {
Service: "codebuild.amazonaws.com",
},
Effect: "Allow",
Sid: ""
}
]
})
});
// Attach the AWSCodeBuildDeveloperAccess managed policy to the role
const managedPolicyAttachment = new aws.iam.RolePolicyAttachment("managedPolicyAttachment", {
role: codeBuildRole.name,
policyArn: "arn:aws:iam::aws:policy/AWSCodeBuildDeveloperAccess"
});
// Create a custom policy for ECR access
const ecrPolicy = new aws.iam.Policy("ecrPolicy", {
description: "Policy to allow pushing to ECR",
policy: JSON.stringify({
Version: "2012-10-17",
Statement: [
{
Effect: "Allow",
Action: [
"ecr:GetDownloadUrlForLayer",
"ecr:BatchGetImage",
"ecr:BatchCheckLayerAvailability",
"ecr:PutImage"
],
Resource: "*"
}
]
})
});
// Attach the custom policy to the IAM role
const customPolicyAttachment = new aws.iam.RolePolicyAttachment("customPolicyAttachment", {
role: codeBuildRole.name,
policyArn: ecrPolicy.arn
});
// Create a CodeBuild project (example)
const codeBuildProject = new aws.codebuild.Project("codeBuildProject", {
serviceRole: codeBuildRole.arn,
artifacts: {
type: "NO_ARTIFACTS"
},
environment: {
computeType: "BUILD_GENERAL1_SMALL",
image: "aws/codebuild/standard:4.0",
type: "LINUX_CONTAINER"
},
source: {
type: "GITHUB",
location: "https://github.com/your-repo/your-project.git"
}
});
Deploy this code
Want to deploy this code? Sign up for a free Pulumi account to deploy in a few clicks.
Sign upNew to Pulumi?
Want to deploy this code? Sign up with Pulumi to deploy in a few clicks.
Sign upThank you for your feedback!
If you have a question about how to use Pulumi, reach out in Community Slack.
Open an issue on GitHub to report a problem or suggest an improvement.