AWS Builder Center
Building Secure EC2-to-S3 Private Access Using AWS VPC Gateway Endpoint, IAM and Terraform

Building Secure EC2-to-S3 Private Access Using AWS VPC Gateway Endpoint, IAM and Terraform

Learn how to build a secure AWS infrastructure using Amazon VPC, EC2, Amazon S3, IAM least-privilege policies, S3 Gateway Endpoints and Terraform. This hands-on project demonstrates private AWS service connectivity, infrastructure automation, security best practices and real-world troubleshooting.

Student passionate Aws Cloud
Building Secure EC2-to-S3 Private Access Using AWS VPC Gateway Endpoint, IAM and Terraform
Introduction
Cloud security is not just about launching an EC2 instance or creating an S3 bucket. It is about ensuring that resources communicate securely, access is restricted, and infrastructure is designed with security in mind.
In this hands-on project, we will build an AWS environment where an EC2 instance accesses a private Amazon S3 bucket through an S3 Gateway VPC Endpoint.
The project demonstrates how to combine networking, identity and access management, storage security, monitoring and Infrastructure as Code.
Project Objectives
By completing this lab, you will learn how to:
  • Create a custom Amazon VPC and public subnet.
  • Deploy an Amazon EC2 Linux web server.
  • Create a private S3 bucket with Block Public Access enabled.
  • Configure an S3 Gateway VPC Endpoint.
  • Associate the endpoint with a VPC route table.
  • Attach a least-privilege IAM role to EC2.
  • Access S3 without requiring a NAT Gateway for S3 connectivity.
  • Automate infrastructure using Terraform.
  • Monitor EC2 CPU utilization using CloudWatch.
Architecture Overview
The architecture contains:
  1. Amazon VPC – isolated networking environment.
  1. Public subnet – hosts the EC2 instance.
  1. Internet Gateway – provides inbound web access.
  1. EC2 – runs an Nginx web server.
  1. IAM Role – provides restricted S3 permissions.
  1. S3 Gateway Endpoint – routes S3 traffic through the AWS network.
  1. Amazon S3 – stores private application files.
  1. Amazon CloudWatch – monitors EC2 metrics.
Important: Internet access to the web server and private S3 connectivity are two different traffic paths. The S3 Gateway Endpoint does not make the entire EC2 instance private.
Step 1: Prerequisites
Before starting, prepare:
  • An AWS account.
  • AWS CLI configured with appropriate deployment permissions.
  • Terraform installed.
  • Basic knowledge of Linux and networking.
  • An AWS region such as ap-south-1 (Mumbai).
Check your CLI and Terraform installation:
aws --version
terraform --version
aws sts get-caller-identity
Never upload AWS access keys, secret keys, account credentials or sensitive configuration files to a public repository.
Step 2: Create the Infrastructure Using Terraform
Create a project directory:
mkdir secure-ec2-s3-lab
cd secure-ec2-s3-lab
Create a file named main.tf.
The following configuration provisions the VPC, subnet, EC2 instance, private S3 bucket, IAM permissions, S3 Gateway Endpoint and CloudWatch alarm.
terraform {
required_version = ">= 1.5.0"
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 5.0"
}
random = {
source = "hashicorp/random"
version = "~> 3.6"
}
}
}
provider "aws" {
region = "ap-south-1"
}
data "aws_availability_zones" "available" {
state = "available"
}
data "aws_ami" "amazon_linux" {
most_recent = true
owners = ["amazon"]
filter {
name = "name"
values = ["al2023-ami-2023.*-x86_64"]
}
filter {
name = "architecture"
values = ["x86_64"]
}
}
resource "random_id" "suffix" {
byte_length = 4
}
# VPC
resource "aws_vpc" "lab" {
cidr_block = "10.0.0.0/16"
enable_dns_support = true
enable_dns_hostnames = true
tags = {
Name = "Secure-Lab-VPC"
}
}
# Internet Gateway
resource "aws_internet_gateway" "igw" {
vpc_id = aws_vpc.lab.id
tags = {
Name = "Secure-Lab-IGW"
}
}
# Public Subnet
resource "aws_subnet" "public" {
vpc_id = aws_vpc.lab.id
cidr_block = "10.0.1.0/24"
availability_zone = data.aws_availability_zones.available.names[0]
map_public_ip_on_launch = true
tags = {
Name = "Secure-Lab-Public-Subnet"
}
}
# Public Route Table
resource "aws_route_table" "public" {
vpc_id = aws_vpc.lab.id
route {
cidr_block = "0.0.0.0/0"
gateway_id = aws_internet_gateway.igw.id
}
tags = {
Name = "Secure-Lab-Public-RT"
}
}
resource "aws_route_table_association" "public" {
subnet_id = aws_subnet.public.id
route_table_id = aws_route_table.public.id
}
# Security Group
resource "aws_security_group" "web" {
name = "secure-lab-web-sg"
description = "Allow HTTP web access"
vpc_id = aws_vpc.lab.id
ingress {
description = "HTTP"
from_port = 80
to_port = 80
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
egress {
from_port = 0
to_port = 0
protocol = "-1"
cidr_blocks = ["0.0.0.0/0"]
}
}
# Private S3 Bucket
resource "aws_s3_bucket" "app" {
bucket = "secure-ec2-s3-${random_id.suffix.hex}"
tags = {
Name = "Secure-App-Bucket"
Environment = "Lab"
}
}
resource "aws_s3_bucket_public_access_block" "app" {
bucket = aws_s3_bucket.app.id
block_public_acls = true
block_public_policy = true
ignore_public_acls = true
restrict_public_buckets = true
}
resource "aws_s3_bucket_server_side_encryption_configuration" "app" {
bucket = aws_s3_bucket.app.id
rule {
apply_server_side_encryption_by_default {
sse_algorithm = "AES256"
}
}
}
resource "aws_s3_bucket_versioning" "app" {
bucket = aws_s3_bucket.app.id
versioning_configuration {
status = "Enabled"
}
}
# IAM Trust Policy
data "aws_iam_policy_document" "ec2_trust" {
statement {
actions = ["sts:AssumeRole"]
principals {
type = "Service"
identifiers = ["ec2.amazonaws.com"]
}
}
}
resource "aws_iam_role" "ec2_role" {
name = "SecureLabEC2Role"
assume_role_policy = data.aws_iam_policy_document.ec2_trust.json
}
# Least-Privilege S3 Permissions
resource "aws_iam_role_policy" "s3_access" {
name = "SecureLabS3Access"
role = aws_iam_role.ec2_role.id
policy = jsonencode({
Version = "2012-10-17"
Statement = [
{
Effect = "Allow"
Action = [
"s3:ListBucket"
]
Resource = aws_s3_bucket.app.arn
},
{
Effect = "Allow"
Action = [
"s3:GetObject",
"s3:PutObject"
]
Resource = "${aws_s3_bucket.app.arn}/*"
}
]
})
}
# SSM Session Manager access
resource "aws_iam_role_policy_attachment" "ssm" {
role = aws_iam_role.ec2_role.name
policy_arn = "arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore"
}
resource "aws_iam_instance_profile" "ec2" {
name = "SecureLabEC2Profile"
role = aws_iam_role.ec2_role.name
}
# S3 Gateway Endpoint
resource "aws_vpc_endpoint" "s3" {
vpc_id = aws_vpc.lab.id
service_name = "com.amazonaws.ap-south-1.s3"
vpc_endpoint_type = "Gateway"
route_table_ids = [
aws_route_table.public.id
]
policy = jsonencode({
Version = "2012-10-17"
Statement = [
{
Effect = "Allow"
Principal = "*"
Action = [
"s3:ListBucket",
"s3:GetObject",
"s3:PutObject"
]
Resource = [
aws_s3_bucket.app.arn,
"${aws_s3_bucket.app.arn}/*"
]
}
]
})
tags = {
Name = "Secure-S3-Gateway-Endpoint"
}
}
# EC2 Instance
resource "aws_instance" "web" {
ami = data.aws_ami.amazon_linux.id
instance_type = "t3.micro"
subnet_id = aws_subnet.public.id
vpc_security_group_ids = [aws_security_group.web.id]
iam_instance_profile = aws_iam_instance_profile.ec2.name
user_data = <<-EOF
#!/bin/bash
dnf install -y nginx
systemctl enable nginx
systemctl start nginx
cat > /usr/share/nginx/html/index.html <<'HTML'
<html>
<body>
<h1>Secure AWS EC2-to-S3 Lab</h1>
<p>EC2 Web Server Successfully Deployed!</p>
<p>Private S3 access is configured through a VPC Gateway Endpoint.</p>
</body>
</html>
HTML
EOF
tags = {
Name = "Secure-Lab-EC2"
}
depends_on = [
aws_vpc_endpoint.s3,
aws_iam_role_policy_attachment.ssm
]
}
# CloudWatch CPU Alarm
resource "aws_cloudwatch_metric_alarm" "cpu" {
alarm_name = "Secure-Lab-High-CPU"
comparison_operator = "GreaterThanThreshold"
evaluation_periods = 2
metric_name = "CPUUtilization"
namespace = "AWS/EC2"
period = 300
statistic = "Average"
threshold = 70
alarm_description = "EC2 CPU utilization is above 70 percent"
dimensions = {
InstanceId = aws_instance.web.id
}
}
output "ec2_public_ip" {
value = aws_instance.web.public_ip
}
output "s3_bucket_name" {
value = aws_s3_bucket.app.bucket
}
output "ec2_instance_id" {
value = aws_instance.web.id
}
Step 3: Deploy the Infrastructure
Initialize Terraform:
terraform init
Validate the configuration:
terraform validate
Review the deployment plan:
terraform plan
Deploy the resources:
terraform apply
Type yes when prompted.
After deployment, retrieve the outputs:
terraform output
Record the EC2 instance ID and S3 bucket name.
Step 4: Access the EC2 Instance
Open the AWS Management Console.
  1. Navigate to EC2.
  1. Select Instances.
  1. Select Secure-Lab-EC2.
  1. Choose Connect.
  1. Open the Session Manager tab.
  1. Start a session.
The instance has an IAM role for Systems Manager and S3 access. Session Manager avoids opening SSH port 22 to the internet.
Step 5: Test Private S3 Access
Inside the EC2 terminal, check the attached IAM identity:
aws sts get-caller-identity
Create a test file:
echo "Hello from my secure AWS lab" > test.txt
Upload the file to S3:
aws s3 cp test.txt s3://YOUR_BUCKET_NAME/test.txt
List the objects:
aws s3 ls s3://YOUR_BUCKET_NAME/
Download the file:
aws s3 cp s3://YOUR_BUCKET_NAME/test.txt downloaded.txt
Verify the downloaded content:
cat downloaded.txt
Expected result:
Hello from my secure AWS lab
Replace YOUR_BUCKET_NAME with the bucket name printed by Terraform.
Step 6: Verify the VPC Gateway Endpoint
Navigate to:
AWS Console → VPC → Endpoints.
Find the endpoint named:
Secure-S3-Gateway-Endpoint
Verify:
  • Endpoint type: Gateway.
  • Service: Amazon S3.
  • VPC: Secure-Lab-VPC.
  • Route table association: Secure-Lab-Public-RT.
  • State: Available.
The S3 prefix-list route should be visible in the associated route table.
The route table directs same-region S3 traffic through the Gateway Endpoint instead of the default Internet Gateway route.
Step 7: Test the Web Server
Copy the EC2 public IP from Terraform output.
Open this URL in your browser:
Expected result:
Secure AWS EC2-to-S3 Lab
EC2 Web Server Successfully Deployed!
This confirms that the web server is responding to HTTP requests.
Step 8: Monitor EC2 Using CloudWatch
Navigate to:
AWS Console → CloudWatch → Alarms.
Find:
Secure-Lab-High-CPU
The alarm monitors EC2 CPU utilization.
Configuration:
  • Metric: CPUUtilization
  • Namespace: AWS/EC2
  • Threshold: Greater than 70%
  • Evaluation periods: 2
  • Period: 5 minutes
This demonstrates basic infrastructure monitoring.
Step 9: Security Best Practices
The following controls are implemented:
Security Control
Implementation
S3 public access
Blocked
S3 encryption
AES-256
IAM permissions
Bucket-specific
EC2 access
IAM instance profile
SSH access
Not opened
Management access
Session Manager
S3 connectivity
Gateway Endpoint
Monitoring
CloudWatch alarm
Important security distinction: A Gateway Endpoint provides private routing for supported S3 traffic from the associated route table. It does not automatically force every request to the bucket through that endpoint. Enforcing endpoint-only bucket access requires an additional S3 bucket policy using the aws:SourceVpce condition.
Step 10: Troubleshooting
Problem 1: AccessDenied when uploading to S3
Check:
  • EC2 IAM role attachment.
  • IAM policy resource ARN.
  • S3 bucket name.
  • VPC endpoint policy.
Problem 2: S3 endpoint is not working
Check:
  • Endpoint state is Available.
  • Correct VPC selected.
  • Correct route table associated.
  • Bucket and endpoint are in the same AWS Region.
  • Security group and network ACL allow the required traffic.
Problem 3: EC2 web page is not loading
Check:
  • EC2 instance state.
  • Nginx service status.
  • Security group inbound HTTP rule.
  • Public subnet route to the Internet Gateway.
Useful command:
sudo systemctl status nginx
Step 11: Clean Up AWS Resources
Do not leave lab resources running unnecessarily.
After completing the experiment, run:
terraform destroy
Type yes when prompted.
Note: S3 buckets containing objects cannot be deleted automatically by Terraform unless the objects are removed first. Empty the test bucket before destroying the infrastructure.
Project Outcome
Through this project, I explored how multiple AWS services work together to create a more secure cloud environment.
Key practical concepts:
  • VPC networking and routing.
  • EC2 deployment and Linux administration.
  • S3 bucket security.
  • IAM roles and least-privilege access.
  • VPC Gateway Endpoints.
  • Terraform Infrastructure as Code.
  • AWS Systems Manager Session Manager.
  • CloudWatch monitoring.
  • Troubleshooting and resource cleanup.
This project helped me connect theoretical AWS concepts with practical cloud infrastructure deployment.
What’s Next?
Possible improvements for the next version:
  1. Move EC2 into a private subnet.
  1. Add an Application Load Balancer.
  1. Configure HTTPS using ACM.
  1. Add CloudTrail for API auditing.
  1. Add S3 bucket policies to enforce endpoint-only access.
  1. Integrate Terraform with GitHub Actions.
  1. Add automated deployment and monitoring.
Conclusion
Building secure cloud infrastructure requires more than deploying resources. It requires understanding how networking, identity, storage and monitoring work together.
The combination of EC2, S3, IAM and VPC Gateway Endpoints provides a practical foundation for learning AWS cloud security.
I would love to hear from the AWS community:
How would you improve this architecture for a production environment? Would you move EC2 into a private subnet, add an Application Load Balancer, or introduce additional security controls?
Share your suggestions and feedback in the comments!
#AWS #AWSSecurity #AmazonEC2 #AmazonS3 #Terraform
Any opinions in this article are those of the individual author and may not reflect the opinions of AWS.
Enjoyed reading this content? Let the author know!

Your likes, comments, shares, and saves help creators reach more builders.

Loading recommendations

Loading article