PR合并至main分支时,GitHub Action通过OIDC调用AWS STS角色授权失败
问题原因分析
当PR合并到main分支时,GitHub生成的OIDC Token的sub字段格式为repo:organisation-name/repo:pull_request:${PR_NUMBER}(例如repo:organisation-name/repo:pull_request:123),而你的AWS角色信任策略中StringLike规则仅配置了repo:organisation-name/repo:pull_request,无法匹配带PR编号的sub值,导致STS拒绝角色申请。
而推送(push)到main分支时,sub字段是repo:organisation-name/repo:ref:refs/heads/main,正好匹配策略里的规则,所以可以正常运行。
修复方案
修改AWS角色的信任策略,将sub的匹配规则改为带通配符的格式:
{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": { "Federated": "arn:aws:iam::5599526xxxxx:oidc-provider/token.actions.githubusercontent.com" }, "Action": "sts:AssumeRoleWithWebIdentity", "Condition": { "StringEquals": { "token.actions.githubusercontent.com:aud": "sts.amazonaws.com" }, "StringLike": { "token.actions.githubusercontent.com:sub": [ "repo:organisation-name/repo:ref:refs/heads/main", "repo:organisation-name/repo:pull_request:*" ] } } } ] }
额外说明
- 你添加的自定义权限策略(允许
sts:AssumeRoleWithWebIdentity)并不是问题所在,这个权限是给IAM用户/角色调用STS的权限,当前场景核心限制在角色信任策略。 - 若需更严格限制仅合并PR时触发,可结合GitHub Action的
github.event.pull_request.merged条件做判断,不过通配符*已经能覆盖PR创建、更新、合并等所有PR相关场景。
内容的提问来源于stack exchange,提问作者MJ Ghani
相关产品推荐
相关产品推荐

