Skip to content

Instantly share code, notes, and snippets.

@eelzinaty
Created July 31, 2022 05:58
Show Gist options
  • Save eelzinaty/ab5e1b8b4aa670f223ba8e6e4ed5927f to your computer and use it in GitHub Desktop.
Save eelzinaty/ab5e1b8b4aa670f223ba8e6e4ed5927f to your computer and use it in GitHub Desktop.
CloudFormation Template for Creating: GitHub OIDC, IAM Role, IAM Policy to push images from GitHub Action to AWS ECR
---
AWSTemplateFormatVersion: 2010-09-09
Parameters:
GitHubOrg:
Type: String
OIDCProviderArn:
Description: Arn for the GitHub OIDC Provider.
Default: ''
Type: String
Conditions:
CreateOIDCProvider: !Equals
- Ref: OIDCProviderArn
- ''
Resources:
Policy:
Type: 'AWS::IAM::Policy'
Properties:
PolicyName: AllowPushImagesToECR
PolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow # Retrieves an authorization token to login into ECR
Action: 'ecr:GetAuthorizationToken'
Resource: '*'
- Effect: Allow # Get container image information from ECR
Action:
- 'ecr:GetDownloadUrlForLayer'
- 'ecr:BatchGetImage'
- 'ecr:BatchCheckLayerAvailability'
Resource: !Sub 'arn:aws:ecr:${AWS::Region}:${AWS::AccountId}:repository/*'
- Effect: Allow # upload container image to ECR
Action:
- 'ecr:CompleteLayerUpload'
- 'ecr:UploadLayerPart'
- 'ecr:InitiateLayerUpload'
- 'ecr:PutImage'
Resource: !Sub 'arn:aws:ecr:${AWS::Region}:${AWS::AccountId}:repository/*'
Roles:
- !Ref Role # Reference to the AWS IAM role
Role:
Type: 'AWS::IAM::Role'
Properties:
RoleName: GithubOIDCIAMRole
AssumeRolePolicyDocument:
Statement:
- Effect: Allow
Action: 'sts:AssumeRoleWithWebIdentity' # Action to get a WebIdentityToken
Principal:
Federated:
- !Ref GithubOidc # AWS OIDCProvider resource created earlier
Condition:
StringLike:
'token.actions.githubusercontent.com:sub': !Sub 'repo:${GitHubOrg}/*' # Allow any repo in under your GitHub Organization to assume this IAM Role
GithubOidc:
Type: 'AWS::IAM::OIDCProvider'
Condition: CreateOIDCProvider
Properties:
Url: 'https://token.actions.githubusercontent.com'
ClientIdList:
- sts.amazonaws.com
ThumbprintList:
- a031c46782e6e6c662c2c87c76da9aa62ccabd8e
Outputs:
Role:
Value: !GetAtt Role.Arn
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment