Monday, January 19, 2026

What Happens When You Run swapoff -a on a Running Server?

 

What Happens When You Run swapoff -a on a Running Server?

✅ 1. All swap pages are moved into RAM

swapoff disables swap.
But before the kernel can turn it off, every page currently in swap must be loaded back into physical RAM.

If enough free RAM is available

→ System continues normally.
→ You’ll probably notice some slowdown as the system swaps pages back into memory.

If RAM is insufficient

→ Linux starts struggling to free enough memory
→ Can trigger the OOM-Killer (Out Of Memory Killer)


❌ 2. OOM-Killer might kill important services

The kernel tries to free memory by killing processes based on OOM score.

This can result in:

  • Database services dying (MySQL, PostgreSQL, Oracle, MongoDB)
  • JVM applications crashing
  • Docker containers terminating
  • SSH sessions closing
  • Even the kernel panicking in rare cases

As a Database Architect, this is high-risk because DB instances usually use large buffers (Oracle SGA, MySQL InnoDB buffer pool).


⚠️ 3. System may freeze or become unresponsive

If memory pressure becomes too high:

  • System may hang
  • Commands stop responding
  • You might lose remote access
  • Only a forced reboot recovers the machine

🧠 4. Why swap was being used matters

If swap is actively used heavily

Turning it off is dangerous because the system needed that memory.

If swap is barely used

Impact is minimal. You can check with:

free -h

or:

swapon --show


🛡️ Best Practices Before Running swapoff

✔️ 1. Check swap usage

If swap is >20–30% used, consider scaling RAM or stopping heavy services first.

✔️ 2. Add temporary RAM using zRAM (safe method)s

systemctl enable --now zramswap.service

✔️ 3. Reduce swap use instead of disabling it

Usually the goal is to stop active swapping, not to disable swap entirely.
Use:

sysctl -w vm.swappiness=10

✔️ 4. Only disable swap during maintenance window

Especially on DB or production servers.


🧩 Summary

SituationWhat happens after swapoff
Enough free RAMSystem works normally, small slowdown.
Moderate swap in useSystem slows, may trigger OOM-Killer.
Heavy swap usage + low RAMHigh chance of service crash or freeze.
DB servers under loadVery high risk of outages.

If you want, I can also help you evaluate your server’s swap usage and memory safety before you disable swap — just share the output of:

free -h
swapon --show
top -o %MEM | head -20

Friday, January 16, 2026

AWS EC2 interview Question and Answers

 

EC2 Instances

What is an EC2 instance?

An EC2 instance is a virtual machine running in the Amazon Elastic Compute Cloud (EC2) environment. It provides scalable compute capacity in the AWS cloud, allowing you to deploy applications without investing in physical hardware. EC2 instances can run various operating systems (Linux, Windows, etc.) and can be resized, stopped, started, or terminated based on needs. They form the core compute layer for applications hosted in AWS.


Explain the difference between an instance and an AMI.

An EC2 instance is an operational virtual server currently running in AWS.
An Amazon Machine Image (AMI) is a template used to create instances.

AMI serves as the blueprint containing:

  • OS
  • Application software
  • Configurations
  • Optional data

You use AMIs to create new instances rapidly and consistently. Instances are the live, running machines created from these AMIs.


How do you launch an EC2 instance?

You can launch an EC2 instance in several ways:

  1. AWS Management Console – The GUI-based approach where you pick an AMI, choose instance type, configure storage, networking, security groups, and launch.
  2. AWS CLI – Using commands like: 
    aws ec2 run-instances --image-id ami-12345 --instance-type t2.micro
  3. AWS SDKs – Using Python, Java, or other languages with programmatic control.

What is the significance of an instance type?

Instance types define the hardware characteristics assigned to an instance, such as:

  • CPU (vCPUs)
  • Memory (RAM)
  • Networking throughput
  • Storage type and capacity

AWS categorizes instance types into:

  • General Purpose
  • Compute Optimized
  • Memory Optimized
  • Storage Optimized
  • Accelerated Computing

Choosing the correct instance type directly affects performance, cost, and application behavior.


What is the purpose of user data in EC2 instances?

User data lets you supply scripts or configuration commands that run automatically when the instance starts for the first time. Typical use cases include:

  • Software installation
  • Bootstrapping applications
  • File downloads
  • System configuration
  • Automated deployments

User data scripts run as root and significantly reduce manual configuration effort.


How can you stop and start an EC2 instance?

You can stop, start, or restart EC2 instances through:

  • AWS Console
  • AWS CLI using commands like:
    aws ec2 stop-instances --instance-id i-1234
    aws ec2 start-instances --instance-id i-1234
  • AWS SDK

Stopping an instance shuts it down but preserves its EBS-backed data.


What is the difference between stopping and terminating an EC2 instance?

  • Stopping an instance:

    • Halts the VM
    • Retains the EBS root volume
    • You can start it again
    • You continue incurring EBS charges
  • Terminating an instance:

    • Permanently deletes the VM
    • Deletes the root volume (unless “Delete on Termination” is disabled)
    • Cannot be restarted

How do you resize an EC2 instance?

To change the instance type:

  1. Stop the instance.
  2. Modify instance type from the console or CLI.
  3. Start the instance again.

Some instance families require the underlying virtualization type to be compatible.


Can you attach an IAM role to an existing EC2 instance?

Yes. You can attach or modify an IAM role for an existing instance by:

  • Stopping the instance (sometimes optional)
  • Editing IAM role settings
  • Restarting the instance

IAM roles eliminate the need to store access keys inside instances.


Explain the concept of an Elastic IP address.

An Elastic IP (EIP) is a static public IPv4 address assigned to your AWS account. You can map it to any instance, ensuring:

  • The public IP remains the same even if the instance stops/starts
  • High availability by remapping it to a standby instance

AWS charges for unused Elastic IPs to encourage efficient usage.


Security Groups

What is a security group in EC2?

A security group acts as a virtual stateful firewall controlling inbound and outbound traffic at the instance level. You define rules based on:

  • Protocol (TCP, UDP, ICMP)
  • Port range
  • Source/destination (IP or security group)

How is a security group different from a NACL?

Security GroupNACL
Instance-levelSubnet-level
StatefulStateless
Automatically allows response trafficRequires explicit inbound & outbound rules
Applied to EC2 instancesApplied to subnets

Can you associate multiple security groups with one EC2 instance?

Yes. An instance can have multiple security groups, and the rules from all associated groups are combined (logical OR).


What are inbound and outbound rules?

  • Inbound rules: Define allowed incoming traffic to the instance.
  • Outbound rules: Define allowed outgoing traffic from the instance.

All unspecified traffic is automatically denied.


How does security group evaluation work?

Security groups allow only the traffic explicitly permitted by rules. Because they are stateful:

  • If inbound traffic is allowed, outbound response is automatically allowed.
  • If outbound traffic is allowed, inbound response is automatically allowed.

Default behavior: deny all unless explicitly allowed.


EBS Volumes

What is an EBS volume?

An EBS volume is durable, block-level storage that persists independently from EC2 instances. It replicates data within an Availability Zone to ensure high availability and can be used as:

  • Root volumes
  • Data volumes
  • Database storage

Difference between EBS-backed and instance-store backed instances.

  • EBS-backed:

    • Root volume stored on EBS
    • Persistent across stop/start
    • Supports snapshots and resizing
  • Instance-store backed:

    • Root volume stored on ephemeral storage on host hardware
    • Data is lost if instance stops or fails
    • Higher performance but non-persistent

How can you increase EBS volume size?

Steps:

  1. Take a snapshot of the existing volume (optional but recommended).
  2. Modify the volume size from console or CLI.
  3. Expand the filesystem inside the OS.

Modern EBS volumes allow online resizing without detaching.


Can you attach multiple EBS volumes to an EC2 instance?

Yes. Instances can have multiple EBS volumes (limited by instance type), each assigned a unique device name like /dev/xvdf.


Difference between gp2 and io1.

  • gp2 (General Purpose SSD):

    • Balanced price/performance
    • Baseline performance with burst capability
  • io1/io2 (Provisioned IOPS SSD):

    • Designed for high I/O workloads like databases
    • You can specify exact IOPS
    • Higher cost and more consistent performance

DLM (Data Lifecycle Manager)

What is AWS Data Lifecycle Manager?

AWS DLM automatically manages EBS snapshot creation, retention, and deletion based on defined policies, reducing manual backup management overhead.


How do you create a lifecycle policy?

You define:

  • Target volumes
  • Snapshot frequency
  • Retention rules
  • Tags

DLM automates snapshot creation and cleanup using the policy.


What is a retention policy?

Retention policies specify:

  • How many snapshots to keep
  • How long snapshots should be retained

Older snapshots are automatically deleted by AWS.


Snapshots

What is an EBS snapshot?

A snapshot is a point‑in‑time backup of an EBS disk stored in Amazon S3 (managed internally). You can restore these snapshots to create new EBS volumes or AMIs.


How do you create a snapshot?

Through:

  • Console
  • CLI: aws ec2 create-snapshot --volume-id vol-1234
  • SDKs

Snapshots are incremental, storing only changed blocks.


Can you snapshot a root volume of a running instance?

Yes, AWS supports snapshots of running volumes. For perfect consistency, especially for databases, stopping the instance or freezing the filesystem is recommended.


Difference between a snapshot and an AMI.

  • Snapshot = Backup of a single EBS volume.
  • AMI = Template to launch instances that includes:
    • OS image
    • Software
    • Configuration
    • One or more snapshots

Load Balancers

What is an Elastic Load Balancer?

An ELB automatically distributes incoming traffic across multiple targets (EC2, containers, IP addresses) and ensures high availability and fault tolerance.


Types of AWS load balancers:

  1. Application Load Balancer (ALB) – Layer 7 (HTTP/HTTPS), intelligent routing, host/path‑based routing.
  2. Network Load Balancer (NLB) – Layer 4 (TCP/UDP), high performance, low latency.
  3. Classic Load Balancer (CLB) – Legacy Layer 4/7 load balancer.

Difference between ALB and NLB.

  • ALB – Works at application layer, supports HTTP routing, WebSockets, microservices
  • NLB – Works at transport layer, supports millions of connections per second, static IPs

What is a Target Group?

Target Groups define where the load balancer forwards traffic. Targets (EC2, IPs, Lambda) are registered and monitored using health checks.


Auto Scaling Group

What is Auto Scaling?

Auto Scaling automatically adjusts EC2 capacity based on demand. It helps maintain performance while minimizing cost.


How do you set up an Auto Scaling Group?

  1. Define a Launch Template or Launch Configuration
  2. Create an Auto Scaling Group specifying:
    • Min/Max/Desired capacity
    • VPC and subnets
    • Load balancer (optional)

Scaling policies define when to add/remove instances.


Significance of Launch Configurations?

A Launch Configuration is a template describing:

  • AMI
  • Instance type
  • Key pair
  • Security groups
  • Storage

It ensures new instances launched by Auto Scaling are identical.


IAM Roles for EC2

What is an IAM role?

An IAM role is an identity in AWS that provides temporary permissions through policies. It is used by AWS services and applications without exposing credentials.


How do you associate an IAM role with EC2?

Either:

  • During instance launch
    OR
  • Modify the IAM role of a running instance via console or CLI

Advantages of IAM roles for EC2?

  • No need to store credentials in code
  • Automatically rotated temporary credentials
  • Centralized access control and least privilege
  • More secure than environment variables or config files

Elastic Beanstalk

What is AWS Elastic Beanstalk?

Elastic Beanstalk is a Platform‑as‑a‑Service (PaaS) that simplifies application deployment. AWS automatically handles:

  • EC2 provisioning
  • Load balancing
  • Auto scaling
  • Monitoring
  • Deployment orchestration

You only upload your code.


How does Elastic Beanstalk differ from EC2?

  • Beanstalk = Fully managed deployment environment
  • EC2 = Requires manual setup and management

With Beanstalk, the infrastructure is abstracted away.


Supported platforms:

Elastic Beanstalk supports:

  • Java, Python, Node.js, Ruby
  • Go, PHP, .NET
  • Docker
  • Nginx/Apache web servers

Placement Groups

What is a placement group?

Placement Groups influence how AWS places your instances to meet performance or high availability requirements.


Types of placement groups:

  1. Cluster – Instances placed close together for high network throughput.
  2. Spread – Instances spread across different hardware to reduce failure risk.
  3. Partition – Instances split into partitions useful for distributed systems like Hadoop.

Cluster vs Spread Placement Group?

  • Cluster – Low latency, high bandwidth, but higher failure risk.
  • Spread – Isolates instances across hardware for better resilience.

Can you move an instance to a placement group?

No. You must:

  • Create an AMI of the instance
  • Launch a new instance inside the placement group

Systems Manager – Run Command

What is AWS Systems Manager Run Command?

A fully managed service that lets you execute commands at scale on EC2 or on-prem servers without SSH/RDP. It centralizes command execution with logging and security controls.


How do you run a command on multiple instances?

Using:

  • SSM console
  • Predefined or custom SSM Document
  • Selecting target instances via tags

Benefits over SSH/RDP:

  • No open inbound ports
  • No need for key pairs
  • Fully auditable
  • Works even without public IPs

What are SSM Documents?

JSON/YAML files that define the actions Run Command or Automation should execute. They contain steps, parameters, and execution logic.


How do you schedule commands?

Using State Manager, which lets you apply:

  • Patches
  • Configuration changes
  • Scripts

on a defined schedule.


Difference between Run Command and Automation:

  • Run Command = Manual execution
  • Automation = Workflow‑based, event-driven execution

Systems Manager – Parameter Store

What is Parameter Store?

A secure hierarchical store for:

  • Secrets
  • Config values
  • Environment variables

Supports versioning and encryption.


Types of parameters:

  • String – Plain text
  • SecureString – Encrypted with KMS

How to retrieve a parameter on EC2?

Using CLI:

aws ssm get-parameter --name MyParam --with-decryption


Benefits over environment variables/config files:

  • Centralized management
  • More secure (KMS encryption)
  • Versioning
  • IAM access control

SecureString vs String:

  • SecureString: KMS-encrypted, used for secrets
  • String: plain text, used for non-sensitive configs

Systems Manager – Session Manager

What is Session Manager?

A secure way to connect to EC2 instances using a browser or CLI without SSH/RDP, even if they have no public IP.


How does it ensure security?

  • IAM‑based access control
  • All actions logged in CloudWatch/CloudTrail
  • No inbound ports required (0 open ports)

Can it connect to on‑prem servers?

Yes, as long as the SSM agent is installed and the server is registered in AWS Systems Manager.


Advantages over SSH/RDP:

  • No key management
  • No open ports
  • Full session logging
  • Fine‑grained IAM control

How do you configure Session Manager?

Ensure:

  1. SSM Agent is installed
  2. Instance has IAM role with SSM permissions
  3. Instance is connected to Systems Manager (via VPC endpoints or internet)

Thursday, January 15, 2026

AWS IAM interview Question and Answers

 

1. What is AWS IAM?

Answer:
AWS Identity and Access Management (IAM) is a core AWS service that enables you to securely manage access to AWS resources. It allows you to create and manage users, groups, and roles, and define policies that control what actions these entities can perform. IAM provides fine-grained access control, ensuring that only authorized identities can access specific AWS services and resources.


2. Explain the purpose of IAM in AWS.

Answer:
The primary purpose of IAM is to provide a centralized and secure access management system for AWS resources. It helps organizations:

  • Implement least privilege access.
  • Assign permissions based on roles and responsibilities.
  • Enforce compliance by auditing and monitoring access.
  • Enable secure integration with external identity providers.
    IAM ensures that access is controlled, monitored, and aligned with organizational security policies.

3. What are IAM users, groups, and roles?

Answer:

  • IAM Users: Individual identities within your AWS account. Each user has unique credentials (password, access keys) and can be assigned permissions via policies.
  • Groups: Collections of IAM users. Permissions applied to a group are inherited by all its members, simplifying management.
  • Roles: Temporary identities with defined permissions that can be assumed by trusted entities (AWS services, users, or external identities). Roles do not have permanent credentials; instead, they provide temporary security tokens.

4. How do you secure your AWS account with IAM?

Answer:
Best practices include:

  • Enable MFA for root and IAM users.
  • Strong password policies and regular rotation.
  • Principle of Least Privilege: Grant only necessary permissions.
  • Avoid long-term access keys: Use roles for temporary access.
  • Enable CloudTrail: Monitor all API activity.
  • Regular audits: Review IAM policies and remove unused accounts.

5. How do you grant permissions to an IAM user?

Answer:
Permissions are granted by attaching IAM policies to users, groups, or roles.

  • Direct attachment: Attach a policy directly to a user.
  • Group-based: Add the user to a group with predefined policies.
    Policies define allowed or denied actions on AWS resources.

6. Explain the concept of IAM policies.

Answer:
IAM policies are JSON documents that define permissions. They specify:

  • Actions: What operations are allowed (e.g., s3:GetObject).
  • Resources: Which resources the actions apply to.
  • Conditions: Optional constraints (e.g., IP address, time).
    Policies can be attached to users, groups, or roles.

7. What are the different types of IAM policies?

Answer:

  • Managed Policies:
    • AWS Managed: Predefined by AWS for common use cases.
    • Customer Managed: Created and managed by you.
  • Inline Policies: Embedded directly into a user, group, or role for specific permissions.

8. What is the principle of least privilege in IAM?

Answer:
Grant only the minimum permissions required for a user or role to perform their tasks. This reduces the risk of accidental or malicious misuse.


9. How do you manage access keys for IAM users?

Answer:
Access keys (Access Key ID and Secret Access Key) allow programmatic access. Best practices:

  • Rotate keys regularly.
  • Delete unused keys.
  • Avoid hardcoding keys in applications; use AWS SDK or Secrets Manager.

10. What is MFA (Multi-Factor Authentication) in IAM?

Answer:
MFA adds an extra layer of security by requiring two forms of authentication:

  • Something you know (password).
  • Something you have (MFA device or app).
    This prevents unauthorized access even if credentials are compromised.

11. Explain IAM roles for EC2 instances.

Answer:
IAM roles allow EC2 instances to access AWS services without storing credentials locally. The instance assumes the role and receives temporary credentials via the Instance Metadata Service.


12. What is IAM federation?

Answer:
IAM federation integrates external identity providers (e.g., Active Directory, SAML, OIDC) with AWS. Users can access AWS resources using existing corporate credentials without creating separate IAM users.


13. What is the IAM policy evaluation logic?

Answer:
IAM follows deny by default. Evaluation steps:

  • If an explicit deny exists → Access denied.
  • If an explicit allow exists → Access granted.
  • If no policy allows the action → Access denied.

14. How do you create a custom IAM policy?

Answer:
Create via AWS Console, CLI, or SDK:

  • Define actions, resources, and conditions in JSON format.
  • Validate using IAM Policy Simulator.
  • Attach to users, groups, or roles.

15. What is IAM condition element in a policy?

Answer:
Conditions restrict when a policy applies. Examples:

  • IP-based: Allow access only from specific IP ranges.
  • Time-based: Allow access during business hours.
  • Tag-based: Allow actions only on resources with specific tags.

16. How do you rotate access keys for an IAM user?

Answer:
Steps:

  1. Create a new access key.
  2. Update applications to use the new key.
  3. Delete the old key.
    This ensures uninterrupted access during rotation.

17. What is IAM policy versioning?

Answer:
AWS maintains multiple versions of a policy. You can roll back to previous versions if needed. Only one version is active at a time.


18. How can you monitor IAM events and activities?

Answer:
Enable AWS CloudTrail to log all IAM API calls. Analyze logs for suspicious activity and integrate with Amazon CloudWatch for alerts.


19. What is AWS Organizations and how does it relate to IAM?

Answer:
AWS Organizations allows centralized management of multiple AWS accounts. It uses Service Control Policies (SCPs) to enforce permissions across accounts. IAM operates at the account level, while Organizations provides governance at the organizational level.


20. How do you troubleshoot IAM permission issues?

Answer:

  • Use IAM Policy Simulator to test permissions.
  • Check attached policies and resource-based policies.
  • Review CloudTrail logs for denied actions.
  • Validate conditions and explicit denies.

AWS Security Interview Question and Answers

 

Securing AWS Account

What are some best practices for securing an AWS account?

  • Enable Multi-Factor Authentication (MFA): Add an extra layer of security for root and IAM users.
  • Use Strong Password Policies: Enforce complexity and rotation for IAM users.
  • Least Privilege Principle: Grant only the permissions required for a task.
  • Regularly Review IAM Policies: Audit permissions and remove unused accounts or keys.
  • Monitor Account Activity: Enable AWS CloudTrail for logging and AWS Config for compliance checks.
  • Enable GuardDuty: For continuous threat detection and anomaly monitoring.
  • Use Organizations and Service Control Policies (SCPs): For centralized account governance.

What is AWS IAM Access Analyzer and how can it help in securing an AWS account?
IAM Access Analyzer helps identify resources (like S3 buckets, IAM roles, KMS keys) that are shared externally. It analyzes resource policies and generates findings so you can:

  • Detect unintended public access.
  • Validate compliance with security standards.
  • Reduce risk of data exposure.

Securing Load Balancers

What are some security considerations for AWS Elastic Load Balancers (ELBs)?

  • Use Security Groups: Restrict inbound traffic to only required ports (e.g., 80/443).
  • Enable SSL/TLS: Encrypt traffic between clients and the load balancer.
  • Access Logs: Enable logging to S3 for auditing and troubleshooting.
  • Protect with WAF: Mitigate common web attacks like SQL injection and XSS.
  • Restrict IP Access: Use NACLs or WAF rules for IP whitelisting/blacklisting.

How can you restrict access to an AWS Application Load Balancer (ALB) based on IP address?

  • Configure Security Groups to allow only specific IP ranges.
  • Use Network ACLs for subnet-level filtering.
  • Apply AWS WAF IP match conditions for granular control.

What is the purpose of SSL termination on a load balancer?
SSL termination offloads the decryption process from backend servers to the load balancer, improving performance and reducing CPU load on application servers.


What are some best practices for securing applications hosted on AWS?

  • Regularly patch OS and application software.
  • Implement AWS WAF for web attack protection.
  • Use Security Groups and NACLs for network isolation.
  • Enable CloudWatch Logs and GuardDuty for monitoring.
  • Encrypt data in transit (TLS) and at rest (KMS).

AWS WAF and Web ACL

What is AWS WAF and how does it help in securing web applications?
AWS WAF is a web application firewall that protects against common exploits like SQL injection and XSS. It allows you to:

  • Filter HTTP/HTTPS traffic.
  • Block malicious requests.
  • Integrate with ALB, API Gateway, and CloudFront.

What is a Web ACL in AWS WAF?
A Web ACL is a collection of rules that define conditions for allowing, blocking, or counting requests. It can include IP match, string match, and managed rule sets.


What is the benefit of using AWS Managed Rules with AWS WAF?
AWS Managed Rules provide pre-built protections against common threats, reducing the need for manual rule creation and ensuring up-to-date security.


AWS Shield

What is AWS Shield and how does it help protect against DDoS attacks?
AWS Shield is a managed DDoS protection service:

  • Shield Standard: Automatic protection against common network and transport layer attacks.
  • Shield Advanced: Enhanced protection with 24/7 DDoS Response Team and cost protection.

How does AWS Shield protect against network and transport layer DDoS attacks?
It uses:

  • Always-on traffic monitoring.
  • Real-time anomaly detection.
  • Automated mitigation techniques.

Difference between Shield Standard and Shield Advanced:

  • Standard: Free, basic protection.
  • Advanced: Paid, includes advanced detection, response team, and SLA guarantees.

Amazon CloudFront

How can you use Amazon CloudFront to enhance security?

  • Distribute content securely via HTTPS.
  • Enable Geo-restriction to block regions.
  • Integrate with AWS WAF for attack mitigation.
  • Use Origin Access Identity (OAI) for private S3 content.

What is Origin Access Identity (OAI)?
A virtual identity that allows CloudFront to access private S3 buckets without exposing them publicly.


How to prevent hotlinking of content?
Configure CloudFront to validate the Referer header and serve content only to approved domains.


Purpose of signed URLs and cookies:
Control access to premium or time-sensitive content by requiring signed requests.


AWS KMS and Data Encryption

What is AWS KMS and its purpose?
AWS Key Management Service (KMS) is a managed service for creating and controlling encryption keys used to protect data across AWS services.


How does AWS KMS secure data at rest in S3 and EBS?
KMS provides encryption keys that services use to encrypt data before storing it, ensuring confidentiality.


What is a Customer Master Key (CMK)?
A logical representation of a master key in KMS used for encryption and decryption operations.


What is envelope encryption and how does AWS KMS use it?
Envelope encryption uses a data key to encrypt data, and then encrypts the data key with a CMK. This improves performance and security.


Difference between AWS managed keys and customer managed keys:

  • AWS Managed Keys: Created and managed by AWS for services.
  • Customer Managed Keys: Created and controlled by you for custom use cases.

How to rotate a CMK?
Enable automatic rotation or manually create a new CMK and update applications to use it.


What are AWS KMS grants?
Grants allow temporary or delegated permissions for other AWS identities or services to use your CMK.


How does AWS KMS integrate with AWS services?
Services like S3, EBS, and RDS call KMS APIs to encrypt/decrypt data using CMKs.


What is AWS CloudHSM?
A hardware security module for secure key storage and cryptographic operations, useful for compliance-heavy workloads.


How to encrypt data in Amazon RDS?
Enable encryption at rest during instance creation or modify an existing instance. RDS uses KMS keys for encryption.


What is AWS SSM Parameter Store?
A secure storage service for configuration data and secrets, supporting encryption via KMS.


How to handle security incidents in AWS?

  • Implement an incident response plan.
  • Use CloudTrail and GuardDuty for detection.
  • Isolate compromised resources and rotate credentials.

How to secure sensitive information like API keys and passwords?
Use AWS Secrets Manager or SSM Parameter Store for secure storage and retrieval.

AWS VPC Interview Questions and Answers

 

VPC Basics

What is a Virtual Private Cloud (VPC) in AWS?
A Virtual Private Cloud (VPC) is a logically isolated section of the AWS cloud that you control. It acts like your own private data center within AWS, where you can define networking components such as IP address ranges, subnets, route tables, and gateways. This isolation ensures that your resources are secure and operate independently from other AWS customers. You can also configure connectivity to on-premises networks using VPN or Direct Connect.

Why would you use a VPC in AWS?
A VPC provides network isolation, security, and flexibility. Key benefits include:

  • Security: Control inbound and outbound traffic using Security Groups and NACLs.
  • Customization: Define IP ranges, create subnets, and configure routing.
  • Hybrid Connectivity: Connect AWS resources to on-premises environments securely.
  • Compliance: Meet regulatory requirements by isolating workloads.
    Example: Hosting a multi-tier application where the web tier is in a public subnet and the database tier is in a private subnet.

Can you have multiple VPCs within a single AWS account?
Yes. AWS allows multiple VPCs per region within a single account. This is useful for:

  • Environment Separation: Development, staging, and production environments.
  • Business Unit Isolation: Different teams or projects can have their own VPCs.
  • Security: Isolate workloads to reduce blast radius in case of a breach.

What is the default VPC?
AWS creates a default VPC in each region for new accounts. It includes:

  • One subnet per Availability Zone.
  • An Internet Gateway attached.
  • Preconfigured route tables and security groups.
    This makes it easy to launch resources without manual setup.

Can you delete the default VPC?
Yes, you can delete it. However, AWS recommends creating custom VPCs for production workloads because they offer better control over IP addressing, subnetting, and security.


CIDR Ranges

What is a CIDR range in the context of VPC?
CIDR (Classless Inter-Domain Routing) notation defines the IP address range for your VPC. For example:

  • 10.0.0.0/16 → 65,536 IP addresses.
  • 192.168.0.0/24 → 256 IP addresses.
    This determines how many IPs you can assign to resources.

How do you select an appropriate CIDR block for a VPC?
Consider:

  • Current Needs: Number of EC2 instances, load balancers, etc.
  • Future Growth: Avoid running out of IPs.
  • Avoid Overlap: Ensure no overlap with on-premises networks or other VPCs for peering or VPN.
    Example: For a large environment, choose /16. For small workloads, /24 may suffice.

What is the smallest and largest VPC CIDR block you can create?

  • Smallest: /28 → 16 IP addresses (11 usable after AWS reserves 5).
  • Largest: /16 → 65,536 IP addresses (65,531 usable).
    AWS reserves 5 IPs per subnet:
  • Network address.
  • VPC router.
  • DNS.
  • Future use.
  • Broadcast address.

Public and Private Subnets

What is the difference between a public subnet and a private subnet in a VPC?

  • Public Subnet: Has a route to the Internet Gateway. Instances can have public IPs and be accessed from the internet.
  • Private Subnet: No direct route to the internet. Instances rely on NAT Gateway or NAT Instance for outbound traffic.

How are internet-facing resources placed in a VPC?
Internet-facing resources (e.g., web servers) are placed in public subnets with public IPs. Alternatively, they can be in private subnets and access the internet through a NAT Gateway for outbound traffic only.

How do private subnets communicate with the internet?
Through a NAT Gateway or NAT Instance, which allows outbound traffic while blocking inbound traffic from the internet.


Network ACLs

What is a Network Access Control List (NACL) in a VPC?
A NACL is a stateless firewall at the subnet level that controls inbound and outbound traffic using numbered rules (allow/deny). Each rule specifies protocol, port range, and source/destination IP.

How does a NACL differ from a security group?

  • NACL: Stateless, subnet-level, explicit allow/deny rules.
  • Security Group: Stateful, instance-level, only allow rules.
    Example: NACL can block traffic from a specific IP range, while Security Groups cannot deny traffic explicitly.

Can a NACL block traffic based on protocol and port number?
Yes. NACL rules can filter traffic by protocol (TCP, UDP, ICMP) and port numbers.


VPC Peering

What is VPC peering and when would you use it?
VPC peering connects two VPCs so resources can communicate privately as if on the same network. Use cases:

  • Sharing resources between environments.
  • Multi-tier applications across VPCs.

Can you peer VPCs in different AWS accounts?
Yes, cross-account peering is supported with mutual acceptance of the peering request.

What are the limitations of VPC peering?

  • Peering is not transitive (A-B-C cannot communicate through B).
  • Limited to the same region unless using inter-region peering.

Transit Gateway Basics

What is an AWS Transit Gateway?
A Transit Gateway acts as a central hub to connect multiple VPCs, VPNs, and Direct Connect links, simplifying network architecture.

How does a Transit Gateway simplify connectivity?
It eliminates complex peering meshes by providing a single point for routing traffic between networks.

Can a Transit Gateway span multiple AWS regions?
Yes, Transit Gateway supports inter-region peering.


Site-to-Site VPN Connection

What is a Site-to-Site VPN connection in AWS?
It securely connects your on-premises network to your AWS VPC over an encrypted tunnel using a Virtual Private Gateway.

When would you use a Site-to-Site VPN connection?
When you need secure connectivity without exposing resources to the public internet.

What information is needed to establish a Site-to-Site VPN connection?

  • Customer Gateway public IP
  • Pre-shared key
  • BGP ASN (if using dynamic routing)

VPC Endpoints

What is a VPC endpoint?
A VPC endpoint enables private connectivity between your VPC and AWS services without traversing the public internet.

How does a VPC endpoint enhance security?
Traffic stays within the AWS network, reducing exposure to external threats.

Types of VPC endpoints:

  • Interface Endpoint: For most AWS services (powered by PrivateLink).
  • Gateway Endpoint: For S3 and DynamoDB.

Routing in a VPC

How does routing work within a VPC?
Each subnet uses a route table to determine traffic flow. Routes can point to Internet Gateway, NAT Gateway, VPN, or VPC peering.

What is the purpose of a route table?
It defines the next hop for traffic based on destination IP.

Can you associate multiple route tables with a subnet?
No, only one route table per subnet, but you can create multiple route tables for different subnets.


Elastic IP Addresses

What is an Elastic IP (EIP)?
A static public IPv4 address that remains associated with your account, even if the instance stops or terminates.

How do you associate an Elastic IP with an EC2 instance?
Via AWS Console, CLI, or SDK. Once associated, it becomes the instance’s public IP.


Direct Connect

What is AWS Direct Connect?
A dedicated network link between your on-premises data center and AWS for private, high-bandwidth, low-latency connectivity.

When use Direct Connect instead of VPN?
For higher performance, reliability, and when transferring large volumes of data.


Flow Logs

What are VPC Flow Logs?
Logs capturing IP traffic details for network interfaces in your VPC, useful for monitoring and troubleshooting.

How are Flow Logs useful?
They help analyze traffic patterns, detect anomalies, and troubleshoot connectivity issues.


NAT Gateways vs NAT Instances

Purpose of NAT Gateway:
Allows private subnet resources to access the internet without exposing them to inbound traffic.

Difference from NAT Instance:
NAT Gateway is managed, scalable, and highly available. NAT Instance requires manual setup and maintenance.


VPC Endpoints for S3 & DynamoDB

What is a VPC endpoint for S3/DynamoDB?
Provides private connectivity to S3/DynamoDB without using the public internet, improving security and performance.


VPC Security Best Practices

  • Use Security Groups and NACLs effectively.
  • Minimize public exposure by using private subnets.
  • Enable Flow Logs for monitoring.
  • Encrypt data in transit and at rest.

VPC Limits

AWS imposes quotas on VPC resources (e.g., number of VPCs per region, subnets per VPC, Elastic IPs per account). These limits are documented in AWS service quotas.

AWS S3 Interview Questions and Answers

 

1. What is AWS S3?

Amazon Simple Storage Service (S3) is a highly scalable, durable, and secure object storage service provided by AWS. It is designed to store and retrieve any amount of data from anywhere on the web. S3 is commonly used for hosting static websites, storing backups, archiving data, and serving as a data lake for analytics. It offers 11 nines (99.999999999%) durability, making it extremely reliable for long-term storage.


2. Explain the S3 storage classes.

AWS S3 offers multiple storage classes optimized for different use cases:

  • Standard: High durability and availability for frequently accessed data.
  • Intelligent-Tiering: Automatically moves objects between frequent and infrequent tiers based on access patterns.
  • Standard-IA (Infrequent Access): Lower cost for data accessed less often but still requires rapid retrieval.
  • One Zone-IA: Similar to Standard-IA but stored in a single Availability Zone (lower cost, less redundancy).
  • Glacier: Low-cost archival storage with retrieval times ranging from minutes to hours.
  • Glacier Deep Archive: Cheapest option for long-term archival with retrieval times up to 12 hours.

3. How is data organized in S3?

Data in S3 is stored in buckets, which act like top-level containers. Each bucket contains objects, which are the actual files or data. Objects consist of:

  • Key (unique identifier within the bucket)
  • Value (the data)
  • Metadata (information about the object)

4. What is a bucket policy?

A bucket policy is a JSON-based access control document attached to an S3 bucket. It defines permissions for users, roles, or services, specifying which actions (e.g., GetObject, PutObject) are allowed or denied. Bucket policies are essential for implementing fine-grained access control.


5. Explain CORS in S3.

Cross-Origin Resource Sharing (CORS) allows web applications hosted on one domain to access resources from another domain. In S3, CORS is configured at the bucket level to enable browsers to make cross-origin requests to S3 objects, which is critical for web apps using S3-hosted assets.


6. How can you secure data in S3?

Security in S3 involves multiple layers:

  • Access Control: Use IAM policies, bucket policies, and ACLs.
  • Encryption:
    • In-transit: Use SSL/TLS (HTTPS).
    • At-rest: Use Server-Side Encryption (SSE-S3, SSE-KMS, SSE-C) or Client-Side Encryption.
  • Block Public Access: Enable S3’s block public access settings.
  • Monitoring: Use AWS CloudTrail and S3 Access Logs for auditing.

7. What is versioning in S3?

Versioning allows you to keep multiple versions of an object in a bucket. It helps protect against accidental deletions or overwrites. When enabled, every update creates a new version, and previous versions can be restored.


8. Explain the difference between S3 and EBS.

  • S3: Object storage, ideal for static files, backups, and large-scale data storage.
  • EBS (Elastic Block Store): Block storage for EC2 instances, suitable for databases and applications requiring low-latency disk access.

9. How do you enable versioning for an S3 bucket?

Enable versioning via:

  • AWS Console: Navigate to bucket → Properties → Enable Versioning.
  • AWS CLI: aws s3api put-bucket-versioning --bucket <bucket-name> --versioning-configuration Status=Enabled.

10. What is the significance of S3 Object URL?

Each object in S3 has a unique URL (HTTP/HTTPS) that allows direct access. Example:
https://bucket-name.s3.amazonaws.com/object-key.
Access depends on permissions and whether the object is public or private.


11. Explain S3 Object Lifecycle Policies.

Lifecycle policies automate object management by transitioning objects to cheaper storage classes or deleting them after a certain period. Example: Move objects to Glacier after 90 days.


12. What is S3 Transfer Acceleration?

It speeds up uploads/downloads by routing traffic through Amazon CloudFront edge locations, reducing latency for global users.


13. What is Multipart Upload in S3?

Multipart Upload splits large files into smaller parts and uploads them in parallel, improving speed and reliability. Recommended for files >100 MB.


14. How do you secure data in transit to S3?

Use HTTPS (SSL/TLS) for all communications with S3 to encrypt data in transit.


15. What is the maximum size for an S3 object?

5 TB per object. For uploads >100 MB, use Multipart Upload.


16. Explain Cross-Region Replication in S3.

CRR automatically replicates objects from one bucket to another in a different AWS region for disaster recovery and compliance.


17. Difference between S3 and EFS?

  • S3: Object storage for static data.
  • EFS (Elastic File System): Shared file storage for EC2, supports NFS protocol.

18. Use case for S3 Select?

Retrieve only required data from large objects (CSV, JSON, Parquet) using SQL-like queries, reducing transfer costs and improving performance.


19. Concept of S3 Access Points?

Access Points provide unique hostnames with custom permissions for different applications accessing the same bucket.


20. S3 event notification feature?

Triggers notifications (SNS, SQS, Lambda) for events like object creation, deletion, or restore.


21. Monitor S3 bucket metrics?

Use Amazon CloudWatch for metrics like request count, storage size, and replication status.


22. Difference between S3 and Glacier?

S3 = immediate access; Glacier = archival storage with retrieval times from minutes to hours.


23. Optimize costs in S3?

Use Intelligent-Tiering, Lifecycle Policies, and delete unused objects. Analyze access patterns with Storage Class Analysis.


24. How S3 works with CloudFront?

S3 acts as an origin for CloudFront, enabling global content delivery with caching and low latency.


25. S3 Storage Class Analysis feature?

Analyzes access patterns to recommend transitions to cost-effective storage classes.


26. Enable logging for an S3 bucket?

Specify a target bucket for logs in bucket properties. Logs include request details for auditing.


27. What is S3 Select + Glacier?

Allows querying data stored in Glacier without full retrieval, saving time and cost.


28. Set up CORS in S3?

Add CORS configuration in bucket properties with allowed origins, headers, and methods.


29. Use of S3 Batch Operations?

Perform bulk actions (copy, tag, delete) on millions of objects using a manifest file.


30. Enable server access logging for an S3 bucket?

Specify target bucket and prefix in bucket properties to store access logs.


Scenario-Based Detailed Answers

  • Optimizing performance: Used Transfer Acceleration, multi-part uploads, and parallel threads.
  • Securing sensitive data: SSL/TLS for transit; SSE-KMS for at-rest; strict IAM policies.
  • Cost optimization: Intelligent-Tiering + Lifecycle Policies for infrequent data.
  • Multi-region architecture: CRR with versioning and Transfer Acceleration.
  • Large dataset migration: AWS Snowball/DataSync, multi-part uploads, integrity checks.
  • Handling cost spikes: CloudWatch alerts, Intelligent-Tiering, Lifecycle Policies.
  • Improving query performance: S3 Select for partial data retrieval.
  • Troubleshooting permissions: Checked bucket policy, ACLs, IAM roles for conflicts.
  • Cross-account access: Bucket policy with external account ARN and allowed actions.

What Happens When You Run swapoff -a on a Running Server?

  What Happens When You Run swapoff -a on a Running Server? ✅ 1. All swap pages are moved into RAM swapoff disables swap. But before the k...