问题描述
我想调用Cloudformation中维护的API网关。我有Cloudformation堆栈名称( CF_STACK_NAME
),API网关资源名称( API_GATEWAY_NAME
)和Cloudformation名称我需要承担IAM角色( API_ROLE_NAME
)。
I want to make a call to an API Gateway maintained in Cloudformation. I have the Cloudformation stack name (CF_STACK_NAME
), the API Gateway resource name (API_GATEWAY_NAME
), and Cloudformation name of the IAM Role I need to assume (API_ROLE_NAME
).
我可以通过以下方式进入Cloudformation堆栈:
I can get to my Cloudformation stack via,
cf_client = boto3.client('cloudformation')
api_role_resource = cf_client.describe_stack_resource(
StackName=CF_STACK_NAME,
LogicalResourceId=API_ROLE_NAME
)
api_resource = cf_client.describe_stack_resource(
StackName=CF_STACK_NAME,
LogicalResourceId=API_GATEWAY_NAME
)
从阅读,我看到了如何获取该角色的密钥,
From reading Switching to an IAM Role, I see how to get my keys for the role,
sts_client = boto3.client('sts')
credentials = sts_client.assume_role(
RoleArn='arn:aws:iam::{account_id}:role/{role_name}'.format(
account_id=sts_client.get_caller_identity().get('Account'),
role_name=api_role_resource['PhysicalResourceId']
),
RoleSessionName="AssumeRoleSession1"
)['Credentials']
但是当我想调用API网址时,
But when I want to call the API url,
apigateway_client = boto3.client('apigateway')
restapi_id = apigateway_client.get_rest_api(restApiId=api_logical_id)['id']
url = f'https://{restapi_id}.execute-api.{region}.amazonaws.com/{stage}/{api_query}
api_output = requests.get(url).json()
我得到了
An error occurred (AccessDeniedException) when calling the GetRestApi operation: User: arn:aws:iam::0123456789:user/my-user is not authorized to perform: apigateway:GET on resource: arn:aws:apigateway:us-west-2::/restapis/ServerlessRestApi
如何进行API调用使用此CloudFormation信息?
How do I make my API call using this CloudFormation info?
推荐答案
我的猜测是您没有使用STS的新凭据。
My guess is that you are not using the new credentials from STS.
您将需要使用新的凭据(使用以下代码)来创建apigateway客户端:
You will need to create the apigateway client using the new credentials using code like this:
client = boto3.client(
'apigateway',
aws_access_key_id=credentials['Credentials']['AccessKeyId'],
aws_secret_access_key=credentials['Credentials']['SecretAccessKey'],
aws_session_token=credentials['Credentials']['SessionToken'])
这篇关于如何使用Boto3在Cloudformation中获取API网关的预签名URL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!