首页 > 解决方案 > 使用 AWS Boto3 从 EC2 实例调用 API 网关

问题描述

我正在尝试从具有 IAM 角色的 EC2 实例之一调用 AWS API Gateway 端点。我在 EC2 实例上安装了 boto3 库,并尝试使用以下代码执行简单的网关 API,但仍然出现 Authentication missing 错误。

import boto3
import json
import requests
from aws_requests_auth.aws_auth import AWSRequestsAuth

session = boto3.Session()
credentials = session.get_credentials()

headers = {'params': 'ABC'}
response = requests.get('https://restapiid.execute-api.us-east-1.amazonaws.com/stage/resource_path',
                        auth=credentials, headers=headers)

这对于具有 IAM 角色的 EC2 实例应该非常简单。请任何建议。

标签: python-requestsaws-api-gatewayboto3

解决方案


由于您的问题中缺少详细信息(缺少实例角色详细信息、API 网关策略、未知headersiam_auth已启用),我只能提供并评论给出的 python 代码。

使用角色的 python 代码应该是(这是我用来验证代码的示例):

import boto3
import requests
from aws_requests_auth.aws_auth import AWSRequestsAuth

session = boto3.Session()
credentials = session.get_credentials()

auth = AWSRequestsAuth(aws_access_key=credentials.access_key,
                       aws_secret_access_key=credentials.secret_key,
                       aws_token=credentials.token,
                       aws_host='fzoskzctgd.execute-api.us-east-1.amazonaws.com',
                       aws_region='us-east-1',
                       aws_service='execute-api')


response = requests.get('https://fzoskzctgd.execute-api.us-east-1.amazonaws.com/test', auth=auth)

print(response.content)

我用authorizationTypeset to测试AWS_IAM了这个资源 a 测试。

API 资源策略

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": {
                "AWS": "arn:aws:iam::123456:role/instance-role"
            },
            "Action": "execute-api:Invoke",
            "Resource": "arn:aws:execute-api:us-east-1:170576413884:fzoskzctgd/test/*"
        }
    ]
}

实例角色

不需要任何 api 调用权限,因为它们是通过 API 资源策略提供的。instance-role 必须只存在并附加到实例。


推荐阅读