如何获得使用Boto3在Cloudformation的API网关签署的预网址?(How do I g

2019-10-30 05:08发布

我想打一个API网关保持在Cloudformation通话。 我有Cloudformation堆栈名称( CF_STACK_NAME ),API网关资源名称( API_GATEWAY_NAME )和IAM角色,我需要承担(的Cloudformation名API_ROLE_NAME )。

我可以通过得到我Cloudformation栈,

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
)

从阅读切换到IAM角色 ,我看看如何得到我的钥匙的作用,

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网址,

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

我如何使用这个CloudFormation信息让我的API调用?

Answer 1:

我的猜测是,你不使用从STS新的凭据。

您将需要使用像这样使用代码的新的凭据来创建apigateway客户端:

client = boto3.client(
       'apigateway',
        aws_access_key_id=credentials['Credentials']['AccessKeyId'],
        aws_secret_access_key=credentials['Credentials']['SecretAccessKey'],
        aws_session_token=credentials['Credentials']['SessionToken'])


文章来源: How do I get a pre-signed url for an API Gateway in Cloudformation using Boto3?