使用CDK Python创建Instance Profile报gitLabRunner-glue已存在如何解决
问题原因
- 你直接给
CfnInstanceProfile的roles参数传入字符串字面量的用法不符合CDK的资源引用规则,CDK无法识别这是一个已存在的外部角色,会默认尝试在当前栈中新建同名角色,因此触发已存在报错。 - 如果你此前运行过注释中创建
gitLabRunner-glue角色的代码并完成部署,注释代码后没有同步更新栈资源移除该角色,CDK的状态记录中仍残留该角色的定义,再次关联同名资源也会触发冲突。
解决方法
场景1:角色由当前CDK应用的其他栈创建
在创建角色的栈中暴露角色输出,在当前栈导入后直接传入即可:
# 角色所在栈的配置代码示例 class RoleStack(cdk.Stack): def __init__(self, scope, id, **kwargs): super().__init__(scope, id, **kwargs) self.gitlab_role = _iam.Role( self, "gitLabRunner-glue", role_name="gitLabRunner-glue", assumed_by=_iam.ServicePrincipal("ec2.amazonaws.com") ) # 实例配置文件栈导入角色 class Ec2InstanceProfile(cdk.Stack): def __init__(self, scope, construct_id, role, **kwargs): super().__init__(scope, construct_id, **kwargs) ec2gitLabRunnerinstanceprofile = _iam.CfnInstanceProfile( self, "ec2gitLabRunnerinstanceprofile", instance_profile_name="ec2-gitLabRunner-glue", roles=[role.role_name] ) # app.py 中关联两个栈 app = cdk.App() role_stack = RoleStack(app, "RoleStack") profile_stack = Ec2InstanceProfile(app, "Ec2InstanceProfile", role=role_stack.gitlab_role)
场景2:角色已存在于AWS账号,不由当前CDK应用管理
先通过CDK的导入方法获取已存在角色对象,再传入参数:
from aws_cdk import core as cdk from aws_cdk import aws_iam as _iam class Ec2InstanceProfile(cdk.Stack): def __init__(self, scope: cdk.Construct, construct_id: str, **kwargs) -> None: super().__init__(scope, construct_id, **kwargs) # 导入已存在的角色 existing_gitlab_role = _iam.Role.from_role_name( self, "imported-gitlab-role", role_name="gitLabRunner-glue" ) ec2gitLabRunnerinstanceprofile = _iam.CfnInstanceProfile( self, "ec2gitLabRunnerinstanceprofile", instance_profile_name="ec2-gitLabRunner-glue", roles=[existing_gitlab_role.role_name] )
额外排查项
- 运行
cdk diff检查当前栈的变更列表,确认是否存在新建gitLabRunner-glue角色的操作,如果有需要先清理栈中残留的旧角色资源定义后再部署。 - 确认已存在的
gitLabRunner-glue角色的信任策略中已添加ec2.amazonaws.com服务主体,否则关联后EC2实例无法正常使用该实例配置文件。
内容的提问来源于stack exchange,提问作者Deepak
相关产品推荐
相关产品推荐

