Skip to content

Instantly share code, notes, and snippets.

@npalm
Created February 23, 2022 22:36
Show Gist options
  • Save npalm/8f796f57fcdc95b09699baf330294a93 to your computer and use it in GitHub Desktop.
Save npalm/8f796f57fcdc95b09699baf330294a93 to your computer and use it in GitHub Desktop.
GitHub Actions AWS OpenID connect demo
_....._
_.:`.--|--.`:._
.: .'\o | o /'. '.
// '. \ o| / o '.\
//'._o'. \ |o/ o_.-'o\\
|| o '-.'.\|/.-' o ||
||--o--o-->|
provider "aws" {
region = local.aws_region
}
locals {
aws_region = "eu-west-1"
repo = "<ORG/REPO"
bucket. = "<YOUR_BUCKET_NAME>"
}
resource "aws_iam_openid_connect_provider" "github_actions" {
url = "https://token.actions.githubusercontent.com"
client_id_list = ["sts.amazonaws.com"]
thumbprint_list = ["6938fd4d98bab03faadb97b34396831e3780aea1"]
}
data "aws_iam_policy_document" "github_actions_assume_role_policy" {
statement {
actions = ["sts:AssumeRoleWithWebIdentity"]
principals {
type = "Federated"
identifiers = [
aws_iam_openid_connect_provider.github_actions.arn
]
}
condition {
test = "StringEquals"
variable = "token.actions.githubusercontent.com:aud"
values = ["sts.amazonaws.com"]
}
condition {
test = "StringLike"
variable = "token.actions.githubusercontent.com:sub"
values = ["repo:${local.repo}:*"]
}
condition {
test = "StringNotLike"
variable = "token.actions.githubusercontent.com:sub"
values = ["repo:${local.repo}:pull_request"]
}
}
}
resource "aws_iam_role" "deploy" {
name = "gh-action-${replace(local.repo, "/", "-")}"
assume_role_policy = data.aws_iam_policy_document.github_actions_assume_role_policy.json
}
resource "aws_iam_role_policy" "deploy_policy" {
name = "deploy-policy"
role = aws_iam_role.deploy.name
policy = data.aws_iam_policy_document.deploy.json
}
data "aws_iam_policy_document" "deploy" {
statement {
sid = "1"
actions = [
"s3:ListBucket",
"s3:GetObject",
]
resources = [
aws_s3_bucket.example.arn,
"${aws_s3_bucket.example.arn}*",
]
}
}
resource "aws_s3_bucket" "example" {
bucket = local.bucket
force_destroy = true
}
resource "aws_s3_object" "object" {
bucket = aws_s3_bucket.example.bucket
key = "lunch.txt"
source = "lunch.txt"
etag = filemd5("lunch.txt")
}
output "s3" {
value = {
bucket = aws_s3_bucket.example.bucket
}
}
output "role" {
value = aws_iam_role.deploy.arn
}
name: test
on:
push:
branches:
- main
pull_request:
workflow_dispatch:
jobs:
test:
permissions:
id-token: write
runs-on: ubuntu-latest
steps:
- name: configure aws credentials
uses: aws-actions/configure-aws-credentials@v1
with:
role-to-assume: ${{ secrets.AWS_ROLE }}
role-session-name: demo
aws-region: eu-west-1
- run: |
echo "Lunch!!!"
aws s3 cp --quiet s3://<YOUR_BUCKET_NAME>lunch.txt /dev/stdout
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment