添加对流层中现有 sns 主题的订阅

Adding a subscription to an existing sns topic in troposphere

我有一个用例,其中我有一个现有的 sns 主题,我正在使用 cloudformation 和 troposphere 创建 lambda 函数。我必须以某种方式创建我的堆栈,使主题向我的 lambda 函数发送订阅,但不应重新创建主题本身。

下面是我的代码:

from troposphere import FindInMap, GetAtt, Join, Output
from troposphere import Template, Ref
from troposphere.awslambda import Function, Code, Permission
from troposphere.sns import Topic, SubscriptionResource

folder_names = ["welt", "jukin"]

t = Template()

t.set_version("2010-09-09")

t.add_mapping("MapperToTenantId",
              {
                  u'welt': {'id': u't-012'},
                  u'jukin': {'id': u't-007'}
              }
              )

t.add_mapping("LambdaExecutionRole",
                {u'lambda-execution-role': {u'ARN': u'arn:aws:iam::498129003450:role/service-role/lambda_execution_role'}}
            )

code = [
    "def lambda_handler(event, context):\n",
    "    message = event[‘Records’][0][‘Sns’][‘Message’]\n",
    "    print(“From SNS: “ + message)\n",
    "    return message\n"
]


for cp in folder_names:
    lambda_function = t.add_resource(Function(
        f"{cp}MapperLambda",
        Code=Code(
        ZipFile=Join("", code)
    ),
    Handler="index.handler",
    Role=FindInMap("LambdaExecutionRole", "lambda-execution-role", "ARN"),
    Runtime="python3.6",
    )
    )

    t.add_resource(Permission(
        f"InvokeLambda{cp}Permission",
        FunctionName=GetAtt(lambda_function, "Arn"),
        Action="lambda:InvokeFunction",
        SourceArn='arn:aws:sns:us-west-2:498129003450:IngestStateTopic',
        Principal="sns.amazonaws.com"
    ))

    t.add_resource(SubscriptionResource(
        EndPoint=GetAtt(lambda_function, "Arn"),
        Protocol='lambda',
        TopicArn='arn:aws:sns:us-west-2:498129003450:IngestStateTopic'
    ))



with open('mapper_cf.yaml', 'w') as y:
    y.write(t.to_yaml())

我收到以下错误,我无法找到解决办法:

Traceback (most recent call last):
  File "create_cloudformation.py", line 54, in <module>
    TopicArn='arn:aws:sns:us-west-2:498129003450:IngestStateTopic'
TypeError: __init__() missing 1 required positional argument: 'title'

这在对流层中可以做到吗?我不想硬编码云形成中的块,但我想在对流层中生成它。

这甚至可以做到吗?

请给我一些提示。

您遇到的错误与未指定标题字符串有关。试试这个:

t.add_resource(SubscriptionResource(
    f"{cp}Subscription",
    EndPoint=GetAtt(lambda_function, "Arn"),
    Protocol='lambda',
    TopicArn='arn:aws:sns:us-west-2:498129003450:IngestStateTopic'
))