<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Remmy on Medium]]></title>
        <description><![CDATA[Stories by Remmy on Medium]]></description>
        <link>https://medium.com/@r-owino?source=rss-89c9d1406517------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Stories by Remmy on Medium</title>
            <link>https://medium.com/@r-owino?source=rss-89c9d1406517------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 21:56:59 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@r-owino/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[RDS Multi-AZ Connectivity Trap]]></title>
            <link>https://medium.com/@r-owino/rds-multi-az-connectivity-trap-4abcd3418ba0?source=rss-89c9d1406517------2</link>
            <guid isPermaLink="false">https://medium.com/p/4abcd3418ba0</guid>
            <category><![CDATA[development]]></category>
            <category><![CDATA[rds-multi-az]]></category>
            <category><![CDATA[rds]]></category>
            <category><![CDATA[production]]></category>
            <dc:creator><![CDATA[Remmy]]></dc:creator>
            <pubDate>Fri, 13 Jun 2025 17:57:44 GMT</pubDate>
            <atom:updated>2025-06-13T18:20:22.543Z</atom:updated>
            <content:encoded><![CDATA[<h4>So well hidden, you’ll pull your hair trying to reach the RDS instance</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/585/1*8CQ4noOeKMIPLQM9vRljAw.png" /><figcaption>[<a href="https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/multi-az-db-clusters-concepts.html">Source</a>] Amazon RDS Multi-AZ DB cluster</figcaption></figure><h3>The Problem</h3><p>Is that you have deployed a PostgreSQL RDS instance in a VPC using Terraform and set it to be publicly accessible from a public subnet (publicly_accessible = true ) with proper security groups allowing port 5432 from anywhere, and public subnets with internet gateways. Yet local connection attempts time out:</p><pre>$ nc -nz demo-postgres.c6c8mn7fake0.us-west-2.rds.amazonaws.com 5432<br>Trying 12.123.123.123...<br>telnet: Unable to connect to remote host: Connection timed out</pre><p>Meanwhile, an identically configured instance created through the AWS Console connects without issues. The difference? One critical setting: multi_az = true</p><h3>So you decide to dig in</h3><p>And discover that AWS RDS Multi-AZ deployments introduce a subtle but critical networking complexity. Why? When you enable Multi-AZ, Amazon RDS creates a primary DB instance in one Availability Zone that is associated with a subnet. Then, Amazon RDS creates a standby DB instance in a different Availability Zone that is associated with a different subnet.</p><p>The critical issue: In a Multi-AZ DB deployment, you can’t choose the Availability Zones for the primary and secondary DB instances because Amazon RDS chooses them for you randomly. This means your primary instance might end up in a subnet with inadequate routing configuration for public access. Interesting!</p><h3>And dig in deeper</h3><p>To understand subnet selection behavior in a Multi-AZ DB cluster in RDS, because it doesn’t guarantee which subnet becomes the primary. Even with identically configured “public” subnets, subtle differences in route table associations or timing can cause connectivity issues.</p><p>If the primary instance’s subnet has different traffic-routing rules than the standby DB instance’s subnet, you might experience connection issues after a failover. This principle applies even during initial deployment — if the randomly selected primary subnet has routing issues, you’ll face immediate connectivity problems.</p><h3>Awesome! With this additional knowledge</h3><p>You analyse your Terraform configuration again for the umpteenth time, starting with the VPC, subnets, and the security group attached to the RDS instance configuration:</p><pre>resource &quot;aws_vpc&quot; &quot;main&quot; {<br>  cidr_block           = &quot;10.0.0.0/16&quot;<br>  enable_dns_hostnames = true<br>  enable_dns_support   = true<br><br>  tags = {<br>    Name        = &quot;${var.project_name}-vpc&quot;<br>    Environment = var.environment<br>  }<br>}<br><br>resource &quot;aws_internet_gateway&quot; &quot;main&quot; {<br>  vpc_id = aws_vpc.main.id<br><br>  tags = {<br>    Name        = &quot;${var.project_name}-igw&quot;<br>    Environment = var.environment<br>  }<br>}<br><br># route table<br>resource &quot;aws_route_table&quot; &quot;public&quot; {<br>  vpc_id = aws_vpc.main.id<br><br>  route {<br>    cidr_block = &quot;0.0.0.0/0&quot;<br>    gateway_id = aws_internet_gateway.main.id<br>  }<br><br>  tags = {<br>    Name        = &quot;${var.project_name}-public-rt&quot;<br>    Environment = var.environment<br>  }<br>}<br><br>resource &quot;aws_route_table_association&quot; &quot;public&quot; {<br>  count = length(aws_subnet.public)<br><br>  subnet_id      = aws_subnet.public[count.index].id<br>  route_table_id = aws_route_table.public.id<br>}<br><br># subnets<br>resource &quot;aws_subnet&quot; &quot;public&quot; {<br>  count = 2<br><br>  vpc_id                  = aws_vpc.main.id<br>  cidr_block              = &quot;10.0.${count.index + 1}.0/24&quot;<br>  availability_zone       = data.aws_availability_zones.available.names[count.index]<br>  map_public_ip_on_launch = true<br><br>  tags = {<br>    Name        = &quot;${var.project_name}-public-${count.index + 1}&quot;<br>    Environment = var.environment<br>  }<br>}<br><br>data &quot;aws_availability_zones&quot; &quot;available&quot; {<br>  state = &quot;available&quot;<br>}<br><br># rds security group<br>resource &quot;aws_security_group&quot; &quot;rds&quot; {<br>  name_prefix = &quot;${var.project_name}-rds&quot;<br>  vpc_id      = aws_vpc.main.id<br><br>  ingress {<br>    from_port   = 5432<br>    to_port     = 5432<br>    protocol    = &quot;tcp&quot;<br>    cidr_blocks = [&quot;0.0.0.0/0&quot;]<br>  }<br><br>  tags = {<br>    Name        = &quot;${var.project_name}-rds-sg&quot;<br>    Environment = var.environment<br>  }<br>}</pre><p>VPC networking is okay because it correctly includes:</p><ul><li>Public subnets with map_public_ip_on_launch = true</li><li>Internet Gateway attached to VPC</li><li>Route table with 0.0.0.0/0 → Internet Gateway</li><li>Security group allowing inbound port 5432</li></ul><p>You proceed to the RDS configuration:</p><pre>resource &quot;aws_db_instance&quot; &quot;postgres&quot; {<br>  identifier            = &quot;${var.project_name}-postgres&quot;<br>  engine                = &quot;postgres&quot;<br>  engine_version        = &quot;17.5&quot;<br>  instance_class        = &quot;db.t3.micro&quot;<br>  allocated_storage     = 20<br>  max_allocated_storage = 100<br>  storage_type          = &quot;gp2&quot;<br>  storage_encrypted     = true<br><br>  publicly_accessible = true<br><br>  db_name  = &quot;db-name&quot;<br>  username = &quot;postgres&quot;<br>  password = random_password.db_password.result<br><br>  vpc_security_group_ids = [aws_security_group.rds.id]<br>  db_subnet_group_name   = aws_db_subnet_group.main.name<br><br>  multi_az = true # this is your headache<br><br>  tags = {<br>    Name        = &quot;${var.project_name}-postgres&quot;<br>    Environment = var.environment<br>  }<br>}</pre><p>To diagnose the subnet selection issues, you run these commands:</p><pre># Check which subnets your Multi-AZ instance is using<br>aws rds describe-db-instances \<br>  --db-instance-identifier db-identifier-name \<br>  --query &#39;DBInstances[0].DBSubnetGroup.Subnets[*].[SubnetIdentifier,AvailabilityZone.Name]&#39; \<br>  --output table<br><br># Verify route table associations for each subnet<br>aws ec2 describe-route-tables \<br>  --filters &quot;Name=association.subnet-id,Values=subnet-xxxxx&quot; \<br>  --query &#39;RouteTables[0].Routes[*].[DestinationCidrBlock,GatewayId]&#39; \<br>  --output table</pre><h3>Networking is okay</h3><p>Of course, it’s okay because you manually created a similar RDS instance on the console, but minus enabling the Multi-AZ setting. So, what would be a quick fix here?</p><p><strong>Disabling the Multi-AZ setting</strong></p><p>This is a development environment, where high availability is a non-issue</p><pre>resource &quot;aws_db_instance&quot; &quot;postgres&quot; {<br>  # ... other configuration<br>  publicly_accessible = true<br>  multi_az = false  # Forces single-AZ deployment<br>  # ... rest of configuration<br>}</pre><p>For a production environment, which typically requires Multi-AZ, ensure subnet consistency:</p><pre># Ensure identical route table associations<br>resource &quot;aws_route_table_association&quot; &quot;public&quot; {<br>  count = length(aws_subnet.public)<br>  <br>  subnet_id      = aws_subnet.public[count.index].id<br>  route_table_id = aws_route_table.public.id<br>}<br><br># Verify all subnets have identical NACL rules<br>resource &quot;aws_network_acl_association&quot; &quot;public&quot; {<br>  count = length(aws_subnet.public)<br>  <br>  network_acl_id = aws_network_acl.public.id<br>  subnet_id      = aws_subnet.public[count.index].id<br>}</pre><p>Alternatively, you can configure an RDS Proxy and use it for consistent connectivity:</p><pre>resource &quot;aws_db_proxy&quot; &quot;main&quot; {<br>  name                   = &quot;${var.project_name}-proxy&quot;<br>  engine_family          = &quot;POSTGRESQL&quot;<br>  require_tls            = true<br>  vpc_subnet_ids         = aws_subnet.private[*].id<br>  <br>  target {<br>    db_instance_identifier = aws_db_instance.postgres.id<br>  }<br>  <br>  auth {<br>    auth_scheme = &quot;SECRETS&quot;<br>    secret_arn  = aws_secretsmanager_secret.db_credentials.arn<br>  }<br>}</pre><h3>Now you know</h3><p>That Multi-AZ isn’t just about failover — it fundamentally changes how your database is deployed across subnets.</p><p>For development environments</p><ul><li>Use multi_az = false for cost and connectivity simplicity.</li><li>Enable Multi-AZ only when testing failover scenarios.</li></ul><p>For Production Environments</p><ul><li>Verify subnet route table consistency before deployment.</li><li>Use private subnets with NAT Gateways for better security or VPC endpoints to access other AWS services.</li><li>Implement RDS Proxy for connection pooling and consistent endpoints.</li><li>Test failover scenarios in staging with identical subnet configurations.</li></ul><h3>In conclusion</h3><p>Multi-AZ connectivity issue represents a classic infrastructure gotcha: a feature designed for reliability (Multi-AZ) introducing complexity that can break basic functionality (connectivity). This happens because Amazon RDS chooses them for you randomly without considering your specific networking requirements.</p><p>Key takeaway - Multi-AZ isn’t just a checkbox for high availability; it’s a fundamental architectural decision that affects subnet selection, routing, and connectivity patterns. Always validate your networking configuration across all potential AZ combinations before deploying Multi-AZ instances in production.</p><p>For development workflows, the simple solution is often the best: disable Multi-AZ until you specifically need to test failover scenarios. For production systems, invest in proper subnet consistency validation and consider RDS Proxy for additional connection reliability.</p><h3>Read more</h3><p><a href="https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/Concepts.MultiAZ.html">AWS RDS Multi-AZ Documentation</a></p><p><a href="https://aws.amazon.com/premiumsupport/knowledge-center/avoid-route-table-issues-rds/">Troubleshoot connectivity issues to Amazon RDS Multi-AZ instances after failover</a></p><p><a href="https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_VPC.WorkingWithRDSInstanceinaVPC.html">Working with a DB instance in a VPC</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4abcd3418ba0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Files On Cloud: Hands-On AWS Project]]></title>
            <link>https://medium.com/@r-owino/files-on-cloud-hands-on-aws-project-64af111843b9?source=rss-89c9d1406517------2</link>
            <guid isPermaLink="false">https://medium.com/p/64af111843b9</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[docker-compose]]></category>
            <category><![CDATA[github-actions]]></category>
            <dc:creator><![CDATA[Remmy]]></dc:creator>
            <pubDate>Fri, 11 Apr 2025 03:11:53 GMT</pubDate>
            <atom:updated>2026-05-05T20:52:02.182Z</atom:updated>
            <content:encoded><![CDATA[<h4>Part 4: The Deployment — On Amazon ECS using Amazon ECR and GitHub Actions</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4l2eNoBBJyVjP52U" /><figcaption>Photo by <a href="https://unsplash.com/@goian?utm_source=medium&amp;utm_medium=referral">Ian Schneider</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>At last! We have a functional and fully responsive web application that users can interact with! But, not so fast… Currently, the app runs on the localhost, which is good for us because we can play with it to our heart’s content, but bad for users because they remain locked out of the experience we’ve worked so hard to create.</p><p>We can make the deployment process less painful by adopting DevOps principles.</p><p>In this article, we’ll go through the steps of understanding why containerization is important and build that understanding into a local multi-service environment using Docker Compose. Then, we’ll bridge into cloud deployment by implementing a CI pipeline with GitHub Actions and finally deploy the application to Amazon ECS with a custom domain and SSL certificate. Let’s get deploying!</p><h3>Pre-requisites</h3><p>This guide assumes that you have the Docker Engine and Docker Compose installed on your local machine. If not, use <a href="https://docs.docker.com/engine/install/">this guide</a> to install Docker Engine and <a href="https://docs.docker.com/compose/install/">this guide</a> to install Docker Compose.</p><h3>Deployment Architecture</h3><p>The final architecture diagram takes this format:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IXTRGwasFVlnKdNpgyq-5w.png" /><figcaption>[Author’s diagram] Deployment architecture diagram</figcaption></figure><p>Key flow:</p><ol><li>User access — Route 53 acts as the authoritative DNS service that translates the human-readable domain into the IP address of the Application Load Balancer.</li><li>Load balancing — After Route 53 resolves the domain to the ALB’s IP address, traffic flows to the ALB in the public subnet.</li><li>Certificate management — ACM provides SSL/TLS certificates to secure the communication between users and the ALB, ensuring all data transmission is encrypted.</li><li>Cross-zone load balancing — ALB distributes incoming requests across the ECS Fargate containers running in private subnets across multiple availability zones.</li></ol><h3>Containerization</h3><p>To deploy to cloud, we first need to understand how to orchestrate multiple services working together. This application depends on Redis for session management and file metadata caching, requires infrastructure provisioning through Terraform, and benefits from API health monitoring to ensure reliability.</p><p>Docker Compose provides a platform where we can experiment locally with how the services work together before deploying them to cloud production.</p><h4>Containerize the Flask Application</h4><p>In the Dockerfile in the /api directory, have the following:</p><pre># Build stage<br>FROM python:3.11-alpine AS builder<br><br># Update package index and install build dependencies<br>RUN apk update &amp;&amp; apk add --no-cache --virtual .build-deps \<br>    gcc \<br>    musl-dev \<br>    libffi-dev \<br>    openssl-dev<br><br># Install Python dependencies<br>WORKDIR /app<br>COPY api/requirements.txt .<br>RUN --mount=type=cache,target=/root/.cache/pip \<br>    pip install --no-cache-dir --prefix=/install -r requirements.txt<br><br># Test stage<br>FROM python:3.11-alpine AS test<br><br># Install runtime dependencies<br>RUN apk add --no-cache libffi openssl &amp;&amp; \<br>    addgroup -g 1000 appuser &amp;&amp; \<br>    adduser -D -u 1000 -G appuser appuser<br><br># Copy installed packages<br>COPY --from=builder /install /usr/local<br><br># Copy application and test files<br>COPY --chown=appuser:appuser api/v1/app.py api/v1/cognito.py api/v1/config.py api/v1/__init__.py /app/v1/<br>COPY --chown=appuser:appuser api/v1/routes/ /app/v1/routes/<br>COPY --chown=appuser:appuser api/v1/static/ /app/v1/static/<br>COPY --chown=appuser:appuser api/v1/templates/ /app/v1/templates/<br>COPY --chown=appuser:appuser api/tests /app/tests<br><br>USER appuser<br>WORKDIR /app<br>ENV PYTHONPATH=/app \<br>    PATH=&quot;/usr/local/bin:$PATH&quot; \<br>    PYTHONUNBUFFERED=1 \<br>    AWS_SECRET_NAME=filesoncloud-app-secrets \<br>    AWS_REGION=us-west-2<br><br># Testing command<br>CMD [&quot;python&quot;, &quot;-m&quot;, &quot;pytest&quot;, &quot;tests/&quot;, &quot;-v&quot;]<br><br># Production stage<br>FROM python:3.11-alpine AS production<br><br># Install runtime dependencies and create user<br>RUN apk add --no-cache libffi openssl &amp;&amp; \<br>    addgroup -g 1000 appuser &amp;&amp; \<br>    adduser -D -u 1000 -G appuser appuser<br><br># Copy installed packages<br>COPY --from=builder /install /usr/local<br><br># Copy application files<br>COPY --chown=appuser:appuser api/v1/app.py api/v1/cognito.py api/v1/config.py api/v1/__init__.py /app/v1/<br>COPY --chown=appuser:appuser api/v1/routes/ /app/v1/routes/<br>COPY --chown=appuser:appuser api/v1/static/ /app/v1/static/<br>COPY --chown=appuser:appuser api/v1/templates/ /app/v1/templates/<br><br>USER appuser<br>WORKDIR /app/v1<br>ENV PYTHONPATH=/app \<br>    PATH=&quot;/usr/local/bin:$PATH&quot; \<br>    PYTHONUNBUFFERED=1 \<br>    AWS_SECRET_NAME=filesoncloud-app-secrets \<br>    AWS_REGION=us-west-2<br><br>CMD [&quot;gunicorn&quot;, &quot;-w&quot;, &quot;4&quot;, &quot;-k&quot;, &quot;gthread&quot;, &quot;-b&quot;, &quot;0.0.0.0:5000&quot;, &quot;v1.app:app&quot;]</pre><p>This Dockerfile leverages multi-stage builds to create a maintainable containerized environment for the Flask application. It uses a three-stage build process that addresses dependency management, testing integration, and production optimization, each stage serving a specific purpose in creating the deployment pipeline.</p><h4>Containerize Terraform Infrastructure</h4><p>Before containerizing the Terraform code, add modules for Route53, ACM, ALB, ECR, ECS Fargate, and VPC. These modules will handle Docker image storage, application deployment, DNS resolution, and certificate management. The final file structure for the /infra directory should be as follows:</p><pre>$ infra<br>.<br>├── backend.tf<br>├── bootstrap<br>│   ├── main.tf<br>│   ├── outputs.tf<br>│   ├── providers.tf<br>│   └── variables.tf<br>├── Dockerfile<br>├── main.tf<br>├── modules<br>│   ├── acm<br>│   │   ├── main.tf<br>│   │   ├── outputs.tf<br>│   │   └── variables.tf<br>│   ├── alb<br>│   │   ├── main.tf<br>│   │   ├── outputs.tf<br>│   │   └── variables.tf<br>│   ├── api_gateway<br>│   │   ├── api-gateway-policy.json<br>│   │   ├── main.tf<br>│   │   ├── outputs.tf<br>│   │   └── variables.tf<br>│   ├── cloudfront<br>│   │   ├── main.tf<br>│   │   ├── outputs.tf<br>│   │   ├── public_key.pem<br>│   │   └── variables.tf<br>│   ├── cognito<br>│   │   ├── main.tf<br>│   │   ├── outputs.tf<br>│   │   └── variables.tf<br>│   ├── dynamodb<br>│   │   ├── main.tf<br>│   │   ├── outputs.tf<br>│   │   └── variables.tf<br>│   ├── ecr<br>│   │   ├── main.tf<br>│   │   ├── outputs.tf<br>│   │   └── variables.tf<br>│   ├── ecs<br>│   │   ├── ecs-assume-role-policy.json<br>│   │   ├── ecs-execution-policy.json<br>│   │   ├── ecs-secrets-policy.json<br>│   │   ├── ecs-task-policy.json<br>│   │   ├── main.tf<br>│   │   ├── outputs.tf<br>│   │   └── variables.tf<br>│   ├── lambda<br>│   │   ├── delete_file_lambda.py<br>│   │   ├── file-metadata-lambda-dynamodb-policy.json<br>│   │   ├── file_metadata_lambda.py<br>│   │   ├── lambda-delete-file-policy.json<br>│   │   ├── lambda-dynamodb-policy.json<br>│   │   ├── lambda-logs-policy.json<br>│   │   ├── lambda-policy.json<br>│   │   ├── lambda-s3-policy.json<br>│   │   ├── main.tf<br>│   │   ├── outputs.tf<br>│   │   ├── requirements.txt<br>│   │   ├── upload_file_metadata_lambda.py<br>│   │   ├── upload-lambda-dynamodb-policy.json<br>│   │   ├── userdata-lambda-dynamodb-policy.json<br>│   │   ├── userdata_lambda.py<br>│   │   └── variables.tf<br>│   ├── route53<br>│   │   ├── main.tf<br>│   │   ├── outputs.tf<br>│   │   └── variables.tf<br>│   ├── s3<br>│   │   ├── bucket-policy.json<br>│   │   ├── cloudfront-s3-policy.json<br>│   │   ├── log-bucket-policy.json<br>│   │   ├── main.tf<br>│   │   ├── outputs.tf<br>│   │   └── variables.tf<br>│   ├── secrets_manager<br>│   │   ├── main.tf<br>│   │   ├── outputs.tf<br>│   │   ├── secrets-access-policy.json<br>│   │   ├── secrets-access-role.json<br>│   │   └── variables.tf<br>│   └── vpc<br>│       ├── main.tf<br>│       ├── outputs.tf<br>│       └── variables.tf<br>├── outputs.tf<br>├── providers.tf<br>└── variables.tf</pre><p>In the Dockerfile in the directory, paste the following contents:</p><pre># Build stage<br>FROM alpine:3.20 AS builder<br><br>ARG TERRAFORM_VERSION=1.11.3<br>RUN apk update &amp;&amp; apk add --no-cache wget unzip python3 py3-pip zip jq openssl<br>RUN wget -q https://releases.hashicorp.com/terraform/${TERRAFORM_VERSION}/terraform_${TERRAFORM_VERSION}_linux_amd64.zip &amp;&amp; \<br>    unzip terraform_${TERRAFORM_VERSION}_linux_amd64.zip<br><br># Production stage<br>FROM alpine:3.20 AS production<br><br>RUN apk update &amp;&amp; apk add --no-cache ca-certificates python3 py3-pip zip jq openssl &amp;&amp; \<br>    adduser -D -u 1000 terraform<br><br>COPY --from=builder terraform /usr/local/bin/<br>COPY --chown=terraform infra/main.tf infra/outputs.tf infra/providers.tf infra/variables.tf ./<br>COPY --chown=terraform infra/modules/ ./modules/<br><br>USER terraform<br>WORKDIR /terraform</pre><p>Unlike the API Dockerfile, this one follows a simpler two-stage approach that focuses on creating a portable, consistent infrastructure management environment. This consistency ensures that infrastructure changes behave predictably regardless of where they’re executed, reducing the “works on my machine” problems that plague infrastructure management.</p><h3>Connect the Services Using Docker Compose</h3><p>Now that both the Flask app and the Terraform code are containerized, we need them to communicate effectively while efficiently storing Flask session state in the Redis container and periodically checking the health status of the API.</p><p>In the project’s root directory, createdocker-compose.yaml file. The full file is in the <a href="https://github.com/R-Owino/files-on-cloud">GitHub repository</a>. The api service below illustrates the key patterns, such as healthcheck, service dependencies, and environment configuration.</p><pre>services:<br>  api:<br>    container_name: api<br>    build:<br>      context: .<br>      dockerfile: api/Dockerfile<br>      target: production<br>    ports:<br>      - &quot;5000:5000&quot;<br>    volumes:<br>      - ~/.aws:/home/appuser/.aws:ro<br>      - ./api/v1/static:/app/v1/static:ro<br>      - ./api/v1/templates:/app/v1/templates:ro<br>      - api_tmp:/tmp<br>    depends_on:<br>      redis:<br>        condition: service_healthy<br>    networks:<br>      - filesoncloud<br>    environment:<br>      - PYTHONPATH=/app<br>      - PYTHONUNBUFFERED=1<br>      - ENVIRONMENT=local<br>      - REDIS_HOST=redis<br>    healthcheck:<br>      test: [&quot;CMD&quot;, &quot;python&quot;, &quot;-c&quot;, &quot;import requests; requests.get(&#39;http://localhost:5000/health/liveness&#39;, timeout=3)&quot;]<br>      interval: 10s<br>      timeout: 5s<br>      retries: 10<br>      start_period: 30s<br>    restart: unless-stopped<br>    logging:<br>      driver: json-file<br>      options:<br>        max-size: &quot;10m&quot;<br>        max-file: &quot;3&quot;</pre><p>This file manages 4 Docker containers on a Docker network. Let’s go over each service setup:</p><h4><strong>Terraform service</strong></h4><ul><li>Builds from the Terraform Dockerfile</li><li>Runs complete infrastructure deployment: init → validate → plan → apply</li><li>Mounts AWS credentials and caches Terraform state</li><li>Creates a completion marker file for dependency coordination</li><li>Uses a custom healthcheck to signal when the infrastructure is ready</li></ul><h4>Redis service</h4><ul><li>Custom Redis build with AWS integration</li><li>Retrieves configuration (Redis password and port number) from AWS Secrets Manager</li><li>Runs the health check script to verify connectivity</li><li>Acts as a session store/cache for the API</li></ul><h4>API service</h4><ul><li>The Flask application running on port 5000</li><li>Waits for both Terraform and Redis services to be healthy before starting</li><li>Mounts AWS credentials and static assets</li><li>Uses Python requests for HTTP health checks to the health endpoint</li><li>Configured with log rotation and restart policies</li></ul><h4>Health-monitor service</h4><ul><li>Lightweight curl-based monitoring container</li><li>Continuously polls the API health endpoint every 60 seconds</li><li>Runs with security hardening (read-only, no-new-privileges, non-root user)</li><li>Provides ongoing health visibility after startup</li></ul><p>When we build and run Docker Compose, we should be able to access the application through the browser. Run this command, ensuring you’re at the root of the project on the terminal.</p><pre>docker compose up --build</pre><p>To access the application, enter <a href="http://0.0.0.0:5000/">http://0.0.0.0:5000/</a> in your browser:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LdfDDSG2PhHnpdUdR7wSbA.png" /><figcaption>[Author’s image] Files on cloud home page before deployement</figcaption></figure><h3>CI pipeline with GitHub Actions</h3><p>Now that we have a sense of how the services integrate locally and are ready to automate the deployment process to Amazon ECS, we can automate the build, test, and deploy processes using a simple pipeline with GitHub Actions. The Docker Compose environment and the ECS environment serve similar orchestration purposes, but operate at different scales with different constraints. The CI pipeline handles the translation between these environments.</p><p>Create a directory .github in the project’s root directory. The directory’s file structure should look like this:</p><pre>.<br>├── actions<br>│   ├── aws-setup<br>│   │   └── action.yaml<br>│   ├── python-setup<br>│   │   └── action.yaml<br>│   └── terraform-setup<br>│       └── action.yaml<br>└── workflows<br>    ├── ci-build.yaml<br>    ├── ci-deploy-app.yaml<br>    ├── ci-deploy-infra.yaml<br>    ├── ci-test.yaml<br>    ├── linting.yaml<br>    └── main.yaml</pre><p>We need to securely access AWS services to run the Terraform code in the workflow. One way would be to use AWS credentials stored in GitHub secrets. This approach is risky because:</p><ol><li>The credentials are visible to collaborators and anyone with admin or write access to the repository, and they could exfiltrate the credentials.</li><li>The secrets can be exposed unintentionally in poorly written workflows.</li><li>Credentials stored in GitHub secrets are static access keys, which, if compromised, can be used indefinitely until rotated.</li></ol><p>A more secure way is to integrate OpenID Connect into the workflow. This approach does not require storing the credentials as long-lived secrets in GitHub secrets. It ensures that we do not need to create, rotate, or manage access and secret keys, therefore reducing unauthorized access risks.</p><h4>Create an OIDC identity provider and a role</h4><p>Follow the steps below to create the OIDC identity provider for the workflow:</p><ol><li>Navigate to the IAM console in AWS.</li><li>Go to Identity Providers under the Access management section.</li><li>Select OpenID Connect as the provider type.</li><li>In the Provider URL, enter <a href="https://token.actions.githubusercontent.com/"><em>https://token.actions.githubusercontent.com</em></a></li><li>In the Audience field, enter <a href="http://sts.amazonaws.com/"><em>sts.amazonaws.com</em></a></li><li>Click Add provider to finalize.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*x0XQRurDHnn2hdKU" /><figcaption>Create an OIDC identit provider</figcaption></figure><p>Once you click on Add provider, a new identity provider will be created:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*p-yXT04KocAM8Pe3" /><figcaption>Newly created OIDC identity provider</figcaption></figure><p>Create the role that uses the OIDC provider. This is what we’ll use in the workflow:</p><ol><li>Navigate to Roles under the Access Management section</li><li>Click Create role.</li><li>Choose Web Identity as the Trusted Entity Type.</li><li>Choose the OIDC identity provider created in the last step.</li><li>Select sts.amazonaws.com for the Audience.</li><li>Input your GitHub Username for the GitHub organization; otherwise, put the name of your GitHub organization.</li><li>You can choose to input the repository and branch name that will use the role.</li><li>Click Next.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*x-YHRSeVZia-lCH-" /><figcaption>Choose Web Identuty as the trusted entity type while creating the role</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jX7zZbmjCX28mcy4" /></figure><p>9. Attach a permission policy for the role. AdministratorAccess policy works, but you can fine-grain the permissions to suit your needs.</p><p>10. Click Next</p><p>11. Give your role a name and a description.</p><p>12. Review the Trust Policy generated.</p><p>13. Click Create Role.</p><p>In the workflow, we will use the role’s ARN to configure AWS Credentials. In the actions/aws-setup/actions.yaml file, have the following composite action:</p><pre>name: AWS Credentials Setup<br>description: Composite action to configure AWS credentials by assuming an IAM role<br><br>inputs:<br>  role-to-assume:<br>    description: ARN of the IAM role to assume for AWS Credentials<br>    required: true<br>  role-session-name:<br>    description: Identifier for the assumed role session<br>    required: true<br><br>runs:<br>  using: &quot;composite&quot;<br>  steps:<br>    - name: Configure AWS credentials<br>      uses: aws-actions/configure-aws-credentials@v4<br>      with:<br>        role-to-assume: ${{ inputs.role-to-assume }}<br>        role-session-name: ${{ inputs.role-session-name }}<br>        aws-region: ${{ env.AWS_REGION }}</pre><p>In each workflow that requires AWS credentials, this composite action will be referenced.</p><p>The main workflow orchestrates the entire deployment process from code commit to production deployment. It demonstrates how to maintain reliability while enabling rapid iteration. The full workflow file is in the repository. Here’s the jobs section that shows the dependency chain:</p><pre>jobs:<br>  build:<br>    uses: ./.github/workflows/ci-build.yaml<br>    secrets: inherit<br><br>  test:<br>    needs: build<br>    uses: ./.github/workflows/ci-test.yaml<br>    secrets: inherit<br><br>  deploy-infrastructure:<br>    if: github.ref == &#39;refs/heads/main&#39;<br>    needs: [build, test]<br>    uses: ./.github/workflows/ci-deploy-infra.yaml<br>    secrets: inherit<br><br>  deploy-application:<br>    if: github.ref == &#39;refs/heads/main&#39;<br>    needs: [build, test, deploy-infrastructure]<br>    uses: ./.github/workflows/ci-deploy-app.yaml<br>    secrets: inherit<br><br>  cleanup:<br>    if: always() &amp;&amp; (github.ref == &#39;refs/heads/main&#39;)<br>    needs: [deploy-application]<br>    ...</pre><p>The job dependencies ensure that infrastructure changes are applied before application deployment, while the output passing between jobs enables dynamic configuration based on actual infrastructure state.</p><p>The deploy-infra job runs in two stages to handle ACM validation cleanly:</p><ul><li>Stage 1 creates the ACM certificate and the Route 53 DNS validation records, then polls AWS with aws acm wait certificate-validated until the certificate status changes to ISSUED . This step requires your domain’s nameservers to already point to Route 53, otherwise ACM won’t find the validation record and it will time out. See the domain configuration section below for how to set this up before running the pipeline for the first time.</li><li>Stage 2 runs the full terraform apply once the certificate is confirmed valid. At this point, the aws_acm_certificate_validation Terraform resource completes immediately since ACM has already issued the certificate. All remaining infrastructure is provisioned in this step.</li></ul><p>This separation means a slow DNS propagation only blocks Stage 1, not the entire apply, and makes the failure point explicit.</p><p>The image tagging strategy using Git SHA provides traceability between deployments and source code, making it easy to identify which code version is running in production. The ECS service update with force deployment ensures that new container images are deployed even when the task definition hasn’t changed.</p><h4>Deploy to Amazon ECS</h4><p>The main CI workflow runs successfully, the application has been deployed to Amazon ECS, now what? Verify by checking the interconnected components to ensure everything is working correctly. This verification helps in catching issues early and understanding the deployment’s current state before configuring the domain.</p><p>Navigate to the console and systematically verify each component that the Terraform code configuration should have created:</p><ol><li>ECR repository verification — on the ECR console, confirm that the Docker images are present in the repository. There should be images with tags corresponding to the CI pipeline runs, commit SHA in this case.</li><li>ECS cluster and service status — on the ECS console, navigate to the created cluster and examine both the cluster overview and the individual services. The ECS tasks should show as “RUNNING” status, not “PENDING” or “STOPPED”. If tasks are cycling between states, this indicates configuration issues. Pay close attention to the task definition revision numbers, which should match your latest deployment.</li><li>ALB health — on the load balancer section in the EC2 console, verify that the ALB is active and that its target groups show healthy targets. Unhealthy targets suggest that the application containers aren’t responding correctly to health checks, which could indicate application startup issues, incorrect health check configuration, or networking problems.</li></ol><p>Before configuring a custom domain, test the application using the ALB’s automatically generated DNS name. This intermediate testing step is crucial because it isolates potential application issues from domain configuration problems.</p><p>Access the application by navigating to the ALB’s DNS name in your browser. This DNS name follows the format your-alb-name-1234567890.us-west-2.elb.amazonaws.com and can be found in the Load Balancer details page. The application should load correctly and be fully functional at this stage. Test critical functionality like main dashboard access as a guest user, user registration, file uploads, downloads, and deletion, to ensure the deployment is truly successful.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*20JjagG-9NO2FRobrhTjOA.png" /><figcaption>[Author’s image] Accessing the application through ALB’s DNS name</figcaption></figure><p>If the application doesn’t load at this stage, investigate ECS service logs, ALB access logs, and application logs to identify the root cause. Common issues include incorrect environment variables, missing AWS permissions, or database connectivity problems. Resolving these issues now prevents confusion later when domain-related problems might obscure underlying application problems.</p><h3>Domain configuration and certificate management</h3><p>Register a domain name either through Route53’s console or through external domain registrars like Namecheap, GoDaddy, or Google Domains. While using Route 53 for registration simplifies the process by keeping everything within AWS, you can successfully use external registrars with proper configuration.</p><p>Add the domain name to variables.tf file in the root of /infra directory.</p><pre>variable &quot;domain_name&quot; {<br>  description = &quot;Custom domain name for the application&quot;<br>  type        = string<br>  default     = &quot;your-domain-name&quot; # replace with your actual domain name<br>}</pre><h4>One-time DNS setup</h4><p>Because stage 1 of the pipeline waits for ACM certificate validation, your domain’s nameservers must already point to Route 53 before the pipeline runs. This is a one-time setup:</p><ol><li>Run terraform apply locally (or target just the Route 53 module) to create the hosted zone: terraform -chdir=infra apply -target=module.route53</li><li>On the AWS console, navigate to Route 53 → Hosted Zones and open the hosted zone for your domain. Copy the four nameserver values from the NS record. They look like ns-123.awsdns-45.com, ns-678.awsdns-90.net, ns-901.awsdns-12.org, ns-345.awsdns-67.co.uk.</li><li>Update your domain’s nameservers at your registrar’s control panel with these four values.</li><li>Wait for DNS propagation so that ACM can validate. It can take from a few minutes up to 48 hours. Once the NS records resolve to the Route 53 nameservers, the pipeline’s Stage 1 certificate validation will succeed.</li><li>Verify that the DNS configuration is correct using command-line tools that query DNS records directly. The dig command provides detailed DNS information that helps confirm your configuration:</li></ol><pre># Check that your domain uses AWS name servers<br>dig your-domain-name NS<br><br># Verify that your domain resolves to your ALB<br>dig your-domain-name A<br><br># Test HTTPS certificate and connectivity<br>curl -I https://your-domain-name</pre><p>The first command should return AWS name servers, confirming that DNS authority has transferred to Route 53. The second command should return IP addresses associated with the ALB. The third command tests HTTPS connectivity and should return a successful response with proper SSL certificate information.</p><p>Once DNS propagation completes and your certificate validates, test the application using your custom domain name. Navigate to https://your-domain-name and verify that your application loads with a valid SSL certificate (look for the lock icon in your browser&#39;s address bar). Test all critical application functionality to ensure that the domain change hasn&#39;t introduced any issues.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cS_vd1yh2cOevUxdBJ2z1g.png" /><figcaption>[Author’s image] Accessing the application through the custom domain</figcaption></figure><h3>Conclusion</h3><p>Yay! We have successfully built an end-to-end secure and scalable project on AWS and served it using Flask. Moreover, we’ve containerized the application on Docker using AWS’s Amazon ECR, ensuring our environment variables are kept safe using AWS Secrets Manager. We’ve also deployed the application seamlessly and automatically to Amazon ECS using GitHub Actions and have configured a custom domain with proper SSL encryption, providing a professional user experience that builds trust and credibility.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=64af111843b9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Files On Cloud: Hands-On AWS Project]]></title>
            <link>https://medium.com/@r-owino/files-on-cloud-hands-on-aws-project-aee7c185867b?source=rss-89c9d1406517------2</link>
            <guid isPermaLink="false">https://medium.com/p/aee7c185867b</guid>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[flask]]></category>
            <category><![CDATA[motos]]></category>
            <category><![CDATA[pytest]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Remmy]]></dc:creator>
            <pubDate>Fri, 28 Mar 2025 16:20:55 GMT</pubDate>
            <atom:updated>2025-08-07T10:35:31.982Z</atom:updated>
            <content:encoded><![CDATA[<h4>Part 3: The App</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lqtKl5vYLbEeofJNMQIJkQ.png" /></figure><p>So far, we have <a href="https://medium.com/@r-owino/files-on-cloud-hands-on-aws-project-8bc778679500">architected</a> the infrastructure and <a href="https://medium.com/@r-owino/files-on-cloud-hands-on-aws-project-6fff6bbacc3d">provisioned</a> it on AWS using Terraform. While these work for developers, end users would find it useless if they do not have an interface to interact with, unless, of course, they can cURL the endpoints or run AWS CLI commands. For this project, I chose Flask, a lightweight Python web framework, to quickly develop a website without much fuss. Let’s get started.</p><h3>Setting up a Flask Application</h3><p>This section assumes you already have Python3 installed; if not, you can download and install it from the <a href="https://www.python.org/downloads/">official</a> Python site.</p><h4>Step 1: Create a project directory and a virtual environment</h4><p>Create a folder that will hold your project:</p><pre>mkdir flask_demo<br>cd flask_demo</pre><p>Structure your directory as follows:</p><pre>flask_demo/<br>├── app.py<br>└── templates/<br>    └── index.html</pre><p>A virtual environment allows you to manage your Python projects by creating isolated, self-contained Python installations. Essentially, it’s a directory with a specific structure that contains everything you need to run a Python project in isolation from other projects.</p><p>The following commands create and activate a virtual environment called <em>venv:</em></p><pre># Create a virtual environment<br>python3 -m venv venv<br><br># Activate the environment<br>source venv/bin/activate</pre><h4>Step 2: Install Flask</h4><p>With the virtual environment activated, we can now install the packages we need without conflicting with other projects that could be running on specific versions of the same packages. Run this command to install Flask:</p><pre># installs the latest version of Flask<br>pip install Flask<br><br># installs flask version 2.8.5<br>pip install Flask==2.8.5</pre><h4>Step 3: Create the main application file</h4><p>In the app.py file, paste the following code:</p><pre>from flask import Flask, render_template<br><br># Create a new Flask application instance<br>app = Flask(__name__)<br><br># Define a route for the root URL (&#39;/&#39;) that renders our template<br>@app.route(&#39;/&#39;)<br>def home():<br>    return render_template(&#39;index.html&#39;)<br><br># Run the application if this script is executed directly<br>if __name__ == &#39;__main__&#39;:<br>    app.run(debug=True)</pre><p><em>@app.route</em> is a Python decorator that specifies each route in Flask — something like a direction marker. It defines the URL path to a specific function in the application, so that when a request is sent through that URL, the associated function is invoked. In the example above, <em>@app.route(‘/’)</em> tells Flask that whenever a web browser requests the URL endpoint ‘/’, it should trigger the home function and render an HTML page.</p><h4>Step 4: Create the HTML page</h4><p>In templates/index.html file, have the following code:</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>&lt;head&gt;<br>    &lt;meta charset=&quot;UTF-8&quot;&gt;<br>    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt;<br>    &lt;title&gt;Success Page&lt;/title&gt;<br>    &lt;style&gt;<br>        body {<br>            margin: 0;<br>            height: 100vh;<br>            display: flex;<br>            justify-content: center;<br>            align-items: center;<br>            font-family: Arial, sans-serif;<br>            background-color: #f0f0f0;<br>        }<br>        .message {<br>            padding: 20px;<br>            background-color: white;<br>            border-radius: 8px;<br>            box-shadow: 0 2px 4px rgba(0,0,0,0.1);<br>        }<br>    &lt;/style&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>    &lt;div class=&quot;message&quot;&gt;<br>        &lt;h1&gt;You successfully set up the application&lt;/h1&gt;<br>    &lt;/div&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><h4>Step 5: Run the application</h4><p>Open the terminal and confirm you’re in your project directory, flask_demo<strong><em>, </em></strong>and execute this command to run the application:</p><pre>python3 app.py</pre><p>You should see the following output:</p><pre>$ python3 app.py<br> * Serving Flask app &#39;app&#39;<br> * Debug mode: on<br>WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.<br> * Running on http://127.0.0.1:5000<br>Press CTRL+C to quit<br> * Restarting with stat<br> * Debugger is active!<br> * Debugger PIN: 363-553-908</pre><p>On your web browser, navigate to <a href="http://127.0.0.1:5000/">http://127.0.0.1:5000/</a> to see your application running. If everything runs as expected, you should see this page:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Sl1BoPCmoknwOCjp" /><figcaption>Demo application running on Flask</figcaption></figure><p>Now that you have a foundation of what the Flask app entails, let’s build our application.</p><h3>The Application</h3><p>The file structure of the Flask application looks like this:</p><pre>$ api<br>.<br>├── Dockerfile<br>├── requirements.txt<br>├── tests<br>│   ├── conftest.py<br>│   ├── test_check_file.py<br>│   ├── test_cognito.py<br>│   ├── test_confirm.py<br>│   ├── test_delete_account.py<br>│   ├── test_delete.py<br>│   ├── test_download.py<br>│   ├── test_file_metadata.py<br>│   ├── test_invalidate_cloudfront_path.py<br>│   ├── test_landing.py<br>│   ├── test_login.py<br>│   ├── test_logout.py<br>│   ├── test_main.py<br>│   ├── test_register.py<br>│   ├── test_resend_code.py<br>│   ├── test_search_file.py<br>│   └── test_upload.py<br>└── v1<br>    ├── app.py<br>    ├── cognito.py<br>    ├── config.py<br>    ├── __init__.py<br>    ├── routes<br>    │   ├── check_file.py<br>    │   ├── confirm.py<br>    │   ├── delete_account.py<br>    │   ├── delete.py<br>    │   ├── download.py<br>    │   ├── file_metadata.py<br>    │   ├── health.py<br>    │   ├── __init__.py<br>    │   ├── landing.py<br>    │   ├── login.py<br>    │   ├── logout.py<br>    │   ├── main.py<br>    │   ├── private_key.pem<br>    │   ├── register.py<br>    │   ├── resend_code.py<br>    │   ├── search_file.py<br>    │   └── upload.py<br>    ├── static<br>    │   ├── css<br>    │   │   ├── 404.css<br>    │   │   ├── confirm.css<br>    │   │   ├── index.css<br>    │   │   ├── login.css<br>    │   │   ├── main.css<br>    │   │   └── register.css<br>    │   └── js<br>    │       ├── confirm.js<br>    │       ├── fileActions.js<br>    │       ├── fileDisplay.js<br>    │       ├── fileUpload.js<br>    │       ├── login.js<br>    │       ├── main.js<br>    │       ├── notifications.js<br>    │       ├── register.js<br>    │       ├── sidebar.js<br>    │       └── utils.js<br>    └── templates<br>        ├── 404.html<br>        ├── confirm.html<br>        ├── index.html<br>        ├── login.html<br>        ├── main.html<br>        └── register.html</pre><p>As in the demo application above, our Flask app will be run from app.py Notice that instead of having all our routes defined in app.py , we have each route defined in its file in the routes directory. In this approach, we can group related routes using Flask’s Blueprint. This Blueprint is what we register in app.py when it is available in the factory function.</p><blockquote>All code is available in this <a href="https://github.com/R-Owino/FilesOnCloud">GitHub</a> repository.</blockquote><h4>Test cases</h4><p>In this project, we will follow the Test-Driven Development approach to write the API code. For running the test cases, we will use <a href="https://docs.pytest.org/en/stable/">Pytest</a> and <a href="https://docs.getmoto.org/en/latest/">Moto</a> for unit testing. Pytest makes it easy to write and execute tests in Python and can scale to support complex functional testing. Moto is an AWS unit testing package that allows us to mock AWS services. Although it doesn’t have all the services/features supported yet (it’ll throw a NotImplementedError error), it works well for our project. The linked GitHub repository has the test cases for each route. You can add more test cases to test additional edge cases that escaped my notice.</p><ul><li><a href="https://docs.pytest.org/en/stable/">pytest documentation</a></li><li><a href="https://github.com/getmoto/moto">GitHub - getmoto/moto: A library that allows you to easily mock out tests based on AWS infrastructure.</a></li></ul><h4>User Authentication and Authorization</h4><p>In cognito.py there are three functions we’ll use for user authentication and authorization: <em>register_user, </em><em>confirm_user </em>and<em> </em><em>login_user</em>. Each of these functions sends a request to the Cognito Identity Provider defined in the boto3 SDK to authenticate and authorize a user. A user sends requests to sign up, verify the provided email address, and log in through the endpoints defined in register, confirm, and login routes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Oj22XqG0e8MyofPXjIMBDg.jpeg" /><figcaption>User authentication steps in the UI</figcaption></figure><p>Suppose the email verification page session expires or the sent code expires, a user can request a confirmation code to be resent. The resend_code route handles this scenario by triggering the <em>resend_verification_code</em> function in cognito.py.</p><p>Both authorised and guest users can access the main page, but guest users are limited to viewing the files on display and searching for files through the catalog. Up to now, you should have test cases testing for various edge cases in Cognito user authentication functions, register, login, confirm, and resend_code routes.</p><h4>File Display</h4><p>Both authorised and guest users can view the display files. The API Gateway method that triggers the Lambda function that fetches the file metadata has no authorization set to allow guest users to view the files.</p><p>To fetch the recent files, the API Gateway method triggers a Lambda function to scan the documents DynamoDB table and returns the 15 most recent files for file display.</p><p>In hindsight, a scan operation on a growing DynamoDB table is a very bad choice. So why scan instead of query? Well, on the table, we have DocumentId as the partition key. To get the recent files, we have to sort the files using the upload_timestamp field — this means creating a global secondary index (GSI). To keep the GSI updated, while performing a write operation, the item also has to be recorded in the GSI. This results in two tables with the same information occupying double space in DynamoDB. Using a scan operation, even though it means we still have to pay for returning all the items in the table, is still cost-efficient in this case.</p><p><a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/bp-query-scan.html">Best practices for querying and scanning data in DynamoDB</a></p><p><em>file_metadata</em> Lambda function handles sorting the files using the upload_timestamp field and returns the sorted list to the API Gateway method.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FpB8NUh-ufmUAoCu" /><figcaption>Recently uploaded files shown in the UI</figcaption></figure><h4>File Search</h4><p>The same API Gateway method and Lambda function that fetches file metadata from the Documents DynamoDB table handles the file search operation. A user keys in a search term in the Search files input box to get a specific file; otherwise, a helpful message is displayed when the file is not found.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Io0zwVF4yuH15Kkm" /><figcaption>Search results when file name with the search term is keyed in and found</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wxVePBR5n9qxWptw" /><figcaption>Search results when file name with the search term is keyed in not found</figcaption></figure><h4>File Upload</h4><p>Because we’re using Amazon S3 to store the files and DynamoDB to store the file metadata, you can approach this step in 3 ways.</p><ol><li><strong>API Gateway and Lambda</strong></li></ol><ul><li>In this approach, we create an API gateway resource for the upload process and invoke permissions to trigger the lambda function to upload file metadata to the DynamoDB table. This sounds like the go-to way, especially because we already have API Gateway defined in the infrastructure.</li><li>The problem with this approach is we will have trouble uploading large sized files. This is because API Gateway has a payload limit of 10MB, uploading an 11 MB file is not possible, and increasing the payload quota is not possible in API Gateway.</li></ul><p><a href="https://repost.aws/questions/QUuinc6g08T2iRQQd03PHjbQ/increase-the-payload-size-limit-of-api-gateway">Increase the payload size limit of API Gateway</a></p><p>2. <strong>Amazon S3 pre-signed URL</strong></p><ul><li>In this approach, we request S3 to generate a pre-signed URL for a single PUT request to S3. No matter the size of the file, just one pre-signed URL is generated for the PUT request.</li><li>This approach is not efficient because if the connection becomes unstable, the upload might fail and have to restart. This can be frustrating.</li></ul><p>3. <strong>Amazon S3 multipart upload</strong></p><ul><li>We can upload a file in chunks to S3. The idea is that when a user selects the file they want to upload, the client-side code splits the file into chunks of, say 5MB, and requests pre-signed URLs for each chunk from the upload route. To minimize the risk of a file chunk not being uploaded, we’ll enable S3 Transfer Acceleration in the S3 bucket so that the AWS backbone network is used to upload a file instead of a user’s connection.</li><li>This approach is efficient because S3 Transfer Acceleration enables faster file uploads, and implementing multipart uploads allows multiple parallel uploads, reducing the overall time it takes to upload a file.</li></ul><p>In the case that different users want to upload a file with the same name, check_file route scans the Documents DynamoDB table to check if a file with a similar name is available. The user can choose either to abort the upload process or continue, which overwrites the existing file and updates the file’s metadata.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MLeRbt8UBqowb_5_UigL_w.jpeg" /><figcaption>File upload steps in the UI</figcaption></figure><p>If we can see the file in the UI, it means it was successfully stored in the S3 bucket and its metadata was stored in the DynamoDB table. We can confirm that by running the following CLI commands:</p><pre># check S3 bucket for notes.pdf<br>$ aws s3 ls s3://bucket-name --recursive --summarize<br><br>2025-03-25 10:08:19     210740 image-files/AWS_Support_Plans.png<br>2025-03-21 12:31:35    3382746 image-files/IMG_2235.jpeg<br>2025-03-10 23:01:30    7969154 text-files/97_Things_Every_Cloud_Engineer_Should_Know__Collective_--_Emily_Freeman_Nathen_Harvey_--_1_2020_--_Oreilly__Associates_Inc_.pdf<br>2025-03-13 23:18:30    6661810 text-files/Docker.pdf<br>2025-03-13 23:19:40   20215328 text-files/Practical_MLOps_Operationalizing_Machine_Learning_Models_Noah_Gift_Alfredo_Deza_z-lib.org.epub<br>2025-03-28 12:05:44   32863112 text-files/notes.pdf # recently uploaded file<br><br>Total Objects: 6<br>   Total Size: 71302890<br><br><br># check documents table for notes.pdf<br>$ aws dynamodb scan --table-name documents-metadata --limit 3<br>{<br>    &quot;Items&quot;: [<br>        {<br>            &quot;object_url&quot;: {<br>                &quot;S&quot;: &quot;https://bucket-name.s3.amazonaws.com/text-files/Docker.pdf&quot;<br>            },<br>            &quot;upload_timestamp&quot;: {<br>                &quot;S&quot;: &quot;2025-03-13T20:19:04.920784+00:00&quot;<br>            },<br>            &quot;DocumentId&quot;: {<br>                &quot;S&quot;: &quot;3f83841b-a7e3-4c62-b03f-8fc4fd9b8361&quot;<br>            },<br>            &quot;size_bytes&quot;: {<br>                &quot;N&quot;: &quot;6661810&quot;<br>            },<br>            &quot;file_name&quot;: {<br>                &quot;S&quot;: &quot;Docker.pdf&quot;<br>            },<br>            &quot;file_key&quot;: {<br>                &quot;S&quot;: &quot;text-files/Docker.pdf&quot;<br>            }<br>        },<br>        {<br>            &quot;object_url&quot;: {<br>                &quot;S&quot;: &quot;https://bucket-name.s3.amazonaws.com/text-files/notes.pdf&quot; # file recently uploaded<br>            },<br>            &quot;upload_timestamp&quot;: {<br>                &quot;S&quot;: &quot;2025-03-28T09:08:01.258021+00:00&quot;<br>            },<br>            &quot;DocumentId&quot;: {<br>                &quot;S&quot;: &quot;a0b24949-4ff5-45ed-ac26-31c1affcec83&quot;<br>            },<br>            &quot;size_bytes&quot;: {<br>                &quot;N&quot;: &quot;32863112&quot;<br>            },<br>            &quot;file_name&quot;: {<br>                &quot;S&quot;: &quot;notes.pdf&quot;<br>            },<br>            &quot;file_key&quot;: {<br>                &quot;S&quot;: &quot;text-files/notes.pdf&quot;<br>            }<br>        },<br>        {<br>            &quot;object_url&quot;: {<br>                &quot;S&quot;: &quot;https://bucket-name.s3.amazonaws.com/image-files/IMG_2235.jpeg&quot;<br>            },<br>            &quot;upload_timestamp&quot;: {<br>                &quot;S&quot;: &quot;2025-03-21T09:31:43.243371+00:00&quot;<br>            },<br>            &quot;DocumentId&quot;: {<br>                &quot;S&quot;: &quot;7fe7282b-3a0e-4a85-9019-fc84c833ba06&quot;<br>            },<br>            &quot;size_bytes&quot;: {<br>                &quot;N&quot;: &quot;3382746&quot;<br>            },<br>            &quot;file_name&quot;: {<br>                &quot;S&quot;: &quot;IMG_2235.jpeg&quot;<br>            },<br>            &quot;file_key&quot;: {<br>                &quot;S&quot;: &quot;image-files/IMG_2235.jpeg&quot;<br>            }<br>        }<br>    ],<br>    &quot;Count&quot;: 3,<br>    &quot;ScannedCount&quot;: 3,<br>    &quot;LastEvaluatedKey&quot;: {<br>        &quot;DocumentId&quot;: {<br>            &quot;S&quot;: &quot;7fe7282b-3a0e-4a85-9019-fc84c833ba06&quot;<br>        }<br>    }<br>}</pre><h4>File Download</h4><p>Like in the file upload process, there are 3 approaches to downloading a file from S3.</p><ol><li><strong>Use an API Gateway endpoint</strong></li></ol><ul><li>In this approach, we create an API Gateway resource with a GET method that fetches the file from the S3 bucket. This approach is not efficient because of the strict 10MB payload limit of API Gateway.</li><li>This makes it unsuitable for downloading larger files, and even if the file can be split into chunks, this is unnecessary complexity added. What’s more, passing the file through API Gateway adds latency and because the file isn’t being cached, download performance for frequently downloaded files is impacted.</li></ul><p>2. <strong>Direct S3 access with a pre-signed URL</strong></p><ul><li>This is a more straightforward approach where we generate a pre-signed URL from S3 that we use to directly download the file from S3. Compared to the first approach, it gives a better file download performance for large files because of the built-in features to handle large file downloads.</li><li>However, this approach isn’t ideal when you need robust security controls or custom authentication, as these URLs are only time-limited and cannot include custom tokens or JWT authentication. Additionally, pre-signed URLs pose security risks as they can be logged in browser histories or server logs, and once generated, anyone with the URL can access the file until expiration.</li></ul><p>3. <strong>CloudFront Distribution with S3 as origin</strong></p><ul><li>In this approach, we create a CloudFront distribution with the S3 bucket as the origin. CloudFront provides 2 ways to restrict access to S3 origin: Origin Access Control (OAC) and Origin Access Identity (OAI). In this approach, we use OAC because of its benefits over OAI, such as support for all buckets in all regions and S3-SSE with AWS KMS.</li><li>This approach works because CloudFront is well-optimized for large file distributions with better global delivery performance. It has in-built file caching capabilities, which is excellent for frequently downloaded files, and it has no file size restrictions.</li></ul><p>We created key pairs for CloudFront signers in the previous article and uploaded the public key to the CloudFront distribution in a trusted key group. In this step, we use the private key to sign a portion of the URL or the cookie to allow file download.</p><p><a href="https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/private-content-trusted-signers.html#private-content-adding-trusted-signers">Specify signers that can create signed URLs and signed cookies</a></p><pre># download.py<br>PRIVATE_KEY_PATH = os.path.join(os.path.dirname(__file__), &quot;private_key.pem&quot;)<br><br>def load_private_key():<br>   &quot;&quot;&quot;<br>   Load the private key<br><br>   Returns:<br>       The loaded private key<br><br>   Raises:<br>       FileNotFoundError: File key not found at the path given<br>       Exception: There is an error loading the private key<br>   &quot;&quot;&quot;<br>   key_path = PRIVATE_KEY_PATH<br><br>   try:<br>       with open(key_path, &quot;rb&quot;) as key_file:<br>           private_key = serialization.load_pem_private_key(<br>               key_file.read(),<br>               password=None,<br>               backend=default_backend<br>           )<br>           return private_key<br><br>   except FileNotFoundError as e:<br>       logger.error(f&quot;Private key file not found at {key_path}: {e}&quot;)<br>       raise<br>   except Exception as e:<br>       logger.error(f&quot;Error loading private key from {key_path}: {e}&quot;)<br>       raise</pre><p>When a user requests a file download, CloudFront sends a GET request to the S3 bucket and returns the file for a direct download. The CloudFront URL is proxy’d so that it’s not visible to the user.</p><h4>File Delete</h4><p>A file delete request deletes the specified file from the S3 bucket and its metadata from the documents DynamoDB table. In the delete route, we use the identity token to confirm user authorization because it triggers an API Gateway method. If we wanted to use the access token, we should have specified the OAuth scopes option in the API Gateway method since we used Cognito user pools as API gateway authorizer. But since we didn’t, API gateway will look for the identity token to verify the claimed identity against the one from the user pool.</p><p><a href="https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-enable-cognito-user-pool.html">Integrate a REST API with an Amazon Cognito user pool</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*V006upMn3d-bXIvx" /><figcaption>File delete steps in the UI</figcaption></figure><p>If we check the bucket and the DynamoDB table, <em>notes.pdf</em> should not be there.</p><pre># check S3 for notes.pdf<br>$ aws s3 ls s3://bucket-name --recursive --summarize<br>2025-03-25 10:08:19     210740 image-files/AWS_Support_Plans.png<br>2025-03-21 12:31:35    3382746 image-files/IMG_2235.jpeg<br>2025-03-10 23:01:30    7969154 text-files/97_Things_Every_Cloud_Engineer_Should_Know__Collective_--_Emily_Freeman_Nathen_Harvey_--_1_2020_--_Oreilly__Associates_Inc_.pdf<br>2025-03-13 23:18:30    6661810 text-files/Docker.pdf<br>2025-03-13 23:19:40   20215328 text-files/Practical_MLOps_Operationalizing_Machine_Learning_Models_Noah_Gift_Alfredo_Deza_z-lib.org.epub<br><br>Total Objects: 5<br>   Total Size: 38439778<br><br><br><br># check documents table for notes.pdf<br>$ aws dynamodb scan --table-name documents-metadata --limit 3<br>{<br>    &quot;Items&quot;: [<br>        {<br>            &quot;object_url&quot;: {<br>                &quot;S&quot;: &quot;https://bucket-name.s3.amazonaws.com/text-files/Docker.pdf&quot;<br>            },<br>            &quot;upload_timestamp&quot;: {<br>                &quot;S&quot;: &quot;2025-03-13T20:19:04.920784+00:00&quot;<br>            },<br>            &quot;DocumentId&quot;: {<br>                &quot;S&quot;: &quot;3f83841b-a7e3-4c62-b03f-8fc4fd9b8361&quot;<br>            },<br>            &quot;size_bytes&quot;: {<br>                &quot;N&quot;: &quot;6661810&quot;<br>            },<br>            &quot;file_name&quot;: {<br>                &quot;S&quot;: &quot;Docker.pdf&quot;<br>            },<br>            &quot;file_key&quot;: {<br>                &quot;S&quot;: &quot;text-files/Docker.pdf&quot;<br>            }<br>        },<br>        {<br>            &quot;object_url&quot;: {<br>                &quot;S&quot;: &quot;https://bucket-name.s3.amazonaws.com/image-files/IMG_2235.jpeg&quot;<br>            },<br>            &quot;upload_timestamp&quot;: {<br>                &quot;S&quot;: &quot;2025-03-21T09:31:43.243371+00:00&quot;<br>            },<br>            &quot;DocumentId&quot;: {<br>                &quot;S&quot;: &quot;7fe7282b-3a0e-4a85-9019-fc84c833ba06&quot;<br>            },<br>            &quot;size_bytes&quot;: {<br>                &quot;N&quot;: &quot;3382746&quot;<br>            },<br>            &quot;file_name&quot;: {<br>                &quot;S&quot;: &quot;IMG_2235.jpeg&quot;<br>            },<br>            &quot;file_key&quot;: {<br>                &quot;S&quot;: &quot;image-files/IMG_2235.jpeg&quot;<br>            }<br>        },<br>        {<br>            &quot;object_url&quot;: {<br>                &quot;S&quot;: &quot;https://bucket-name.s3.amazonaws.com/image-files/AWS_Support_Plans.png&quot;<br>            },<br>            &quot;upload_timestamp&quot;: {<br>                &quot;S&quot;: &quot;2025-03-25T07:08:24.649076+00:00&quot;<br>            },<br>            &quot;DocumentId&quot;: {<br>                &quot;S&quot;: &quot;36d30bb4-4df4-47b7-bed3-307f529d4ae8&quot;<br>            },<br>            &quot;size_bytes&quot;: {<br>                &quot;N&quot;: &quot;210740&quot;<br>            },<br>            &quot;file_name&quot;: {<br>                &quot;S&quot;: &quot;AWS_Support_Plans.png&quot;<br>            },<br>            &quot;file_key&quot;: {<br>                &quot;S&quot;: &quot;image-files/AWS_Support_Plans.png&quot;<br>            }<br>        }<br>    ],<br>    &quot;Count&quot;: 3,<br>    &quot;ScannedCount&quot;: 3,<br>    &quot;LastEvaluatedKey&quot;: {<br>        &quot;DocumentId&quot;: {<br>            &quot;S&quot;: &quot;36d30bb4-4df4-47b7-bed3-307f529d4ae8&quot;<br>        }<br>    }<br>}</pre><p>In this article, we’ve gone through the step-by-step process of building the Flask side of the application for user interaction. If you have a question or need clarification on any section, comment on it, and I will get back to you.</p><h3>Next Up…</h3><p>A comprehensive CI/CD pipeline to build, test, and deploy the application. Stay tuned!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aee7c185867b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Files On Cloud: Hands-On AWS Project]]></title>
            <link>https://medium.com/@r-owino/files-on-cloud-hands-on-aws-project-6fff6bbacc3d?source=rss-89c9d1406517------2</link>
            <guid isPermaLink="false">https://medium.com/p/6fff6bbacc3d</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[iac]]></category>
            <dc:creator><![CDATA[Remmy]]></dc:creator>
            <pubDate>Wed, 19 Mar 2025 12:18:58 GMT</pubDate>
            <atom:updated>2026-05-05T12:01:24.223Z</atom:updated>
            <content:encoded><![CDATA[<h4>Part 2: The Infrastructure</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GN45Y59XDoBEWNDU.jpg" /></figure><p>There are a number of ways you can choose to provision your infrastructure on AWS. A popular way to do this is through the console, click-ops, if you will. But what if you have to provision a number of services, each interacting with the other? What if you need to quickly re-provision your infrastructure to another region, let’s say, for backup? What if you hit an error and need to recreate the error? Will you remember all the steps you took while provisioning the services?</p><h3>Infrastructure as Code</h3><p>In comes Infrastructure as Code, where you literally code your infrastructure. The benefits of using IaC, you ask? It eliminates manual processes to achieve remarkable speed and consistency across environments. Using IaC enhances security through automated compliance checks while improving efficiency as you and your team share templated solutions. The reliability of declarative configurations prevents human error, with built-in drift detection ensuring environments remain as intended. You benefit from reduced costs because you pay only for resources actively used, and the ease of provisioning facilitates rapid experimentation. This means you can scale quickly on demand, delivering more with fewer resources. Most importantly, for us developers at least, you can version your infrastructure - meaning if there’s something wrong with recent changes, you can easily roll back to the previous version.</p><p>But there are several IaC tools. Which one should you go for?</p><h3>Terraform</h3><p>For the sake of world peace. Terraform remains a widely adopted IaC tool, with <a href="https://devops.com/survey-significant-shift-in-iac-tool-preferences/#:~:text=The%20report%20finds%2057%25%20of,half%20of%20their%20cloud%20assets.">60% usage rates</a> among IT professionals due to its unique flexibility. This is why it stands tall among other IaC tools:</p><ol><li>It uses declarative language, allowing you to define what you want without detailing how to get there. Its configurations are very easy to write and understand.</li><li>If you have several resources being used together, Terraform allows you to containerize them into modules that you can reuse across your infrastructure. This makes the configurations more scalable and improves maintainability.</li><li>Suppose your infrastructure relies on multi-cloud environments; Terraform’s flexibility and its multi-cloud support feature would make the integration seamless for you.</li><li>Terraform keeps a state file for mapping resources created in your configuration. This enables Terraform to prevent unnecessary modifications and provide more effective execution plans. If you’re working in a team, Terraform allows you to lock the state file so that only one teammate at a time can apply changes to your configurations.</li></ol><h3>The Infrastructure</h3><p>We already have the <a href="https://medium.com/@r-owino/files-on-cloud-hands-on-aws-project-8bc778679500">architecture</a>, so let’s get coding!</p><h4>Pre-requisites</h4><ol><li>An AWS account with an IAM user set up. The user needs to have administrative permissions or follow the least privilege principle to grant the user only the permissions needed for the project.</li><li>AWS CLI is installed and configured with the IAM user’s credentials. Confirm AWS CLI installation by running this command:</li></ol><pre>aws --version</pre><blockquote>Terraform can still make API calls without depending on AWS CLI if you choose to hardcode your IAM credentials or use another method to access AWS, like setting up Single Sign-on.</blockquote><p>3. <a href="https://developer.hashicorp.com/terraform/install">Terraform</a> downloaded and installed. Test the installation by running the following command:</p><pre>terraform --version</pre><h4>Infrastructure Setup</h4><p>The Terraform infrastructure will take the following structure:</p><pre>$ infra<br>.<br>├── backend.tf<br>├── bootstrap<br>│   ├── main.tf<br>│   ├── outputs.tf<br>│   ├── providers.tf<br>│   └── variables.tf<br>├── Dockerfile<br>├── main.tf<br>├── modules<br>│   ├── api_gateway<br>│   │   ├── api-gateway-policy.json<br>│   │   ├── main.tf<br>│   │   ├── outputs.tf<br>│   │   └── variables.tf<br>│   ├── cloudfront<br>│   │   ├── main.tf<br>│   │   ├── outputs.tf<br>│   │   ├── public_key.pem<br>│   │   └── variables.tf<br>│   ├── cognito<br>│   │   ├── main.tf<br>│   │   ├── outputs.tf<br>│   │   └── variables.tf<br>│   ├── dynamodb<br>│   │   ├── main.tf<br>│   │   ├── outputs.tf<br>│   │   └── variables.tf<br>│   ├── lambda<br>│   │   ├── delete_file_lambda.py<br>│   │   ├── file-metadata-lambda-dynamodb-policy.json<br>│   │   ├── file_metadata_lambda.py<br>│   │   ├── lambda-delete-file-policy.json<br>│   │   ├── lambda-dynamodb-policy.json<br>│   │   ├── lambda-logs-policy.json<br>│   │   ├── lambda-policy.json<br>│   │   ├── lambda-s3-policy.json<br>│   │   ├── main.tf<br>│   │   ├── outputs.tf<br>│   │   ├── requirements.txt<br>│   │   ├── upload_file_metadata_lambda.py<br>│   │   ├── upload-lambda-dynamodb-policy.json<br>│   │   ├── userdata-lambda-dynamodb-policy.json<br>│   │   ├── userdata_lambda.py<br>│   │   └── variables.tf<br>│   ├── s3<br>│   │   ├── bucket-policy.json<br>│   │   ├── cloudfront-s3-policy.json<br>│   │   ├── log-bucket-policy.json<br>│   │   ├── main.tf<br>│   │   ├── outputs.tf<br>│   │   └── variables.tf<br>│   └── secrets_manager<br>│      ├── main.tf<br>│      ├── outputs.tf<br>│      ├── secrets-access-policy.json<br>│      ├── secrets-access-role.json<br>│      └── variables.tf<br>├── outputs.tf<br>├── providers.tf<br>└── variables.tf</pre><p>The code can be found on this <a href="https://github.com/R-Owino/FilesOnCloud">GitHub repository</a>.</p><h4>Providers</h4><p>Terraform needs to know which services it is interacting with. This is what we define in the providers.tf file at the root of the infra directory. The providers defined are plugins that Terraform relies on to interact with remote systems. In our case, we must declare the AWS provider in the configurations so that Terraform can install and use it, and we do not have to worry about the API calls that Terraform makes to create the infrastructure. providers.tf has the following:</p><pre>terraform {<br> required_providers {<br>   aws = {<br>     source = &quot;hashicorp/aws&quot;<br>      version = &quot;~&gt; 5.0&quot;<br>   }<br> }<br>}<br><br>provider &quot;aws&quot; {<br> region = var.aws_region<br>}</pre><p>This instructs Terraform to initialize the AWS provider version 5.0 and above with its local name (defined in the provider block) in a region where we want the resources created.</p><h4>Configuring the Resources</h4><p>We said earlier that one of Terraform’s strengths is its declarative language. We could simply create one main.tf file and configure all our resources in the same file. But this would be chaotic, seeing as we have to configure several services. A solution would be to use Terraform’s modular approach in configuring resources. This would greatly improve the maintainability of the code.</p><p>In the modules directory, we configure each service’s resources that we require for the application. Each module has a:</p><ul><li>main.tf file — has the resources’ configuration for each service, including permissions and policies that the service needs, such as Lambda invoke permissions and policies that service roles need to interact with other services.</li><li>outputs.tf file — has each module’s value that we either want to use in another module or print out in the main Terraform’s output on the console.</li><li>variables.tf file — has the variables used in a module. The variables could be from the main variables.tf file or outputs from other modules, with their types and descriptions defined. These variables are also called local variables because their scope is that particular module where they are defined.</li></ul><p>At the root of the directory, we have the same files as in the modules, but they serve a different purpose:</p><ul><li>main.tf — consolidates all the modules and serves as the orchestration hub in the project — it is the primary entry point for Terraform.</li><li>variables.tf — contains the definitions of the input variables used in the project. Here, we define the input types, descriptions, and/or default values.</li><li>outputs.tf — contains the output values of the Terraform configurations that we want to see printed on the console. We will use these in the Flask app.</li></ul><blockquote>These files could be named anything as long as they have the <em>.tf</em> extension so that Terraform can consider them. These are just generic naming conventions used in the industry.</blockquote><h4>CloudFront Signers</h4><p>To download a file from S3 through CloudFront, we will need signers to create signed URLs. To create the signed URL, we will use the trusted key group resource in the CloudFront module. The signer will ensure that end users use the signed URLs to download files, and we can use the private key generated from the pair to sign a portion of the URL. When an end user wants to download a file, CloudFront will compare the URL’s signature and the unsigned part to confirm it has not been interfered with or that the URL is valid.</p><p>Since we only have one cache behaviour in the distribution, this requires that end users must use a signed URL to download a file.</p><p><strong>Creating the key pair for the signer</strong></p><p>The key pair we create must meet the following requirements:</p><ul><li>It must be an SSH-2 RSA key pair.</li><li>It must be in base64-encoded PEM format.</li><li>It must be a 2048-bit key pair.</li></ul><p>Use any method to create the key pair as long as the keys meet the above requirements. A simpler way would be to execute the following commands:</p><pre>openssl genrsa -out private_key.pem 2048</pre><p>This generates an RSA key pair with a length of 2048 bits and saves it to the file named private_key.pem.</p><pre>openssl rsa -pubout -in private_key.pem -out public_key.pem</pre><p>This splits the key into public and private keys, each in its own file.</p><p>Have the public key in the CloudFront module. We will use the private key in the Flask app.</p><blockquote>NB: Ensure <strong>not</strong> to expose your private key. Do not upload it to your versioning system.</blockquote><h3>Deploying the Infrastructure</h3><p>We have the infrastructure configuration ready; time to provision it on AWS!</p><p>On the terminal in the root directory of the project, run this command to initialize the Terraform project:</p><pre>terraform init</pre><p>Once this is done, we can see and verify the changes Terraform wants to make. Run this command to see the planned changes:</p><pre>terraform plan</pre><p>If you’re satisfied with the changes to be made, go ahead and create the resources and see them on the AWS console, interact with them through the AWS CLI, or call them in an SDK. Run this command to apply:</p><pre>terraform apply</pre><p>If you want to bypass the confirmation prompt displayed by terraform apply, directly run this command:</p><pre>terraform apply -auto-approve</pre><p>When complete, it displays the output we specified in the outputs.tf file in the root directory. In our example, the output will be as so:</p><pre>Apply complete! Resources: 2 added, 1 changed, 0 destroyed.<br><br>Outputs:<br><br>api_gateway_delete_url = &quot;https://&lt;api-id&gt;.execute-api.us-west-2.amazonaws.com/dev/files/delete&quot;<br>api_gateway_fetch_metadata_url = &quot;https://&lt;api-id&gt;.execute-api.us-west-2.amazonaws.com/dev/files/metadata&quot;<br>aws_region = &quot;us-west-2&quot;<br>cloudfront_distribution_id = &quot;E***********G&quot;<br>cloudfront_domain_name = &quot;d2***********.cloudfront.net&quot;<br>cloudfront_public_key_id = &quot;K***********D&quot;<br>cognito_user_pool_client_id = &quot;3f****************it&quot;<br>cognito_user_pool_id = &quot;us-west-2_w*******R&quot;<br>documents_dynamodb_table_name = &quot;documents-metadata&quot;<br>s3_bucket_name = &quot;filesoncloud-randomstring&quot;<br>secret_name = &quot;filesoncloud-app-secrets&quot;<br>userdata_dynamodb_table_name = &quot;userdata&quot;</pre><h3>State Management and Remote Backends</h3><p>Running terraform apply creates two new files: terraform.tfstate and terraform.tfstate.backup. The beauty of Terraform is, it only deals with the resources created using Terraform alone — meaning if we want to destroy these resources, it will destroy only the resources it created. To manage these resources, Terraform creates state files to save the mapping information regarding the resources and the configurations we coded to their real entities in the AWS cloud.</p><p>terraform.tfstate maintains the current state of the resources as they are in the cloud — provisioned, yet to be provisioned, and deleted resources.</p><h4>Remote Backend</h4><p>When working in a team, we would not want multiple people updating the state files at the same time, as this would cause inconsistencies and potentially destructive conflicts. For this reason, Terraform has evolved to provide robust state management through remote backends, with Amazon S3 being the most popular choice due to its reliability and now enhanced native locking capabilities. When S3 locking is enabled, Terraform creates a lock file in the same location as the state file, using S3’s atomic operations to ensure only one Terraform operation can modify the state at any given time. This is how the remote backend feature works:</p><ol><li>Multiple developers contributing to the same Terraform project have their own project setups locally. Once they’ve made their changes locally, they push the changes to the remote repository.</li><li>When they execute terraform plan command locally, Terraform creates a lock file directly in the S3 bucket using S3’s conditional write operations. This lock prevents the other team members from simultaneously planning or applying changes. Terraform queries the current state information from S3, validates the proposed changes against the actual infrastructure, presents the execution plan, and then releases the state lock by removing the lock file.</li><li>When they execute terraform apply<em> </em>command locally, Terraform again creates the S3-native lock file, queries the current state information, identifies the differences between the desired and actual infrastructure state, and applies the changes to AWS. The locking mechanism ensures that if another team member tries to run Terraform simultaneously, they’ll receive a clear error about the locked state.</li><li>When completed (or failed), Terraform automatically releases the lock by removing the lock file from S3. This is similar to the terraform destroy command, ensuring safe teardown of infrastructure even in team environments.</li></ol><p>In our project, we have a bootstrap configuration that creates the S3 bucket that both stores and locks the state file, and a backend.tf file where we point Terraform to the backend resources. You have to initialize and apply the configurations in the bootstrap directory to create the S3 bucket.</p><p>To apply these changes in the root directory, you’ll have to run terraform init first, then terraform apply, since we’ve changed the backend information. This is a sample output you’ll get when you run terraform init<em>:</em></p><pre>$ terraform init<br><br>Initializing the backend...<br>Do you want to copy existing state to the new backend?<br>  Pre-existing state was found while migrating the previous &quot;local&quot; backend to the<br>  newly configured &quot;s3&quot; backend. No existing state was found in the newly<br>  configured &quot;s3&quot; backend. Do you want to copy this state to the new &quot;s3&quot;<br>  backend? Enter &quot;yes&quot; to copy and &quot;no&quot; to start with an empty state.<br><br>  Enter a value: yes<br><br><br>Successfully configured the backend &quot;s3&quot;! Terraform will automatically<br>use this backend unless the backend configuration changes.<br><br>Initializing provider plugins...<br>- Reusing previous version of hashicorp/aws from the dependency lock file<br>- Using previously-installed hashicorp/aws v5.90.0<br><br>Terraform has been successfully initialized!<br><br>You may now begin working with Terraform. Try running &quot;terraform plan&quot; to see<br>any changes that are required for your infrastructure. All Terraform commands<br>should now work.<br><br>If you ever set or change modules or backend configuration for Terraform,<br>rerun this command to reinitialize your working directory. If you forget, other<br>commands will detect it and remind you to do so if necessary.</pre><h3>Next Up…</h3><p>The Flask app, so end users can use your resources. Stay tuned!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6fff6bbacc3d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Files On Cloud: Hands-On AWS Project]]></title>
            <link>https://medium.com/@r-owino/files-on-cloud-hands-on-aws-project-8bc778679500?source=rss-89c9d1406517------2</link>
            <guid isPermaLink="false">https://medium.com/p/8bc778679500</guid>
            <category><![CDATA[cognito-user-pools]]></category>
            <category><![CDATA[dynamodb]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[aws-cloudfront]]></category>
            <category><![CDATA[s3]]></category>
            <dc:creator><![CDATA[Remmy]]></dc:creator>
            <pubDate>Mon, 17 Mar 2025 13:13:23 GMT</pubDate>
            <atom:updated>2026-05-08T04:17:43.786Z</atom:updated>
            <content:encoded><![CDATA[<h4>Part 1: The Architecture</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BRd09-ruoZRfWYYK8pL8mg.png" /><figcaption>[Author’s image] FilesOnCloud landing page</figcaption></figure><p>In this project, you are going to learn how to use AWS and some of its services to build a file-sharing web application. You will learn how to choose the right services for the job, considering the problems the application needs to solve, the cost of the application using the selected services, and effectively optimizing the cost, mapping out how the services will interact with each other in the application, and applying security measures to the application while making the application scalable. First, the services.</p><h3>Choosing the Services</h3><p>The task is to develop an application that enables users to share files. The users can upload, download, delete, view, and search files from the shared platform. The upload, download, and delete actions require the users to be authenticated, while the viewing and searching actions can be done by both authenticated and guest users. The files need to be securely stored and accessed from the shared platform.</p><p>In this light, we can now break down the workflow to solve the problem and choose the service(s) that are required to achieve each step cost-effectively and operationally efficiently.</p><h4>1. User authentication and authorization</h4><p>For authenticating users, Amazon Cognito provides us with a production-ready authentication system that handles user management, security, and scalability while allowing us to focus on the core development of the application. Its extensive feature set, combined with ease of implementation and enterprise-grade security, makes it suitable for applications that require robust user authentication and authorization requirements, such as this application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/592/0*7lqZlXtJcsOpAsW9" /><figcaption>[Author’s image] Sequence diagram showing user authentication through Cognito</figcaption></figure><h4>Pricing</h4><p>Amazon Cognito uses a pay-as-you-go pricing model, with no minimum fees and no upfront charges. For this project, we’ll use Cognito user pools, whose pricing is based on Monthly Active Users (MAUs). An MAU is a user who, within a calendar month, has generated an identity operation like sign-in, sign-up and token refresh. Cognito does not charge for subsequent sessions or inactive users within that calendar month.</p><p>AWS introduced new pricing tiers for Cognito in November 2024: Lite, Essentials, and Plus. For new user pools created after November 22, 2024, the Essentials tier provides 10,000 free MAUs per month, after which pricing is $0.015 per MAU.</p><p>In this application, if, for example, we get 1000 MAUs, the monthly charge would be $0 on the Essentials pricing tier.</p><blockquote>Note that Cognito has a free tier that doesn’t automatically end with the 12-month free tier period. But, it is not available for user pool local and federated users in the AWS GovCloud region.</blockquote><h4>2. File upload</h4><p>File storage has never been made easier and more pocket-friendly than it is with Amazon S3. But, as we store the file, we also want to efficiently extract and store file metadata. AWS Lambda, a serverless service, seamlessly integrates with S3 to extract the required file metadata. To store the metadata, we will use an Amazon DynamoDB table, as it provides fast, consistent access to file metadata, efficient querying capabilities, and automatic scaling with on-demand capacity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/831/0*Cp6MH9d0-0dks1kv" /><figcaption>[Author’s image] Sequence diagram showing file storage and metadata extraction</figcaption></figure><h4>Pricing</h4><p>In S3, we create an estimate for standard storage (the objects will be stored in a standard storage bucket when uploaded), S3 Intelligent-tiering (objects older than 180 days are relocated to intelligent-tiering storage), and data transfer.</p><p>In the application, we could be using 100GB standard storage per month at $0.023 per GB ($2.30), with 10,000 PUT, COPY, POST, LIST requests to S3 at $0.0005 per 1000 requests ($0.005), and another 10,000 GET, SELECT, and all other requests from S3 at $0.0004 per 1000 requests ($0.004). Then, 50GB intelligent-tiering storage at $0.0125 per GB ($0.625), with 100 lifecycle transition requests at $0.01 per 1000 requests ($0.001). And finally, inbound data transfer from the internet, which is free, and outbound data transfer to Amazon CloudFront, which is free within AWS. This totals approximately $2.93 monthly costs.</p><h4>3. File listing</h4><p>API Gateway provides flexible access control for viewing files stored in S3, supporting both authenticated and guest users through different authorization strategies. While the gateway can integrate with Amazon Cognito for user authentication in other endpoints, the file listing REST API method implements no authorization requirements, enabling guest users to view files alongside authenticated users. When combined with AWS Lambda, we reap API Gateway’s built-in security benefits, such as SSL/TLS encryption and the ability to apply IAM role-based access control where needed. With this setup, we don’t have to manage any servers, and sudden spikes in requests are handled efficiently. API Gateway’s caching reduces DynamoDB calls, and Lambda’s fast cold starts are performance-efficient for metadata queries. Combining these services creates a scalable, flexible, and cost-effective system to retrieve metadata that handles variable workload while maintaining low operational costs and accommodating different user access patterns.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/747/0*Gww60HDnc8bjB6Ij" /><figcaption>[Author’s image] Sequence diagram showing fetching file metadata</figcaption></figure><h4>Pricing</h4><p>We will use an API Gateway’s REST API to send requests to fetch file metadata for file listing. If 200,000 requests are sent, then the cost estimate will be $0.70 per month ($3.50 per million requests for the first 333 million).</p><h4>4. File caching and download</h4><p>To download a file from Amazon S3, we will use Amazon CloudFront — a powerful content delivery network (CDN) service that remarkably enhances the delivery of files from Amazon S3. CloudFront’s global edge network significantly reduces latency and parallel connections with optimized routing through the AWS network, streamlining file downloads. With CloudFront, we don’t have to plan capacity prior to usage. It has a built-in load-balancing feature that distributes traffic, expertly handling sudden traffic spikes. In addition, using CloudFront comes with the benefit of automatic protection of AWS Shield Standard at no additional cost. The edge caching feature in CloudFront reduces the load on the S3 bucket, minimizing data transfer costs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*mTsHSOjjYdJWNTik" /><figcaption>[Author’s image] Sequence diagram showing file download over CloudFront</figcaption></figure><h4>Pricing</h4><p>Since we’re only using CloudFront for file downloads, with 5,000 HTTPS requests per month, the estimated cost varies per region. For the US and Europe price class, costs are approximately $0.085 per 10,000 HTTPS requests ($0.043 for 5,000 requests), plus data transfer costs, which depend on the total GB transferred, but transfers from S3 to CloudFront within the same region are free. At this request volume, the total monthly estimate is approximately $0.04–$0.50, with the upper end accounting for meaningful data egress to end users.</p><h4>5. File deletion</h4><p>To delete a file, Amazon API Gateway, authorized by Amazon Cognito, is used in combination with AWS Lambda. This solution for file deletion is robust, secure, and cost-effective as it ensures reliable, atomic operations across S3 and DynamoDB. Pricing for delete operations is very pocket-friendly since DELETE requests are free in S3, and the Lambda function only runs when needed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/799/0*WJlvQRs1i9nhIyWl" /><figcaption>[Author’s image] Sequence diagram showing file deletion</figcaption></figure><h4>Monthly Total Price Estimate</h4><p>These estimates assume moderate usage — approximately 1,000 MAUs, 200 file operations per day, and 100 GB of stored files in us-west-2 region.</p><ul><li>Amazon Cognito (essentials tier, less than 10,000 MAUs)— $0</li><li>Amazon S3 (100GB storage, standard + intelligent-tiering) —~ $2.93</li><li>Amazon API Gateway (200,000 requests) — ~$0.70</li><li>Amazon CloudFront (5, 000 HTTPS requests) — ~ $0.04-$0.50</li><li>AWS Lambda — we have 4 Lambda functions, which are charged for the execution duration that each function takes. But, Lambda has an always-free tier of 1 million requests per month, after that, requests are priced at $0.20–$0.28 per million. Assuming we get 200,000 requests per month and the functions take an average of 400ms to execute with 128MB memory allocated, then the charges would approximately be $0 because the free tier covers 400,000 GB-seconds per month.</li><li>Amazon DynamoDB — with 2 tables each using on-demand capacity modes, DynamoDB charges for the actual read capacity units(RCUs) and write capacity units(WCUs) consumed by the application’s request. For 2.5GB of storage per month and 0.20WCUs and 0.20RCUs, the charges would be $0.77.</li><li>Amazon ECS Fargate Spot (1 task, 0.25 vCPU, 1 GB memory) — ~$3.15</li><li>Application Load Balancer (base hourly rate) — ~$11.52</li><li>Amazon ECR (~2 GB image storage) — ~$0.20</li><li>Amazon Route 53 (1 hosted zone) — ~$0.50</li><li>AWS Secrets Manager (2 secrets) — ~$0.80</li><li>NAT Instance (EC2 instance, t3.nano) — ~$3.74</li><li>Amazon CloudWatch Logs — ~$0.50</li><li>Total monthly cost estimate: $24.85 — $25.31</li></ul><h3>The Architecture</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Am7xdTbqys1Ne1IL" /><figcaption>The architecture diagram for the file sharing application</figcaption></figure><ol><li>User Authentication and Authorization</li></ol><ul><li>A user sends an authentication request through the Flask app.</li><li>Cognito handles authentication by adding the user to a user pool and triggers a lambda function post-confirmation to save the user data to DynamoDB.</li><li>Cognito returns authentication tokens to Flask for session management.</li></ul><p>2. Fetch File Metadata</p><ul><li>Flask requests file metadata from the DynamoDB through the API gateway.</li><li>API Gateway triggers a lambda function that fetches the file metadata.</li><li>API Gateway returns the file metadata to Flask for file listing.</li></ul><p>3. Upload File</p><ul><li>The user sends a file upload request through Flask, which initiates the upload process.</li><li>S3 returns pre-signed URLs that enable direct multipart uploads.</li><li>A lambda function, triggered by S3 PUT events, processes the file metadata and stores it in DynamoDB for file listing.</li></ul><p>4. Download File</p><ul><li>The user sends a file download request, and Flask handles the initial request.</li><li>The primary path uses CloudFront for optimized delivery, which serves the file from edge locations.</li></ul><p>5. Delete File</p><ul><li>The user requests file deletion from the DynamoDB through Flask.</li><li>Flask sends the request to API Gateway, which is authorised by Cognito, unlike the fetch file metadata operation.</li><li>API Gateway triggers a lambda function that deletes the file from S3 and its corresponding metadata from DynamoDB.</li><li>API gateway returns the response through Flask to confirm deletion.</li></ul><h3>Next up…</h3><p>The infrastructure. Stay tuned!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8bc778679500" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Storage Protocols: NFS]]></title>
            <link>https://medium.com/@r-owino/storage-protocols-nfs-1ef33929aa29?source=rss-89c9d1406517------2</link>
            <guid isPermaLink="false">https://medium.com/p/1ef33929aa29</guid>
            <category><![CDATA[nfs-client]]></category>
            <category><![CDATA[amazon-efs]]></category>
            <category><![CDATA[nfs-server]]></category>
            <dc:creator><![CDATA[Remmy]]></dc:creator>
            <pubDate>Fri, 01 Nov 2024 11:29:45 GMT</pubDate>
            <atom:updated>2024-11-02T06:11:48.363Z</atom:updated>
            <content:encoded><![CDATA[<h4>No, not Need For Speed…kinda…a little bit</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HTCOZxfaBp24DPKh" /><figcaption>Photo by <a href="https://unsplash.com/@leiadakrozjhen?utm_source=medium&amp;utm_medium=referral">Leiada Krozjhen</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In my previous <a href="https://medium.com/@r-owino/storage-protocol-iscsi-0ea490cab5cf">article</a>, I touched a little on Network File System (NFS) protocol, describing it as a protocol that permits easy file sharing between systems. It has enabled efficient file access and sharing among clients both in a single network setup, or configured to work across multiple setups as well. NFS has rules that allow multiple users to share the same file without data conflicts.</p><p>In AWS, there are a range of services that support NFS. One of them is Amazon Elastic File System (Amazon EFS) that abstracts away the hassle of the do-it-yourself approach normally required for NFS.</p><p>In this article, we’ll take a look at NFS in depth and how its abstraction in Amazon EFS has significantly reduced the complexity of configuring it for file access and sharing.</p><h3>What is NFS?</h3><p>NFS is a distributed file system protocol that lets you access files and directories on a client computer over a network as if they were stored locally. It operates within a distributed system , which is a collection of independent devices that appear to you as a single system.</p><p>It was developed by Sun Microsystems with a primary purpose of providing a transparent remote access to shared files across networks for UNIX-based systems. This makes it possible for you to work with remote files like they are stored locally on your device.</p><p>NFS has 3 main components that can be viewed as logically residing at the application, presentation and session layers of the OSI model. These are:</p><ol><li>Sun’s Remote Procedure Call (RPC) — provides a procedure-oriented interface to remote services. A server supplies a program (a set of procedures), and NFS is one such program. One remote service procedure is specified by a combination of host address, program number, version number, and procedure number.</li><li>External Data Representation (XDR) — standardizes data representation across different machines and operating systems.</li><li>Server Procedures — defined set of operations that clients can request from the server. They include procedures for file access, directory operations, and other file system functions.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/664/0*L2uCzgTHLTUpPWm0" /><figcaption>[<a href="http://www.tcpipguide.com/free/t_NFSArchitectureandComponents.htm">Source</a>] Comparing OSI, TCP/IP and NFS models</figcaption></figure><p>Other components that NFS leverages to fully function are:</p><ol><li>Mount protocol — it provides operating system specific services to get NFS off the ground such as looking up server path names, validating user identity, and checking access permissions. It is kept separate from the NFS protocol to make it easy to plug in new access checking and validation methods without changing the NFS server protocol.</li><li>NFS file system model — NFS assumes a hierarchical file system structure with directories and files.</li></ol><p>Over the years, NFS has grown with each version being an improvement of the previous version. The most recent version is NFSv4 and has the following components specific to it:</p><ol><li>Compound operations — allows multiple operations to be combined into a single RPC request.</li><li>Client caching — enables clients to cache file data and metadata locally for improved performance.</li><li>Strong security features — includes support for authentication and encryption, unlike in NFSv2 and NFSv3 that relied on UNIX style authentication to check permissions of various operations. Firewall configurations are also simplified using a single well-known port, 2049, over TCP/IP.</li><li>Internationalisation support — allows for handling of non-ASCII characters in filenames and other strings</li></ol><h3>How NFS Works</h3><p>NFS uses a client/server architecture to operate. The client requests for access to the server through the mount process and the server responds by exporting the files and directories over the network , which the client mounts to make them locally accessible.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/552/0*KoPjK0VCGP2-X05k" /><figcaption>[<a href="https://users.cs.fiu.edu/~czhang/teaching/cop6611/slides/nfs.pdf">Source</a>]Client-server architecture of NFS</figcaption></figure><p>There are 5 main steps to this operation:</p><ol><li><strong>Mounting</strong></li></ol><p>The client sends a request to the server to connect to a specific directory, setting up the necessary structures for subsequent NFS operations. It involves the following sub-processes:</p><ul><li>Server discovery — the client needs to locate the NFS server. This can be done manually or automatically using protocols like DHCP or DNS.</li><li>Export information retrieval — once the server is identified, the client retrieves information about available exports using the MOUNT protocol. This involves sending an RPC call to the server’s mount daemon to get details about shared file systems.</li><li>Mount request — with the export information, the client sends a mount request to the server, which specifies the exported file system the client wants to access.</li><li>File Handle Allocation — upon successful mounting, the server allocates a unique <strong><em>file handle</em></strong> for the mounted file system. File handles are opaque identifiers used by NFS operations to reference files and directories.</li></ul><p>2.<strong> Request Processing</strong></p><p>Once the remote directory is mounted, clients start accessing the files and directories. This is how the process works:</p><ul><li>RPC call construction — when a client needs to perform an operation (like reading a file), it constructs an RPC call. The RPC call encapsulates the NFS operation along with relevant parameters such as the file handle, the operation type, file attributes just to mention a few.</li><li>Transport layer transmission — the RPC call is then transmitted over the network using TCP or UDP. NFSv4 and later versions primarily use TCP for improved reliability.</li><li>RPC processing — upon receiving the RPC call, the server processes it according to NFS protocol specifications and performs the requested operation (e.g., read, write, lookup).</li><li>Response generation — after completing the operation, the server generates an RPC response which contains the result of the operation, including any requested data.</li><li>Error handling — both the client and server handle potential errors according to NFS specifications. Error codes are standardised to ensure consistent behaviour across implementations.</li><li>File locking — this is an optional RPC call that depends on the version and configuration of NFS being used. It allows multiple clients to access files safely without corrupting the data.</li></ul><p><strong>3. Authentication</strong></p><p>Regardless of the authentication method used, NFS servers will always identify the clients using their IP addresses and host names. In NFSv3 and earlier, authentication was handled using AUTH_SYS(UNIX authentication). This method uses UID/GID pairs, which have security limitations. But, starting with NFSv4, RPCSEC_GSS(Kerberos) authentication became supported. Using Kerberos 5 authentication, the client and server must establish a security context for NFS requests, providing stronger security.</p><p><strong>4. Data Transfer</strong></p><p>If authenticated, the server transfers the requested data to the client. It typically involves the following considerations:</p><ul><li>Read operations — clients send READ requests to retrieve file contents, to which the servers respond with the requested data, potentially using read-ahead techniques.</li><li>Write operations — WRITE requests are sent by clients to modify file contents. Servers acknowledge writes, potentially using asynchronous operations.</li><li>File attributes — GETATTR and SETATTR operations are used to manipulate file attributes and include metadata such as timestamps, permissions, and size.</li><li>Large files and blocks — NFSv4.2 introduced support for large blocks and sparse files to improve efficiency when dealing with very large files.</li></ul><p><strong>5. Caching</strong></p><p>This is an optimisation technique used by clients to cache frequently accessed data locally. This involves the following considerations:</p><ul><li>Client-side caching — clients maintain caches of recently accessed data to reduce network traffic, improving responsiveness and overall system performance.</li><li>Cache consistency — various mechanisms are employed to maintain cache consistency, including callbacks from the server to invalidate stale cached data.</li></ul><h3><strong>NFS in AWS</strong></h3><p>NFS has influenced AWS in simplifying how a central file storage can be accessed by multiple machines. Primarily, AWS uses it though Amazon EFS, allowing Linux-based EC2 instances to mount folders stored on EFS as local drives. Amazon EFS is more expensive per GB compared to Amazon Elastic Block Store (Amazon EBS), but it becomes economical when accessed by multiple machine instances because of its shared storage model.</p><p>Apart from Amazon EFS, AWS has integrated NFS with other services such as Amazon Storage Gateway for connecting on-premise file storage to cloud-based storage and Amazon FSx for additional file system options, including support for NetApp ONTAP, Windows FileServer, Lustre and OpenZFS.</p><h4><strong>NFS and Amazon EFS</strong></h4><p>Amazon EFS is a scalable, agile cloud-native NFS file system that minimizes your overhead by providing a simple, serverless set-and-forget elastic file system for AWS compute services. Multiple NFS clients can access your Amazon EFS file system simultaneously, allowing applications that grow beyond a single connection to access a file system.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*u792BeyJGSXGTxGJ" /><figcaption>[<a href="https://digitalcloud.training/amazon-efs/">Source</a>]An overview of how EFS can connect to multiple instances across various availability zones and on-premise connection through NFS protocol</figcaption></figure><p>Amazon EFS integrates the NFS protocol seamlessly, providing a familiar file sharing mechanism for Linux-based applications running on AWS. When you create an EFS file system, you can mount it on Amazon EC2 instances through the NFS versions 4.0 and 4.1 protocol. This integration allows you to access your EFS file system concurrently from multiple NFS clients.</p><p>Depending on the workload, EFS uses NFS to offer two performance modes — Max I/O for higher throughput and General Purpose for lower latency. By balancing file system performance according to access patterns, the NFS protocol makes it possible for applications to either prioritise low latency or maximise data throughput.</p><p>NFS in EFS ensures robust file consistency, making sure that any modifications made by one client are instantly apparent to others. Because it guarantees that every instance accessing the file system is using the most recent version of the data, this functionality is essential for applications where concurrency and data integrity are critical. EFS also offers high availability and durability by automatically replicating file system data across several availability zones.</p><h4><strong>NFS and Amazon Storage Gateway</strong></h4><p>Amazon Storage Gateway allows you to extend your on-premise storage to the cloud, achieving a hybrid architecture for storage. AWS uses the S3 File Gateway feature in Storage Gateway to provide access files stored as objects in Amazon S3 using protocols such as NFS. One of the benefits of File Gateway is that it provides low-latency performance by caching frequently accessed data locally while storing data securely in Amazon S3.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/706/0*_25ahqhwmKlNAC74" /><figcaption>[<a href="https://docs.aws.amazon.com/filegateway/latest/files3/file-gateway-concepts.html">Source</a>] NFS integration with Amazon Storage Gateway</figcaption></figure><p>File Gateway supports Linux clients connecting to the gateway using NFS versions 3 and 4.1 and connects on-premise NFS clients to Amazon S3 storage. It mounts the requested files or directories remotely on the client, providing access via a virtual connection. Through NFS, the Linux clients can interact with remote files as if they were local, enhancing usability and compatibility.</p><h3>Hands-on: Setup a Shared Data Repository for a Multi-node Application</h3><p>In this demo, you will create a shared repository where a simulated application — or a simulated microservice, if you’d wish to work with one — logs data, retrieves configuration files, or shares temporary files.</p><h4>Pre-requisites</h4><ol><li>AWS account with administrative permissions.</li><li>AWS CLI installed and configured.</li></ol><p><strong><em>Note: EFS is a regional service, so all the resources should be in one region.</em></strong></p><h4>Step 1: Create the EC2 resources</h4><p>In this step, you will:</p><ul><li>Create a Virtual Private Cloud (VPC)</li><li>Create two security groups</li><li>Launch EC2 instances</li></ul><p><strong>Step 1.1: Create a VPC and subnets</strong></p><p>Run the following commands to create your VPC while specifying the IPv4 CIDR block and an IPv4-only private subnet:</p><pre>aws ec2 create-vpc \<br>--cidr-block 10.0.0.0/24 \<br>--query Vpc.VpcId</pre><p>This command outputs a vpc-id in this format: <em>vpc-1a2b3c4d5e6f1a2b3</em>. You will use the ID to create the private subnets using the following command, replacing the vpc-id with yours:</p><pre>cidr_blocks=(&quot;10.0.0.0/28&quot; &quot;10.0.0.16/28&quot; &quot;10.0.0.32/28&quot;)<br>azs=(&quot;us-west-2a&quot; &quot;us-west-2b&quot; &quot;us-west-2c&quot;)<br><br>for i in ${!azs[@]}; do<br>  aws ec2 create-subnet \<br>    --vpc-id VPC-ID \<br>    --cidr-block ${cidr_blocks[$i]} \<br>    --availability-zone ${azs[$i]} \<br>    --query Subnet.SubnetId<br>done</pre><p>You will be SSH’ing into your EC2 instances from your local machine and therefore need to make the subnets public using an Internet Gateway(IGW). Follow the steps below to achieve that.</p><ul><li>Create the IGW, note the ID being returned by the command. You can also get the ID by running the describe command below.</li></ul><pre># create the IGW<br>aws ec2 create-internet-gateway \<br>--query InternetGateway.InternetGatewayId \<br>--output text<br><br># get the IGW ID<br>aws ec2 describe-internet-gateways</pre><ul><li>Attach the IGW to the VPC</li></ul><pre>aws ec2 attach-internet-gateway \<br>--internet-gateway-id IGW-ID \<br>--vpc-id VPC-ID</pre><ul><li>When you created the VPC, a route table was automatically associated with it. Run the following command to find its ID to update the table for public access:</li></ul><pre>aws ec2 describe-route-tables \<br>--filters &quot;Name=vpc-id,Values=VPC-ID&quot; \<br>--query &quot;RouteTables[0].RouteTableId&quot; \<br>--output text</pre><ul><li>Then add a route for internet traffic to the route table</li></ul><pre>aws ec2 create-route \<br>--route-table-id RTB-ID \<br>--destination-cidr-block 0.0.0.0/0 \<br>--gateway-id IGW-ID</pre><ul><li>Associate the route table with each subnet to ensure each subnet routes traffic to the IGW</li></ul><pre>for subnet in subnet-Id1 subnet-Id2 subnet-Id3; do<br> aws ec2 associate-route-table \<br> --route-table-id RTB-ID \<br> --subnet-id $subnet<br>done</pre><p><strong>Step 1.2: Create Security Groups</strong></p><p>Now that you have your VPC ready, create 2 security groups, one for your EC2 instances and another for your EFS mount targets. You will use the VPC-ID from the previous step.</p><p>Run this command to create the security group for your EC2 instances, taking note of the security group ID:</p><pre>aws ec2 create-security-group \<br>--group-name efs-demo-ec2-sg \<br>--description &quot;SG for EC2 instances&quot; \<br>--vpc-id VPC-ID</pre><p>And this command to create the security group for your EFS mount targets:</p><pre>aws ec2 create-security-group \<br>--group-name efs-demo-mnt-sg \<br>--description &quot;SG for mount target&quot; \<br>--vpc-id VPC-ID</pre><p>Currently, both security groups have only one outbound rule that allows all traffic out. You’ll authorise additional access that enables you to connect to your EC2 instances and enable traffic between an instance and an EFS mount target.</p><p>Run the following command to authorise incoming SSH connections to the security group for your EC2 instance. This will allow you to connect from any host using SSH.</p><pre>aws ec2 authorize-security-group-ingress \<br>--group-id SG-ID-FOR-EC2 \<br>--protocol tcp \<br>--port 22 \<br>--cidr 0.0.0.0/0 </pre><p>Run the following command to authorise inbound access to the security group for the EFS mount target.</p><pre>aws ec2 authorize-security-group-ingress \<br>--group-id SG-ID-FOR-EFS-MOUNT-TARGETS \<br>--protocol tcp \<br>--port 2049 \<br>--source-group SG-ID-FOR-EC2 </pre><p>Run the following command to double-check that both security groups now authorise inbound access.</p><pre>aws ec2 describe-security-groups \<br>--group-ids SG-ID-FOR-EC2 SG-ID-FOR-EFS-MOUNT-TARGETS</pre><p><strong>Step 1.3: Launch EC2 instances</strong></p><p>To finish off this section, you are going to launch three EC2 instances in the three subnets you created earlier. You will need the following to launch the instances:</p><ul><li>Amazon Machine Image ID (AMI Id) (example: ami-004a0173a724e2261 for Amazon Linux 2 HVM)</li><li>Key pair name</li><li>Security group ID for the instances</li><li>Subnet IDs of the subnets you created above. You’ll launch an EC2 instance in each subnet.</li><li><em>user-data.sh</em> file containing user data to your EC2 instances during launch</li></ul><p>For the AMI Id, you’ll have to log in to the console and get it from the AMI catalog in the EC2 service page. Browse through the AMIs and copy the AMI Id you want. For this demo, I’ll use Amazon Linux 2 AMI (HVM) 64-bit(x86) for all instances.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*TtoCi_1rucPPy7le" /><figcaption>AWS Console showing the AMI Catalog for AMI IDs</figcaption></figure><p>Run this command to create a key-pair:</p><pre>aws ec2 create-key-pair \<br>--key-name efs-demo \<br>--query &#39;KeyMaterial&#39; \<br>--output text &gt; efs-demo.pem</pre><p>Create a <em>user-data.sh</em> file with the following content:</p><pre>#!/usr/bin/env bash <br><br># Update Amazon Linux <br>sudo yum update -y<br><br># Install NFS client <br>sudo yum -y install nfs-utils<br><br># Make directory for mounting the EFS<br>mkdir ~/efs-mount-point</pre><p>When launched, the EC2 instances will get the latest updates, install the NFS client and create a shared directory where you’ll mount the file system.</p><p>Once you have everything ready, run this command to launch an EC2 instance in each subnet, taking note of the instance IDs returned:</p><pre>for subnet in subnet-Id1 subnet-Id2 subnet-Id3; do<br> aws ec2 run-instances \<br> --image-id ami-004a0173a724e2261 \<br> --count 1 \<br> --instance-type t2.micro \<br> --associate-public-ip-address \<br> --key-name efs-demo \<br> --security-group-ids SG-ID-FOR-EC2 \<br> --subnet-id $subnet \<br> --user-data file://user-data.sh<br>done</pre><p>Run this command to get the instance IDs:</p><pre>aws ec2 describe-instances \<br>--filters &quot;Name=subnet-id,Values=subnet-Id1,subnet-Id2,subnet-Id3&quot; &quot;Name=instance-state-name,Values=running&quot; \<br>--query &quot;Reservations[*].Instances[*].InstanceId&quot; \<br>--output text</pre><h4>Step 2: Create EFS resources</h4><p>In this step, you will:</p><ul><li>Create an encrypted EFS file system.</li><li>Enable lifecycle management.</li><li>Create mount targets in the Availability Zones where you have your EC2 instances launched.</li></ul><p><strong>Step 2.1: Create the file system</strong></p><p>Run this command to create an encrypted file system, noting down the <em>FileSystemId</em> that you’ll use later to create mount targets for the file system.</p><pre>aws efs create-file-system \<br>--encrypted \<br>--creation-token SharedRepositoryFileSystem \<br>--tags Key=Name,Value=SharedRepo</pre><p>The file system created has the default parameters such as General Purpose for performance mode and Bursting for throughput mode.</p><p>Run this command to get the <em>FileSystemId</em> of the file system you’ve just created:</p><pre>aws efs describe-file-systems \<br>--creation-token SharedRepositoryFileSystem \<br>--query &quot;FileSystems[*].FileSystemId&quot; \<br>--output text</pre><p><strong>Step 2.2: Enable lifecycle management</strong></p><p>Enabling lifecycle management on your file system allows you to use EFS Infrequent Access storage class. Run this command to enable it:</p><pre>aws efs put-lifecycle-configuration \<br>--file-system-id FILE-SYSTEM-ID \<br>--lifecycle-policies TransitionToIA=AFTER_30_DAYS</pre><p><strong>Step 2.3: Create mount targets</strong></p><p>You’ll create mount targets in the Availability Zones where you launched your EC2 instances. Ensure you have the following ready:</p><ul><li>File system ID</li><li>Subnet IDs — you will create mount targets in the same subnets where you have your EC2 instances</li><li>Security group ID of the EFS mount target</li></ul><p>Run this command to create the mount targets:</p><pre>for subnet in subnet-Id1 subnet-Id2 subnet-Id3; do<br> aws efs create-mount-target \<br> --file-system-id FILE-SYSTEM-ID \<br> --subnet-id $subnet \<br> --security-group SG-ID-FOR-EFS-MOUNT-TARGETS<br>done</pre><h4>Step 3: Mount the file system on the EC2 instances</h4><p>For this step, you’ll need the mount target IPs your file system</p><p><strong>Step 3.1: Connect to your EC2 instances through SSH</strong></p><p>Change the file permissions of the key-pair file you created earlier:</p><pre>chmod 400 efs-demo.pem</pre><p>The file is sensitive and must only be read by the user only, so this is the only permission the user is granted.</p><p>Run the following command to get the public IPs of your instances. Note that it gets the IP addresses of all instances currently running in that region in the order of the Availability Zones they’re in.</p><pre>aws ec2 describe-instances \<br>--filters &quot;Name=instance-state-name,Values=running&quot; \<br>--query &quot;Reservations[*].Instances[*].PublicIpAddress&quot; \<br>--output text</pre><p>Run this command to SSH into your instances:</p><pre>ssh -i efs-demo.pem ec2-user@PublicIpAddress</pre><p>If all goes well up to this point, you should be able to connect to your EC2 instances.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*NKNQfEQft9mxHk1Q" /><figcaption>Successfully connected to the EC2 instances using SSH</figcaption></figure><p><strong>Step 3.2: Mounting the file system</strong></p><p>Run this command to get the mount target IP for each subnet:</p><pre>aws efs describe-mount-targets \<br>--file-system-id FILE-SYSTEM-ID \<br>--query &quot;MountTargets[*].[MountTargetId,IpAddress,SubnetId]&quot; \<br>--output table</pre><p>Mount the file system to each instance using this command via the IP:</p><pre>sudo mount -t nfs4 -o nfsvers=4.1,rsize=1048576,wsize=1048576,hard,timeo=600,retrans=2,noresvport mount-target-ip:/ efs-mount-point/</pre><p>Verify that the mounting is successful:</p><pre>df -hT | grep efs</pre><p>Once the file system has been mounted, you can create files to test it. Change into <em>efs</em> directory and change permissions to create files because the root directory of the file system is owned by and writable by the root user upon creation.</p><pre>cd efs-mount-point/<br>sudo chmod 666</pre><p>Create a test file in one of the instances in the efs directory:</p><pre>echo &quot;Try this demo using IaC&quot; | sudo tee ~/efs-mount-point/testfile1.txt</pre><p>Confirm you can access the test file in other instances using the <em>ls</em> command and <em>cat</em> to view the file’s contents:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yFaDdteCj5fQZnFk" /><figcaption>Testing the file system after mounting it on 3 EC2 instances</figcaption></figure><h4>Step 4: Implementing application use cases</h4><p>You’ll focus on three use cases that mimic real-world scenarios of file sharing and concurrent access across multiple clients that you can modify to meet your needs.</p><ol><li><strong>Log aggregation</strong></li></ol><p>One client writes the logs while the others monitor or aggregate them.</p><ul><li>Create a script that writes logs on one instance in the shared directory every few seconds.</li></ul><pre>cat &lt;&lt; &#39;EOF&#39; &gt; ~/efs-mount-point/log_writer.sh<br>#!/usr/bin/env bash<br>while true; do<br>    echo &quot;$(date): Log entry from $(hostname)&quot; &gt;&gt; ~/efs-mount-point/shared_log.txt<br>    sleep 5<br>done<br>EOF<br>chmod +x ~/efs-mount-point/log_writer.sh</pre><ul><li>Run this command to run the script in the background</li></ul><pre>nohup ~/efs-mount-point/log_writer.sh &amp;</pre><ul><li>On the other instances, run this command to monitor <em>shared_log.txt</em></li></ul><pre>tail -f ~/efs-mount-point/shared_log.txt</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*W7mjvqkrr0XAZPDh" /><figcaption>Log aggregation among NFS clients sharing an EFS file system</figcaption></figure><p>This configuration demonstrates how logs from several instances may be combined and tracked in real time.</p><p>2. <strong>Configuration file management</strong></p><p>Each client can share and update a configuration file from the shared repository.</p><p>On one of the instances, create a configuration file in the shared directory:</p><pre>echo &quot;setting=value&quot; | sudo tee ~/efs-mount-point/app_config.conf</pre><p>On another instance, modify the configuration file and verify that the changes reflect immediately in other instances. Run this command in the other instances to verify:</p><pre>cat ~/efs-mount-point/app_config.conf</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gIGD5RPYkzM82EH0" /><figcaption>NFS clients accessing a configuration file and viewing changes in real time</figcaption></figure><p>In this step, all application nodes can obtain any updates, simulating centralised configuration management.</p><p>3. <strong>Data pipeline simulation</strong></p><p>Each client writes portions of data and one aggregates them.</p><p>On each instance, create this script that generates unique data segments to the shared repository.</p><pre>cat &lt;&lt; &#39;EOF&#39; &gt; ~/efs-mount-point/data_writer.sh <br>#!/usr/bin/env bash <br>for i in {1..10}; do <br>  echo &quot;$(hostname): Data segment $i&quot; &gt; ~/efs-mount-point/data_$(hostname)_$i.txt <br>  sleep 2 <br>done <br>EOF <br>chmod +x ~/efs-mount-point/data_writer.sh</pre><p>And run the script on each instance:</p><pre>nohup ~/efs-mount-point/data_writer.sh &amp;</pre><p>On one instance, create the following script to aggregate all the data files:</p><pre>cat &lt;&lt; &#39;EOF&#39; &gt; ~/efs-mount-point/data_aggregator.sh<br>#!/usr/bin/env bash<br>cat ~/efs-mount-point/data_*.txt &gt; ~/efs-mount-point/aggregated_data.txt<br>EOF<br>chmod +x ~/efs-mount-point/data_aggregator.sh</pre><p>And run it:</p><pre>./data_aggregator.sh</pre><p>On the other instances, view the <em>aggregated_data.txt</em> file to confirm that all the data have been consolidated</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gXynw36AkIPEohDUIgKmtQ.png" /><figcaption>How NFS clients can utilise a shared repository to create a data pipeline</figcaption></figure><p>With each client writing its data to a central location for processing, this configuration shows how EFS may be used to manage a data pipeline.</p><h4>Step 5: Clean up</h4><p>Once you’re done with the resources you created, you should remove them to avoid costly charges.</p><ol><li><strong>Remove the EC2 resources</strong></li></ol><p>Log out of your instances</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ju6e1hI27QD_dn2g" /><figcaption>Logging out of the EC2 instances</figcaption></figure><p>Then, terminate all the instances, or stop them if you’ll still use them another time.</p><pre># terminate EC2 instances<br>aws ec2 terminate-instances --instance-ids $(aws ec2 describe-instances \<br>--filters &quot;Name=subnet-id,Values=subnet-Id1,subnet-Id2,subnet-Id3&quot; &quot;Name=instance-state-name,Values=running&quot; \<br>--query &quot;Reservations[*].Instances[*].InstanceId&quot; \<br>--output text)</pre><pre># stop EC2 instances<br>aws ec2 stop-instances --instance-ids $(aws ec2 describe-instances \<br>--filters &quot;Name=subnet-id,Values=subnet-Id1,subnet-Id2,subnet-Id3&quot; &quot;Name=instance-state-name,Values=running&quot; \<br>--query &quot;Reservations[*].Instances[*].InstanceId&quot; \<br>--output text)</pre><p>Delete the mount targets</p><pre>for mount_target in $(aws efs describe-mount-targets \<br>--file-system-id FILE-SYSTEM-ID \<br>--query &quot;MountTargets[*].MountTargetId&quot; \<br>--output text); do<br>  aws efs delete-mount-target --mount-target-id &quot;$mount_target&quot;<br>  echo &quot;Deleted mount target: $mount_target&quot;<br>done</pre><p>Optionally, you can delete the security groups too, but you don’t get billed for them. You have to delete the EFS security group before the EC2 security group because it references it. Run this command to delete a security group:</p><pre>aws ec2 delete-security-group --group-id SG-ID</pre><p>2. <strong>Remove the EFS resources</strong></p><p>Finally, delete the file system</p><p>Get the file system ID and delete the file system:</p><pre>for fs_id in $(aws efs describe-file-systems --query &quot;FileSystems[*].FileSystemId&quot; --output text); do<br>  aws efs delete-file-system --file-system-id &quot;$fs_id&quot;<br>  echo &quot;Deleted file system: $fs_id&quot;<br>done</pre><h3>Troubleshooting NFS in Amazon EFS</h3><p>The following scenarios describe the common NFS and EFS troubleshooting situations. Finding the source of the problem requires systematically checking resource usage, DNS resolution, network connectivity, and permissions.</p><ol><li><strong>Mount Target Not Reachable</strong></li></ol><p>Issue: Unable to mount EFS file system, getting “nfs: server not responding” error. The NFS client cannot establish a connection to the EFS mount target</p><p>Possible Causes:</p><ul><li>Incorrect mount target IP address</li><li>Security group rules blocking NFS traffic</li><li>VPC DNS settings not configured correctly</li><li>Mount target in a different subnet/VPC than the EC2 instance</li></ul><p>Possible Solutions:</p><ul><li>Verify the correct mount target IP address is being used</li><li>Check security group rules allow NFS traffic (port 2049) between EC2 and mount target</li><li>Ensure VPC DNS settings are enabled</li><li>Create mount target in same subnet/VPC as EC2 instance</li><li>Use the <em>noresvport</em> mount option to avoid TCP port reuse issues</li></ul><p>2. <strong>Permissions Issues</strong></p><p>Issue: Mount fails with “access denied by server” error. The NFS client lacks proper permissions to mount the EFS file system</p><p>Possible Causes:</p><ul><li>Missing <em>-o iam</em> mount option when using IAM authentication</li><li>File system policy or IAM role permissions not configured correctly</li><li>Access point permissions not set properly</li></ul><p>Possible Solutions:</p><ul><li>Add <em>-o iam</em> mount option when using IAM auth</li><li>Review and update file system policy and IAM role permissions</li><li>Set proper ownership and permissions on access point root directory</li><li>Use the EFS mount helper utility to manage permissions</li></ul><p>3. <strong>DNS Resolution Problems</strong></p><p>Issue: Mount fails when using EFS DNS name, works with IP address. DNS resolution failing for EFS mount target</p><p>Possible Causes:</p><ul><li>VPC DNS settings not enabled</li><li>Custom DNS settings interfering with EFS DNS resolution</li><li>Mount target in different VPC than EC2 instance</li></ul><p>Possible Solutions:</p><ul><li>Enable VPC DNS settings</li><li>Check for conflicting custom DNS configurations</li><li>Create mount target in same VPC as EC2 instance</li><li>Use mount target IP address instead of DNS name temporarily</li></ul><p>4. <strong>Performance Issues</strong></p><p>Issue: Operations on mounted EFS file system are slow or unresponsive. High latency or throughput limitations affecting EFS performance.</p><p>Possible Causes:</p><ul><li>Large file writes blocking other operations</li><li>Insufficient provisioned throughput</li><li>Network bandwidth constraints</li><li>Many small file operations</li></ul><p>Possible Solutions:</p><ul><li>Implement periodic fsync() calls for long-running write operations</li><li>Increase provisioned throughput on the EFS file system</li><li>Optimise network configuration (e.g. jumbo frames)</li><li>Consider using General Purpose performance mode for metadata-heavy workloads</li></ul><p>5. <strong>Mount Target Lifecycle Issues</strong></p><p>Issue: Mount target stuck in “creating” or “deleting” state</p><p>Possible Causes:</p><ul><li>Conflicting DNS records in VPC</li><li>Insufficient IAM permissions</li><li>Network connectivity issues</li><li>AWS service limits reached</li></ul><p>Possible Solutions:</p><ul><li>Retry mount target creation/deletion</li><li>Check for conflicting DNS records and remove if needed</li><li>Verify IAM permissions for EFS actions</li><li>Contact AWS support if issue persists</li></ul><h3>Conclusion</h3><p>NFS still remains the go-to protocol when configuring servers and clients for shared storage access. It requires careful configuration on the server and client to function correctly because it doesn’t work out of the box. In an on-premise file storage architecture, it is the system administrators’ job to ensure that all configurations match and the protocol is periodically updated. In the cloud file storage architecture, this complexity has been abstracted and the system administrators can smoothly implement file storage systems for organisations, all made possible using NFS protocol.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1ef33929aa29" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Storage Protocol: iSCSI]]></title>
            <link>https://medium.com/@r-owino/storage-protocol-iscsi-0ea490cab5cf?source=rss-89c9d1406517------2</link>
            <guid isPermaLink="false">https://medium.com/p/0ea490cab5cf</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[storage]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[iscsi]]></category>
            <category><![CDATA[aws-storage-gateway]]></category>
            <dc:creator><![CDATA[Remmy]]></dc:creator>
            <pubDate>Wed, 16 Oct 2024 09:33:16 GMT</pubDate>
            <atom:updated>2025-07-15T12:54:24.412Z</atom:updated>
            <content:encoded><![CDATA[<h4>Integration with AWS cloud environment</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Wd6XKv481OlYLXIA" /><figcaption>Photo by <a href="https://unsplash.com/@redaquamedia?utm_source=medium&amp;utm_medium=referral">Denny Müller</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>For data-driven businesses, which currently is a majority, having an efficient data storage and management with sharing capabilities is essential. Networks have grown overtime and become so vast necessitating the need for secure and scalable data storage and sharing solutions.</p><p>There are two such protocols that enable effective data sharing: Internet Small Computer System Interface (iSCSI) and Network File System (NFS). iSCSI brought about block-level storage over IP networks, allowing remote access to data storage like it were local. NFS, on the other hand, permits easy file sharing between different systems much like the way different people can share two different files without direct access to one another. Both protocols transformed the way we handle and organize information, especially within the cloud computing infrastructures, such as AWS, where they now support scalable, flexible data-sharing solutions.</p><p>In this article, we’ll extensively explore how iSCSI works and its adoption in AWS storage services.</p><h3><strong>Understanding iSCSI and How it Works</strong></h3><p>To fully grasp iSCSI, we first need to understand the Small Computer System Interface (SCSI) protocol. SCSI is a family of protocols devised for communication between computers and peripheral systems including hard drives, tape drives, CD and DVD drives, printers, and scanners.</p><p>The SCSI model consists of an initiator issuing commands to a target in the form of Command Descriptor Blocks(CDBs) that describe the action required to be executed. Thus, the target processes these commands and returns a status — success or failure — along with the data that needs to be returned. SCSI works in a client-server architecture: the client is the initiator that sends the requests, and the server is the target serving those requests. The initiator and target devices are referred to as <strong><em>Logical Units</em></strong>(LUs) and each has a unique identifier called a <strong><em>Logical Unit Number </em></strong>(LUN). An iSCSI target may have many logical units.</p><p>Traditional SCSI started as a protocol for direct, physical connections between computers and storage. As data networks evolved, it became desirable to extend the functionality of SCSI across IP networks — and that’s where iSCSI comes in.</p><p>iSCSI, from its name, is SCSI over IP. Instead of operating over a direct physical connection, it takes the familiar SCSI command set and allows it to function over TCP/IP networks. The basic SCSI concepts, such as initiators, targets, commands and LUNs, are still maintained in iSCSI, only that instead of using physical SCSI cables, the commands are delivered over standard Ethernet networks using the TCP/IP protocol, over TCP port 3260.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zjNCSzjiqFwzSsQJ" /><figcaption>iSCSI architecture: Initiators connect to a remote iSCSI target over an IP-based intranet.</figcaption></figure><h4><strong>How it works</strong></h4><p>iSCSI works by transporting the SCSI command set on a standard TCP/IP connection over an Ethernet based network between an initiator and a target. These actions can be divided into two:</p><ol><li><strong>The Login Process</strong></li></ol><p>This is when an initiator wishes to establish communication to a target. It starts by the initiator sending a login request to the target. The login request contains crucial information about the initiator and the specific storage target it wishes to connect to. If Challenge Handshake Authentication Protocol (CHAP) is being used, the request will also include CHAP information for authentication purposes. The target then verifies the initiator’s credentials using the provided information. If the authentication is successful, the login completes, and a session is established between the initiator and the target. This session typically remains active for extended periods, often days or months, until either the initiator or the target initiates a logout command to close the connection.</p><p>2<strong>. The Data Transfer Process</strong></p><p>After the login process is complete and a session established, the data transfer process begins. This process involves several layers of encapsulation and transmission. It starts at the application level on the host, where block-level I/O operations are generated. These operations are then translated into SCSI commands at the presentation layer. At the session layer, where iSCSI operates, the SCSI commands are encapsulated into PDUs. These PDUs are then wrapped in TCP segments at the transport layer, placed within IP datagrams at the network layer, and finally inserted into Ethernet frames at the data link layer. The completed Ethernet frame, containing the iSCSI PDU as payload, is then transmitted over the physical network to reach the target storage array.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/0*bXUshGdrgImGblpC" /><figcaption>[<a href="https://infohub.delltechnologies.com/nl-nl/l/iscsi-implementation-guide-for-dell-emc-storage-arrays-running-powermaxos-1/how-iscsi-works/">Source</a>] How iSCSI works through the OSI layer</figcaption></figure><p>Upon reception, the process is reversed, with each layer removing its respective encapsulation until the original SCSI commands reach the target’s presentation layer for interpretation and processing. This complex process allows iSCSI to efficiently transport block-level data across standard TCP/IP networks, effectively extending local storage capabilities to remote devices.</p><p>For example, when an application on an iSCSI initiator wants to read data from a remote disk, it would send a SCSI READ command encapsulated within an iSCSI Protocol Data Unit(PDU). This PDU would be transmitted over TCP/IP to the iSCSI target, which would then process the SCSI READ command and return the requested data along with a status response.</p><p>iSCSI has allowed us to build Storage Area Networks(SANs) using cheap and widely accessible IP infrastructure. Traditional SCSI required proprietary hardware. This has been slashed down by iSCSI, as it runs over regular Ethernet, minimizing costs and complexities, while still allowing block-level access to storage.</p><h3>iSCSI in AWS</h3><p>Suppose you are using an on-premise architecture and you would wish to extend your on-premise storage into the cloud, iSCSI enables this by creating hybrid storage solutions that are flexible, scalable and cost effective. In AWS, the AWS Storage Gateway service leverages iSCSI to allow you connect your on-premise storage to cloud storage, providing a seamless bridge between your IT environment and the cloud.</p><h4>iSCSI and AWS Storage Gateway</h4><p>AWS Storage Gateway gives your applications on-premises and in-cloud access to virtually unlimited cloud storage. You can deploy Storage Gateway as a virtual machine (VM) within your VMware, Hyper-V, or Linux KVM virtual environment, or as an Amazon EC2 instance within your Amazon VPC. The volume gateway presents iSCSI block storage volumes to your on-premise applications that you can store in Amazon S3 or migrate to Amazon EBS.</p><p>In the Storage Gateway Volume Gateway, iSCSI is used as the primary communication protocol between your on-premises applications and cloud storage. There are two main ways you can work with the volume gateway:</p><ul><li>Cached Volumes — stores frequently accessed data locally using EBS, with Amazon S3 as main data storage. You can create a storage volume of up to 32TB and connect it to local systems as an iSCSI device. The storage volume then stores any infrequently-used data automatically to S3, reducing the load on local stores, while using cloud storage in a cost-effective manner.</li><li>Stored Volumes — treats your local storage as main data storage, but performs asynchronous backup to Amazon S3, as an EBS snapshot. This gives you an off-site backup of a local drive. The Stored Volume is mounted as an iSCSI device within on-premise applications. Stored Volumes can be 1GB to 16TB in size.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-nuk-Z5hB9NRWmgZ" /><figcaption>[<a href="https://www.youtube.com/watch?v=Bb8nk0oWJbU&amp;list=PLahkoIgBSDWmBd8wwcdCzni0tqjd5_0B5&amp;ab_channel=AmazonWebServices">Source</a>] An illustration of how AWS Storage Gateway works</figcaption></figure><h3><strong>Hands-on: Configure iSCSI connectivity to an AWS Storage Gateway Volume Gateway</strong></h3><h4>Pre-requisites</h4><ol><li>AWS account with administrator permissions.</li><li>AWS CLI installed and configured.</li><li>On-premise server that will be the iSCSI initiator to connect to the Volume Gateway, with iSCSI installed and configured.</li></ol><p><strong>Step 1: Activate the gateway</strong></p><p>You should have already set up the gateway software on your on-premise server. Run this command on your client machine, replacing the values with your own.</p><pre>aws storagegateway activate-gateway \<br>--activation-key YOUR_ACTIVATION_KEY \<br>--gateway-name YOUR_GATEWAY_NAME \<br>--gateway-timezone YOUR_TIMEZONE \<br>--gateway-region YOUR_REGION \<br>--gateway-type STORED</pre><ul><li>YOUR_ACTIVATION_KEY: The activation key provided by AWS. To get the activation key, log in to your gateway’s local console from the hardware appliance and get the activation key.</li><li>YOUR_GATEWAY_NAME — a name for your gateway</li><li>YOUR_TIMEZONE — your local timezone</li><li>YOUR_REGION — the AWS region where you’re activating the gateway</li><li>STORED— the gateway type (this is for stored volumes. Replace with CACHED if you want a cached volume.)</li></ul><p>The output for this command is the Amazon Resource Name(ARN) for the gateway you’ve created and activated. Take note of the ARN. You can run the following command to get information about the gateway:</p><pre>aws storagegateway describe-gateway-information \<br>--gateway-arn YOUR-GATEWAY-ARN</pre><p><strong>Step 2: Add disk to the gateway</strong></p><p>Add a disk to your gateway for storing data by running this command, replacing DISK_ID with the disk you want to add.</p><pre>aws storagegateway add-cache \<br>--gateway-arn YOUR_GATEWAY_ARN \<br>--disk-id DISK_ID</pre><p><strong>Step 3: Create the Stored Volume</strong></p><p>Create a stored volume on the gateway, replacing the placeholders appropriately. You can choose to preserve data on the local disk by setting the option to True. In this demo, I want an empty disk.</p><pre>aws storagegateway create-stored-iscsi-volume \<br>--gateway-arn YOUR_GATEWAY_ARN \<br>--disk-id DISK_ID \<br>--preserve-existing-data False \<br>--target-name TARGET_NAME \<br>--network-interface-id NETWORK_INTERFACE_ID \<br>--tags Key=Environment,Value=Test</pre><p>This command outputs the following:</p><ol><li>VolumeARN — the ARN of the configured volume</li><li>VolumeSizeInBytes — the size of the volume in bytes</li><li>TargetARN — the ARN of the volume target, which includes the iSCSI name that initiators can use to connect to the target.</li></ol><p>You can get the volume information by running this command:</p><pre>aws storagegateway describe-stored-iscsi-volumes \<br>--volume-arns YOUR_VOLUME_ARN</pre><p><strong>Step 4: Configure CHAP authentication (optional, but recommended)</strong></p><p>Run this command if you want to configure CHAP authentication, replacing the placeholders with your values, otherwise skip this step:</p><pre>aws storagegateway update-chap-credentials \<br>--target-arn TARGET_ARN \<br>--secret-to-authenticate-initiator SECRET_KEY \<br>--initiator-name INITIATOR_NAME</pre><ul><li>TARGET_ARN — your target ARN from step 3</li><li>SECRET_KEY — the secret key that the initiator must provide to participate in mutual CHAP with the target</li><li>INITIATOR_NAME — the iSCSI initiator that connects to the target.</li></ul><p>The output for this command are the TARGET_ARN and INITIATOR_NAME, same as passed in the command.</p><p><strong>Step 5: Discover the iSCSI target and login to it</strong></p><p>Run this command on your on-premise server to see the available targets, replacing GATEWAY-IP-ADDRESS with the IP address of your storage gateway.</p><pre>sudo iscsiadm --mode discovery --type sendtargets --portal GATEWAY-IP-ADDRESS</pre><p>Then login to the target</p><pre>sudo iscsiadm --mode node --targetname TARGET-ARN --portal GATEWAY-IP-ADDRESS --login</pre><p><strong>Step 6: Confirm the connection</strong></p><p>List all connected iSCSI sessions</p><pre>sudo iscsiadm --mode session</pre><p><strong>Step 7: Format and mount the new volume</strong></p><p>After logging into the iSCSI target, the volume will appear as a local disk on the client machine. You can format and mount it like a regular disk.</p><p>List the available volumes:</p><pre>sudo fdisk -l</pre><p>Then format (as an ext4, for example) and mount the disk</p><pre>sudo mkfs.ext4 /dev/sdX<br>sudo mount /dev/sdX /mnt/my-iscsi-volume</pre><p>If you want your on-premise server to automatically login to the target volume during boot-up, run this command to enable it</p><pre>sudo iscsiadm --mode node \<br>--targetname TARGET_ARN \<br>--portal GATEWAY-IP-ADDRESS \<br>--op update \<br>--name node.startup \<br>--value automatic</pre><h3><strong>Security measures with data transfer over Storage Gateway through iSCSI</strong></h3><p>Because you’d never want your data leaked or breached, especially when it’s being transferred to another storage space, AWS has employed security measures that ensures secure transfer of your data between your on-premise location and cloud storage through iSCSI using Storage Gateway. These are some of the ways AWS accomplishes this:</p><ol><li><strong>Encryption in Transit</strong></li></ol><p>SSL/TLS Encryption — all data transferred between the gateway appliance and AWS storage services is encrypted using SSL/TLS protocols. This ensures that data remains confidential during transmission over potentially untrusted networks.</p><p>FIPS Compliant Endpoints — for highly sensitive environments, AWS Storage Gateway offers FIPS 140–2 compliant endpoints in AWS GovCloud regions. This provides an additional layer of cryptographic security for government agencies and other organizations with strict compliance requirements.</p><p>2. <strong>Encryption at Rest</strong></p><p>Default Server-Side Encryption — by default, all data stored by AWS Storage Gateway in S3 is encrypted server-side using Amazon S3-Managed Encryption Keys (SSE-S3). This ensures that even if unauthorized access occurs at the storage level, the data itself remains encrypted.</p><p>Customer Managed Keys — for additional control, users can optionally configure encryption using AWS Key Management Service (AWS KMS) managed keys via the Storage Gateway API. This allows you to manage your own encryption keys, providing an extra layer of security and control over their data.</p><p>3. <strong>Access Control and Authentication</strong></p><p>CHAP Authentication — AWS Storage Gateway supports CHAP for authenticating iSCSI connections between initiators and targets. This ensures that only authorized systems can access the storage resources.</p><p>AWS IAM Integration — Storage Gateway integrates natively with AWS IAM. This allows administrators to manage and secure access to Storage Gateway resources using fine-grained policies and roles.</p><p>4. <strong>Data Integrity and Consistency</strong></p><p>Optimized Data Transfer — Storage Gateway optimizes data transfer by sending only changed data and compressing it when possible. This not only improves efficiency but also reduces the risk of data corruption during transmission.</p><p>Intelligent Buffering — the service employs intelligent buffering techniques to manage network variations and optimize upload performance, further enhancing data integrity during transfer.</p><p>5. <strong>Monitoring and Logging</strong></p><p>CloudWatch Integration — Storage Gateway publishes health and performance logs and metrics to Amazon CloudWatch. This allows for real-time monitoring of gateway operations and quick detection of any security anomalies.</p><p>CloudTrail Integration — AWS Storage Gateway integrates with AWS CloudTrail for logging account activity, providing a comprehensive audit trail of all actions performed on the gateway.</p><p>6. <strong>Compliance and Certifications</strong></p><p>PCI DSS Compliance — AWS Storage Gateway is compliant with the Payment Card Industry Data Security Standard (PCI DSS), demonstrating its ability to handle sensitive financial data securely.</p><p>AWS Compliance Programs — regular third-party audits verify the effectiveness of AWS’s security measures as part of various compliance programs.</p><p>7. <strong>Shared Responsibility Model</strong></p><p>AWS operates under a shared responsibility model — AWS is responsible for protecting the infrastructure that runs AWS services, you are responsible for securing your data, applications, and access to AWS services.</p><h3>Troubleshooting iSCSI in AWS Storage Gateway</h3><p>A few common issues that may arise in this set-up include:</p><ol><li>iSCSI Target Discovery Failure</li></ol><p>Issue: Can’t discover any targets on the on-premise server machine. This occurs when the iSCSI initiator fails to locate the iSCSI target on the AWS Storage Gateway.</p><p>Possible Causes:</p><ul><li>Incorrect iSCSI target IP or DNS name</li><li>Firewall blocking iSCSI traffic</li><li>Network connectivity issues between client and gateway</li><li>Mismatched iSCSI qualified names (IQNs)</li></ul><p>Possible Solutions:</p><ul><li>Verify the iSCSI target IP or DNS name is correct</li><li>Check firewall rules to ensure port 3260 (default iSCSI port) is open</li><li>Confirm network connectivity between client and gateway</li><li>Double-check that IQNs match between initiator and target</li></ul><p>2. Authentication Failure</p><p>Issue: Unable to log in to the iSCSI target due to authentication failure. This happens when the iSCSI initiator cannot authenticate with the target, often due to incorrect credentials or misconfigured CHAP settings.</p><p>Possible Causes:</p><ul><li>Incorrect CHAP username or secret</li><li>Mismatched CHAP settings between initiator and target</li><li>Expired or invalid credentials</li><li>Incorrect CHAP configuration.</li><li>CHAP authentication might not be configured properly on either the initiator or the Storage Gateway.</li></ul><p>Possible Solutions:</p><ul><li>Verify CHAP username and secret are correctly configured</li><li>Ensure CHAP settings match between initiator and target</li><li>Reset CHAP credentials if they’ve expired or become invalid</li><li>Check that CHAP is enabled and configured with the same username and password on both the AWS Storage Gateway volume and the iSCSI initiator.</li><li>If CHAP is disabled on the AWS Storage Gateway, ensure no authentication is expected on the initiator side.</li></ul><p>3. Connection Timeout</p><p>Issue: Connections to the iSCSI target consistently time out. This indicates that the initiator cannot establish a stable connection with the target, possibly due to network issues or resource constraints.</p><p>Possible Causes:</p><ul><li>High network latency between client and gateway</li><li>Insufficient network bandwidth</li><li>Overloaded gateway resources</li></ul><p>Possible Solutions:</p><ul><li>Optimize network path between client and gateway</li><li>Increase network bandwidth allocation</li><li>Scale up gateway resources if overloaded</li></ul><p>4. Data Corruption</p><p>Issue: Data written to the iSCSI target becomes corrupted or unreadable. This can occur due to various factors affecting data integrity during transfer or storage.</p><p>Possible Causes:</p><ul><li>Network errors during data transfer</li><li>Hardware failures in either the gateway or client</li><li>Incompatible or outdated drivers</li></ul><p>Possible Solutions:</p><ul><li>Run data integrity checks on the affected volume</li><li>Update drivers and firmware on both gateway and client</li><li>Replace faulty hardware components if identified</li></ul><p>5. Performance Degradation</p><p>Issue: iSCSI performance degrades significantly over time, leading to slow data transfers.</p><p>Possible Causes:</p><ul><li>Increased load on the gateway</li><li>High latency in the network connection between the client and the Storage Gateway.</li><li>Outdated gateway software</li></ul><p>Possible Solutions:</p><ul><li>Monitor and analyze performance metrics using CloudWatch focusing on metrics such as <em>CachePercentDirty</em>, <em>CacheHitPercent</em>, and <em>CloudBytesUploaded</em>.</li><li>Monitor network latency using tools like <em>ping</em> or <em>iperf</em> to check for any bottlenecks.</li><li>Update gateway software to the latest version</li></ul><h3>Conclusion</h3><p>Because of iSCSI, you can efficiently and cost-effectively manage your storage infrastructure in AWS by extending your on-premise storage to cloud using AWS Storage Gateway. iSCSI runs the familiar SCSI command set over IP, meaning you can build scalable and efficient Storage Area Networks. Whether for disaster recovery, data migration, or simply extending storage capacity, iSCSI’s role in AWS continues to be a base of modern, cloud-driven storage strategies. By understanding how to use iSCSI effectively, you can future-proof your storage systems and remain competitive in an increasingly data-centric world.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0ea490cab5cf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Networking for Cloud Architects — Border Gateway Protocol in AWS]]></title>
            <link>https://medium.com/@r-owino/networking-for-cloud-architects-border-gateway-protocol-in-aws-bbdbd3913eed?source=rss-89c9d1406517------2</link>
            <guid isPermaLink="false">https://medium.com/p/bbdbd3913eed</guid>
            <category><![CDATA[bgp]]></category>
            <category><![CDATA[junosos]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[bgp-routing-policies]]></category>
            <category><![CDATA[aws-direct-connect]]></category>
            <dc:creator><![CDATA[Remmy]]></dc:creator>
            <pubDate>Wed, 02 Oct 2024 05:19:50 GMT</pubDate>
            <atom:updated>2025-04-02T23:35:34.183Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Networking for Cloud Architects — Border Gateway Protocol in AWS</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uQfY2vWVlZIIgXh1qVlQng.png" /></figure><p>The Border Gateway Protocol(BGP) is the backbone of internet routing, and for network architects working with AWS, mastering BGP is essential especially when building scalable, resilient and flexible cloud architectures and handling complex multi-cloud or hybrid architectures. BGP allows dynamic routing across Autonomous Systems(AS) ensuring that data efficiently traverses networks based on real time network conditions.</p><p>In AWS, BGP is primarily used to establish and manage network connectivity between different Virtual Private Clouds(VPCs), as well as between VPCs and on-premises networks. Understanding how BGP functions within the AWS environment enables you to manage large scale routing tables, failover mechanisms and optimize path selection for smoother, uninterrupted data flows across networks.</p><p>In this article, we’ll break down BGP’s role in AWS, its key features and how to configure it for your infrastructure.</p><h3>Understanding BGP</h3><p>BGP is an inter-autonomous system routing protocol that is designed to exchange network reachability information among the autonomous systems on the internet. It is an exterior gateway protocol that is used to connect to external organizations. It is a path vector routing protocol — it uses a path algorithm to make routing decisions based on paths, network policies or rule sets configured by a network administrator. It runs over the Transport Control Protocol(TCP) on port 179 to establish its connections and on the application layer of the OSI model. Using TCP as its transport protocol ensures reliability without needing separate mechanisms to implement re-transmission, sequencing, acknowledgements and explicitly update network information fragmentation.</p><p>Some of the routing components that BGP uses are:</p><ul><li>Autonomous Systems (AS) — independent network managed by a single organization, typically an ISP.</li><li>Autonomous System Number (ASN) — an Autonomous System unique identifier.</li><li>BGP peers/BGP speakers — connection between BGP routers to exchange routing information.</li><li>BGP routes — paths that data packets take to reach their destination.</li><li>Border routes — routers on the boundary of one AS exchanging information with another AS.</li></ul><h4><strong>How BGP works</strong></h4><p>Before delving into how BGP works, there are two forms of BGP we have to understand:</p><ol><li>Interior BGP (iBGP) — this is when BGP runs among peers in the same AS allowing routers to communicate routing information locally. It doesn’t automatically advertise routes learned from one iBGP to another to avoid routing loops.</li><li>Exterior BGP (eBGP) — this is when BGP runs among peers in different AS’es. To prevent routing loops and maintain route validity, the AS path is crucial because the routers are in different organizations.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3g5ihZmBs7ZXylKm" /><figcaption>[<a href="https://kadiska.com/how-does-bgp-routing-work/">Source</a>] Difference between iBGP and eBGP in AS’es</figcaption></figure><p>This is how BGP works:</p><p><strong>Establishing a peer connection</strong></p><p>First, it establishes a peer connection between routers (called BGP peers/speakers) in a manual process called neighbour adjacency. The speakers create a TCP session on port 179 that initializes a BGP session to exchange routing information by sharing periodic “keepalive” messages to ensure the connection is still live. Once this session is established, the routers begin advertising routes. Each side of the BGP connection must have its own Autonomous System Number (ASN) to identify its AS. On AWS, this peer relationship is built between resources like Transit Gateway and on an on-premise router or another cloud provider.</p><p><strong>Route advertisement and exchange</strong></p><p>BGP advertises the route to enable the peers to exchange information about the best routes to various destinations. It does this by broadcasting routing information to peers. This aspect of BGP is used for exchanging routing and reachability information among AS’es on the internet. Each peer maintains a table of possible network destinations, along with attributes such AS path and hop count. They then advertise their own routes to neighbouring routers and receive information about routes from those neighbours. BGP allows cloud architects to have granular control over which routes are advertised and accepted. When advertising the routes, a cloud architect can decide to apply filters on AWS and external routers to control which routes are advertised or accepted, control the number of routes a BGP session can receive by defining prefix limits and summarizing route tables into a single broader prefix to reduce the size of the route table and simplify route management.</p><p><strong>Path Selection</strong></p><p>A BGP routing table usually has multiple paths from which it selects the best path to a destination using a process called path selection to choose the best route. Consider only synchronized routes with no AS loops with a reachable next hop, BGP will prefer a route based on these attributes:</p><ul><li>Highest weight from local to exterior router — a route with a weight of 1000 will be preferred over a route with a weight of 100. This is the most preferred attribute.</li><li>Highest local preference — if no weight is applied on a route, a route with a local preference of 500 is chosen over a route with a local preference of 200.</li><li>Directly connected route — suppose both the weight and local preference applied on multiple routes are equal, BGP will select the route that is directly connected from the local router to the other router.</li><li>AS path length — The shorter the AS path, the more preferred the route. For example, a path that traverses three AS’es will be preferred over one that crosses five.</li><li>Lowest Multi-Exit Discriminator(MED) — by default it’s 0 and it is exchanged between AS’es, it hints to the external peers about preferred entry points into an AS.</li><li>Neighbour type — assuming all the other attributes are same, BGP will prefer an eBGP route over an iBGP route.</li></ul><h3>BGP in AWS</h3><p>BGP plays a critical role in AWS networking by providing a flexible and scalable way to manage traffic and routing. It allows network administrators to control traffic flow between different segments, ensure high availability, redundancy, and seamless connectivity between on-premises and cloud resources. By leveraging BGP with services like AWS Direct Connect, Transit Gateway Connect, and site-to-site VPN, organizations can enhance performance, security, and overall user experience while gaining greater control over their network architecture.</p><h4>BGP in AWS Direct Connect</h4><p>Direct Connect is a service that allows you to create a private and dedicated network connection between your on-premise network and AWS infrastructure. This set-up ensures security of your data on transit as the connection is encrypted reducing the risk of data breaches and other security threats. While in transit, your network traffic remains on the AWS global network and never touches the public internet, significantly lowering the network latency.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/858/0*fv7HtZNB5uQH2nPq" /><figcaption>[<a href="https://repost.aws/articles/ARIKYhXEYyQQqtO2ulKERrbw/bgp-negotiation-over-aws-site-to-site-vpn-and-direct-connect-troubleshooting-strategies-for-efficient-networking">Source</a>] Direct Connect connection setup between AWS and customer network</figcaption></figure><p>BGP is used in Direct Connect to exchange routing information between your on-premises network and your VPCs in AWS. Essentially, BGP is a protocol that helps different networks share route information with each other.</p><ul><li><strong>Dynamic Routing:</strong> BGP automatically learns and updates routes in real-time. If you add or remove VPCs or change your network setup, BGP detects these changes and updates routes without manual intervention.</li><li><strong>Efficient Traffic Routing:</strong> BGP ensures that your network traffic takes the quickest and most efficient path between your on-premises data center and AWS, reducing transfer times and network delays.</li><li><strong>Redundancy:</strong> BGP can set up multiple paths for your traffic. If one path fails, it automatically switches to a backup path, ensuring high availability and reliability for critical applications.</li><li><strong>Granular Control:</strong> BGP gives you detailed control over how traffic flows. You can set custom rules to decide how traffic is routed based on factors like speed, cost, or specific network paths.</li><li><strong>Authentication:</strong> BGP supports MD5 authentication, which ensures that BGP routers only establish connections with trusted peers. This adds a layer of security by verifying the identity of the devices exchanging route information, protecting your network from unauthorized access.</li><li><strong>Security:</strong> BGP can improve security by identifying and tagging routes using BGP communities. This ensures traffic only travels through authorized routes, keeping your data segregated and safe.</li></ul><h4><strong>BGP in Transit Gateway Connect</strong></h4><p>Transit Gateway connects your VPCs and on-premises networks through a central hub, simplifying your network and eliminating the need for complex peering relationships. It acts as a highly scalable cloud router — each new connection is made only once. It provides you with added benefits such as improved bandwidth and supports dynamic routing with increased route limits, reducing the need to set up multiple IPsec VPNs between Software-Defined Wide Area Network (SD-WAN) appliances and the Transit Gateway.</p><p>Transit Gateway Connect supports BGP to simplify branch connectivity through native integration of network virtual appliances. Any third-party appliances, including SD-WAN appliances that support BGP, work seamlessly with Transit Gateway.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/864/0*33k2DSs3MayZIIxk" /><figcaption>[<a href="https://repost.aws/articles/ARIKYhXEYyQQqtO2ulKERrbw/bgp-negotiation-over-aws-site-to-site-vpn-and-direct-connect-troubleshooting-strategies-for-efficient-networking">Source</a>] Transit Gateway Connect with BGP peering</figcaption></figure><p>Transit Gateway Connect provides a number of advantages, including:</p><ul><li><strong>Simplified Network Setup:</strong> TGW Connect creates a central hub for routing between your on-premises networks and VPCs, making your network design easier to manage. It removes the need for configuring many VPN or VPC peering connections, reducing errors and complexity. BGP dynamically updates and manages routes, ensuring smooth connectivity.</li><li><strong>Scalability:</strong> TGW Connect scales easily to handle a large number of VPCs and on-premises networks, making it ideal for bigger deployments. With BGP, it can adapt to network changes without manual intervention.</li><li><strong>Better Performance:</strong> TGW Connect offers fast, low-latency connections between your VPCs and on-premises systems by leveraging AWS’s global, resilient network infrastructure. BGP helps optimize traffic routing for the best performance using its path selection algorithm.</li><li><strong>Enhanced Security:</strong> With TGW Connect, you get advanced security features like Transit Gateway firewall integration and VPC isolation. This ensures that your network segments are secure, and BGP helps enforce proper routing and traffic flow across trusted paths.</li><li><strong>Cost Savings:</strong> By consolidating many connections into one central transit gateway, TGW Connect reduces the need for expensive networking hardware and lowers data transfer costs. BGP simplifies route management, further cutting down the administrative burden and costs.</li></ul><h4>BGP in AWS Site-to-Site VPN</h4><p>AWS Site-to-Site VPN lets you create secure, private connections between your on-premises network and AWS VPCs over the public internet using IPsec VPN tunnels. BGP is used to exchange routing information between the two networks, allowing you to control traffic by advertising your own or AWS-assigned IP prefixes.</p><p>With BGP, you can manage traffic flow, apply route filtering, and create policies for better control between your on-premises network and AWS. This enables reliable, scalable connectivity for cloud applications and services.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WbGloyjBRkuPTCy6" /><figcaption>[<a href="https://repost.aws/articles/ARIKYhXEYyQQqtO2ulKERrbw/bgp-negotiation-over-aws-site-to-site-vpn-and-direct-connect-troubleshooting-strategies-for-efficient-networking">Source</a>] A site-to-site VPN connection between AWS and customer network</figcaption></figure><h3>Hands-On: Add a BGP peer to an AWS Direct Connect virtual interface</h3><p>Let’s add an IPv4 BGP peering session to a virtual interface using the AWS CLI. The virtual interface can support a single IPv4 session. Since IPv4 operates in a dual stack mode for the virtual interface, multi-protocol BGP won’t be supported. By default, AWS enables MD5, and this option can’t be modified.</p><p><strong>Prerequisites</strong></p><ol><li>AWS account with administrator access.</li><li>Basic AWS CLI knowledge.</li><li>Basic router OS knowledge — JunosOS in this example.</li></ol><h4>Step 1: Create a Direct Connect connection</h4><p>You’ll need to know the location where you’ll establish the Direct Connect connection. To get all the available locations in the region you configured, run this command to save the locations to a file where you can choose location name/code, the bandwidth and a provider, if you need to specify one :</p><pre>aws directconnect describe-locations &gt; DX_locations.txt</pre><p>After selecting a location, you can now create a connection, noting the connectionId:</p><pre>aws directconnect create-connection \<br>--location SNAP \<br>--bandwidth 1Gbps \<br>--connection-name &quot;DemoConnection&quot;</pre><p>Replace the location option with the one you chose, preferably, use the location code, as well as the bandwidth and connection name. Once the connection is created, a JSON-like output will be displayed. You can always get the details of the connection by running this command:</p><pre>aws directconnect describe-connections</pre><p>Once you’ve created the connection, you’ll receive an email from AWS to provide additional information concerning the connection you want to set up (remember Direct connect is a <strong>physical link</strong> between your premise and AWS).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/959/1*8ljUXMlHfjLdi0iZloGFew.png" /><figcaption>Email from AWS after creating a connection</figcaption></figure><h4>Step 2: Create a virtual interface (VIF)</h4><p>The type of virtual interface you create will depend on your requirements. Create a public VIF if you need to connect to public services such as Amazon S3 or Amazon Connect, create a private VIF if you need to access your VPCs and private workloads or create a transit VIF if you want to access one or more Amazon Transit Gateways associated with Direct Connect gateways. In this demo, we’ll create a public VIF, which will require the following:</p><ol><li>Connection ID — this is the Id of the Direct Connect connection you just created. You can get it using the describe-connections command above.</li><li>Customer ASN — this is your network’s BGP ASN. If you don’t have one, AWS assigns a default ASN.</li><li>Amazon Address (Public IPv4 CIDR) — this is the IP address Amazon uses for BGP peering. AWS assigns it automatically when creating the VIF.</li><li>Customer Address (Public IPv4 CIDR) — this is the IP address from your network that you will use for BGP peering.</li><li>Public Prefixes — the public IPv4 prefixes (CIDR blocks) to advertise over the BGP session.</li></ol><p>Run this command to create one:</p><pre>aws directconnect create-public-virtual-interface \<br>  --connection-id &lt;your-dx-connection-id&gt; \<br>  --new-public-virtual-interface \<br>  &#39;{<br>    &quot;virtualInterfaceName&quot;: &quot;MyPublicVIF&quot;,<br>    &quot;vlan&quot;: &lt;your-vlan&gt;,<br>    &quot;asn&quot;: &lt;your-bgp-asn&gt;,<br>    &quot;amazonAddress&quot;: &quot;&lt;amazon-address&gt;&quot;,<br>    &quot;customerAddress&quot;: &quot;&lt;customer-address&gt;&quot;,<br>    &quot;routeFilterPrefixes&quot;: [<br>      {&quot;cidr&quot;: &quot;&lt;public-prefix&gt;&quot;},<br>      {&quot;cidr&quot;: &quot;&lt;public-prefix&gt;&quot;}<br>    ]<br>  }&#39;</pre><blockquote>Ensure amazonAddress and customerAddress are valid public IP addresses. If you want AWS to automatically assign one for you, leave out the option. For the customerAddress, you can use a public IP that you own or get a public IP address block from your ISP.</blockquote><h4>Step 3: Create the BGP peering session</h4><p>To create the peering session, you have to configure BGP both on your on-premise network and on Direct Connect public VIF.</p><p>First, collect the information needed for configuration, which you should have from the public VIF creation process above. The information include:</p><ol><li>Virtual Interface Id — the Id of the public VIF you created. You can retrieve it using this command:</li></ol><pre>aws directconnect describe-virtual-interfaces</pre><p>2. Amazon BGP ASN — provided by AWS, and can be found when you created the VIF.</p><p>3. Your ASN — the ASN your network.</p><p>4. Amazon IP Address — the IP address AWS will use for BGP peering (either automatically assigned by AWS or provided by you).</p><p>5. Your IP Address — the IP address you will use for BGP peering on your side.</p><p>6. BGP Authentication Key (optional) — by default, AWS offers MD5 authentication which if you want to use, you’ll have to set a shared key for both ends of the peering session.</p><p>Then, configure BGP on the AWS side. But, in our case, no additional configuration is needed on AWS directly because we included the BGP settings while creating the public VIF. You can verify the public VIF configuration by running this command and check the details in the bgpPeers section:</p><pre>aws directconnect describe-virtual-interfaces</pre><p>It should look something similar to this:</p><pre>&quot;bgpPeers&quot;: [<br>          {<br>              &quot;bgpStatus&quot;: &quot;down&quot;,<br>              &quot;customerAddress&quot;: &quot;&lt;your-address&gt;&quot;,<br>              &quot;addressFamily&quot;: &quot;ipv4&quot;,<br>              &quot;authKey&quot;: &quot;S0m3@UthKE¥&quot;,<br>              &quot;bgpPeerState&quot;: &quot;available&quot;,<br>              &quot;amazonAddress&quot;: &quot;&lt;amazon-address&gt;&quot;,<br>              &quot;asn&quot;: &lt;asn-configured&gt;<br>          },</pre><p>Lastly, configure BGP on your router. In this demo, we’ll use a Juniper router.</p><pre>set routing-options autonomous-system &lt;Your-ASN&gt;<br>set protocols bgp group AWS neighbor &lt;Amazon-IP&gt; peer-as &lt;AWS-ASN&gt;<br>set protocols bgp group AWS neighbor &lt;Amazon-IP&gt; description AWS Direct Connect<br>set protocols bgp group AWS neighbor &lt;Amazon-IP&gt; authentication-key &lt;BGP-MD5-Key&gt;  # Optional<br>set protocols bgp group AWS neighbor &lt;Amazon-IP&gt; local-address &lt;Your-IP&gt;<br>set protocols bgp group AWS family inet unicast<br>set policy-options policy-statement EXPORT-POLICY term 1 from route-filter &lt;Your-Public-Prefix1&gt;/24 exact<br>set policy-options policy-statement EXPORT-POLICY term 1 then accept<br>set protocols bgp export EXPORT-POLICY</pre><p>Once you’ve configured BGP on your router, it should start the negotiation process with AWS. You can monitor the status of the BGP session using your router’s command for viewing BGP neighbours. Use this command in the Juniper router:</p><pre>show bgp summary</pre><p>You can also verify that your public IP prefixes are being correctly advertised to AWS. You can run this command to confirm that:</p><pre>show route advertising-protocol bgp &lt;Amazon-IP&gt;</pre><h3><strong>Troubleshooting BGP in AWS</strong></h3><p>As in any other configuration, issues can arise due to misconfiguration, connectivity problems, or routing conflicts. Let’s look at some of the BGP-related issues in Direct Connect connections and how to solve them.</p><p><strong>BGP session establishment failure</strong></p><p>Issue: Either a session fails to establish or remains in an idle state.</p><p>Solution:</p><ul><li>Verify the Direct Connect link status is up and there’s connectivity between BGP peer IP addresses.</li><li>Check BGP configuration:</li><li>Ensure correct ASNs are configured.</li><li>Verify peer IPs are correctly configured.</li><li>Confirm MD5 authentication key matches exactly, if you’ve used one.</li><li>Ensure not advertising more than 100 prefixes for private VIFs or 1,000 for public VIFs.</li><li>Check for firewall rules blocking TCP port 179 or ephemeral ports.</li><li>Review BGP logs for errors or warnings</li></ul><p><strong>Routing issues</strong></p><p>Issue: Cannot route traffic over the virtual interface despite established BGP session.</p><p>Solution:</p><ul><li>Ensure advertising routes for on-premises network prefixes over BGP.</li><li>Check VPC security groups and network ACLs allow inbound/outbound traffic.</li><li>Verify VPC route tables have correct prefixes pointing to virtual private gateway.</li><li>Consider enabling route propagation to automatically update routes.</li></ul><p><strong>Excessive route advertisement</strong></p><p>Issue: BGP session goes idle due to too many advertised routes.</p><p>Solution:</p><ul><li>Summarize routes so the number of advertised routes is less than or equal to 100.</li><li>Alternatively, advertise a default route over the BGP session to AWS.</li></ul><p><strong>Layer 2 Connectivity Issues</strong></p><p>Issue: Virtual interface is down despite physical connection being up.</p><p>Solution:</p><ul><li>Verify peer IP address configuration and VLAN tagging.</li><li>Check Address Resolution Protocol(ARP) table entries.</li><li>Ensure intermediate devices have VLAN trunking enabled.</li><li>Clear Address Resolution Protocol cache if needed.</li></ul><h3>Conclusion</h3><p>This is a tip of the iceberg of how powerful the Border Gateway Protocol is. In AWS, it provides the control and flexibility needed to manage complex networks, enabling dynamic routing, high availability, and seamless connectivity between cloud and on-premises resources. Whether you’re traffic engineering, building scalable multi-region architectures, or ensuring network resilience, BGP is an essential tool for any network cloud architect. By mastering BGP, you can create robust, secure, and efficient networks that adapt to your organization’s growing needs.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bbdbd3913eed" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Amazon S3 Multi-Region Access Points for Global Data Resilience]]></title>
            <link>https://medium.com/@r-owino/amazon-s3-multi-region-access-points-for-global-data-resilience-01c159b0ff68?source=rss-89c9d1406517------2</link>
            <guid isPermaLink="false">https://medium.com/p/01c159b0ff68</guid>
            <category><![CDATA[mrap]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[resilience]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[s3]]></category>
            <dc:creator><![CDATA[Remmy]]></dc:creator>
            <pubDate>Thu, 25 Jul 2024 20:33:31 GMT</pubDate>
            <atom:updated>2024-07-25T20:57:50.239Z</atom:updated>
            <content:encoded><![CDATA[<p>Amazon Simple Storage Service(S3) is an object storage service that provides virtually unlimited storage for your file storage needs. S3 comes with storage management features such as S3 replication that let’s you replicate objects to one or more destination buckets in the same or different AWS regions for reduced latency and other use cases.</p><h4>Global Data Resilience</h4><p>Data resilience is the ability of your data systems and infrastructure to maintain integrity, accessibility and functionality across various geographic locations, in the face of disruptions. The disruptions could be anything from cyber threats and attacks, natural disasters, hardware failure to human errors. The main goal of data resilience is to ensure continuous and uninterrupted service to your customers while ensuring their data remains intact, secure and available regardless of the disruptions.</p><p>You can ensure data resilience of your systems and infrastructure by:</p><p>- Keeping multiple copies of your data in different geographic locations in case a storage location is compromised.</p><p>- Regularly taking back ups of your data across multiple regions and having an efficient recovery process in place to restore data quickly after a disruption that accounts for regional and global disruptions.</p><p>- Ensuring your data remains accurate and consistent across all locations, even after recovery from disruptions. Put in place data integrity mechanisms to prevent unauthorised access and modifications or corruption of the data by using techniques such as checksums and distributed databases.</p><p>- Implement data encryption, access controls, firewalls and intrusion detection systems to protect the data from unauthorised access, potential cyber attacks and breaches.</p><p>- Continuously monitor your data systems using monitoring tools such as Grafana and Prometheus that detect and respond to issues in real time before there are any significant disruptions.</p><p>- Use a cloud storage solution with strong data resilience that offer a combination of features to ensure safety, availability and integrity of the data.</p><h4><strong>S3 Multi-Region Access Points (MRAP)</strong></h4><p>Before MRAP, and given your needs to store, replicate and access copies of your S3 data in multiple regions, you had to manually create regionally isolated copies of your data in the regions you needed them to be using S3 Cross-Region Replication. To access the multi-region copies, you had to build a logic in the multi-region applications to route requests to the correct regional copy of your data. This meant that the application had to keep track of which client routes to which region. This complexity was difficult to manage, until MRAP.</p><p>MRAP provides a single global endpoint to access replicated data spanning multiple buckets in multiple regions S3. This allows your multi-region applications to operate across multiple regions without code changes. Development of these multi-region applications is also simplified because MRAP allows you build the applications with a single architecture in a single region then run the application anywhere globally. Additionally, with its built-in network resilience, MRAP improves performance with dynamic routing request over the AWS backbone to the closest-proximity S3 bucket with an active routing status.</p><figure><img alt="How Multi-Region Access Points work" src="https://cdn-images-1.medium.com/max/1024/1*uAyelJiWtz2q_iA3WIqt2g.png" /><figcaption>How Multi-Region Access Points work</figcaption></figure><h4><strong>Hands-On: Create a Multi-Region Access Points</strong></h4><p><strong>Prerequisites</strong></p><p>1. An AWS account with administrative privileges</p><p>2. Basic AWS CLI knowledge</p><p>3. Couple of files for testing MRAP</p><p><strong>Step 1: Create 3 buckets in 3 different regions and enable versioning</strong></p><p><em>Remember that the bucket names need to be globally unique.</em></p><pre>aws s3 mb s3://my-bucket1 --region us-west-2<br>aws s3 mb s3://my-bucket1 --region eu-north-1<br>aws s3 mb s3://my-bucket1 --region ap-southeast-2</pre><p>Then you enable versioning for each bucket. Versioning will allow you set cross-region replication among the buckets.</p><pre>aws s3api put-bucket-versioning \<br> --bucket my-bucket1 \<br> --versioning-configuration \<br> Status=Enabled</pre><p>To confirm that versioning is enabled, run the following command:</p><pre>aws s3api get-bucket-versioning --bucket my-bucket1</pre><p>The output will include the <em>“Status”: “Enabled”</em> field if versioning is enabled, otherwise the status will be <em>“Suspended”</em>.</p><p>Up to here, you should have 3 buckets in 3 different regions. You can confirm this by running this command that lists all your buckets:</p><pre>aws s3api list-buckets --query &quot;Buckets[].Name&quot;</pre><p><strong>Step 2: Enable Cross-Region Replication (CRR)</strong></p><p>Cross-region replication will synchronize data across the geographically separate buckets.</p><p>First, you will create a role and relevant policies attached to it to allow CRR.</p><p>Create 2 files and add the following content to them respectively:</p><blockquote>Note: The files should be in the same location where you installed the AWS CLI, otherwise you will have to explicitly specify the path to the files while running the commands.</blockquote><p><em>trust-policy.json</em> file that defines the trust relationship for the replication role</p><pre>{<br>  &quot;Version&quot;: &quot;2012-10-17&quot;,<br>  &quot;Statement&quot;: [<br>    {<br>      &quot;Effect&quot;: &quot;Allow&quot;,<br>      &quot;Principal&quot;: {<br>        &quot;Service&quot;: &quot;s3.amazonaws.com&quot;<br>      },<br>      &quot;Action&quot;: &quot;sts:AssumeRole&quot;<br>    }<br>  ]<br>}</pre><p><em>permissions-policy.json </em>file<em> </em>that<em> </em>grants the necessary permissions for S3 to replicate objects</p><pre>{<br>  &quot;Version&quot;: &quot;2012-10-17&quot;,<br>  &quot;Statement&quot;: [<br>    {<br>      &quot;Effect&quot;: &quot;Allow&quot;,<br>      &quot;Action&quot;: [<br>        &quot;s3:GetObjectVersionForReplication&quot;,<br>        &quot;s3:GetObjectVersionAcl&quot;,<br>        &quot;s3:GetObjectVersionTagging&quot;<br>      ],<br>      &quot;Resource&quot;: [<br>        &quot;arn:aws:s3:::my-bucket1/*&quot;,<br>        &quot;arn:aws:s3:::my-bucket2/*&quot;,<br>        &quot;arn:aws:s3:::my-bucket3/*&quot;<br>      ]<br>    },<br>    {<br>      &quot;Effect&quot;: &quot;Allow&quot;,<br>      &quot;Action&quot;: [<br>        &quot;s3:ListBucket&quot;,<br>        &quot;s3:GetReplicationConfiguration&quot;<br>      ],<br>      &quot;Resource&quot;: [<br>        &quot;arn:aws:s3:::my-bucket1&quot;,<br>        &quot;arn:aws:s3:::my-bucket2&quot;,<br>        &quot;arn:aws:s3:::my-bucket3&quot;<br>      ]<br>    },<br>    {<br>      &quot;Effect&quot;: &quot;Allow&quot;,<br>      &quot;Action&quot;: [<br>        &quot;s3:ReplicateObject&quot;,<br>        &quot;s3:ReplicateDelete&quot;,<br>        &quot;s3:ReplicateTags&quot;<br>      ],<br>      &quot;Resource&quot;: [<br>        &quot;arn:aws:s3:::my-bucket1/*&quot;,<br>        &quot;arn:aws:s3:::my-bucket2/*&quot;,<br>        &quot;arn:aws:s3:::my-bucket3/*&quot;<br>      ]<br>    }<br>  ]<br>}</pre><p>Now that you have the files ready, run the following commands to create the IAM role, taking note of the ARN generated as you will use it later, and attach the policy to the created role:</p><pre>aws iam create-role --role-name S3ReplicationRole --assume-role-policy-document file://trust-policy.json<br>aws iam put-role-policy --role-name S3ReplicationRole --policy-name S3ReplicationPolicy --policy-document file://permissions-policy.json</pre><p>Next, you will create a<em> replication-config.json</em> file that will set the Replication Rule to your source bucket. Replace the <em>&lt;Role-ARN&gt; </em>with the one you got from creating the role.</p><pre>{<br>  &quot;Role&quot;: &quot;&lt;Role-ARN&gt;&quot;,<br>  &quot;Rules&quot;: [<br>    {<br>      &quot;Status&quot;: &quot;Enabled&quot;,<br>      &quot;Priority&quot;: 1,<br>      &quot;DeleteMarkerReplication&quot;: {&quot;Status&quot;: &quot;Disabled&quot;},<br>      &quot;Filter&quot;: {&quot;Prefix&quot;: &quot;&quot;},<br>      &quot;Destination&quot;: {<br>        &quot;Bucket&quot;: &quot;arn:aws:s3:::my-bucket2&quot;,<br>        &quot;StorageClass&quot;: &quot;STANDARD&quot;<br>      }<br>    },<br>    {<br>      &quot;Status&quot;: &quot;Enabled&quot;,<br>      &quot;Priority&quot;: 2,<br>      &quot;DeleteMarkerReplication&quot;: {&quot;Status&quot;: &quot;Disabled&quot;},<br>      &quot;Filter&quot;: {&quot;Prefix&quot;: &quot;&quot;},<br>      &quot;Destination&quot;: {<br>        &quot;Bucket&quot;: &quot;arn:aws:s3:::my-bucket3&quot;,<br>        &quot;StorageClass&quot;: &quot;STANDARD&quot;<br>      }<br>    }<br>  ]<br>}</pre><p>Run this command to set the rule on your source bucket:</p><pre>aws s3api put-bucket-replication --bucket my-bucket1 --replication-configuration file://replication-config.json</pre><p>To verify that the replication rule has been attached, run the following command:</p><pre>aws s3api get-bucket-replication --bucket my-bucket1</pre><p>This will create a one-way replication between bucket 1 to buckets 2 and 3. To create a two-way replication among all the buckets, create 2 more replication configuration files for buckets 2 and 3 as the source buckets then run the <em>put-bucket-replication</em> command to set the rule on buckets 2 and 3.</p><p><strong>Step 3: Create the Multi-Region Access Points</strong></p><p>To create a multi-region access point, run the following command:</p><pre>aws s3control create-multi-region-access-point \<br>  --account-id &lt;your-account-id&gt; \<br>  --details Name=my-mrap,Regions=[{Bucket=my-bucket1,BucketAccountId=&lt;your-account-id&gt;},{Bucket=my-bucket2,BucketAccountId=&lt;your-account-id&gt;}, {Bucket=my-bucket3, BucketAccountId=&lt;your-account-id&gt;}]</pre><p>The output for this is a <em>RequestTokenARN</em> associated with your request. There is an alias generated, <em>something.mrap</em>, which you can access all the buckets attached to the MRAP instead of having an endpoint for each bucket.</p><p>Once the MRAP is created, you can confirm if the replication is how you need it to be on the console</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gZQI7bJ5h0wx8Z_wHBKosw.png" /><figcaption>Bucket replication overview on the console</figcaption></figure><p><strong>Step 4: Test the Multi-Region Access Point</strong></p><p>Create a 10mb size file with random data in a region where your buckets are not located. I chose us-east-1.</p><blockquote>You will have to change the default location in your <em>~/.aws/</em>config file.</blockquote><p>Run this command to create the file:</p><pre>dd if=/dev/urandom of=test1.file bs=1M count=10</pre><p>After the file is created, copy it to a bucket using this command. Ensure to have a copy your MRAP’s ARN</p><pre>aws s3 cp test1.file s3://&lt;mrap-arn&gt;</pre><p>This will prompt MRAP to redirect it to the closest S3 bucket it serves. In my case, the closest bucket is in us-west-2. It will also replicate the file to the other buckets as well. Run this command to see the file in the buckets:</p><pre>aws s3 ls s3://my-bucket1</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/456/1*RSu75EolY2mPqtmUX_Ceiw.png" /><figcaption>File created and replicated across the buckets</figcaption></figure><p>You can create more test files in different regions and copy them to S3 through the MRAP endpoint to see the consistency and lag of replication.</p><p><strong>Step 5: Clean-up</strong></p><p>MRAP is <strong>not</strong> a free-tier eligible service, so to prevent incurring extra costs, you need to delete it. You have to delete the MRAP endpoint first before emptying and deleting the buckets.</p><p>Delete the MRAP by running the following command:</p><pre>aws s3control delete-multi-region-access-point --account-id &lt;your-account-id&gt; --details Name=my-mrap</pre><p>Empty the buckets by running the following commands:</p><pre>aws s3api delete-object --bucket my-bucket1 --key test1.file<br>aws s3api delete-object --bucket my-bucket2 --key test1.file<br>aws s3api delete-object --bucket my-bucket3 --key test1.file</pre><p>Remove replication from the buckets and disable their versioning.</p><pre># Remove replication from all the buckets<br>aws s3api delete-bucket-replication --bucket my-bucket1<br>aws s3api delete-bucket-replication --bucket my-bucket2<br>aws s3api delete-bucket-replication --bucket my-bucket3<br><br># Disable versioning from each bucket<br>aws s3api put-bucket-versioning  --bucket my-bucket1  --versioning-configuration Status=Suspended<br>aws s3api put-bucket-versioning  --bucket my-bucket2  --versioning-configuration Status=Suspended<br>aws s3api put-bucket-versioning  --bucket my-bucket3  --versioning-configuration Status=Suspended</pre><p>Finally, delete the buckets.</p><blockquote>Even though you’ve removed replication and disabled versioning, there might still be some versioned objects or delete markers present in the bucket that need to be cleared. The easiest solution to delete the buckets is to use Python and boto3</blockquote><pre>#!/usr/bin/env python3<br><br>import boto3<br><br>BUCKET = &#39;bucket-name&#39;<br><br>s3 = boto3.resource(&#39;s3&#39;)<br>bucket = s3.Bucket(BUCKET)<br>bucket.object_versions.delete()<br><br>bucket.delete()<br>print(f&quot;Deleted bucket: {BUCKET}&quot;)</pre><h4><strong>Leverage MRAP for Global Data Resilience</strong></h4><p>We’ve seen how MRAP can greatly simplify your storage and access needs on S3 in a multi-region architecture. This is why you can leverage it for global data resilience of your multi-region applications:</p><ul><li><strong>Dynamic routing for improved performance</strong></li></ul><p>MRAP utilizes AWS Global Accelerator so that instead of sending requests over the congested public internet, the requests are dynamically routed over the AWS network to the closest copy of your data. This dynamic routing can significantly improve your applications’ performance and reliability by avoiding congested network segments on the public internet.</p><ul><li><strong>Active-active configuration for high availability</strong></li></ul><p>S3 requests are automatically routed to buckets in the closest active AWS region through a global S3 endpoint name provided by MRAP to automatically route requests over the high-speed AWS Global Accelerator Network to a bucket with the lowest latency</p><ul><li><strong>Centralised management and control</strong></li></ul><p>MRAP offers centralised controls that let you manage S3 replication rules through Cross-Region Replication (CRR), failover between AWS regions through latency-based policies and network routing. This significantly simplifies management of multi-region S3 deployments so you can focus on application development.</p><ul><li><strong>Failover controls for disaster recovery</strong></li></ul><p>MRAP supports both active-active and active-passive configurations. In active-passive configuration, you can easily shift S3 data request traffic to a passive region in minutes suppose a disruption occurs. This ensures continuity while minimising downtimes.</p><ul><li><strong>Efficient content transfers and dataset replication</strong></li></ul><p>You can efficiently enhance content transfers using MRAP integrated with other AWS services such as CloudFront. This setup uses latency-based routing to ensure fast content delivery to users globally.</p><h4>Final Thoughts</h4><p>By leveraging S3 Multi-Region Access Points, you can achieve enhanced data resilience, improved application performance, and simplified management of global data access and replication. This approach not only mitigates risks associated with data loss but also supports business continuity and operational efficiency in a globally distributed environment.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=01c159b0ff68" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>