Professional Documents
Culture Documents
#amazon-
web-
services
Table of Contents
About 1
Remarks 2
Versions 2
Examples 2
Examples 4
Examples 7
Examples 8
CloudFormation sample script to create an EC2 instance along with a Security Group to asso 8
Introduction 19
Remarks 19
Examples 19
Remarks 22
Examples 22
example-task.json 22
Deploy a sample application on AWS ECS service as a proof of concept 23
Follow following steps to try out a sample application on AWS ECS service as a proof of co 23
Remarks 28
Examples 28
Examples 31
Business class 36
Credits 39
About
You can share this PDF with anyone you feel could benefit from it, downloaded the latest version
from: amazon-web-services
It is an unofficial and free amazon-web-services ebook created for educational purposes. All the
content is extracted from Stack Overflow Documentation, which is written by many hardworking
individuals at Stack Overflow. It is neither affiliated with Stack Overflow nor official amazon-web-
services.
The content is released under Creative Commons BY-SA, and the list of contributors to each
chapter are provided in the credits section at the end of this book. Images may be copyright of
their respective owners unless otherwise specified. All trademarks and registered trademarks are
the property of their respective company owners.
Use the content presented in this book at your own risk; it is not guaranteed to be correct nor
accurate, please send your feedback and corrections to info@zzzprojects.com
https://riptutorial.com/ 1
Chapter 1: Getting started with amazon-web-
services
Remarks
This section provides an overview of what amazon-web-services is, and why a developer might
want to use it.
It should also mention any large subjects within amazon-web-services, and link out to the related
topics. Since the Documentation for amazon-web-services is new, you may need to create initial
versions of those related topics.
Versions
1.0.0 2017-01-10
Examples
Before it is too late
Unlike tags, the IAM Role is set once and for all on EC2 instanciation (even after 4 years) ! Try
to identify and categorize beforehand your instances so you can give an them appropriate IAM
roles. IAM Roles are a nice way to identify your machines, it will let amazon automatically store
Instance Profile credentials safely in your machines, and you will be easily able to give extra
privileges.
Consider the following situation where you have Database servers, and you realize you want to
monitor memory/disk usage. Amazon CloudWatch does not provide this metric out-of-the-box, and
You'll need to set up extra privileges to send custom data to CloudWatch. If you have an IAM
"Database" Role, you can easily attach new policies to your existing Database instances to let
them send Memory reports to CloudWatch. No IAM Roles ? You have to recreate your Database
instances, or give them permission individually.
Amazon lets you snapshot EBS volumes, however in case you use several volumes on the same
https://riptutorial.com/ 2
machine (in RAID configuration, multiple EBS volumes for your database), it is impossible to
guarantee the integrity of those snapshots, which may happen at different times on the different
EBS volumes.
Always ensure no data is written (stop the VM, or use application specific code (eg db.fsyncLock())
to ensure no data is written during the snapshot.
CloudWatch
• Use Amazon Cloudwatch + SNS alerts on top of your application error notifiers
Create alerts for anormal behavior of your machines, and configure to send notifications via
Amazon SNS (eg email addresses) in case of problems. Having exception notifiers on your
application won't help if your server cannot even be pinged. On the other hand, apart from 500
error codes Amazon has little information on your application and how it is supposed to work, you
should consider adding application-specific health monitoring.
https://riptutorial.com/ 3
Chapter 2: Amazon Cognito
Examples
User Identity management using Amazon Cognito
app.signUp = function(){
app.userName = $('#userName').val();
app.password = $('#password').val();
app.email = $('#form-email').val();
app.phoneNumber = $('#form-phone').val();
app.emailRegex =
/^(([^<>()\[\]\.,;:\s@\"]+(\.[^<>()\[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.
/*
Put the User input validation logic here.
*/
if (!app.userName) {
alert("Please provide a user name");
return;
}
if (!app.password) {
alert("Please provide a password");
return;
}
if (!app.email) {
alert("Please provide an Email address");
return;
}
if(!app.emailRegex.test(app.email)){
alert("Please provide a valid Email address");
return;
}
if (!app.phoneNumber) {
alert("Please provide a Phone Number");
return;
}
AWSCognito.config.region = 'us-east-1';
AWSCognito.config.credentials = new AWS.CognitoIdentityCredentials({
IdentityPoolId: '...' // your identity pool id here
});
// Need to provide placeholder keys unless unauthorised user access is enabled for user pool
https://riptutorial.com/ 4
AWSCognito.config.update({accessKeyId: 'anything', secretAccessKey: 'anything'})
var poolData = {
UserPoolId : APP_CONSTANT.USER_POOL_ID,
ClientId : APP_CONSTANT.CLIENT_ID
};
userPool = new AWSCognito.CognitoIdentityServiceProvider.CognitoUserPool(poolData);
var dataEmail = {
Name : 'email',
Value : app.email //Email Id where the confirmation code would be sent.
};
var dataPhoneNumber = {
Name : 'phone_number',
Value : app.phoneNumber
};
var attributeEmail = new
AWSCognito.CognitoIdentityServiceProvider.CognitoUserAttribute(dataEmail);
//Uncomment below once the phone number format is confirmed
/*var attributePhoneNumber = new
AWSCognito.CognitoIdentityServiceProvider.CognitoUserAttribute(dataPhoneNumber);*/
attributeList.push(attributeEmail);
/* attributeList.push(attributePhoneNumber);*/
// Put the user id and password collected from user below for signup
userPool.signUp(app.userName, app.password, attributeList, null, function(err, result){
if (err) {
alert(err);
return;
}
cognitoUser = result.user;
// Return the user name once the user signed up, still need to confirm with confirmation code
send to mail.
$("#form-confirmCode").css("display", "block");
alert('user name is ' + cognitoUser.getUsername());
// Now since the user is signed up and pending for confirmaion, disable all the pervious input
but confirmation code.
$("#userName").prop("readonly", true);
$("#password").prop("readonly", true);
$("#form-email").prop("readonly", true);
$("#form-phone").prop("readonly", true);
$("#signUpBtn").hide();
$("#confirm-block").show();
});
};
https://riptutorial.com/ 5
cognito
https://riptutorial.com/ 6
Chapter 3: Amazon DynamoDB
Examples
DynamoDB basic Crud Operation using NodeJS
function readOperation(cnxt) {
var params = {
TableName: tblName,
Key: {
"id": "2013",
"topic": "Turn It Down, Or Else!"
},
AttributesToGet: [
"id", "client_name", "info"
],
ConsistentRead: false
};
dynamo.getItem(params, function(err, data) {
if (err) console.log("Error: "+err); // an error occurred
else {
var jsonDoc = JSON.parse(data.Item.info); // successful response
cnxt.succeed(jsonDoc);
}
});
}
https://riptutorial.com/ 7
Chapter 4: AWS CloudFormation
Examples
CloudFormation sample script to create an EC2 instance along with a Security
Group to associate with.
This example will create an EC2 instance of t2.micro type in N.Virginia region running Amazon
Linux. During the execution, it will ask to select the KeyPair to use and an I.P. CIDR from where
you can SSH to the instance, use default to make SSH open to the internet
{
"AWSTemplateFormatVersion" : "2010-09-09",
"Parameters" : {
"KeyName": {
"Description" : "Name of an existing EC2 KeyPair to enable SSH access to the instance",
"Type": "AWS::EC2::KeyPair::KeyName",
"ConstraintDescription" : "must be the name of an existing EC2 KeyPair."
},
"SSHLocation" : {
"Description" : "The IP address range that can be used to SSH to the EC2 instances",
"Type": "String",
"MinLength": "9",
"MaxLength": "18",
"Default": "0.0.0.0/0",
"AllowedPattern": "(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})/(\\d{1,2})",
"ConstraintDescription": "must be a valid IP CIDR range of the form x.x.x.x/x."
}
},
"Resources" : {
"EC2Instance" : {
"Type" : "AWS::EC2::Instance",
"Properties" : {
"InstanceType" : “t2.micro”,
"SecurityGroups" : [ { "Ref" : "InstanceSecurityGroup" } ],
"KeyName" : { "Ref" : "KeyName" },
"ImageId" : “ami-6869aa05”
}
},
"InstanceSecurityGroup" : {
"Type" : "AWS::EC2::SecurityGroup",
"Properties" : {
"GroupDescription" : "Enable SSH access via port 22",
"SecurityGroupIngress" : [ {
"IpProtocol" : "tcp",
"FromPort" : "22",
"ToPort" : "22",
https://riptutorial.com/ 8
"CidrIp" : { "Ref" : "SSHLocation"}
} ]
}
}
},
"Outputs" : {
"InstanceId" : {
"Description" : "InstanceId of the newly created EC2 instance",
"Value" : { "Ref" : "EC2Instance" }
},
"AZ" : {
"Description" : "Availability Zone of the newly created EC2 instance",
"Value" : { "Fn::GetAtt" : [ "EC2Instance", "AvailabilityZone" ] }
},
"PublicDNS" : {
"Description" : "Public DNSName of the newly created EC2 instance",
"Value" : { "Fn::GetAtt" : [ "EC2Instance", "PublicDnsName" ] }
},
"PublicIP" : {
"Description" : "Public IP address of the newly created EC2 instance",
"Value" : { "Fn::GetAtt" : [ "EC2Instance", "PublicIp" ] }
}
}
}
CloudFormer template translates the existing AWS entities to a generate new CloudFormation
template to accelerate the time to recreate the environment. The CloudFormer launches in a
default VPC which might not be suitable in the cases where the default VPC is deleted. This code
base is fork from the original CloudFormer which would be launched inside a new VPC.
{
"AWSTemplateFormatVersion" : "2010-09-09",
"Description" : "A custom CloudFormer template forked from AWS provided to extend the
capability to provide the ability to specify the VPC. Creates a Separate Stand-Alone VPC,
Subnet - 10.0.0.0/16 to launch the CloudFormer Instance. AWS CloudFormer Beta - template
creation prototype application. This tool allows you to create an AWS CloudFormation template
from the AWS resources in your AWS account. **Warning** This template creates a single EC2
instance in your account to run the application - you will be billed for the instance at
normal AWS EC2 rates.",
"Parameters" : {
"Username" : {
"Description" : "Username to log in to CloudFormer",
"Type" : "String"
},
"Password" : {
"Description" : "Password to log in to CloudFormer",
"Type" : "String",
"NoEcho" : "true"
},
"CommonNameTag" : {
"Description" : "Common Identifier / Friendly Name for the Stack",
"Type" : "String",
https://riptutorial.com/ 9
"Default" : "CloudFormer - Non Default VPC"
}
},
"Mappings" : {
"NetworkValues" : {
"VPC" : {"CIDR" : "10.0.0.0/16"},
"Subnet" : {"CIDR" : "10.0.10.0/16"}
},
"Region2Examples" : {
"us-east-1" : { "Examples" : "https://s3.amazonaws.com/cloudformation-examples-us-
east-1" },
"us-west-2" : { "Examples" : "https://s3-us-west-2.amazonaws.com/cloudformation-
examples-us-west-2" },
"us-west-1" : { "Examples" : "https://s3-us-west-1.amazonaws.com/cloudformation-
examples-us-west-1" },
"eu-west-1" : { "Examples" : "https://s3-eu-west-1.amazonaws.com/cloudformation-
examples-eu-west-1" },
"eu-central-1" : { "Examples" : "https://s3-eu-central-1.amazonaws.com/cloudformation-
examples-eu-central-1" },
"ap-southeast-1" : { "Examples" : "https://s3-ap-southeast-
1.amazonaws.com/cloudformation-examples-ap-southeast-1" },
"ap-northeast-1" : { "Examples" : "https://s3-ap-northeast-
1.amazonaws.com/cloudformation-examples-ap-northeast-1" },
"ap-southeast-2" : { "Examples" : "https://s3-ap-southeast-
2.amazonaws.com/cloudformation-examples-ap-southeast-2" },
"ap-northeast-2" : { "Examples" : "https://s3-ap-northeast-
2.amazonaws.com/cloudformation-examples-ap-northeast-2" },
"sa-east-1" : { "Examples" : "https://s3-sa-east-1.amazonaws.com/cloudformation-
examples-sa-east-1" },
"cn-north-1" : { "Examples" : "https://s3.cn-north-
1.amazonaws.com.cn/cloudformation-examples-cn-north-1" }
},
"Region2Principal" : {
"us-east-1" : { "EC2Principal" : "ec2.amazonaws.com", "OpsWorksPrincipal" :
"opsworks.amazonaws.com" },
"us-west-2" : { "EC2Principal" : "ec2.amazonaws.com", "OpsWorksPrincipal" :
"opsworks.amazonaws.com" },
"us-west-1" : { "EC2Principal" : "ec2.amazonaws.com", "OpsWorksPrincipal" :
"opsworks.amazonaws.com" },
"eu-west-1" : { "EC2Principal" : "ec2.amazonaws.com", "OpsWorksPrincipal" :
"opsworks.amazonaws.com" },
"ap-southeast-1" : { "EC2Principal" : "ec2.amazonaws.com", "OpsWorksPrincipal" :
"opsworks.amazonaws.com" },
"ap-northeast-1" : { "EC2Principal" : "ec2.amazonaws.com", "OpsWorksPrincipal" :
"opsworks.amazonaws.com" },
"ap-southeast-2" : { "EC2Principal" : "ec2.amazonaws.com", "OpsWorksPrincipal" :
"opsworks.amazonaws.com" },
"ap-northeast-2" : { "EC2Principal" : "ec2.amazonaws.com", "OpsWorksPrincipal" :
"opsworks.amazonaws.com" },
"sa-east-1" : { "EC2Principal" : "ec2.amazonaws.com", "OpsWorksPrincipal" :
"opsworks.amazonaws.com" },
"cn-north-1" : { "EC2Principal" : "ec2.amazonaws.com.cn", "OpsWorksPrincipal" :
"opsworks.amazonaws.com.cn" },
"eu-central-1" : { "EC2Principal" : "ec2.amazonaws.com", "OpsWorksPrincipal" :
"opsworks.amazonaws.com" }
},
"AWSInstanceType2Arch" : {
https://riptutorial.com/ 10
"t1.micro" : { "Arch" : "PV64" },
"t2.nano" : { "Arch" : "HVM64" },
"t2.micro" : { "Arch" : "HVM64" },
"t2.small" : { "Arch" : "HVM64" },
"t2.medium" : { "Arch" : "HVM64" },
"t2.large" : { "Arch" : "HVM64" },
"m1.small" : { "Arch" : "PV64" },
"m1.medium" : { "Arch" : "PV64" },
"m1.large" : { "Arch" : "PV64" },
"m1.xlarge" : { "Arch" : "PV64" },
"m2.xlarge" : { "Arch" : "PV64" },
"m2.2xlarge" : { "Arch" : "PV64" },
"m2.4xlarge" : { "Arch" : "PV64" },
"m3.medium" : { "Arch" : "HVM64" },
"m3.large" : { "Arch" : "HVM64" },
"m3.xlarge" : { "Arch" : "HVM64" },
"m3.2xlarge" : { "Arch" : "HVM64" },
"m4.large" : { "Arch" : "HVM64" },
"m4.xlarge" : { "Arch" : "HVM64" },
"m4.2xlarge" : { "Arch" : "HVM64" },
"m4.4xlarge" : { "Arch" : "HVM64" },
"m4.10xlarge" : { "Arch" : "HVM64" },
"c1.medium" : { "Arch" : "PV64" },
"c1.xlarge" : { "Arch" : "PV64" },
"c3.large" : { "Arch" : "HVM64" },
"c3.xlarge" : { "Arch" : "HVM64" },
"c3.2xlarge" : { "Arch" : "HVM64" },
"c3.4xlarge" : { "Arch" : "HVM64" },
"c3.8xlarge" : { "Arch" : "HVM64" },
"c4.large" : { "Arch" : "HVM64" },
"c4.xlarge" : { "Arch" : "HVM64" },
"c4.2xlarge" : { "Arch" : "HVM64" },
"c4.4xlarge" : { "Arch" : "HVM64" },
"c4.8xlarge" : { "Arch" : "HVM64" },
"g2.2xlarge" : { "Arch" : "HVMG2" },
"g2.8xlarge" : { "Arch" : "HVMG2" },
"r3.large" : { "Arch" : "HVM64" },
"r3.xlarge" : { "Arch" : "HVM64" },
"r3.2xlarge" : { "Arch" : "HVM64" },
"r3.4xlarge" : { "Arch" : "HVM64" },
"r3.8xlarge" : { "Arch" : "HVM64" },
"i2.xlarge" : { "Arch" : "HVM64" },
"i2.2xlarge" : { "Arch" : "HVM64" },
"i2.4xlarge" : { "Arch" : "HVM64" },
"i2.8xlarge" : { "Arch" : "HVM64" },
"d2.xlarge" : { "Arch" : "HVM64" },
"d2.2xlarge" : { "Arch" : "HVM64" },
"d2.4xlarge" : { "Arch" : "HVM64" },
"d2.8xlarge" : { "Arch" : "HVM64" },
"hi1.4xlarge" : { "Arch" : "HVM64" },
"hs1.8xlarge" : { "Arch" : "HVM64" },
"cr1.8xlarge" : { "Arch" : "HVM64" },
"cc2.8xlarge" : { "Arch" : "HVM64" }
},
"AWSInstanceType2NATArch" : {
"t1.micro" : { "Arch" : "NATPV64" },
"t2.nano" : { "Arch" : "NATHVM64" },
"t2.micro" : { "Arch" : "NATHVM64" },
"t2.small" : { "Arch" : "NATHVM64" },
"t2.medium" : { "Arch" : "NATHVM64" },
https://riptutorial.com/ 11
"t2.large" : { "Arch" : "NATHVM64" },
"m1.small" : { "Arch" : "NATPV64" },
"m1.medium" : { "Arch" : "NATPV64" },
"m1.large" : { "Arch" : "NATPV64" },
"m1.xlarge" : { "Arch" : "NATPV64" },
"m2.xlarge" : { "Arch" : "NATPV64" },
"m2.2xlarge" : { "Arch" : "NATPV64" },
"m2.4xlarge" : { "Arch" : "NATPV64" },
"m3.medium" : { "Arch" : "NATHVM64" },
"m3.large" : { "Arch" : "NATHVM64" },
"m3.xlarge" : { "Arch" : "NATHVM64" },
"m3.2xlarge" : { "Arch" : "NATHVM64" },
"m4.large" : { "Arch" : "NATHVM64" },
"m4.xlarge" : { "Arch" : "NATHVM64" },
"m4.2xlarge" : { "Arch" : "NATHVM64" },
"m4.4xlarge" : { "Arch" : "NATHVM64" },
"m4.10xlarge" : { "Arch" : "NATHVM64" },
"c1.medium" : { "Arch" : "NATPV64" },
"c1.xlarge" : { "Arch" : "NATPV64" },
"c3.large" : { "Arch" : "NATHVM64" },
"c3.xlarge" : { "Arch" : "NATHVM64" },
"c3.2xlarge" : { "Arch" : "NATHVM64" },
"c3.4xlarge" : { "Arch" : "NATHVM64" },
"c3.8xlarge" : { "Arch" : "NATHVM64" },
"c4.large" : { "Arch" : "NATHVM64" },
"c4.xlarge" : { "Arch" : "NATHVM64" },
"c4.2xlarge" : { "Arch" : "NATHVM64" },
"c4.4xlarge" : { "Arch" : "NATHVM64" },
"c4.8xlarge" : { "Arch" : "NATHVM64" },
"g2.2xlarge" : { "Arch" : "NATHVMG2" },
"g2.8xlarge" : { "Arch" : "NATHVMG2" },
"r3.large" : { "Arch" : "NATHVM64" },
"r3.xlarge" : { "Arch" : "NATHVM64" },
"r3.2xlarge" : { "Arch" : "NATHVM64" },
"r3.4xlarge" : { "Arch" : "NATHVM64" },
"r3.8xlarge" : { "Arch" : "NATHVM64" },
"i2.xlarge" : { "Arch" : "NATHVM64" },
"i2.2xlarge" : { "Arch" : "NATHVM64" },
"i2.4xlarge" : { "Arch" : "NATHVM64" },
"i2.8xlarge" : { "Arch" : "NATHVM64" },
"d2.xlarge" : { "Arch" : "NATHVM64" },
"d2.2xlarge" : { "Arch" : "NATHVM64" },
"d2.4xlarge" : { "Arch" : "NATHVM64" },
"d2.8xlarge" : { "Arch" : "NATHVM64" },
"hi1.4xlarge" : { "Arch" : "NATHVM64" },
"hs1.8xlarge" : { "Arch" : "NATHVM64" },
"cr1.8xlarge" : { "Arch" : "NATHVM64" },
"cc2.8xlarge" : { "Arch" : "NATHVM64" }
},
"AWSRegionArch2AMI" : {
"us-east-1" : {"PV64" : "ami-d4f7ddbe", "HVM64" : "ami-2df5df47", "HVMG2" : "ami-
95f7c0ff"},
"us-west-2" : {"PV64" : "ami-a9ae4ec9", "HVM64" : "ami-42b15122", "HVMG2" : "ami-
83a744e3"},
"us-west-1" : {"PV64" : "ami-14f68074", "HVM64" : "ami-f7f58397", "HVMG2" : "ami-
ee62138e"},
"eu-west-1" : {"PV64" : "ami-a93484da", "HVM64" : "ami-3c38884f", "HVMG2" : "ami-
25d76556"},
"eu-central-1" : {"PV64" : "ami-e8233884", "HVM64" : "ami-d8203bb4", "HVMG2" : "ami-
8fadb6e3"},
https://riptutorial.com/ 12
"ap-northeast-1" : {"PV64" : "ami-c8aca8a6", "HVM64" : "ami-eeabaf80", "HVMG2" : "ami-
71e6e01f"},
"ap-northeast-2" : {"PV64" : "NOT_SUPPORTED", "HVM64" : "ami-431fd12d", "HVMG2" :
"NOT_SUPPORTED"},
"ap-southeast-1" : {"PV64" : "ami-6702cc04", "HVM64" : "ami-8504cae6", "HVMG2" : "ami-
1e7ab47d"},
"ap-southeast-2" : {"PV64" : "ami-4f04232c", "HVM64" : "ami-a30126c0", "HVMG2" : "ami-
68a1860b"},
"sa-east-1" : {"PV64" : "ami-daf477b6", "HVM64" : "ami-e2f4778e", "HVMG2" :
"NOT_SUPPORTED"},
"cn-north-1" : {"PV64" : "ami-0534fc68", "HVM64" : "ami-3f36fe52", "HVMG2" :
"NOT_SUPPORTED"}
}
},
"Resources" : {
"VPC" : {
"Type" : "AWS::EC2::VPC",
"Properties" : {
"CidrBlock" : { "Fn::FindInMap" : ["NetworkValues", "VPC", "CIDR"] },
"EnableDnsHostnames" : "true",
"Tags" : [
{"Key": "Name", "Value": {"Ref":"CommonNameTag"} }
]
}
},
"Subnet" : {
"Type" : "AWS::EC2::Subnet",
"Properties" : {
"VpcId" : { "Ref" : "VPC" },
"CidrBlock" : { "Fn::FindInMap" : ["NetworkValues", "Subnet", "CIDR"] },
"MapPublicIpOnLaunch" : "true",
"Tags" : [
{"Key": "Name", "Value": {"Ref":"CommonNameTag"} }
]
}
},
"RouteTable" : {
"Type" : "AWS::EC2::RouteTable",
"Properties" : {
"VpcId" : { "Ref" : "VPC" }
}
},
"InternetGateway" : {
"Type" : "AWS::EC2::InternetGateway",
"Properties" : {
"Tags" : [
{"Key": "Name", "Value": {"Ref":"CommonNameTag"} }
]
}
},
"InternetGatewayAttachment" : {
"Type" : "AWS::EC2::VPCGatewayAttachment",
"Properties" : {
"InternetGatewayId" : { "Ref" : "InternetGateway"},
"VpcId" : { "Ref" : "VPC"}
}
https://riptutorial.com/ 13
},
"Route" : {
"Type" : "AWS::EC2::Route",
"Properties" : {
"DestinationCidrBlock" : "0.0.0.0/0",
"GatewayId" : { "Ref" : "InternetGateway" },
"RouteTableId" : { "Ref" : "RouteTable" }
}
},
"SubnetRouteTableAttachment" : {
"Type" : "AWS::EC2::SubnetRouteTableAssociation",
"Properties" : {
"RouteTableId" : { "Ref" : "RouteTable" },
"SubnetId" : { "Ref" : "Subnet" }
}
},
"CFNRole": {
"Type": "AWS::IAM::Role",
"Properties": {
"AssumeRolePolicyDocument": {
"Statement": [{
"Effect": "Allow",
"Principal": { "Service": { "Fn::FindInMap" : [ "Region2Principal", {"Ref" :
"AWS::Region"}, "EC2Principal"]}},
"Action": [ "sts:AssumeRole" ]
}]
},
"Path": "/"
}
},
"CFNRolePolicy": {
"Type": "AWS::IAM::Policy",
"Properties": {
"PolicyName": "CloudFormerPolicy",
"PolicyDocument": {
"Statement": [ {
"Effect": "Allow",
"Action" : [
"autoscaling:Describe*",
"cloudformation:Describe*",
"cloudformation:List*",
"cloudfront:List*",
"cloudFront:Get*",
"cloudtrail:Describe*",
"cloudtrail:Get*",
"cloudwatch:Describe*",
"dynamodb:List*",
"dynamodb:Describe*",
"elasticbeanstalk:Describe*",
"ec2:Describe*",
"elasticloadbalancing:Describe*",
"elasticache:Describe*",
"rds:Describe*",
"rds:List*",
"route53:List*",
"route53:Get*",
"s3:List*",
https://riptutorial.com/ 14
"s3:Get*",
"s3:PutObject",
"sdb:Get*",
"sdb:List*",
"sns:Get*",
"sns:List*",
"sqs:Get*",
"sqs:List*",
"opsworks:Describe*",
"redshift:Describe*",
"kinesis:Describe*",
"kinesis:List*"
],
"Resource": "*"
} ]
},
"Roles": [ { "Ref": "CFNRole" } ]
}
},
"CFNInstanceProfile": {
"Type": "AWS::IAM::InstanceProfile",
"Properties": {
"Path": "/",
"Roles": [ { "Ref": "CFNRole" } ]
}
},
"WebServer": {
"Type": "AWS::EC2::Instance",
"Metadata" : {
"AWS::CloudFormation::Init" : {
"configSets" : {
"full_install" : ["base", "cloudformer"]
},
"base" : {
"packages" : {
"yum" : {
"gcc" : [],
"gcc-c++" : [],
"make" : [],
"libxml2-devel" : [],
"libxslt-devel" : [],
"sqlite-devel" : [],
"patch" : [],
"readline" : [],
"readline-devel" : [],
"zlib" : [],
"zlib-devel" : [],
"libyaml-devel" : [],
"libffi-devel" : [],
"openssl-devel" : [],
"bzip2" : [],
"autoconf" : [],
"automake" : [],
"libtool" : [],
"bison" : [],
"ruby-devel" : []
}
}
},
https://riptutorial.com/ 15
"cloudformer" : {
"sources" : {
"/home/ec2-user/cloudformer" : {"Fn::Join" : ["/", [
{"Fn::FindInMap" : ["Region2Examples", {"Ref" :
"AWS::Region"}, "Examples"]},
"AWSCloudFormer041.zip" ]]}
},
"files" : {
"/home/ec2-user/setup_cloudformer" : {
"content" : { "Fn::Join" : ["", [
"#!/usr/bin/env bash\n",
"cd /home/ec2-user/cloudformer\n",
"# Setup the CloudFormer service\n",
"mkdir -p vendor/bundle\n",
"gem install --local /home/ec2-user/cloudformer/vendor/cache/rake-
10.4.2.gem\n",
"gem install --local /home/ec2-user/cloudformer/vendor/cache/bundler-
1.7.11.gem\n",
"gem install --local /home/ec2-user/cloudformer/vendor/cache/bundle-
0.0.1.gem\n",
"/usr/local/bin/bundle install --local --path /home/ec2-
user/cloudformer/vendor/bundle\n",
"/usr/local/bin/rake RAILS_ENV=production db:migrate\n",
"gem install --local /home/ec2-user/cloudformer/vendor/cache/rack-
1.6.0.gem\n",
"gem install --local /home/ec2-user/cloudformer/vendor/cache/eventmachine-
1.0.4.gem\n",
"gem install --local /home/ec2-user/cloudformer/vendor/cache/daemons-
1.1.9.gem\n",
"gem install --local /home/ec2-user/cloudformer/vendor/cache/thin-
1.6.3.gem\n",
"# Create certificate and private key for SSL\n",
"mkdir -p /home/ec2-user/cloudformer/.ssl\n",
"cd /home/ec2-user/cloudformer/.ssl\n",
"openssl genrsa -des3 -passout pass:\"" , { "Ref" : "Password" }, "\" -out
server.pass.key 1024\n",
"openssl rsa -passin pass:\"", { "Ref" : "Password" }, "\" -in
server.pass.key -out server.key\n",
"openssl req -new -key server.key -out server.csr -subj
\"/C=US/ST=Washington/L=Seattle/O=Amazon Web Services/OU=CloudFormer\"\n",
"openssl x509 -req -days 365 -in server.csr -signkey server.key -out
server.crt\n",
"rm server.pass.key server.csr\n"
]]},
"mode" : "000755",
"owner" : "root",
"group" : "root"
},
"/home/ec2-user/cloudformer/config/initializers/user.rb" : {
"content" : { "Fn::Join" : ["", [
"USER_NAME = \"", { "Ref" : "Username" }, "\"\n",
"PASSWORD = \"", { "Ref" : "Password" }, "\"\n"
]]},
"mode" : "000400",
"owner" : "root",
"group" : "root"
},
"/usr/bin/cloudformer" : {
"content" : { "Fn::Join" : ["", [
"#!/usr/bin/env bash\n",
"cd /home/ec2-user/cloudformer\n",
https://riptutorial.com/ 16
"/usr/local/bin/thin start -p 443 -e production -d --ssl --ssl-key-file
/home/ec2-user/cloudformer/.ssl/server.key --ssl-cert-file /home/ec2-
user/cloudformer/.ssl/server.crt\n"
]]},
"mode" : "000755",
"owner" : "root",
"group" : "root"
}
},
"commands" : {
"01_install_cloudformer" : {
"command" : "/home/ec2-user/setup_cloudformer &>
/var/log/setup_cloudformer.log",
"cwd" : "/home/ec2-user/cloudformer"
},
"02_setup_boot" : {
"command" : "echo '/usr/bin/cloudformer' >> /etc/rc.local",
"cwd" : "/"
}
}
}
}
},
"Properties": {
"ImageId" : { "Fn::FindInMap" : [ "AWSRegionArch2AMI", { "Ref" : "AWS::Region" },
{ "Fn::FindInMap" : [ "AWSInstanceType2Arch", "t2.medium", "Arch" ]
} ] },
"InstanceType" : "t2.medium",
"SecurityGroupIds" : [ {"Ref" : "WebServerSecurityGroup"} ],
"SubnetId" : { "Ref" : "Subnet" },
"IamInstanceProfile" : { "Ref" : "CFNInstanceProfile" },
"UserData" : { "Fn::Base64" : { "Fn::Join" : ["", [
"#!/bin/bash -xe\n",
"yum update -y aws-cfn-bootstrap\n",
"/opt/aws/bin/cfn-init -v ",
" --stack ", { "Ref" : "AWS::StackId" },
" --resource WebServer ",
" --configsets full_install ",
" --region ", { "Ref" : "AWS::Region" }, "\n",
"/opt/aws/bin/cfn-signal -e $? ",
" --stack ", { "Ref" : "AWS::StackId" },
" --resource WebServer ",
" --region ", { "Ref" : "AWS::Region" }, "\n"
]]}}
},
"CreationPolicy" : {
"ResourceSignal" : {
"Timeout" : "PT30M"
}
}
},
"WebServerSecurityGroup" : {
"Type" : "AWS::EC2::SecurityGroup",
"Properties" : {
"GroupDescription" : "Enable HTTPS access via port 443",
"VpcId" : { "Ref" : "VPC" },
"SecurityGroupIngress" : [
{"IpProtocol" : "tcp", "FromPort" : "443", "ToPort" : "443", "CidrIp" : "0.0.0.0/0"}
https://riptutorial.com/ 17
]
}
}
},
"Outputs" : {
"WebsiteURL" : {
"Value" : { "Fn::Join" : ["", ["https://", { "Fn::GetAtt" : [ "WebServer",
"PublicDnsName" ]} ]] },
"Description" : "URL for CloudFormer"
}
}
}
https://riptutorial.com/ 18
Chapter 5: AWS Lambda
Introduction
AWS Lambda is a service that lets you run back-end code without the need to provision or
manage servers. AWS Lambda takes care of scaling and high availability. The cost directly
depends on how often and how long your code executes.
You will find examples of how to create and deploy AWS Lambda functions in different languages.
Remarks
• AWS Lambda code must be written in a stateless manner. While the instance of a lambda
might be retained and re-used, you must never expect this.
Examples
Basic Gradle Java project
To deploy Java code to AWS Lambda, you have to create a distribution zip file that contains all
dependencies that are needed during the runtime. Example project in Gradle:
repositories {
mavenCentral()
}
dependencies {
compile 'com.amazonaws:aws-lambda-java-core:1.1.0'
}
build.dependsOn buildZip
Running gradle build will create a zip file with all dependencies bundled with your code, ready to
deploy.
A lambda needs a handler, which will serve as the entry point to your application. Every handler
needs to implement interface RequestHandler<I, O> where I is the input type and O is the output
https://riptutorial.com/ 19
type. The input type is then passed to the handleRequest() method and the method returns the
output type.
package com.example.lambda;
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;
@Override
public String handleRequest(Integer input, Context context) {
return "You sent " + input;
}
}
A lambda needs a handler, which will serve as the entry point to your application. In the simplest
case, you get your input from the context and pass the result using the callback() function:
exports.handler = (event, context, callback) => { callback(null, 'You sent ' + event.number); };
To create a Java lambda using the GUI, first make sure you have your distribution zip ready. You
will also need an AWS account that can create lambdas.
• Switch to the AWS Lambda, dismiss the introduction screen (or read the Get Started
documentation) and press the button Create a Lambda Function.
• Select an appropriate blueprint. A blueprint is an example template that can help you create
your lambda. For now, start with a Blank Function.
• For now, don't worry about triggers and skip that screen.
• Name your function and upload the zip file.
• On the same configuration screen, type in your Handler name as fully qualified Java class
with package, optionally with the method that will handle the requests. If you have used the
Java interface from Basic Lambda Code example, the class name is enough.
• On the same screen, select Create a new role from template(s) and name your role. The role
is used to give your lambda access to other AWS resources. In this case, leave it empty as
we don't need any other resources.
• Select the lowest available memory (128MB). The memory influnces cost as well. Save your
function.
If you have successfully deployed the Lambda, you can also test it directly in the GUI. When you
click the blue Test button for the first time, it presents you with a creation of a new test event.
https://riptutorial.com/ 20
If you are testing the Java code from the Basic Lambda code in Java example, delete the whole
body and simply add a number 1.
If you are testing the Javascript code from the Basic Lambda code in Javascript (Node) example,
create a json that looks like this:
{
"number": "1"
}
Probably the most common way to invoke a Lambda is to use API Gateway, which maps a REST
call to the lambda code. You can add multiple triggers to your Lambda during at any time,
including when creating a new lambda.
If you are familiar with API Gateway, you can associate any method with a deployed lambda.
Simply create a new method with Integration type set to Lambda function and point to your
lambda. You can map both REST inputs to lambda inputs and outputs to REST outputs.
TODO: Decide whether to describe API Gateway here or reference another part of documentation.
https://riptutorial.com/ 21
Chapter 6: Deploy a docker container image
using ECS
Remarks
Before you can add ECS instances to a cluster you must first go to the EC2 Management Console
and create ecs-optimized instances with an IAM role that has the
AmazonEC2ContainerServiceforEC2Role policy attached.
#!/bin/bash
echo ECS_CLUSTER=your_cluster_name >> /etc/ecs/ecs.config
NOTE: If you a creating a web server you will want to create a securityGroup to allow access to
port 80.
Examples
example-task.json
{
"family": "example-task",
https://riptutorial.com/ 22
"containerDefinitions": [
{
"environment": [],
"name": "example-container",
"image": "example-namespace/example-image:latest",
"cpu": 10,
"memory": 500,
"portMappings": [
{
"containerPort": 8080,
"hostPort": 80
}
],
"entryPoint": [],
"essential": true
}
]
}
https://riptutorial.com/ 23
sudo service docker start
5. Add the ec2-user to the docker group so you can execute Docker commands without using
sudo.
6. Log out from the EC2 and log back in again to pick up the new docker group permissions.
7. Verify that the ec2-user can run Docker commands without sudo.
docker info
8. Installing Git
9. Clone the sample PHP application on the Ec2 instance from git. We will use this application
for our POC.
cd ecs-demo-php-simple-app
ls
10. Go to AWS service catalog -> Compute -> Ec2 Container Service
11. Click on Get Started
https://riptutorial.com/ 24
15. Enter repository name and click next
aws configure
provide AWS Access Key ID, Secret Access key, default region name as per your account
18. Build the Docker image from your Dockerfile. (Recall Step 9, where you downloaded a
sample docker app)
a)
docker images
c) Run the newly built image. The -p 80:80 option maps the exposed port 80 on the container to
https://riptutorial.com/ 25
port 80 on the host system(Ec2 instance in this case).
Ignore the warning “apache2: Could not reliably determine the server's fully qualified domain
name, using 172.17.0.2 for ServerName”
19. Try to access the sample application webpage on browser, make sure port 80 is open in
security groups associated with the instance
http://<ec2-instance-dns-address>
20. Press ctrl + c key, this will stop the docker image. The sample application should not be
accessible.
21. Now after successfully verifying our sample docker application, we will try to configure a
cluster to run the sample application automatically. Also, for the demo purpose we will try to
use the existing ec2 instance as a node in the cluster. This can be achieved by installing a
agent program on the ec2 instance.
22. Installing Amazon ECS Container Agent on the ec2 instance
a)
d) (Optional) You can verify that the agent is running and see some information on your new
container instance with the agent introspection API. Make sure the port 51678 is open in security
group.
curl http://localhost:51678/v1/metadata
23. Go to AWS service catalog -> Compute -> Ec2 Container Service -> Cluster and verify a
default cluster is created
https://riptutorial.com/ 26
24. Now we proceed with creating a task group and adding our docker image as task to run on
the cluster
a) Examine the simple-app-task-def.json file in the ecs-demo-php-simple-app folder.
b) Edit the simple-app-task-def.json and redue the momeory, so that it can run on free tier
eligible instance(i assume one is using free tier eligible ec2 instance for this POC, otherwise
no need to reduce the memory limit)
c) Update memory=250 in all the occurrence on the simple-app-task-def.json file
d) Register a task definition with the simple-app-task-def.json file.
e) Go to task definition in ec2 container service page, you ll find the registered task definition
f) Use the following AWS CLI command to run a task with the console-sample-app task definition.
g) Open the sample web app in browser, it should be accessible(refer step 19)
Thanks for reading, do share your comments and queries for follow up discussion.
https://riptutorial.com/ 27
Chapter 7: Elastic Beanstalk
Remarks
Current Limitations (As of 2016-10-03)
• Environment Tags cannot be changed once the Environment is created, so choose wisely.
• Autoscaling in Elastic Beanstalk is limited to Simple and Scheduled, so if you wish to use
Step-Scaling, re-consider if Elastic Beanstalk is a good fit.
There is a great AWSEB Deployment Plugin for Jenkins that will plug-n-play for deployment to
Elastic Beanstalk (blue/green deployments with automatic idle termination is just a checkbox
away).
Examples
Introduction to Elastic Beanstalk
Elastic Beanstalk (EB) is essentially a hybrid between Golden AMIs and CloudFormation, while
vastly simplifying the learning curve of Puppet or Chef.
An Elastic Beanstalk deployment is broken down into two components: Application and
Environment.
Application
Consider this your top-level grouping, your application itself. For example, a single application
("MyWebApp") may have multiple Environments ("Production" and "Staging").
Environment
Each environment will consist of a complete architecture deployment (EC2 Instances, Elastic Load
Balancer, Autoscaling Group, and Cloudwatch Alarms). The entire environment configuration is
setup and maintained for your automatically.
Deploying an Application
Your application deployment is as simple as uploading a zip file containing your code. Each zip file
(called Application Version) you upload is associated to an Application, so you can upload once
and deploy to multiple Environments.
https://riptutorial.com/ 28
By default, Elastic Beanstalk will deploy "stock" Amazon-Maintained AMIs. For most applications,
this is sufficient, but there may be environmental tweaks that you want to make (eg. changing the
timezone, adding packages/dependencies not present in the code, etc).
There are two ways of customizing the EB AMI that is used: ebextensions or a custom AMI.
ebextensions - A folder, quite literally called '.ebextensions', that can optionally be placed at the
root of your Application Version (the zip you uploaded containing your code). Within the
ebextensions folder, you can place YAML files defining any custom scripts, dependencies, etc that
you want executed server-side during the deployment process. There are a number of hooking
points available, for the latest information, please check the relevant documentation:
http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/ebextensions.html
VPC Checkbox - When creating an environment, the option is discretely made available as to
whether or not the environment should be created/placed within a VPC. If you need your
application to communicate with existing resources that you have created, CHECK THIS BOX.
Otherwise, Elastic Beanstalk will create a new security group that is isolated from the rest of your
VPC. While you will be able to manually adjust the security group settings after creation, trying to
essentially 'add' it into a VPC will cause a variety of problems later on.
RDS - When creating an environment, you have the option to create an RDS instance as part of
the environment. It is not recommended to use this, as anytime you need to 'rebuild' the
environment (eg. blue/green deployments, troubleshooting) it will destroy and recreate the RDS
instance (along with all data).
Blue/Green deployment is a release technique that reduces downtime and risk by running two
identical production environments (one called "Blue", the other called "Green"). At any one time,
only one of the environments is serving live traffic, while the other is sitting idle.
When deploying a new version, the code is deployed to the idle environment (eg. Green) and after
confirming a successful deployment, live traffic is switched (eg. Green has new code, traffic from
Blue is now routed to Green). The next code deploy will occur on the new idle environment
(following the example, that would now be Blue).
Example/Visual Aid:
https://riptutorial.com/ 29
image source: https://cloudnative.io/statics/blog/aws-blue-green-deployment.png
When using Elastic Beanstalk (EB), you can easily create multiple environments that are exact
clones of one another for code deployment. After confirming that the new environment is ready to
go live, it is as simple as using the "Swap URLs" function in EB to swap environments.
https://riptutorial.com/ 30
Chapter 8: Root Class
Examples
Amazon api root class is as following.
https://riptutorial.com/ 31
public class Request
{
public string IsValid { get; set; }
public Itemsearchrequest ItemSearchRequest { get; set; }
}
https://riptutorial.com/ 32
{
public string Amount { get; set; }
public string CurrencyCode { get; set; }
public string FormattedPrice { get; set; }
}
https://riptutorial.com/ 33
public class Height2
{
public string Units { get; set; }
public string text { get; set; }
}
https://riptutorial.com/ 34
public class Lowestrefurbishedprice
{
public string Amount { get; set; }
public string CurrencyCode { get; set; }
public string FormattedPrice { get; set; }
}
https://riptutorial.com/ 35
public class Saleprice
{
public string Amount { get; set; }
public string CurrencyCode { get; set; }
public string FormattedPrice { get; set; }
}
Business class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Linq;
using ApplicationDataServices.SBEntityBox;
namespace ApplicationManagementLayer.Affiliate
{
public class Amazon
{
private int ItemPage { get; set; }
public int TotalNumberOfItem { get; set; }
public Amazon()
{
ItemPage = 1;
TotalNumberOfItem = 0;
}
r1["Operation"] = "ItemSearch";
https://riptutorial.com/ 36
r1["SearchIndex"] = CategoryNames.Where(o =>
o.Key.Equals("AmazonCategoryName")).First().Value;
else
r1["SearchIndex"] = "All";
if (!string.IsNullOrEmpty(q))
r1["Keywords"] = q;
else if (!string.IsNullOrEmpty(categorynamebyid))
r1["Keywords"] = categorynamebyid;
else if (CategoryNames != null && CategoryNames.Any() && CategoryNames.Where(o =>
o.Key.Equals("AmazonCategoryName")).Any())
r1["Keywords"] = CategoryNames.Where(o =>
o.Key.Equals("AmazonCategoryName")).First().Value;
else
return null;
r1["ResponseGroup"] = "Images,ItemAttributes,OfferFull,Offers,Variations";
r1["Version"] = "2013-08-01";
r1["ItemPage"] = ItemPage.ToString();
//r1["Sort"] = "salesrank";
TotalNumberOfItem = !string.IsNullOrEmpty(pro.ItemSearchResponse.Items.TotalResults) ?
Convert.ToInt32(pro.ItemSearchResponse.Items.TotalResults) : 0;
return pro;
https://riptutorial.com/ 37
//return "";
}
catch
{
return null;
}
}
http://stackoverflow.com/documentation/amazon-web-services/drafts/87373#
}
}
https://riptutorial.com/ 38
Credits
S.
Chapters Contributors
No
AWS
4 Hardeep Singh, Naveen Vijay
CloudFormation
Deploy a docker
6 container image mrded, Satish
using ECS
https://riptutorial.com/ 39