惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

The Register - Security
The Register - Security
P
Privacy International News Feed
月光博客
月光博客
博客园 - 聂微东
Blog — PlanetScale
Blog — PlanetScale
V
Visual Studio Blog
Y
Y Combinator Blog
酷 壳 – CoolShell
酷 壳 – CoolShell
Google DeepMind News
Google DeepMind News
罗磊的独立博客
Vercel News
Vercel News
Last Week in AI
Last Week in AI
A
About on SuperTechFans
P
Proofpoint News Feed
M
MIT News - Artificial intelligence
人人都是产品经理
人人都是产品经理
H
Hackread – Cybersecurity News, Data Breaches, AI and More
博客园_首页
T
Tailwind CSS Blog
GbyAI
GbyAI
S
Schneier on Security
L
LINUX DO - 热门话题
C
CERT Recently Published Vulnerability Notes
AWS News Blog
AWS News Blog
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
The Hacker News
The Hacker News
N
News and Events Feed by Topic
云风的 BLOG
云风的 BLOG
博客园 - 【当耐特】
C
Cybersecurity and Infrastructure Security Agency CISA
I
Intezer
V2EX - 技术
V2EX - 技术
The GitHub Blog
The GitHub Blog
Scott Helme
Scott Helme
V
V2EX
IT之家
IT之家
S
SegmentFault 最新的问题
爱范儿
爱范儿
L
LangChain Blog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
MongoDB | Blog
MongoDB | Blog
S
Security Affairs
Security Latest
Security Latest
T
The Blog of Author Tim Ferriss
P
Proofpoint News Feed
S
Secure Thoughts
MyScale Blog
MyScale Blog
F
Fortinet All Blogs
Hugging Face - Blog
Hugging Face - Blog
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Provisioning API Gateway and connecting it to Ec-2 instance using Terraform
Viktor Vasyl · 2026-05-06 · via DEV Community

Previous: Provision SSL Certificate

The architecture of our infrastructure is going to change a bit now, as we have to accommodate the API Gateway in between our Ec-2 and the DNS resolution. The overall architecture looks like this:

  • Provision SSL certificate using ACM, for our API Gateway
  • Provision API Gateway itself, and make it proxy requests to EC-2 instance
  • Update Route53 to point our DNS to the Load Balancer
  • Update EC-2 Instance to enable port 80, and update the security group with rule to accept incoming traffic only from API Gateway.

Github Repository

This guide full code is available in https://github.com/IaC-Toolbox/iac-toolbox-project/tree/main/v5-api-gateway. Feel free to clone it and follow along!

Provision SSL Certificate

You can follow the previous guide on Provisioning SSL Certificate to provision the SSL certificate using ACM. Ensure that you have the certificate ARN available for use in the API Gateway module.

Provisioning AWS API Gateway

Now that we have network and SSL certificate, we can start provisioning the API Gateway itself.

Creating API Gateway

First, let's create API Gateway resource:

# modules/api-gateway/main.tf

resource "aws_apigatewayv2_api" "this" {
  name          = var.api_name
  protocol_type = "HTTP"
}

Enter fullscreen mode Exit fullscreen mode

The above creates an API Container for a new API Gateway HTTP API (v2 is the newer version). We tell the API name an tell it that it is an HTTP API. It could be also web socket one if using protocol_type = WEBSOCKET.

Creating Integration to Ec2

Now, we are going to define the integration between our ec2 and the new api gateway:

# modules/api-gateway/main.tf

resource "aws_apigatewayv2_integration" "ec2" {
  api_id                 = aws_apigatewayv2_api.this.id
  integration_type       = "HTTP_PROXY"
  integration_uri        = var.ec2_public_url
  integration_method     = "ANY"
  payload_format_version = "1.0"
}

Enter fullscreen mode Exit fullscreen mode

We define the both uris above - the API Gateway and the EC-2 instance. integration_type tells that it is an HTTP Proxy meaning that all requests are forwarded into integration_url as is. payload_format_version is simply to ensure the request/response payload use HTTP/1.1 passthrough formatting.

Notice that ec2_public_url has to be a full URL like: "http://<public-ec2-ip>:8080"

Integration Routes

Now that we have integration done, we need to specify when to activate it, i.e., on which request route. In our case it is all the requests should be routed to EC-2, so we need to say "whatever the request route/path, proxy it to ec2". Saying it in terraform language is like following:

# modules/api-gateway/main.tf

resource "aws_apigatewayv2_route" "proxy" {
  api_id    = aws_apigatewayv2_api.this.id
  route_key = "ANY /{proxy+}"
  target    = "integrations/${aws_apigatewayv2_integration.ec2.id}"
}

Enter fullscreen mode Exit fullscreen mode

The ANY - match all HTTP methods: GET, POST, PUT, etc., /{proxy+} is to match any pathname, and the target is naturally the target our ec2 integration.

Adding Stage

API Gateways require definition of deployment and stage. Stages exist because API Gateway is designed for API lifecycle management. They allow us define environments like dev vs prod. Let's start coding it:

# modules/api-gateway/main.tf

resource "aws_apigatewayv2_stage" "default" {
  api_id      = aws_apigatewayv2_api.this.id
  name        = "$default"
  auto_deploy = true
}

Enter fullscreen mode Exit fullscreen mode

We will specify $default stage meaning we do not have production and dev environment, we only have 1 environment, since this is enough for our use case. Note, it bigger projects, we could have wanted multiple stages for better deployment strategies of API like separate environments (dev/staging/prod) but only a single API definition.

the auto_deploy = true means changes to routes/integrations are automatically deployed (no need for manual deploys).

Custom Domain Mapping

Finally we have all the integration and rules in place, we are going to move a big higher in the picture and changing DNS and SSL to our Gateway API. It is pretty simple to do:

# modules/api-gateway/main.tf

resource "aws_apigatewayv2_domain_name" "custom" {
  domain_name = var.domain_name

  domain_name_configuration {
    certificate_arn = var.acm_certificate_arn
    endpoint_type   = "REGIONAL"
    security_policy = "TLS_1_2"
  }
}

Enter fullscreen mode Exit fullscreen mode

We simply specify the domain_name for DNS and the certificate_arn for SSL. endpoint_type = "REGIONAL" means that the API Gateway is deployed regionally and is not optimized for edge like for example in cloudfront. Finally we glue it all together in the mapping:

resource "aws_apigatewayv2_api_mapping" "mapping" {
  api_id      = aws_apigatewayv2_api.this.id
  domain_name = aws_apigatewayv2_domain_name.custom.id
  stage       = aws_apigatewayv2_stage.default.id
}

Enter fullscreen mode Exit fullscreen mode

Together, these ensure our API is available at https://api.example.com instead of the ugly default abcdef123.execute-api.us-east-1.amazonaws.com.

Adding Route53 alias record

Finally, we want to make our DNS entry point at the custom domain in API Gateway:

# modules/dns/main.tf
resource "aws_route53_record" "www" {
  zone_id = var.main_zone_id
  name    = var.domain_name
  type    = "A"
  alias {
    name                   = var.target_domain_name
    zone_id                = var.hosted_zone_id
    evaluate_target_health = false
  }
}

Enter fullscreen mode Exit fullscreen mode

With new accepted variables:

# modules/dns/variables.tf
variable "target_domain_name" { type = string }
variable "hosted_zone_id" { type = string }

Enter fullscreen mode Exit fullscreen mode

And we will pass them from the outputs of API Gateway module. So first, let's define the outputs in modules/api-gateway/outputs.tf:

# modules/api-gateway/outputs.tf

output "aws_apigatewayv2_domain_name" {
  value       = aws_apigatewayv2_domain_name.custom.domain_name_configuration[0].target_domain_name
  description = "The custom domain name for the API Gateway"
}

output "aws_apigatewayv2_hosted_zone_id" {
  value       = aws_apigatewayv2_domain_name.custom.domain_name_configuration[0].hosted_zone_id
  description = "The hosted zone ID for the API Gateway custom domain"
}

Enter fullscreen mode Exit fullscreen mode

Using it as a module

Now that we have defined all the moving pieces of the API Gateway module, we can use it in our terraform as follows:

# main.tf
module "api_gateway" {
  source              = "./modules/api-gateway"
  api_name            = "my-api"
  domain_name         = "myapp.example.com"
  acm_certificate_arn = module.ssl_acm.aws_acm_certificate_arn
  ec2_public_url      = "http://${module.ec2.public_ip}:80"
}

Enter fullscreen mode Exit fullscreen mode

Updating Ec-2 firewall rules

We have added an API Gateway and told it that our ec2 is ready to listen on port 80. Next we need to update the firewall security groups of our ec-2 instance so that the port 80 is actually opened. Once it is opened, we will harden the rule by saying that it should accept connections only from our API Gateway. Let's update the Ec-2 security group. From Deploying EC2 instance on AWS with Terraform, our security group originally looks like this:

resource "aws_security_group" "my_app" {
  vpc_id = aws_vpc.main.id

  ingress {
    cidr_blocks = [
      "0.0.0.0/0"
    ]
    from_port = 22
    to_port   = 22
    protocol  = "tcp"
  }

  egress {
    from_port   = 0
    to_port     = 0
    protocol    = "-1"
    cidr_blocks = ["0.0.0.0/0"]
  }
}

Enter fullscreen mode Exit fullscreen mode

We will update it with port 80:

resource "aws_security_group" "my_app" {
  name   = "SSH port for API"
  vpc_id = aws_vpc.main.id

  ingress {
    from_port   = 80
    to_port     = 80
    protocol    = "tcp"
    cidr_blocks = data.aws_ip_ranges.apigw.cidr_blocks
  }
}

Enter fullscreen mode Exit fullscreen mode

And the cird_blocks are the IP ranges that are allowed for that security group, in our case inbound traffic for port 80. The data.aws_ip_ranges.apigw.cidr_blocks come from the official AWS public IP ranges JSON. It will not work just like that, we need to make terraform fetch this JSON by writing it down:

data "aws_ip_ranges" "apigw" {
  services = ["API_GATEWAY"]  # Only API Gateway IPs
  regions  = ["us-east-1"]    # Your API Gateway region
}

Enter fullscreen mode Exit fullscreen mode

We can also output them to see what IPs are those:

output "apigw_ips" {
  value = data.aws_ip_ranges.apigw.cidr_blocks
}

Enter fullscreen mode Exit fullscreen mode

Testing

Now that we have all the code in place, I will let you glue the modules together. Once the code is ready, run terraform init and terraform apply --auto-approve and see that your infra is working now with the API Gateway!

Destroying Infra

Remember, infra has costs. When you are done experimenting, you can destroy the infra like follows:

terraform destroy --auto-approve

Enter fullscreen mode Exit fullscreen mode

Conclusion

And that is a wrap! We have provisioned the setup that achieves the following:

  • Users hit https://www.example.com
  • DNS (Route 53) resolves to API Gateway
  • API Gateway terminates SSL (using ACM cert)
  • Routes any request → EC2 backend (via public IP).

This architecture is great for simple APIs that need SSL offloading without the overhead of load balancers or CDNs. API Gateway handles scaling, SSL, and routing, while EC2 runs your application logic. Continue experimenting and building and follow into the next article.


Previous: Provision SSL Certificate | Next: Application Load Balancer SSL