python-requests - 使用 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 实例应该非常简单。请任何建议。
解决方案
由于您的问题中缺少详细信息(缺少实例角色详细信息、API 网关策略、未知headers
或iam_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)
我用authorizationType
set 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 必须只存在并附加到实例。
推荐阅读
- xml - 带有命名空间的不相交的 xml 文件
- ethereum - 保护关于solidity的敏感信息的最佳实践?
- python - Python 3.9:从日期时间(元组)的错误时区偏移
- php - wordpress首页的分页问题
- chainlink - 在构建 Chainlink.Request 时,Chainlink 中的 path 和 copyPath 有什么区别?
- javascript - 获取 TypeError:“路径”未定义:使用 JavaScript 为 Windows 执行串行端口程序时未定义
- javascript - Mongodb连接不上
- haskell - 堆栈似乎没有应用包修订
- javascript - 在 c# 中将对象作为函数参数传递,就像在 javascript 中一样
- angular - 我可以更改离子搜索栏角度的样式吗?