DevopsIntermediate

Cloud Security Best Practices: Protecting Your Infrastructure

DeveloperHat Team
9 min read

TL;DR

Learn essential security practices and tools to protect your cloud infrastructure and applications.

Cloud Security Best Practices: Protecting Your Infrastructure

Executive Summary

Cloud security is a shared responsibility: the provider secures the infrastructure, and you secure everything you put in it, starting with identity. This guide covers the controls that prevent the incidents that happen: least-privilege IAM, network segmentation, encryption in transit and at rest, centralised logging, compliance automation, container image hygiene, and security checks embedded in the delivery pipeline. Examples use AWS and Kubernetes because they are the common denominators, but the principles transfer. After reading it, you should be able to audit an estate against a concrete checklist and prioritise fixes by how incidents start: exposed credentials, over-broad permissions, and public data stores.

Why This Matters

Cloud breaches rarely involve exotic exploits. They involve a storage bucket left public, an access key committed to a repository, or an IAM role with administrator rights attached to a compromised workload. The cloud makes these mistakes easy to make at scale: one permissive policy can expose an entire estate, and automation replicates errors as faithfully as good configuration. The controls here are unglamorous and mostly configuration, which is why they work: they remove the common paths.

Core Concepts

Identity and Access Management

Identity is the primary perimeter in the cloud. Grant least privilege: each user, role, and workload gets only the actions it needs, on only the resources it needs, ideally conditioned on source network, tags, or time. This policy allows read and write on one bucket prefix and only from a known network range:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "s3:GetObject",
        "s3:PutObject"
      ],
      "Resource": [
        "arn:aws:s3:::my-bucket/*"
      ],
      "Condition": {
        "IpAddress": {
          "aws:SourceIp": ["192.0.2.0/24"]
        }
      }
    }
  ]
}

Prefer short-lived credentials from roles over long-lived access keys, require MFA for human access, and federate workforce identity rather than maintaining cloud-local users. In Kubernetes, the equivalent discipline is RBAC: namespace-scoped Roles bound to specific subjects, rather than cluster-admin by default:

# Kubernetes RBAC
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  namespace: production
  name: pod-manager
rules:
- apiGroups: [""]
  resources: ["pods"]
  verbs: ["get", "list", "watch", "create", "update", "patch", "delete"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: pod-manager-binding
  namespace: production
subjects:
- kind: User
  name: developer
  apiGroup: rbac.authorization.k8s.io
roleRef:
  kind: Role
  name: pod-manager
  apiGroup: rbac.authorization.k8s.io

Network Segmentation

Design networks so a compromised workload cannot reach everything. Public subnets hold only load balancers and NAT gateways; application and data tiers live in private subnets. Security groups act as per-resource firewalls; network ACLs add a subnet-level layer. Define both as code:

# Terraform VPC configuration
resource "aws_vpc" "main" {
  cidr_block           = "10.0.0.0/16"
  enable_dns_hostnames = true
  enable_dns_support   = true

  tags = {
    Name = "main"
    Environment = "production"
  }
}

resource "aws_subnet" "private" {
  vpc_id            = aws_vpc.main.id
  cidr_block        = "10.0.1.0/24"
  availability_zone = "us-west-2a"

  tags = {
    Name = "Private Subnet"
  }
}

resource "aws_security_group" "web" {
  name        = "web"
  description = "Web Security Group"
  vpc_id      = aws_vpc.main.id

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

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

Treat the wide-open egress in that example as a starting point to tighten: most workloads need a handful of destinations, and unrestricted egress turns a foothold into data exfiltration.

Encryption and TLS

Encrypt data at rest with provider-managed or customer-managed keys (AWS KMS), and understand the difference: customer-managed keys give you rotation control, usage auditing through CloudTrail, and the ability to disable the key, rendering data unreadable. In transit, TLS 1.2 or higher everywhere, including service-to-service traffic inside the network:

# NGINX SSL configuration
server {
    listen 443 ssl http2;
    server_name example.com;

    ssl_certificate /etc/nginx/ssl/fullchain.pem;
    ssl_certificate_key /etc/nginx/ssl/privkey.pem;

    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256;
    ssl_prefer_server_ciphers off;

    ssl_session_timeout 1d;
    ssl_session_cache shared:SSL:50m;
    ssl_session_tickets off;

    # HSTS
    add_header Strict-Transport-Security "max-age=63072000" always;
}

Secrets belong in a dedicated store (Secrets Manager, Key Vault) with rotation, never in environment files, images, or repositories.

Logging, Audit, and Detection

You cannot respond to what you cannot see. Enable cloud audit logging (CloudTrail in AWS) in every account and region, ship logs to a central, access-controlled location, and retain them beyond your incident discovery horizon. In Kubernetes, enable API audit logging with a policy that records metadata broadly and full request detail for sensitive resources such as secrets:

# Kubernetes Audit Policy
apiVersion: audit.k8s.io/v1
kind: Policy
rules:
- level: Metadata
  resources:
  - group: ""
    resources: ["pods"]
- level: RequestResponse
  resources:
  - group: ""
    resources: ["secrets"]

Detection is a pipeline, not a dashboard nobody opens: findings from guardrail services and scanners should route to the queue the team already triages, with severity-based response expectations.

Compliance Automation

Manual audits do not scale; encode the rules and evaluate them continuously. AWS Config rules check resource configuration against policy, for example prohibiting public read on S3 buckets:

{
  "ConfigRule": {
    "ConfigRuleName": "s3-bucket-public-read-prohibited",
    "Description": "Checks that your S3 buckets do not allow public read access",
    "Scope": {
      "ComplianceResourceTypes": [
        "AWS::S3::Bucket"
      ]
    },
    "Source": {
      "Owner": "AWS",
      "SourceIdentifier": "S3_BUCKET_PUBLIC_READ_PROHIBITED"
    }
  }
}

At the organisation level, service control policies set guardrails no account can exceed, and mandatory tagging (owner, environment, cost centre, data classification) makes every resource attributable. For Kubernetes workloads, Pod Security Standards have replaced the old PodSecurityPolicy mechanism; enforce the restricted profile on production namespaces through the built-in admission controls.

Container Security

Containers inherit every mistake in their image. Build from minimal, official base images, run as a non-root user, and drop everything the process does not need:

# Secure Dockerfile
FROM alpine:3.14

# Create non-root user
RUN addgroup -S appgroup && adduser -S appuser -G appgroup

# Set working directory
WORKDIR /app

# Copy application files
COPY --chown=appuser:appgroup . .

# Use non-root user
USER appuser

# Define entrypoint
ENTRYPOINT ["./entrypoint.sh"]

Scan images in the pipeline and block deployment on fixable critical findings:

# Trivy scanner configuration
name: Security Scan

on:
  push:
    branches: [ main ]

jobs:
  scan:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Run Trivy vulnerability scanner
        uses: aquasecurity/trivy-action@master
        with:
          image-ref: 'docker.io/my-organization/my-app:${{ github.sha }}'
          format: 'table'
          exit-code: '1'
          ignore-unfixed: true
          vuln-type: 'os,library'
          severity: 'CRITICAL,HIGH'

Incident Response

Automate the first minutes of response: isolate the resource, preserve evidence, revoke credentials, notify owners. A Lambda function reacting to a security event can quarantine an instance by stripping its security groups while humans assemble:

import boto3
import json

def handle_security_event(event, context):
    """Handle security incidents automatically."""

    # Parse CloudWatch Event
    alert = json.loads(event['Records'][0]['Sns']['Message'])

    # Initialize AWS clients
    ec2 = boto3.client('ec2')
    sns = boto3.client('sns')

    # Take action based on alert type
    if alert['type'] == 'unauthorized_access':
        # Isolate the affected instance
        instance_id = alert['instance_id']
        ec2.modify_instance_attribute(
            InstanceId=instance_id,
            Groups=[]  # Remove all security groups
        )

        # Notify security team
        sns.publish(
            TopicArn='arn:aws:sns:region:account:security-alerts',
            Message=f'Instance {instance_id} isolated due to unauthorized access'
        )

    return {
        'statusCode': 200,
        'body': json.dumps('Security event handled')
    }

The playbook behind the automation matters more than the code: identify, contain, eradicate, recover, and turn the blameless review into tracked fixes.

Decision Framework

SituationRecommendation
Workload needs access to one bucket or queueScoped IAM role with a resource-specific policy, never a managed administrator policy
Human access to productionFederated identity, MFA, short-lived elevation, no standing root use
Data tier reachable from the internetMove it to private subnets behind the application tier; add private endpoints
Compliance must be demonstrated continuouslyConfig rules or equivalent policy-as-code with findings routed to a triage queue
Container image fails scanningFix or replace the base image; time-box exceptions with an owner and an expiry
Secrets found in a repositoryRotate first, then purge; assume the secret is public from the moment it was pushed

Implementation Checklist

  • [ ] MFA enforced for all human access; root account locked down and unused
  • [ ] IAM policies least-privilege and resource-scoped; no long-lived keys for workloads
  • [ ] Data services in private subnets; security group ingress limited to required ports and sources
  • [ ] Encryption at rest enabled everywhere; TLS 1.2+ enforced in transit, HSTS on web properties
  • [ ] Secrets in a managed store with rotation; repositories scanned for committed credentials
  • [ ] Audit logging enabled in all accounts and regions, centralised and retained
  • [ ] Compliance rules evaluated continuously with findings triaged like defects
  • [ ] Images built from minimal bases, run as non-root, scanned in the pipeline with a blocking threshold
  • [ ] Incident response playbook written, with automated containment for common events
  • Trade-offs

    Security controls tax velocity and convenience, and pretending otherwise guarantees workarounds. Least-privilege policies require iteration as applications evolve, and aggressive scanning gates train teams to ignore findings. Centralised logging and compliance tooling cost money roughly proportional to estate size. The correct posture is risk-based: strict controls where data and exposure justify them, lighter ones for internal tooling, and exceptions that are explicit, owned, and expiring.

    When Not to Use

  • A broad managed policy (such as PowerUserAccess) for a production workload: the convenience is never worth the blast radius; scope the policy or split the roles.
  • Perimeter-only thinking: a hardened network around over-privileged identities still fails to the first phished credential; identity controls come first.
  • Blocking pipelines on every scanner finding regardless of severity or reachability: teams will route around the gate; block on fixable criticals and track the rest.
  • Custom-built security tooling where a managed service exists: guardrail, scanning, and secret services are commodities; spend engineering time on your application's own logic.
  • Conclusion

    Cloud security is mostly disciplined configuration: scoped identities, segmented networks, encryption by default, logs you read, and rules evaluated continuously rather than audited annually. None of it is exotic, and all of it compounds; each control removes a class of incident rather than a single instance. Start with identity and exposure, automate the checks into the pipeline, and treat findings as defects with owners.

    References

  • AWS Security Best Practices
  • Kubernetes Security
  • OWASP Cloud Security
  • DevSecOps Guidelines
  • Why This Matters

    Understanding the business and technical context helps you make informed decisions rather than blindly following patterns.

    Trade-offs to Consider

    Every architectural decision involves trade-offs. Consider your specific requirements, team expertise, and scale when evaluating options.

    When NOT to Use This

    Knowing when a solution doesn't apply is as valuable as knowing when it does. Consider alternatives for your specific situation.

    Decision Framework

    Use this framework to evaluate whether this approach is right for your use case based on your specific constraints and requirements.

    Share this articleShare on XShare on LinkedIn

    Keep the decision frameworks coming

    One practical architecture guide a week — patterns, trade-offs, and when not to use them. No spam, unsubscribe anytime.