Programando sua infraestrutura com o AWS CloudFormation

Preview:

DESCRIPTION

Programando sua infraestrutura com o AWS CloudFormation, por Michel Pereir, Solutions Architect da AWS.

Citation preview

AWS CloudFormation

Michel PereiraSolutions Architect

michelp@amazon.com

AWS CloudFormation

• AWS CloudFormation dá aos desenvolvedores e administradores de sistemas uma maneira fácil de criar e gerenciar recursos da AWS, provisionando e atualizando a infra-estrutura de uma maneira ordenada e previsível.

AWS CloudFormation

Templates para descrever os recursos da AWS e qualquer dependência relacionada ou parâmetros requiridos para executar a

sua aplicação

AWS CloudFormation

Você não precisa descobrir a ordem em qual os serviços precisam ser

provisionados ou como fazer essas dependências funcionarem.

AWS CloudFormation

Uma vez executado, você pode modificar e atualizar os recursos de uma maneira controlada e previsível, permitido você

versionar a sua infraestrutura do mesmo jeito que você faz com o seu código

AWS CloudFormation

AWS CloudFormation é gratuito e você só paga pelos recursos que serão utilizados

pelo seu aplicativo.

AWS CloudFormation

• Templates que descrevem os recursos da AWS

• Modifique e atualize os seus recursos AWS de uma maneira controlada e previsível.

• Tenha controle de versão da sua infraestrutura na AWS

AWS CloudFormation

Consegue fazer

em um datacenter

físico?

Anatomiade um template

JSON

JSON

Texto puro

Perfeito para controle de

versão

Pode ser validado

Linguagem declarativa

{

"AWSTemplateFormatVersion" : "2010-09-09",

"Description" : "AWS CloudFormation Sample Template EC2InstanceSample: Create an Amazon EC2 instance running the Amazon Linux AMI. The AMI is chosen based on the region in which the stack is run. This example uses the default security group, so to SSH to the new instance using the KeyPair you enter, you will need to have port 22 open in your default security group. **WARNING** This template an Amazon EC2 instances. You will be billed for the AWS resources used if you create a stack from this template.",

"Parameters" : { "KeyName" : { "Description" : "Name of an existing EC2 KeyPair to enable SSH access to the instance", "Type" : "String" } },

"Mappings" : { "RegionMap" : { "us-east-1" : { "AMI" : "ami-7f418316" }, "us-west-1" : { "AMI" : "ami-951945d0" }, "us-west-2" : { "AMI" : "ami-16fd7026" }, "eu-west-1" : { "AMI" : "ami-24506250" }, "sa-east-1" : { "AMI" : "ami-3e3be423" }, "ap-southeast-1" : { "AMI" : "ami-74dda626" }, "ap-northeast-1" : { "AMI" : "ami-dcfa4edd" } } },

"Resources" : { "Ec2Instance" : { "Type" : "AWS::EC2::Instance", "Properties" : { "KeyName" : { "Ref" : "KeyName" }, "ImageId" : { "Fn::FindInMap" : [ "RegionMap", { "Ref" : "AWS::Region" }, "AMI" ]}, "UserData" : { "Fn::Base64" : "80" } } } },

"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" ] } },

"AWSTemplateFormatVersion" : "2010-09-09",

"Description" : "AWS CloudFormation Sample Template EC2InstanceSample: Create an Amazon EC2 instance running the Amazon Linux AMI. The AMI is chosen based on the region in which the stack is run. This example uses the default security group, so to SSH to the new instance using the KeyPair you enter, you will need to have port 22 open in your default security group. **WARNING** This template an Amazon EC2 instances. You will be billed for the AWS resources used if you create a stack from this template.",

"Parameters" : { "KeyName" : { "Description" : "Name of an existing EC2 KeyPair to enable SSH access to the instance", "Type" : "String" } },

"Mappings" : { "RegionMap" : { "us-east-1" : { "AMI" : "ami-7f418316" }, "us-west-1" : { "AMI" : "ami-951945d0" }, "us-west-2" : { "AMI" : "ami-16fd7026" }, "eu-west-1" : { "AMI" : "ami-24506250" }, "sa-east-1" : { "AMI" : "ami-3e3be423" }, "ap-southeast-1" : { "AMI" : "ami-74dda626" }, "ap-northeast-1" : { "AMI" : "ami-dcfa4edd" } } },

"Resources" : { "Ec2Instance" : { "Type" : "AWS::EC2::Instance", "Properties" : { "KeyName" : { "Ref" : "KeyName" }, "ImageId" : { "Fn::FindInMap" : [ "RegionMap", { "Ref" : "AWS::Region" }, "AMI" ]}, "UserData" : { "Fn::Base64" : "80" } } } },

"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" ] } },…..

CabeçalhoParâmetros

Mapeamentos

Recursos

Saídas

ParâmetrosConfigurações em tempo

de provisionamento

Mapeamentos

Condições

Recursos

Parâmetro

de referência

“KeyName” : { “Ref” : “KeyName” },

Mapeamento

condicional

“ImageId” : { “Fn::FindInMap” : [ “RegionMap”, { “Ref” : “AWS::Region” }, “AMI” ]},

Nome

do mapa

“ImageId” : { “Fn::FindInMap” : [ “RegionMap”, { “Ref” : “AWS::Region” }, “AMI” ]},

Referência

de propriedade

declarada

“ImageId” : { “Fn::FindInMap” : [ “RegionMap”, { “Ref” : “AWS::Region” }, “AMI” ]},

Saídas

Recursos: Quase todos os serviços AWS– O que está faltando (até agora)?

• Amazon Elastic MapReduce (EMR)

• Amazon Simple Workflow Service (SWF)• Amazon Simple Email Service (SES)• Amazon Glacier• Amazon CloudSearch• Pequenas novidades de outros serviços ainda não

implementadas

AWS CloudFormation

Recursos – Amazon Elastic Compute Cloud (EC2):{

"Type" : "AWS::EC2::Instance",

"Properties" : {

"AvailabilityZone" : String,

"DisableApiTermination" : Boolean,

"EbsOptimized" : Boolean,

"IamInstanceProfile" : String,

"ImageId" : String,

"InstanceType" : String,

AWS CloudFormation

Recursos – Amazon EC2:– "KernelId" : String,

– "KeyName" : String,– "Monitoring" : Boolean,– "PlacementGroupName" : String,– "PrivateIpAddress" : String,– "RamdiskId" : String,– "SecurityGroupIds" : [ String, ... ],– "SecurityGroups" : [ String, ... ],

AWS CloudFormation

Recursos – Amazon EC2:

"SourceDestCheck" : Boolean,

"SubnetId" : String,

"Tags" : [ EC2 Tag, ... ],

"Tenancy" : String,

"UserData" : String,

"Volumes" : [ EC2 MountPoint, ... ]

}

}

AWS CloudFormation

METADATA

AWS CloudFormation

Use AWS::CloudFormation::Init com cfn-init para ajudar a fazer o “bootstrap” das instâncias:"Metadata": {

"AWS::CloudFormation::Init" : {

"config" : {

"packages" : {

},

"sources" : {

},

"commands" : {

},

"files" : {

},

"services" : {

},

"users" : {

},

"groups" : {

}

}

}

AWS CloudFormation

Instale pacotes com a ferramenta nativa de gerenciamento de pacotes:“ServerHost" : {

"Type" : "AWS::EC2::Instance",

"Metadata" : {

"AWS:CloudFormation::Init" : {

"config" : {

"packages" : {

"yum" : {

"gcc" : [],

"gcc-c++" : [],

"make" : [],

"automake" : [],

AWS CloudFormation

Configure arquivos:

"/home/ec2-user/.s3cfg": {

"content": { "Fn::Join": [ "", [

"[default]","\n",

"access_key = ", { "Ref": "CFNKeys"}, "\n",

"secret_key = ", { "Fn::GetAtt": [ "CFNKeys", "SecretAccessKey" ]}, "\n" ] ] },

"group": "ec2-user",

"mode": "000600",

"owner": "ec2-user"

},

AWS CloudFormation

Publique código de tar, tar+gzip, tar+bz2 and zip.

Até Github!:"AWS::CloudFormation::Init" : {

"config" : {

"sources" : {

"/var/www/html" : "https://s3.amazonaws.com/cloudformation-examples/CloudFormationPHPSample.zip"

}

}

}

AWS CloudFormation

Ligue serviços dentro do host:"services" : {

"sysvinit" : {

"nginx" : {

"enabled" : "true",

"ensureRunning" : "true",

"files" : ["/etc/nginx/nginx.conf"],

"sources" : ["/var/www/html"]

},

"sendmail" : {

"enabled" : "false",

"ensureRunning" : "false"

}

}

}

AWS CloudFormation

Recursos – Amazon RDS:"MyDB" : {

"Type" : "AWS::RDS::DBInstance",

"Properties" : {

"DBName" : { "Ref" : "DBName" },

"AllocatedStorage" : { "Ref" : "DBAllocatedStorage" },

"DBInstanceClass" : { "Ref" : "DBClass" },

"Engine" : "MySQL",

"EngineVersion" : "5.5",

"MasterUsername" : { "Ref" : "DBUsername" } ,

"MasterUserPassword" : { "Ref" : "DBPassword" },

"DBSubnetGroupName" : { "Ref" : "MyDBSubnetGroup" },

"DBSecurityGroups" : [ { "Ref" : "MyDBSecurityGroup" } ]

}

}

AWS CloudFormation

Recursos – Amazon RDS:"Parameters" : {

"DBName": {

"Default": "MyDatabase",

"Description" : "The database name",

"Type": "String",

"MinLength": "1",

"MaxLength": "64",

"AllowedPattern" : "[a-zA-Z][a-zA-Z0-9]*",

"ConstraintDescription" : "must begin with a letter and contain only alphanumeric characters."

},

"DBUsername": {

"Default": "admin",

"NoEcho": "true",

"Description" : "The database admin account username",

"Type": "String",

"MinLength": "1",

"MaxLength": "16",

"AllowedPattern" : "[a-zA-Z][a-zA-Z0-9]*",

"ConstraintDescription" : "must begin with a letter and contain only alphanumeric characters."

},

AWS CloudFormation

Recursos – security groups:"ControllerSecurityGroup": {

"Type": "AWS::EC2::SecurityGroup",

"Properties": {

"GroupDescription": "Enable SSH access",

"SecurityGroupIngress": [

{

"IpProtocol": "tcp",

"FromPort": "22",

"ToPort": "22",

"CidrIp": "0.0.0.0/0"

}

]

}

}

In VPC? Add in: "VpcId" : { "Ref" : ”<your VPC>" },

AWS CloudFormation

Recursos – Amazon Virtual Private Cloud (VPC):”MyVPC" : {

"Type" : "AWS::EC2::VPC",

"Properties" : {

"CidrBlock" : "192.168.0.0/16”

}

}

AWS CloudFormation

Recursos – Amazon VPC (continued):"PublicSubnet" : {

"Type" : "AWS::EC2::Subnet",

"Properties" : {

"VpcId" : { "Ref" : ”MyVPC" },

"CidrBlock" : "192.168.1.0/24"

}

},

AWS CloudFormation

Recursos – Amazon VPC (continued): "InternetGateway" : {

"Type" : "AWS::EC2::InternetGateway",

"Properties" : {

}

},

"AttachGateway" : {

"Type" : "AWS::EC2::VPCGatewayAttachment",

"Properties" : {

"VpcId" : { "Ref" : ”MyVPC" },

"InternetGatewayId" : { "Ref" : "InternetGateway" }

}

},

AWS CloudFormation

Recursos – Amazon VPC(continued):"PublicRouteTable" : {

"Type" : "AWS::EC2::RouteTable",

"Properties" : {

"VpcId" : {"Ref" :  »MyVPC"},

}

},

"PublicRoute" : {

"Type" : "AWS::EC2::Route",

"Properties" : {

"RouteTableId" : { "Ref" : "PublicRouteTable" },

"DestinationCidrBlock" : "0.0.0.0/0",

"GatewayId" : { "Ref" : "InternetGateway" }

}

},

"PublicSubnetRouteTableAssociation" : {

"Type" : "AWS::EC2::SubnetRouteTableAssociation",

"Properties" : {

"SubnetId" : { "Ref" : "PublicSubnet" },

"RouteTableId" : { "Ref" : "PublicRouteTable" }

}

AWS CloudFormation

Recursos – Amazon Simple Storage Service (S3):"S3Bucket" : {

"Type" : "AWS::S3::Bucket",

"Properties" : {

"AccessControl" : "PublicRead",

"WebsiteConfiguration" : {

"IndexDocument" : "index.html",

"ErrorDocument" : "error.html"

}

},

"DeletionPolicy" : "Retain"

}

}

AWS CloudFormation

Versionamento!

Você tem um repositório de código, certo?

Se não, por favor crie um logo após o Webinar

AWS CloudFormation

Versionamento! • Você rastreia as atualizações no seu código• Mesma coisa com a infraestrutura:

– O que está sendo mudado?– Quem fez a atualização?– Quando foi feita?– Porquê?(atrelada a um ticket/bug/sistema de projetos?)

AWS CloudFormation

Testando:– Validação via API/linha de comando

$ aws --region=us-east-1 cloudformation validate-template --template-body file://$PWD/Lab1-nat_stack.template

{

"ResponseMetadata": {

"RequestId": "174228cc-2c59-11e3-a4b8-8d0a0ca6c09c"

},

"Description": "Builds a NAT host. **WARNING** This template creates Amazon EC2 instance(s). You will be billed for the AWS resources used if you create a stack from this template.",

"Parameters": [

{

"NoEcho": false,

"Description": "SubnetId of an existing Public facing subnet in your Virtual Private Cloud (VPC)",

"ParameterKey": "SubnetId"

},

……..

],

"Capabilities": []

AWS CloudFormation

Publicação e atualização via console ou API/linha de comando:

– Alguns cliques

OU– aws cloudformation create-stack --stack-name myteststack

--template-body file:////home//local//test//sampletemplate.json --parameters ParameterKey=string,ParameterValue=string

AWS CloudFormation

Demo!

Como aprender mais:– RTFM!

• http://aws.amazon.com/cloudformation/• http://aws.amazon.com/documentation/

cloudformation/• https://aws.amazon.com/cloudformation/aws-

cloudformation-templates/

AWS CloudFormation

michelp@amazon.com

Michel Pereira

Solutions Architect