@@ -11,14 +11,31 @@ terraform {
1111
1212data "aws_caller_identity" "current" {}
1313
14+
15+ # See if the GitHub OIDC provider already exists
16+ data "aws_iam_openid_connect_provider" "github" {
17+ url = " https://token.actions.githubusercontent.com"
18+
19+ # This will return empty if not found, rather than error
20+ count = 1
21+ }
22+
23+ locals {
24+ oidc_provider_exists = length (data. aws_iam_openid_connect_provider . github ) > 0 && try (data. aws_iam_openid_connect_provider . github [0 ]. arn , " " ) != " "
25+ }
26+
27+ # Only create if it doesn't exist
1428resource "aws_iam_openid_connect_provider" "github" {
15- count = var. add_oidc_provider ? 1 : 0
16- client_id_list = [" sts.amazonaws.com" ]
17- url = " https://token.actions.githubusercontent.com"
18- thumbprint_list = [
19- " 1c58a3a8518e8759bf075b76b750d4f2df264fcd" ,
20- " 6938fd4d98bab03faadb97b34396831e3780aea1"
21- ]
29+ count = local. oidc_provider_exists ? 0 : 1
30+
31+ url = " https://token.actions.githubusercontent.com"
32+ client_id_list = [" sts.amazonaws.com" ]
33+ thumbprint_list = [" 6938fd4d98bab03faadb97b34396831e3780aea1" ]
34+ }
35+
36+ # Use this output to reference the ARN regardless of creation method
37+ locals {
38+ oidc_provider_arn = local. oidc_provider_exists ? data. aws_iam_openid_connect_provider . github [0 ]. arn : aws_iam_openid_connect_provider. github [0 ]. arn
2239}
2340
2441resource "aws_iam_role" "github_actions" {
@@ -38,29 +55,35 @@ resource "aws_iam_role" "github_actions" {
3855 },
3956 "Effect":"Allow",
4057 "Principal":{
41- "Federated":"arn:aws:iam:: ${ data . aws_caller_identity . current . account_id } :oidc-provider/token.actions.githubusercontent.com "
58+ "Federated":"${ local . oidc_provider_arn } "
4259 }
4360 }
4461 ],
4562 "Version":"2012-10-17"
4663 }
4764 EOF
4865
49- dynamic "inline_policy" {
50- for_each = var. inline_policies
51- content {
52- name = " inline_policy_${ inline_policy . key } "
53- policy = inline_policy. value
54- }
55- }
56-
57- managed_policy_arns = var. managed_policy_arns
58-
5966 tags = var. tags
6067
6168 max_session_duration = var. max_session_duration
6269}
6370
71+ resource "aws_iam_role_policy" "policy" {
72+ for_each = var. policies
73+
74+ name = " ${ aws_iam_role . github_actions . name } _${ each . key } "
75+ role = aws_iam_role. github_actions . name
76+ policy = each. value
77+ }
78+
79+ resource "aws_iam_role_policy_attachment" "managed" {
80+ for_each = toset (var. managed_policy_arns )
81+
82+ role = aws_iam_role. github_actions . name
83+ policy_arn = each. value
84+ }
85+
6486output "role_arn" {
6587 value = aws_iam_role. github_actions . arn
6688}
89+
0 commit comments