简体   繁体   English

如何使用 Python AWS-CDK 将现有资源添加到堆栈?

[英]How to add an existing resource to stack using Python AWS-CDK?

I tried deploying with the following definition but got ExampleRole already exists error.我尝试使用以下定义进行部署,但得到ExampleRole already exists错误。

from aws_cdk import aws_iam as iam
from aws_cdk import core

app = core.App()
stack = core.Stack(app, "MyStack")

existing_role = iam.Role(
    stack,
    id="ExampleRole",
    assumed_by=iam.AccountPrincipal(123456789),
    role_name="ExampleRole",
)
existing_role.apply_removal_policy(core.RemovalPolicy.RETAIN)

app.synth()

What is the correct procedure using CDK only?仅使用 CDK 的正确步骤是什么?

You can use iam.Role.from_role_arn() to import an existing IAM role by ARN;您可以使用iam.Role.from_role_arn()通过 ARN 导入现有的 IAM 角色;

existing_role = iam.Role.from_role_arn(
    stack,
    id="ExampleRole",
    role_arn="arn:aws:iam::123456789012:role/......",
)
existing_role.apply_removal_policy(core.RemovalPolicy.RETAIN)

I've seen cases where functions like SQS from_queue_arn() and similar ones return a read-only reference to the resource, so you can't actually modify it with your CDK code;我见过像 SQS from_queue_arn()这样的函数和类似的函数返回对资源的只读引用的情况,所以你实际上不能用你的 CDK 代码修改它; however, from_role_arn has a mutable=True parameter which says然而, from_role_arn有一个mutable=True参数,它说

mutable ( Optional [ bool ]) – Whether the imported role can be modified by attaching policy resources to it. mutable ( Optional [ bool ]) – 是否可以通过附加策略资源来修改导入的角色。 Default: true默认值:真

So I'm not sure if it will work for you or not.所以我不确定它是否适合你。

Root cause: you created stack, but you fetched role outside of it and therefore it is "orphan" and AWS CDK app cannot understand what it should do with it.根本原因:您创建了堆栈,但您提取了它之外的角色,因此它是“孤立的”,AWS CDK 应用程序无法理解它应该用它做什么。

This problem should be addressed in three steps (bottom-up approach):这个问题应该分三步解决(自下而上的方法):

  • project structure项目结构
  • stack.py堆栈文件
  • app.py应用程序
  • deploy部署

I am using CDK v2.我正在使用 CDK v2。

0.1. 0.1. Project structure项目结构

.
├── app.py
├── cdk.json
├── requirements.txt
├── .gitignore
└── stacks
    ├── stack.py
    └── __init__.py

This is a basic project structure which allows you to interact with AWS CDK.这是一个基本的项目结构,允许您与 AWS CDK 进行交互。

0.2. 0.2. requirements.txt要求.txt

# CDK v2 update: npm install -g aws-cdk@next

aws-cdk-lib==2.0.0-rc.14
boto3

I added the content of requirements.txt just to be sure that we are on the same page.我添加了 requirements.txt 的内容只是为了确保我们在同一页面上。 Also, it is good to update your AWS CDK npm to have the most recent version.此外,最好将您的 AWS CDK npm 更新为最新版本。 This command should be run in cmd.此命令应在 cmd 中运行。

  1. stack.py堆栈文件
import aws_cdk as cdk
from aws_cdk import aws_iam as _iam


class MyNewStack(cdk.Stack):

    def __init__(self, scope, construct_id, **kwargs) -> None:
        super().__init__(scope, construct_id, **kwargs)

        # Fetch existing resources
        role = _iam.Role.from_role_arn(self, "my_existing_role",
                                       role_arn="role_arn_copied_from_webui_as-string", 
                                       mutable=False)

Here we create a stack where we list all our resources (new or already existing) using the CDK API.在这里,我们创建了一个堆栈,我们在其中使用 CDK API 列出了我们的所有资源(新的或已经存在的)。 Link is given below to see all available options.下面给出了链接以查看所有可用选项。

  1. app.py应用程序
from stacks.Stack import *

# Initializing the CDK app
app = cdk.App()
env = cdk.Environment(account=os.getenv('CDK_DEFAULT_ACCOUNT'), region=os.getenv('CDK_DEFAULT_REGION'))

# Stacks
MyNewStack(app, "stack-name-to-be-displayed-in-cloudformation", env=env)

# Required to get files updated in cdk.out
app.synth()

Here we initialize the CDK app and create instance of the class which we built previously.在这里,我们初始化 CDK 应用程序并创建我们之前构建的类的实例。

  1. Deploy部署
$cdk ls
$cdk synth
$cdk deploy stack-name-to-be-displayed-in-cloudformation

Before deployment, it is highly recommended to run cdk ls , cdk synth , cdk diff to see if everything is okay.在部署之前,强烈建议运行cdk lscdk synthcdk diff以查看是否一切正常。

Please let me know in case I can help you more.如果我可以帮助您更多,请告诉我。 Hope you find it useful.希望你觉得它有用。 Cheers!干杯!

References to documentation and more:参考文档等:

  1. Intro CDK: https://docs.aws.amazon.com/cdk/latest/guide/home.html CDK 介绍: https : //docs.aws.amazon.com/cdk/latest/guide/home.html
  2. CDK API reference: https://docs.aws.amazon.com/cdk/api/v2/python/modules.html CDK API 参考: https : //docs.aws.amazon.com/cdk/api/v2/python/modules.html
  3. Better way to structure projects: https://www.sentiatechblog.com/aws-cdk-structure-components构建项目的更好方法: https : //www.sentiatechblog.com/aws-cdk-structure-components
  4. CDK Patterns (real-life examples): https://cdkpatterns.com/ CDK 模式(现实生活中的例子): https : //cdkpatterns.com/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM