Use IAM roles to link GitHub actions with actions in AWS

April 2, 2024

Use IAM roles to link GitHub actions with actions in AWS

Have you ever wanted to initiate a change in your Amazon Web Services (AWS) account after updating a GitHub repository or deploy updates to an AWS application after merging an approval without using AWS Identity and Access Management (IAM) Keys user access? You can do so by configuring an OpenID Connect Identity Provider (IdP) (OIDC) within your AWS account. You can use IAM roles and short-term credentials, eliminating the need for IAM user access keys.


From this article, the authors will walk you through the steps needed to configure a specific GitHub repository to accept an individual role in your AWS account to make changes. You will learn how to create a trusted OIDC connection whose scope includes a separate GitHub repository and how to map the repository to an IAM role on the account. You will develop an OIDC connection, IAM role, and trust relationship in two ways: using the AWS management console and the AWS command line interface (AWS CLI).

This post focuses on creating an OIDC IAM identity provider for GitHub and shows how to authorize access to an AWS account from a specific branch and repository. OIDC identity providers can be used in workflows that support the OpenID Connect standard, such as Google or Salesforce.

Prerequisites

To keep up with the activities discussed in the article, the following prerequisites must be met:

Discussion of the solution

GitHub is a third-party provider independent of AWS. To use GitHub as an OIDC identity provider, you need to follow four steps to access AWS resources from the GitHub repository. Then, in the fifth and final step, you will use AWS CloudTrail to audit the role you created and used in steps 1-4.

  1. Create an OIDC provider in your AWS account. This trust relationship allows GitHub to authenticate and gain permission to take action on your account.
  2. Create an IAM role in your account. Then, define the scope of the IAM role's trust relationship to the intended parts of your GitHub organization, repository, and branch so that GitHub can accept and perform the specified actions.
  3. Assign a minimum level of permissions to the role.
  4. Create a GitHub Actions workflow file in your repository to invoke actions on your account.
  5. Audit role usage using Amazon CloudTrail logs.


Create an OIDC provider in your account.

The first step in this process is to create the OIDC provider that you will use in the trust rules for the IAM role used in this action.

To create an OIDC provider for GitHub (console):

  1. Open the IAM console.
  2. In the left navigation menu, select Identity Providers.
  3. In the Identity Providers pane, select Add Provider.
  4. Select OpenID Connect as the Provider Type.
  5. In the Provider URL field, enter this solution's GitHub OIDC identity provider URL: https://token.actions.GitHubusercontent.com.
  6. Select Get Thumbprint to verify the identity provider's server certificate. To learn more about OIDC thumbprints, see Obtaining a thumbprint for the OpenID Connect identity provider.
  7. In the Recipient field, type sts.amazonaws.com. This will enable this identity provider to call the AWS Security Token Service (AWS STS) API.
  8. (Optional) The Add Tags option allows you to add key-value pairs to help you identify and organize identity providers. To learn more about tagging IAM OIDC identity providers, see Tagging OpenID Connect (OIDC) identity providers.
  9. Check the information you have entered. Your console should match the screenshot in Figure 1. Once verified, select Add Provider.


Note that each provider has a one-to-one relationship with an external identity provider. You can repeat the process if you want to add more identity providers to your account.

Use IAM roles to link GitHub actions with actions in AWS

 

10. When you return to the Identity Provider page, you will see your new identity provider, as shown in Figure 2. Select your provider to view its properties and note the Amazon resource name (ARN).Later in this post, you will use the ARN.The ARN will look similar to the following:
arn:aws:iam::111122223333:oidc-provider/token.actions.GitHubusercontent.com

Use the IAM farm

To create an OIDC provider for GitHub (AWS CLI):
You can add GitHub as an identity provider in your account with a single AWS CLI command. The code below will perform the previous steps described for the console, with the same results. For the value - thumbprint-list you will use the OIDC GitHub fingerprint 938fd4d98bab03faadb97b34396831e3780aea1.

aws iam create-open-id-connect-provider --url 
"https://token.actions.GitHubusercontent.com" --thumbprint-list 
"6938fd4d98bab03faadb97b34396831e3780aea1" --client-id-list 
'sts.amazonaws.com'


To learn more about the GitHub service fingerprint, see GitHub service actions—updating OIDC-based deployments on AWS. At the time of publication, this fingerprint was correct.

Both of the above methods will add an identity provider to your account. You can view the provider on the Identity Provider page in the IAM console.

Step 2: Create an IAM role and define the scope of the trust rules
You can create an IAM role using the IAM console or the AWS CLI. If you create the IAM role using the AWS CLI, you will define the scope of the trust relationship rules before creating the role.

The procedure for creating an IAM role and setting the trust policy scope is from the AWS Identity and Access Management User Guide, which provides detailed instructions on configuring a role and how to configure a role for a GitHub OIDC Identity Provider.

To create an IAM role (IAM console):
1. In the IAM console, on the Identity Provider screen, select Assign a role for the newly created identity provider.


2. In the Assign a role for field, select Create a new role and then select Next, as shown in the following figure.


3. The Create Role page contains several options. An online identity is already selected as a trusted entity, and the Identity Provider field is populated with your identity provider. In the Recipients list, select sts.amazonaws.com and then choose Next.
4. On the Permissions page, select Next. For this demo, you will not be required to add permissions to the role.

Suppose you want to test other activities, such as AWS CodeBuild operations. In that case, you can add permissions according to these blog posts: Complete CI/CD with AWS CodeCommit, AWS CodeBuild, AWS CodeDeploy, and AWS CodePipeline or Techniques for writing least privilege IAM policies.

(Optional) Add tags to this new role on the Tags page, then select Next: Review.

  1. On the Create Role page, add a name for the role. In this show, enter GitHubAction-AssumeRoleWithAction. Optionally, add a description.
  2. To create the role, select Create role.


You will then restrict the IAM role's trust rules to a single GitHub organization, repository, and branch.

To define the scope of the trust policy (IAM console)

  1. Open the newly created role in the IAM console and select Edit trust relationship.
  2. Modify the trust rules on the Edit Trust Rules page to allow your unique GitHub organization, repository, and branch to take over the role. This example trusts a GitHub organization, a repository named, and a branch named. Update the Federated ARN with the previously copied GitHub identity provider ARN.
    {
        "Version": "2012-10-17",
        "Statement": [
            {
                "Effect": "Allow",
                "Principal": {
                    "Federated": "<arn:aws:iam::111122223333:oidc-provider/token.actions.githubusercontent.com>"
                },
                "Action": "sts:AssumeRoleWithWebIdentity",
                "Condition": {
                    "StringEquals": {
                        "token.actions.githubusercontent.com:sub": "repo: <aws-samples/EXAMPLEREPO>:ref:refs/heads/",
                        "token.actions.githubusercontent.com:aud": "sts.amazonaws.com"
                    }
                }
            }
        ]
    }

To create a role (AWS CLI)

In the AWS platform CLI, use the example trust rule for the console shown above. This policy is designed to restrict access to a specific organisation, repository and GitHub branch.

  1. Create and save a JSON file with the example policy on your local machine under the name trustpolicyforGitHubOIDC.json.
  2. Run the following command to create the role

aws iam create-role --role-name GitHubAction-AssumeRoleWithAction --assume-role-policy-document file://C:trustpolicyforGitHubOIDC.json
For more information on creating an OIDC role using the AWS CLI, see Creating a Role for Federated Access (AWS CLI).

Step 3: Assign a minimum level of permissions to the role
In this example, you will not add permissions to the IAM role, but you will assume the role and call STS GetCallerIdentity to demonstrate a GitHub action that will assume the AWS role.

If you want to perform additional actions on your account, you can add permissions to the created GitHubAction-AssumeRoleWithAction role. Typical workflow actions include calling AWS Lambda functions or uploading files to an Amazon Simple Storage Service (Amazon S3) tray. For more information on using IAM to apply for permissions, see Policies and Permissions in IAM.

To run a test, you can add permissions according to these blog posts: Complete CI/CD with AWS CodeCommit, AWS CodeBuild, AWS CodeDeploy, and AWS CodePipeline or Techniques for writing least privilege IAM policies.

Step 4: Create a GitHub action to call the AWS CLI

GitHub service actions are defined as methods that you can use to automate, customise and run software development workflows in the GitHub service. The GitHub service action you create will be authenticated to your account as the role created in Step 2: Create an IAM role and define the trust policy scope.

To create a GitHub action to invoke the AWS CLI:

  1. Create a basic workflow file, such as main.yml, in your repository's .github/workflows directory. This sample workflow will use the GitHubAction-AssumeRoleWithAction role to perform the aws sts get-caller-identity action. Your repository can have multiple workflows, each performing different tasks. Once you have authenticated your GitHub service to a role with a workflow, you can use AWS CLI commands in your account.
  2. Paste the following sample workflow into a file.
# This is a basic workflow to help you get started with Actions
name:Connect to an AWS role from a GitHub repository

# Controls when the action will run. Invokes the workflow on push events but only for the main branch
on:
  push:
    branches: [ main ]
  pull_request:
    branches: [ main ]

env:
  
  AWS_REGION : <"us-east-1"> #Change to reflect your Region

# Permission can be added at job level or workflow level    
permissions:
      id-token: write   # This is required for requesting the JWT
      contents: read    # This is required for actions/checkout
jobs:
  AssumeRoleAndCallIdentity:
    runs-on: ubuntu-latest
    steps:
      - name: Git clone the repository
        uses: actions/checkout@v3
      - name: configure aws credentials
        uses: aws-actions/[email protected]
        with:
          role-to-assume: <arn:aws:iam::111122223333:role/GitHubAction-AssumeRoleWithAction> #change to reflect your IAM role’s ARN
          role-session-name: GitHub_to_AWS_via_FederatedOIDC
          aws-region: ${{ env.AWS_REGION }}
      # Hello from AWS: WhoAmI
      - name: Sts GetCallerIdentity
        run: |
          aws sts get-caller-identity  

3. Modify the workflow to reflect the AWS account information:

  • AWS_REGION: Enter the AWS region for the AWS resource.
  • role-to-assume: replace the ARN with the ARN of the AWS GitHubAction role created earlier.


Figure 5 shows the workflow steps in which GitHub performs the following actions:

- Authenticates in the IAM role with the OIDC identity provider in the region that was defined in the workflow file in the aws credentials configuration step.

- Calls aws sts get-caller-identity in the Hello from AWS step. WhoAmI... Run AWS CLI sts GetCallerIdentity.

Use IAM roles

Step 5: Audit role usage: Querying CloudTrail logs
The final step is to view the AWS CloudTrail logs for the account to audit the usage of the role.

To view the event logs for a GitHub share:

  1. In the AWS Management Console, open CloudTrail and select Event History.
  2. In the Search Attributes list, select Event Source.
  3. In the search bar, type sts.amazonaws.com.Use IAM role
  4. You should see the GetCallerIdentity and AssumeRoleWithWebIdentity events, as shown in Figure 6. The GetCallerIdentity event is the Hello from AWS. step in the GitHub workflow file. This event shows the workflow that calls aws sts get-caller-identity. The AssumeRoleWithWebIdentity event shows the GitHub service authenticating and accepting your IAM role GitHubAction-AssumeRoleWithAction.


You can also view one event at a time.

To view the AWS CLI GetCallerIdentity event:

  1. In the Search Attributes list, select User name.
  2. In the search bar, enter the name-role-session, as defined in the workflow file in your repository. This is not the name of the IAM role, as this name-session-role is defined in line 30 of the example workflow. In the workflow example for this blog post, the name-session-roli is GitHub_to_AWS_via_FederatedOIDC.
  3. You can now see the first event in the CloudTrail history.Use IAM role

To view the AssumeRoleWithWebIdentity event

  1. In the Search Attributes list, select User name.
  2. In the search bar, enter the GitHub organization, repository, and branch defined in the IAM role trust policy. In the earlier example, the username is repo:aws-samples/REF:ref:refs/heads/main.
  3. You can now see a single event in the CloudTrail history.Use the IAM role

 

Applications

When you use IAM roles with OIDC identity providers, you have a trusted way of providing access to AWS resources. GitHub and other OIDC providers can generate temporary security credentials to update your accounts' resources and infrastructure.

This article teaches you how to use federated access to take on a role in AWS directly from a workflow action file in a GitHub repository. With this new identity provider, you can start removing AWS access keys from IAM users and using short-term credentials.

After reading this article, the authors recommend following the AWS Well-Architected Security Pillar IAM directive to use programmatic access to AWS services using temporary credentials and with limited permissions. If you implement federated IAM roles instead of AWS user access keys, follow these guidelines and issue tokens through the AWS Security Token Service. If you would like to share your feedback on this post, please comment below and let us know how you would like to extend the OIDC workflows to help your IAM needs.

If you have comments on this article, please leave them in the Comments section below. If you have questions about this article, please get in touch with AWS support.

Case Studies
Testimonials

Hostersi provides administrative support for the cloud infrastructure of Danone GmbH in Amazon Web Services. As part of this support, Hostersi's specialists take care of a many web projects located in dozens of instances. We are very impressed with the professionalism, quality of service and competence of Hostersi.

Marek Nadra
Business Solution Manager Supporting the Enterprise
Briefly about us
We specialize in IT services such as server solutions architecting, cloud computing implementation and servers management.
We help to increase the data security and operational capacities of our customers.