Whitelisting IPs for Internal API Gateways
Introduction
In this guide, we will configure an API Gateway on AWS and whitelist specific IP addresses to allow access only from those IPs. This is a common requirement for internal APIs to ensure that only trusted sources can access the endpoints.
Step-by-Step Explanation
Step 1: Create an API Gateway
We will start by creating an API Gateway using Pulumi’s AWS SDK. This will involve defining the API, setting up resources, and methods.
Step 2: Define IP Whitelisting
Next, we will define the IP whitelisting rules. This involves creating a resource policy for the API Gateway that specifies which IP addresses are allowed to access the API.
Step 3: Attach the Resource Policy
Finally, we will attach the resource policy to the API Gateway. This will enforce the IP whitelisting rules and ensure that only requests from the specified IP addresses are allowed.
Conclusion
By following these steps, you can secure your internal API Gateway by whitelisting specific IP addresses. This is an effective way to control access and protect your APIs from unauthorized use.
Full Code Example
import * as pulumi from "@pulumi/pulumi";
import * as aws from "@pulumi/aws";
// Step 1: Create an API Gateway
const api = new aws.apigateway.RestApi("myApi", {
name: "myApi",
description: "API Gateway for internal use",
});
// Define a resource in the API Gateway
const resource = new aws.apigateway.Resource("myResource", {
restApi: api.id,
parentId: api.rootResourceId,
pathPart: "myresource",
});
// Define a method for the resource
const method = new aws.apigateway.Method("myMethod", {
restApi: api.id,
resourceId: resource.id,
httpMethod: "GET",
authorization: "NONE",
});
// Step 2: Define IP Whitelisting
const resourcePolicy = new aws.apigateway.RestApiPolicy("myResourcePolicy", {
restApiId: api.id,
policy: pulumi.output(api.id).apply(id => JSON.stringify({
Version: "2012-10-17",
Statement: [
{
Effect: "Allow",
Principal: "*",
Action: "execute-api:Invoke",
Resource: \`arn:aws:execute-api:\${aws.config.region}:\${pulumi.getStack()}:\${id}/*/*/*\`,
Condition: {
IpAddress: {
"aws:SourceIp": [
"203.0.113.0/24", // Replace with your IP range
"198.51.100.0/24" // Replace with your IP range
]
}
}
}
]
}))
});
// Step 3: Attach the Resource Policy
const deployment = new aws.apigateway.Deployment("myDeployment", {
restApi: api.id,
stageName: "prod",
}, { dependsOn: [method] });
const stage = new aws.apigateway.Stage("myStage", {
restApi: api.id,
deployment: deployment.id,
stageName: "prod",
}, { dependsOn: [resourcePolicy] });
export const apiUrl = stage.invokeUrl;
Deploy this code
Want to deploy this code? Sign up for a free Pulumi account to deploy in a few clicks.
Sign upNew to Pulumi?
Want to deploy this code? Sign up with Pulumi to deploy in a few clicks.
Sign upThank you for your feedback!
If you have a question about how to use Pulumi, reach out in Community Slack.
Open an issue on GitHub to report a problem or suggest an improvement.