التخطي إلى المحتوى الرئيسي

Cloud Formation in AWS 2024 | AWS Training in Indore #ShivaConceptSolution

 Create Image Template to create s3 Bucket with Role and AWS Policy

................................................................................................................................


AWS CloudFormation is a service that allows you to model and provision your AWS resources using code. This service helps you manage your infrastructure as code, making it easier to deploy and update resources consistently and efficiently.

1. Getting Started with AWS CloudFormation

  1. Sign in to AWS Management Console:

    • Go to the AWS Management Console and sign in with your credentials.

  2. Navigate to CloudFormation:

    • In the AWS Management Console, search for "CloudFormation" and select it.

  3. Create a Stack:

    • Click on "Create Stack" and provide a name for your stack.

    • Choose a template source (Create Template in JSON or YAML, Upload a Template file, or Use AWS Quick Start templates).

    • Configure the template parameters, if any.

    • Click "Next" and review the template.

    • Click "Create" to create the stack.

2. Writing a CloudFormation Template

A CloudFormation template is a JSON or YAML file that describes the AWS resources you want to create and configure. Here's an example of a simple template that creates an S3 bucket:

Example Template (JSON):

json
{
  "AWSTemplateFormatVersion": "2010-09-09",
  "Resources": {
    "MyS3Bucket": {
      "Type": "AWS::S3::Bucket",
      "Properties": {
        "BucketName": "my-s3-bucket"
      }
    }
  }
}

3. Deploying the Stack

  1. Upload the Template:

    • Go to the CloudFormation console and select "Upload a Template file".

    • Choose the template file you created and upload it.

  2. Create the Stack:

    • Provide a stack name and configure the template parameters, if any.

    • Click "Next" and review the template.

    • Click "Create" to create the stack.

4. Managing the Stack

  1. View Stack Details:

    • Go to the CloudFormation console and select the stack you created.

    • Click on "Stack Details" to view the status and resources of the stack.

  2. Update the Stack:

    • If you need to update the stack, click on "Update Stack".

    • Upload the updated template file and configure the parameters, if any.

    • Click "Next" and review the changes.

    • Click "Update" to apply the changes.

  3. Delete the Stack:

    • If you no longer need the stack, click on "Delete Stack".

    • Confirm the deletion to remove the stack and its resources.

5. Practical Code Example

Here's a practical example of using the AWS SDK for .NET to create a stack using CloudFormation:

Example Code (C#):

csharp
using Amazon.CDK;
using Amazon.CDK.AWS.CloudFormation;

class Program
{
    static void Main(string[] args)
    {
        var app = new App();
        var stack = new Stack(app, "MyCloudFormationStack");

        var bucket = new Bucket(stack, "MyS3Bucket");

        new CfnOutput(stack, "BucketName", new CfnOutputProps
        {
            Value = bucket.BucketName
        });

        app.Synth();
    }


AWS Cloud format to Create S3 Bucket with Role & Policy

AWSTemplateFormatVersion: '2010-09-09'
Description: Create an S3 Bucket and Attach IAM Policy
Resources:
  MyS3Bucket:
    Type: AWS::S3::Bucket
    Properties:
      BucketName: my-kangaroo-bucket-07-03-2024
  MyIAMRole:
    Type: AWS::IAM::Role
    Properties:
      RoleName: MyS3BucketRole
      AssumeRolePolicyDocument:
        Version: "2012-10-17"
        Statement:
          - Effect: Allow
            Principal:
              Service: s3.amazonaws.com
            Action: sts:AssumeRole

  MyIAMPolicy:
    Type: AWS::IAM::Policy
    Properties:
      PolicyName: MyS3BucketPolicy
      PolicyDocument:
        Version: "2012-10-17"
        Statement:
          - Effect: "Allow"
            Action:
              - "s3:CreateBucket"
            Resource: "arn:aws:s3:::*"
      Roles:
        - Ref: MyIAMRole

Create EC2 Instance using Cloud Formation Template:-

"Resources": {
        "EC2IH62B": {
            "Type": "AWS::EC2::Instance",
            "Properties": {
                "AvailabilityZone": "us-east-1a",
                "ImageId": "ami-0f403e3180720dd7e",
                "InstanceType": "t2.micro"
            },
            "Metadata": {
                "AWS::CloudFormation::Designer": {
                    "id": "bb8313f4-0d45-43dc-b4ba-591dff7a9829"
                }
            }
        }
    }

Create DynamoDB database table using cloud formation Template:
 AWSTemplateFormatVersion: '2010-09-09'
Resources:
  MyDynamoDBTable:
    Type: "AWS::DynamoDB::Table"
    Properties:
      TableName: "MyTable"
      AttributeDefinitions:
        -
          AttributeName: "Id"
          AttributeType: "S"
      KeySchema:
        -
          AttributeName: "Id"
          KeyType: "HASH"
      ProvisionedThroughput:
        ReadCapacityUnits: 5
        WriteCapacityUnits: 5

 

Cloud formation to create table and insert record:

AWSTemplateFormatVersion: '2010-09-09'
Resources:
  MyDynamoDBTable:
    Type: 'AWS::DynamoDB::Table'
    Properties:
      BillingMode: PAY_PER_REQUEST
      AttributeDefinitions:
        - AttributeName: pk
          AttributeType: S
        - AttributeName: sk
          AttributeType: S
      KeySchema:
        - AttributeName: pk
          KeyType: HASH
        - AttributeName: sk
          KeyType: RANGE

  MyCustomResourceLambdaFunction:
    Type: 'AWS::Lambda::Function'
    Properties:
      Runtime: nodejs18.x
      Handler: index.handler
      Role: !GetAtt MyLambdaExecutionRole.Arn
      Environment:
        Variables:
          tableName: !Ref MyDynamoDBTable
      Code:
        ZipFile: |
          const AWS = require('aws-sdk');
          const response = require('cfn-response');
          const client = new AWS.DynamoDB();
          const dynamodb = new AWS.DynamoDB.DocumentClient();
     
          exports.handler = async (event, context) => {
            try {
              const tableName = process.env.tableName;
              console.log(tableName);
              var params = {
                TableName: tableName
              };
           
              client.waitFor('tableExists', params, function(err, data) {
                if (err) console.log(err, err.stack); // an error occurred
                else     console.log(data);           // successful response
              });

              const itemsToAdd = [
                { pk: 'item1', sk: 'sortKey1', otherAttribute: 'value1' },
                { pk: 'item2', sk: 'sortKey2', otherAttribute: 'value2' },
                { pk: 'item3', sk: 'sortKey3', otherAttribute: 'value3' },
                { pk: 'item4', sk: 'sortKey4', otherAttribute: 'value4' },
                { pk: 'item5', sk: 'sortKey5', otherAttribute: 'value5' }
              ];
             
              const putItemPromises = itemsToAdd.map((item) => {
                const params = {
                  TableName: tableName,
                  Item: item
                };
                return dynamodb.put(params).promise();
              });
             
              await Promise.all(putItemPromises)
                .then(res => console.log(res))
                .catch(err => console.log(err));
             
              const responseData = { Result: 'Items added successfully' };
              await response.send(event, context, response.SUCCESS, responseData);
            } catch (error) {
              console.log(error);
              const responseData = { Error: 'Something went wrong' };
              await response.send(event, context, response.FAILED, responseData);
            }
          };
      Timeout: 30

  MyLambdaExecutionRole:
    Type: 'AWS::IAM::Role'
    Properties:
      AssumeRolePolicyDocument:
        Version: '2012-10-17'
        Statement:
          - Effect: Allow
            Principal:
              Service: lambda.amazonaws.com
            Action: 'sts:AssumeRole'
      ManagedPolicyArns:
        - 'arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole'
        - 'arn:aws:iam::aws:policy/AmazonDynamoDBFullAccess'

  MyCustomResource:
    Type: 'Custom::MyCustomResource'
    Properties:
      ServiceToken: !GetAtt MyCustomResourceLambdaFunction.Arn



تعليقات

المشاركات الشائعة من هذه المدونة

DSA in C# | Data Structure and Algorithm using C#

  DSA in C# |  Data Structure and Algorithm using C#: Lecture 1: Introduction to Data Structures and Algorithms (1 Hour) 1.1 What are Data Structures? Data Structures are ways to store and organize data so it can be used efficiently. Think of data structures as containers that hold data in a specific format. Types of Data Structures: Primitive Data Structures : These are basic structures built into the language. Example: int , float , char , bool in C#. Example : csharp int age = 25;  // 'age' stores an integer value. bool isStudent = true;  // 'isStudent' stores a boolean value. Non-Primitive Data Structures : These are more complex and are built using primitive types. They are divided into: Linear : Arrays, Lists, Queues, Stacks (data is arranged in a sequence). Non-Linear : Trees, Graphs (data is connected in more complex ways). Example : // Array is a simple linear data structure int[] number...

JSP Page design using Internal CSS

  JSP is used to design the user interface of an application, CSS is used to provide set of properties. Jsp provide proper page template to create user interface of dynamic web application. We can write CSS using three different ways 1)  inline CSS:-   we will write CSS tag under HTML elements <div style="width:200px; height:100px; background-color:green;"></div> 2)  Internal CSS:-  we will write CSS under <style> block. <style type="text/css"> #abc { width:200px;  height:100px;  background-color:green; } </style> <div id="abc"></div> 3) External CSS:-  we will write CSS to create a separate file and link it into HTML Web pages. create a separate file and named it style.css #abc { width:200px;  height:100px;  background-color:green; } go into Jsp page and link style.css <link href="style.css"  type="text/css" rel="stylesheet"   /> <div id="abc"> </div> Exam...

Top 50 Most Asked MERN Stack Interview Questions and Answers for 2025

 Top 50 Most Asked MERN Stack Interview Questions and Answers for 2025 Now a days most of the IT Company asked NODE JS Question mostly in interview. I am creating this article to provide help to all MERN Stack developer , who is in doubt that which type of question can be asked in MERN Stack  then they can learn from this article. I am Shiva Gautam,  I have 15 Years of experience in Multiple IT Technology, I am Founder of Shiva Concept Solution Best Programming Institute with 100% Job placement guarantee. for more information visit  Shiva Concept Solution 1. What is the MERN Stack? Answer : MERN Stack is a full-stack JavaScript framework using MongoDB (database), Express.js (backend framework), React (frontend library), and Node.js (server runtime). It’s popular for building fast, scalable web apps with one language—JavaScript. 2. What is MongoDB, and why use it in MERN? Answer : MongoDB is a NoSQL database that stores data in flexible, JSON-like documents. It...