gpt4 book ai didi

python - 如何创建在Python CDK中引用自身的API网关资源策略?

转载 作者:行者123 更新时间:2023-12-01 06:44:06 29 4
gpt4 key购买 nike

我正在创建一个 API,它通过使用具有 GitHub IP 的资源策略来接受来自 GitHub Webhook 服务器的请求。我已使用控制台成功完成此操作并手动创建资源策略,但在使用 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 中找不到解决方法。

对于其他资源,在创建后使用 aws_iam.add_to_role_policy 广告 IAM 策略确实很容易,但我在 CDK 中找不到 RestApi 类的等效项。看来您在声明 RestApi必须添加 PolicyDocument

此外,这是我尝试在 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 内定义资源,它无法引用自身。

来自documentation :

To set the ARN for the policy, use the !Join intrinsic function with "" as delimiter and values of "execute-api:/" and "*".

这会在您的 CDK 代码中转化为以下内容:

resources=[core.Fn.join('', ['execute-api:/', '*'])]

关于python - 如何创建在Python CDK中引用自身的API网关资源策略?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59324529/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com