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
Sign in to AWS Management Console:
Go to the AWS Management Console and sign in with your credentials.
Navigate to CloudFormation:
In the AWS Management Console, search for "CloudFormation" and select it.
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):
{
"AWSTemplateFormatVersion": "2010-09-09",
"Resources": {
"MyS3Bucket": {
"Type": "AWS::S3::Bucket",
"Properties": {
"BucketName": "my-s3-bucket"
}
}
}
}
3. Deploying the Stack
Upload the Template:
Go to the CloudFormation console and select "Upload a Template file".
Choose the template file you created and upload it.
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
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.
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.
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#):
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
"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'
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
POST Answer of Questions and ASK to Doubt