Sub topic 16
Managing the provider and role as code
This chapter assumes you have already created the IAM OIDC provider and the deployment role by hand, as in the earlier chapters. You should also know basic CloudFormation (templates, stacks, parameters) and the AWS CLI. The goal is to turn that manual setup into a template you can review, repeat, and change safely.
Why move the setup out of the console
The trust policy is the security boundary for your deployments. A single edited sub condition can open a role to every repository in an organization. Console edits leave no review trail, and you cannot easily recreate them in a second account.
When the provider and role are defined in a template:
- Changes go through a pull request, so a reviewer sees any widening of the
subcondition. - The same template can create the setup in a staging account and a production account.
- Drift detection can show whether someone changed the role by hand.
- Deleting the stack removes everything it created, with no orphaned roles.
What the template must contain
The template needs three things:
- An
AWS::IAM::OIDCProviderforhttps://token.actions.githubusercontent.comwith the client IDsts.amazonaws.com. - An
AWS::IAM::Rolewhose trust policy names the provider asFederatedand usessts:AssumeRoleWithWebIdentity. - A permissions policy on that role, kept to what the deployment needs.
An AWS account can hold only one provider per URL. If another stack or an earlier manual setup already created it, a second create fails with an "already exists" error. The template below handles that with a parameter.
A parameterized template
The version in the earlier chapter hard-coded the organization and repository. This version takes them as parameters, so the template can be reused. It also lets you skip creating the provider when one already exists.
AWSTemplateFormatVersion: '2010-09-09'
Description: GitHub Actions OIDC provider and deployment role
Parameters:
GitHubOrg:
Type: String
GitHubRepo:
Type: String
DeployBucket:
Type: String
CreateProvider:
Type: String
AllowedValues: ['true', 'false']
Default: 'true'
ExistingProviderArn:
Type: String
Default: ''
Conditions:
ShouldCreateProvider: !Equals [!Ref CreateProvider, 'true']
Resources:
GitHubOidcProvider:
Type: AWS::IAM::OIDCProvider
Condition: ShouldCreateProvider
Properties:
Url: https://token.actions.githubusercontent.com
ClientIdList:
- sts.amazonaws.com
GitHubDeployRole:
Type: AWS::IAM::Role
Properties:
RoleName: github-deploy
MaxSessionDuration: 3600
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Principal:
Federated: !If
- ShouldCreateProvider
- !Ref GitHubOidcProvider
- !Ref ExistingProviderArn
Action: sts:AssumeRoleWithWebIdentity
Condition:
StringEquals:
token.actions.githubusercontent.com:aud: sts.amazonaws.com
StringLike:
token.actions.githubusercontent.com:sub: !Sub 'repo:${GitHubOrg}/${GitHubRepo}:ref:refs/heads/main'
Policies:
- PolicyName: deploy-site
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Action: s3:ListBucket
Resource: !Sub 'arn:aws:s3:::${DeployBucket}'
- Effect: Allow
Action:
- s3:GetObject
- s3:PutObject
- s3:DeleteObject
Resource: !Sub 'arn:aws:s3:::${DeployBucket}/*'
Outputs:
RoleArn:
Description: Value for role-to-assume in the workflow
Value: !GetAtt GitHubDeployRole.ArnA few details are worth noting:
- For an
AWS::IAM::OIDCProvider,!Refreturns the provider ARN. That is the value the trust policy'sFederatedfield needs. - The
ListBucketaction applies to the bucket ARN, while object actions apply tobucket/*. Mixing them up is a common cause ofAccessDeniedduringaws s3 sync. MaxSessionDurationis set to the default of 3600 seconds, written out so a reviewer sees the limit. Lower values are allowed down to 3600, which is the minimum for this property.- The permissions policy is inline here. That keeps the trust and permissions of this role in one reviewed file. For a policy shared by several roles, use a managed policy resource instead.
Deploying the stack
The role does not exist before the stack does, so the first deployment cannot use OIDC. Run it once from a workstation or an admin pipeline with credentials that can create IAM resources.
aws cloudformation deploy \
--stack-name github-oidc-deploy \
--template-file oidc-deploy.yaml \
--capabilities CAPABILITY_NAMED_IAM \
--parameter-overrides \
GitHubOrg=my-org \
GitHubRepo=my-repo \
DeployBucket=my-example-bucketCAPABILITY_NAMED_IAM is required because the template sets an explicit RoleName. Without the flag, CloudFormation rejects the stack. After it finishes, read the role ARN from the stack outputs and put it in the workflow's role-to-assume:
aws cloudformation describe-stacks \
--stack-name github-oidc-deploy \
--query "Stacks[0].Outputs[?OutputKey=='RoleArn'].OutputValue" \
--output textIf the account already has a GitHub provider, pass CreateProvider=false and ExistingProviderArn=arn:aws:iam::123456789012:oidc-provider/token.actions.githubusercontent.com. The stack then creates only the role.
Who deploys the deployer
Do not let the application deployment role update its own stack. If a workflow on main could change the trust policy of the role it runs under, a compromised workflow could widen its own access. Keep the stack that defines IAM roles separate from the stacks that deploy applications, and use a different, more tightly controlled path to change it:
- Deploy the identity stack manually or from a separate administrative pipeline.
- Require review from a security owner on changes to the template file, for example with a CODEOWNERS entry.
- Give the application role no
iam:*permissions.
Keeping the code and the account in sync
Drift is any difference between the template and the real resource. Detect it with CloudFormation:
aws cloudformation detect-stack-drift --stack-name github-oidc-deployThe command returns a StackDriftDetectionId. Pass that ID to aws cloudformation describe-stack-drift-detection-status and then run aws cloudformation describe-stack-resource-drifts to see which properties changed. A trust policy that differs from the template is a finding worth investigating, because it may mean someone loosened the sub condition by hand.
Other tools
The same resources exist in other tools. In Terraform they are aws_iam_openid_connect_provider and aws_iam_role. In the CDK, OpenIdConnectProvider and Role with WebIdentityPrincipal. The design questions are the same in all of them:
- Is the provider created once per account?
- Are organization and repository parameters rather than literals?
- Is the
subcondition narrow? - Is the role's stack separate from the stacks it deploys?
Review checklist
Before merging a change to the template, check these points:
- The
audcondition is stillsts.amazonaws.com. - The
subpattern names one repository and one branch or environment. - The permissions policy lists only the actions and resources the deployment uses.
- No new
iam:orsts:actions were added. - Any change to parameters in the deploy command matches the intended account.
Exercise
Your template sets CreateProvider=true, but the stack fails on the first deploy with an "already exists" error for the OIDC provider. What happened, and how do you fix it without deleting the existing provider?
Show answer
The account already has an IAM OIDC provider for token.actions.githubusercontent.com, and an account can have only one per URL. Redeploy with CreateProvider=false and set ExistingProviderArn to the existing provider's ARN. The stack then creates only the role and reuses the provider.
Exercise
A teammate proposes letting the application deployment workflow also update the stack that defines its own role, to avoid a manual step. Give two risks and one alternative.
Show answer
Risk 1: a compromised workflow or a malicious pull request merged to main could widen the trust policy or add permissions to its own role. Risk 2: the role would need iam permissions, which breaks least privilege. Alternative: keep the identity stack separate, deploy it from a separate administrative pipeline or manually, and protect the template file with required review from a security owner.