🔧 DevOps

AWS Cloud Services

Last updated: 2025-09-25 02:29:54

Amazon Web Services (AWS)

AWS is a comprehensive cloud computing platform offering over 200 services.

EC2 (Elastic Compute Cloud)

// AWS SDK for Node.js
const AWS = require('aws-sdk');

// Configure AWS
AWS.config.update({
    region: 'us-east-1',
    accessKeyId: process.env.AWS_ACCESS_KEY_ID,
    secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY
});

const ec2 = new AWS.EC2();

// Launch EC2 instance
async function launchInstance() {
    const params = {
        ImageId: 'ami-0abcdef1234567890', // Amazon Linux 2 AMI
        InstanceType: 't2.micro',
        MinCount: 1,
        MaxCount: 1,
        KeyName: 'my-key-pair',
        SecurityGroupIds: ['sg-12345678'],
        SubnetId: 'subnet-12345678',
        UserData: Buffer.from(`#!/bin/bash
            yum update -y
            yum install -y httpd
            systemctl start httpd
            systemctl enable httpd
            echo "

Hello from AWS EC2

" > /var/www/html/index.html `).toString('base64'), TagSpecifications: [{ ResourceType: 'instance', Tags: [ { Key: 'Name', Value: 'MyWebServer' }, { Key: 'Environment', Value: 'Development' } ] }] }; try { const result = await ec2.runInstances(params).promise(); console.log('Instance launched:', result.Instances[0].InstanceId); return result.Instances[0].InstanceId; } catch (error) { console.error('Error launching instance:', error); } } // List instances async function listInstances() { try { const result = await ec2.describeInstances().promise(); result.Reservations.forEach(reservation => { reservation.Instances.forEach(instance => { console.log(`Instance ID: ${instance.InstanceId}`); console.log(`State: ${instance.State.Name}`); console.log(`Type: ${instance.InstanceType}`); console.log('---'); }); }); } catch (error) { console.error('Error listing instances:', error); } }

S3 (Simple Storage Service)

const s3 = new AWS.S3();

// Upload file to S3
async function uploadFile(bucketName, fileName, fileContent) {
    const params = {
        Bucket: bucketName,
        Key: fileName,
        Body: fileContent,
        ContentType: 'text/plain',
        ServerSideEncryption: 'AES256'
    };
    
    try {
        const result = await s3.upload(params).promise();
        console.log('File uploaded successfully:', result.Location);
        return result.Location;
    } catch (error) {
        console.error('Error uploading file:', error);
    }
}

// Download file from S3
async function downloadFile(bucketName, fileName) {
    const params = {
        Bucket: bucketName,
        Key: fileName
    };
    
    try {
        const result = await s3.getObject(params).promise();
        return result.Body.toString();
    } catch (error) {
        console.error('Error downloading file:', error);
    }
}

// List objects in bucket
async function listObjects(bucketName, prefix = '') {
    const params = {
        Bucket: bucketName,
        Prefix: prefix,
        MaxKeys: 100
    };
    
    try {
        const result = await s3.listObjectsV2(params).promise();
        result.Contents.forEach(object => {
            console.log(`Key: ${object.Key}, Size: ${object.Size}, Modified: ${object.LastModified}`);
        });
        return result.Contents;
    } catch (error) {
        console.error('Error listing objects:', error);
    }
}

// Generate presigned URL
async function generatePresignedUrl(bucketName, fileName, expires = 3600) {
    const params = {
        Bucket: bucketName,
        Key: fileName,
        Expires: expires // URL expires in 1 hour
    };
    
    try {
        const url = await s3.getSignedUrlPromise('getObject', params);
        console.log('Presigned URL:', url);
        return url;
    } catch (error) {
        console.error('Error generating presigned URL:', error);
    }
}

Lambda Functions

// Lambda function example
exports.handler = async (event, context) => {
    console.log('Event:', JSON.stringify(event, null, 2));
    
    try {
        // Process the event
        let response;
        
        if (event.httpMethod) {
            // API Gateway event
            response = await handleApiGatewayEvent(event);
        } else if (event.Records) {
            // S3 or SQS event
            response = await handleRecordsEvent(event);
        } else {
            // Custom event
            response = await handleCustomEvent(event);
        }
        
        return response;
    } catch (error) {
        console.error('Error:', error);
        return {
            statusCode: 500,
            body: JSON.stringify({ error: error.message })
        };
    }
};

async function handleApiGatewayEvent(event) {
    const { httpMethod, path, body } = event;
    
    switch (httpMethod) {
        case 'GET':
            return {
                statusCode: 200,
                headers: {
                    'Content-Type': 'application/json',
                    'Access-Control-Allow-Origin': '*'
                },
                body: JSON.stringify({ message: 'Hello from Lambda!', path })
            };
        
        case 'POST':
            const data = JSON.parse(body);
            // Process POST data
            return {
                statusCode: 201,
                headers: {
                    'Content-Type': 'application/json',
                    'Access-Control-Allow-Origin': '*'
                },
                body: JSON.stringify({ message: 'Data processed', data })
            };
        
        default:
            return {
                statusCode: 405,
                body: JSON.stringify({ error: 'Method not allowed' })
            };
    }
}

async function handleRecordsEvent(event) {
    for (const record of event.Records) {
        if (record.eventSource === 'aws:s3') {
            // Handle S3 event
            const bucketName = record.s3.bucket.name;
            const objectKey = decodeURIComponent(record.s3.object.key.replace(/\+/g, ' '));
            console.log(`Processing S3 object: ${bucketName}/${objectKey}`);
            
            // Process the S3 object
            await processS3Object(bucketName, objectKey);
        } else if (record.eventSource === 'aws:sqs') {
            // Handle SQS message
            const message = JSON.parse(record.body);
            console.log('Processing SQS message:', message);
            
            // Process the message
            await processSqsMessage(message);
        }
    }
    
    return { statusCode: 200, body: 'Records processed successfully' };
}

async function processS3Object(bucketName, objectKey) {
    const s3 = new AWS.S3();
    
    try {
        const object = await s3.getObject({
            Bucket: bucketName,
            Key: objectKey
        }).promise();
        
        const content = object.Body.toString();
        console.log('File content:', content.substring(0, 100));
        
        // Process the content...
    } catch (error) {
        console.error('Error processing S3 object:', error);
    }
}

CloudFormation Templates

# CloudFormation YAML template
AWSTemplateFormatVersion: '2010-09-09'
Description: 'Web application infrastructure'

Parameters:
  EnvironmentName:
    Description: Environment name prefix
    Type: String
    Default: 'dev'
  
  InstanceType:
    Description: EC2 instance type
    Type: String
    Default: 't2.micro'
    AllowedValues: [t2.nano, t2.micro, t2.small, t2.medium]

Resources:
  # VPC
  VPC:
    Type: AWS::EC2::VPC
    Properties:
      CidrBlock: 10.0.0.0/16
      EnableDnsHostnames: true
      EnableDnsSupport: true
      Tags:
        - Key: Name
          Value: !Sub ${EnvironmentName}-VPC
  
  # Internet Gateway
  InternetGateway:
    Type: AWS::EC2::InternetGateway
    Properties:
      Tags:
        - Key: Name
          Value: !Sub ${EnvironmentName}-IGW
  
  InternetGatewayAttachment:
    Type: AWS::EC2::VPCGatewayAttachment
    Properties:
      InternetGatewayId: !Ref InternetGateway
      VpcId: !Ref VPC
  
  # Public Subnet
  PublicSubnet:
    Type: AWS::EC2::Subnet
    Properties:
      VpcId: !Ref VPC
      AvailabilityZone: !Select [0, !GetAZs '']
      CidrBlock: 10.0.1.0/24
      MapPublicIpOnLaunch: true
      Tags:
        - Key: Name
          Value: !Sub ${EnvironmentName}-Public-Subnet
  
  # Route Table
  PublicRouteTable:
    Type: AWS::EC2::RouteTable
    Properties:
      VpcId: !Ref VPC
      Tags:
        - Key: Name
          Value: !Sub ${EnvironmentName}-Public-Routes
  
  DefaultPublicRoute:
    Type: AWS::EC2::Route
    DependsOn: InternetGatewayAttachment
    Properties:
      RouteTableId: !Ref PublicRouteTable
      DestinationCidrBlock: 0.0.0.0/0
      GatewayId: !Ref InternetGateway
  
  PublicSubnetRouteTableAssociation:
    Type: AWS::EC2::SubnetRouteTableAssociation
    Properties:
      RouteTableId: !Ref PublicRouteTable
      SubnetId: !Ref PublicSubnet
  
  # Security Group
  WebServerSecurityGroup:
    Type: AWS::EC2::SecurityGroup
    Properties:
      GroupName: !Sub ${EnvironmentName}-WebServer-SG
      GroupDescription: Security group for web server
      VpcId: !Ref VPC
      SecurityGroupIngress:
        - IpProtocol: tcp
          FromPort: 80
          ToPort: 80
          CidrIp: 0.0.0.0/0
        - IpProtocol: tcp
          FromPort: 443
          ToPort: 443
          CidrIp: 0.0.0.0/0
        - IpProtocol: tcp
          FromPort: 22
          ToPort: 22
          CidrIp: 0.0.0.0/0
      Tags:
        - Key: Name
          Value: !Sub ${EnvironmentName}-WebServer-SG
  
  # EC2 Instance
  WebServerInstance:
    Type: AWS::EC2::Instance
    Properties:
      InstanceType: !Ref InstanceType
      ImageId: ami-0abcdef1234567890
      KeyName: my-key-pair
      SubnetId: !Ref PublicSubnet
      SecurityGroupIds:
        - !Ref WebServerSecurityGroup
      UserData:
        Fn::Base64: !Sub |
          #!/bin/bash
          yum update -y
          yum install -y httpd
          systemctl start httpd
          systemctl enable httpd
          echo "

Hello from ${EnvironmentName}

" > /var/www/html/index.html Tags: - Key: Name Value: !Sub ${EnvironmentName}-WebServer Outputs: VPC: Description: VPC ID Value: !Ref VPC Export: Name: !Sub ${EnvironmentName}-VPC-ID PublicSubnet: Description: Public subnet ID Value: !Ref PublicSubnet Export: Name: !Sub ${EnvironmentName}-Public-Subnet-ID WebServerPublicIP: Description: Web server public IP Value: !GetAtt WebServerInstance.PublicIp Export: Name: !Sub ${EnvironmentName}-WebServer-IP