Using AWS Boto3 Invoke API Gateway from EC2 Instance

Viewed 7585

I am trying to invoke AWS API Gateway endpoint from one of the EC2 instance with IAM Role. I have boto3 library installed on EC2 instance and trying to execute simple gateway API using below code but still getting Authentication missing error.

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)

This should be very simple from EC2 Instance with IAM Role. Please any advise.

1 Answers

Due to lack of details in your question, (missing instance role details, API gateway policy, unknown headers, or wheather iam_auth is enabled) I can only provide and comment on the python code given.

The python code to use role should be (this is example that I used to verify the code):

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)

I tested this with authorizationType set to AWS_IAM for the resource a tested.

API resource policy

{
    "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/*"
        }
    ]
}

instance-role

Does not need to have any api invocation permissions as they are provided through API resource policy. The instance-role must only exist and be attached to the instance.

Related