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

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



تعليقات

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

Uncontrolled form input in React-JS

  Uncontrolled form input in React-JS? If we want to take input from users without any separate event handling then we can uncontrolled the data binding technique. The uncontrolled input is similar to the traditional HTML form inputs. The DOM itself handles the form data. Here, the HTML elements maintain their own state that will be updated when the input value changes. To write an uncontrolled component, you need to use a ref to get form values from the DOM. In other words, there is no need to write an event handler for every state update. You can use a ref to access the input field value of the form from the DOM. Example of Uncontrolled Form Input:- import React from "react" ; export class Info extends React . Component {     constructor ( props )     {         super ( props );         this . fun = this . fun . bind ( this ); //event method binding         this . input = React . createRef ();...

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...

JDBC using JSP and Servlet

JDBC means Java Database Connectivity ,It is intermediates from Application to database. JDBC has different type of divers and provides to communicate from database server. JDBC contain four different type of approach to communicate with Database Type 1:- JDBC-ODBC Driver Type2:- JDBC Vendor specific Type3 :- JDBC Network Specific Type4:- JDBC Client-Server based Driver  or JAVA thin driver:- Mostly we prefer Type 4 type of Driver to communicate with database server. Step for JDBC:- 1  Create Database using MYSQL ,ORACLE ,MS-SQL or any other database 2   Create Table using database server 3   Create Form according to database table 4  Submit Form and get form data into servlet 5  write JDBC Code:-     5.1)   import package    import java.sql.*     5.2)  Add JDBC Driver according to database ide tools     5.3)  call driver in program         ...