I have a use case in which i have an existing sns topic and i am creating lambda functions using cloudformation and troposphere . I have to somehow create my stack in such a way in which the topic sends subscriptions to my lambda functions, but the topic itself should not be recreated.
Below is my code :
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())
I am getting the below error and i am not able to figure a way out :
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'
Is this possible to do in troposphere. I don't want to hardcode the block in cloud formation but i want to generate that in troposphere.
Is this even possible to do ?
Kindly give me some hints.
The error you are getting is related to not specifying a title string. Try this:
t.add_resource(SubscriptionResource(
f"{cp}Subscription",
EndPoint=GetAtt(lambda_function, "Arn"),
Protocol='lambda',
TopicArn='arn:aws:sns:us-west-2:498129003450:IngestStateTopic'
))