python - 如何创建在 Python CDK 中引用自身的 API Gateway 资源策略?
问题描述
我正在创建一个 API,它只接受来自 GitHub Webhook服务器的请求,方法是使用带有 GitHub IP 的资源策略。我已经使用控制台成功完成了这项工作并手动创建了资源策略,但是在使用 CDK 时遇到了问题。
这是我的代码:
delete_trigger_integration = aws_apigateway.LambdaIntegration(
trigger_step_lambda, proxy=False, integration_responses=[])
api_policy_document = aws_iam.PolicyDocument()
api = aws_apigateway.RestApi(
self,
"GithubWebhookApi",
rest_api_name=PROJECT_NAME + "-apigateway-trigger-delete",
default_integration=delete_trigger_integration,
policy=api_policy_document)
delete_execution_resource = api.root.add_resource("execution")
delete_execution_method = delete_execution_resource.add_method(
"POST", delete_trigger_integration)
delete_execution_resource.add_cors_preflight(allow_origins=["*"])
create_repo_lambda.add_environment("API_URL",
delete_execution_resource.url)
api_policy_document.add_statements(
aws_iam.PolicyStatement(
effect=aws_iam.Effect.ALLOW,
principals=[aws_iam.AnyPrincipal()],
actions=["execute-api:Invoke"],
resources=[api.arn_for_execute_api()]))
api_policy_document.add_statements(
aws_iam.PolicyStatement(
effect=aws_iam.Effect.DENY,
actions=["execute-api:Invoke"],
conditions={
"NotIpAddress": {
"aws:SourceIp": [
"192.30.252.0/22", "185.199.108.0/22",
"140.82.112.0/20"
]
}
},
principals=[aws_iam.AnyPrincipal()],
resources=[api.arn_for_execute_api()]))
我觉得我非常接近解决方案,但我无法弄清楚它是什么。上面代码的问题是我ValidationError: Circular dependency between resources
在尝试部署它时遇到错误 - 我可以理解,资源策略正在解决它内部的资源。但是我在 CDK 中找不到解决方法。
对于其他资源,在创建后使用广告 IAM 策略非常容易,aws_iam.add_to_role_policy
但我在 CDK 中找不到RestApi
该类的等效项。似乎您必须在PolicyDocument
声明RestApi
.
此外,这是我试图在 CDK 中重新创建的资源策略(导致问题的是那些资源 ARN):
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": "*",
"Action": "execute-api:Invoke",
"Resource": "arn:aws:execute-api:eu-west-1:000000000000:aaaaaaaaaa/*/*/*"
},
{
"Effect": "Deny",
"Principal": "*",
"Action": "execute-api:Invoke",
"Resource": "arn:aws:execute-api:eu-west-1:000000000000:aaaaaaaaaa/*/*/*",
"Condition": {
"NotIpAddress": {
"aws:SourceIp": [
"192.30.252.0/22",
"185.199.108.0/22",
"140.82.112.0/20"
]
}
}
}
]
}
有谁知道我的问题的解决方案?提前致谢!
此外,您可以忽略空的集成响应 - 我仍在努力。
解决方案
这与底层 CloudFormation 资源的工作方式有关。
由于Policy
必须在AWS::ApiGateway::RestApi
资源中定义,它不能引用自身。
从文档中:
要为策略设置 ARN,请使用
!Join
内部函数 with""
as delimiter 和 value of"execute-api:/"
and"*"
。
在您的 CDK 代码中转换为以下内容:
resources=[core.Fn.join('', ['execute-api:/', '*'])]
推荐阅读
- laravel - Laravel 的日程表中的循环定义
- javascript - 在同一页面而不是弹出窗口上打开 Facebook 登录
- python - 使用 Python 对 1000 以下的 3 和 5 的倍数求和
- python-3.x - Python 3 - 如何在不截断中间列的情况下将 CSV 行写入文本文件?
- ruby-on-rails - 如何在 Rails 的视图文件中根据 if 语法进行渲染
- python - 是否有 GUI 可以查看 .npy 文件的内容?
- sql - T-SQL 查询优化
- python - 怎么修 ”
弃用警告:Python 中的无效转义序列? - python-3.x - 使用绘制数据的微型版本作为 python 中的图例句柄
- javascript - D3.stratify 未捕获的错误:不明确:分配属性