[AWS] 06 - AWS CloudFormation
CloudFormation template language (YAML or JSON) 加载到 --> S3, 再创建stack --> Output。
第一波学习
一、资源
目录:https://edu.51cto.com/center/course/lesson/index?id=192589
Ref: 一個文字檔就搞定IT基礎設施:AWS Cloudformation (Infrastructure as code through AWS Cloudformation)
二、基本概念
三、没有对比就没有伤害
-
传统方法
-
CloudFormation方法
CloudFormation >Stacks >Create stack
(1) Upload a template file: yaml.
(2) 基本配置
四、Template & Stack
Create the following resources:
1) an on-demand DynamoDB table with a local secondary index
2) an S3 bucket with a lifecycle policy to clean up after itself
3) an SQS queue with AWS CloudWatch alarms on queue depth
AWSTemplateFormatVersion: 2010-09-09
# 语法的版本
# 有点注解的意思
Description: >-
Create the following resources:
1) an on-demand DynamoDB table with a local secondary index
2) an S3 bucket with a lifecycle policy to clean up after itself
3) an SQS queue with AWS CloudWatch alarms on queue depth
Parameters:
AutoCleanupPrefix:
Description: >-
All object with this prefix will be deleted automatically by S3.
Type: String
RetentionDays:
Description: >-
How many days will the object with `AutoCleanupPrefix` be retained.
Type: Number
# 上面的设置反映在了如下UI的版面中。
InstanceTypeParameter的参数的定义在这里有写。
ec2的模板文件中是这么引用ref: InstanceTypeParameter
# 最重要,唯一必须设置的
Resources:
DDBTable:
Type: AWS::DynamoDB::Table
Properties:
AttributeDefinitions:
-
AttributeName: "ArtistId"
AttributeType: "S"
-
AttributeName: "Concert"
AttributeType: "S"
-
AttributeName: "TicketSales"
AttributeType: "S"
KeySchema:
-
AttributeName: "ArtistId"
KeyType: "HASH"
-
AttributeName: "Concert"
KeyType: "RANGE"
LocalSecondaryIndexes:
-
IndexName: "LSI"
KeySchema:
-
AttributeName: "ArtistId"
KeyType: "HASH"
-
AttributeName: "TicketSales"
KeyType: "RANGE"
Projection:
ProjectionType: "KEYS_ONLY"
BillingMode: "PAY_PER_REQUEST"
AutoCleanupBucket:
Type: AWS::S3::Bucket
Properties:
# enable server-side encryption so that your data is encrypted at rest
# on S3's servers.
BucketEncryption:
ServerSideEncryptionConfiguration:
-
ServerSideEncryptionByDefault:
SSEAlgorithm: AES256
LifecycleConfiguration:
Rules:
-
Id: MakeS3CleanUpAfterItself
Status: Enabled
AbortIncompleteMultipartUpload:
DaysAfterInitiation: !Ref RetentionDays
ExpirationInDays: !Ref RetentionDays
Prefix: !Ref AutoCleanupPrefix
MyQueue:
Type: 'AWS::SQS::Queue'
Properties: {}
QueueDepthAlarm:
Type: 'AWS::CloudWatch::Alarm'
Properties:
AlarmDescription: Alarm if queue depth grows beyond 10 messages
Namespace: AWS/SQS
MetricName: ApproximateNumberOfMessagesVisible
Dimensions:
-
Name: QueueName
Value: !GetAtt
- MyQueue
- QueueName
Statistic: Sum
Period: '300'
EvaluationPeriods: '1'
Threshold: '10'
ComparisonOperator: GreaterThanThreshold
Outputs:
TableName:
Value: !Ref DDBTable
Description: Name of the newly created DynamoDB table
Outputs:
BucketARN:
Description: The ARN of the bucket create.
Value: !GetAtt AutoCleanupBucket.Arn
QueueURL:
Description: URL of newly created SQS Queue
Value: !Ref MyQueue
QueueARN:
Description: ARN of newly created SQS Queue
Value: !GetAtt
- MyQueue
- Arn
QueueName:
Description: Name newly created SQS Queue
Value: !GetAtt
- MyQueue
- QueueName
五、S3的配置示范
Ref: AWS省錢小祕技: 讓S3自動清理不要的objects (Cost-Saving Tips for AWS: Make S3 clean up after itself)
AutoCleanupBucket:
Type: AWS::S3::Bucket
Properties:
BucketEncryption:
ServerSideEncryptionConfiguration:
- ServerSideEncryptionByDefault:
SSEAlgorithm: AES256
LifecycleConfiguration:
Rules:
- Id: MakeS3CleanUpAfterItself
Status: Enabled
AbortIncompleteMultipartUpload:
DaysAfterInitiation: !Ref RetentionDays
ExpirationInDays: !Ref RetentionDays
Prefix: !Ref AutoCleanupPrefix
第二波学习
一、CouldFormation
Ref: Serverless Rest API using AWS and Python | Introduction to AWS CloudFormation (Part-4)
这里涉及到七处 resources。
Ref: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-restapi.html [template文件模板]
AWSTemplateFormatVersion: "2010-09-09"
Description: "My API Gateway and Lambda function"
Resources:
SampleApi:
Type: "AWS::ApiGateway::RestApi"
Properties:
Name: Sample
SampleApiMethod:
Type: "AWS::ApiGateway::Method"
Properties:
AuthorizationType: "NONE"
HttpMethod: "GET"
Integration:
IntegrationHttpMethod: "POST"
Type: "AWS_PROXY"
Uri: !Sub
- "arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${lambdaArn}/invocations"
- lambdaArn: !GetAtt "SampleLambda.Arn"
ResourceId: !GetAtt "SampleApi.RootResourceId"
RestApiId: !Ref "SampleApi"
SampleApiDeployment:
Type: "AWS::ApiGateway::Deployment"
DependsOn: "SampleApiMethod"
Properties:
RestApiId: !Ref "SampleApi"
StageName: test
SampleLambda:
Type: "AWS::Lambda::Function"
Properties:
Code:
ZipFile: |
def handler(event,context):
return {
'body': 'Hello, world!',
'headers': {
'Content-Type': 'text/plain'
},
'statusCode': 200
}
Handler: "index.handler"
Role: !GetAtt "SampleLambdaRole.Arn"
Runtime: python3.7
LambdaApiGatewayInvoke:
Type: "AWS::Lambda::Permission"
Properties:
Action: "lambda:InvokeFunction"
FunctionName: !GetAtt "SampleLambda.Arn"
Principal: "apigateway.amazonaws.com"
SourceArn: !Sub "arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:${SampleApi}/*/GET/"
SampleLambdaRole:
Type: "AWS::IAM::Role"
Properties:
AssumeRolePolicyDocument:
Version: "2012-10-17"
Statement:
- Action: ["sts:AssumeRole"]
Effect: "Allow"
Principal:
Service: ["lambda.amazonaws.com"]
Policies:
- PolicyDocument:
Version: "2012-10-17"
Statement:
- Action: ["cloudwatch:*", "logs:*"]
Effect: "Allow"
Resource: "*"
PolicyName: "lambdaLogPolicy"
SampleLambdaLogGroup:
DependsOn: SampleLambda
Type: "AWS::Logs::LogGroup"
Properties:
LogGroupName: !Sub "/aws/lambda/${SampleLambda}"
加载template文件,开始构建各个服务,如下。
二、SAM
-
视频学习
Ref: Serverless Rest API using AWS and Python | Project Setup using AWS SAM (Part-5)
The AWS Serverless Application Model (SAM) is an open-source framework for building serverless applications.
$ pip install aws-sam-cli
$ sam init
AWS Quick Start Templates
python3.6
Project name [sam-app]: student-api
Cloning app templates from https://github.com/aws/aws-sam-cli-app-templates.git
Template selection: 1 - Hello World Example
登录虚拟环境,再执行:pip install aws-sam-cli,如此安装避免安装依赖错误。
(my-project) jeffrey@unsw-ThinkPad-T490:my-project$ sam init SAM CLI now collects telemetry to better understand customer needs. You can OPT OUT and disable telemetry collection by setting the environment variable SAM_CLI_TELEMETRY=0 in your shell. Thanks for your help! Learn More: https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-telemetry.html Which template source would you like to use? 1 - AWS Quick Start Templates 2 - Custom Template Location Choice: 1 Which runtime would you like to use? 1 - nodejs12.x 2 - python3.8 3 - ruby2.7 4 - go1.x 5 - java11 6 - dotnetcore3.1 7 - nodejs10.x 8 - python3.7 9 - python3.6 10 - python2.7 11 - ruby2.5 12 - java8.al2 13 - java8 14 - dotnetcore2.1 Runtime: 9 Project name [sam-app]: student-api Cloning app templates from https://github.com/awslabs/aws-sam-cli-app-templates.git AWS quick start application templates: 1 - Hello World Example 2 - EventBridge Hello World 3 - EventBridge App from scratch (100+ Event Schemas) 4 - Step Functions Sample App (Stock Trader) Template selection: 1 ----------------------- Generating application: ----------------------- Name: student-api Runtime: python3.6 Dependency Manager: pip Application Template: hello-world Output Directory: . Next steps can be found in the README file at ./student-api/README.md (my-project) jeffrey@unsw-ThinkPad-T490:my-project$ ls student-api/ events hello_world README.md template.yaml tests
这是一个sam template。
-
教程学习
Ref: Tutorial: Deploying a Hello World application
sam-app/ ├── README.md ├── .aws_sam/ | └── build/ | ├── HelloWorldFunction/ | └── template.yaml ├── events/ │ └── event.json ├── hello_world/ │ ├── __init__.py │ ├── app.py # Contains your AWS Lambda handler logic. │ └── requirements.txt # Contains any Python dependencies the application requires, used for sam build ├── template.yaml # Contains the AWS SAM template defining your application's AWS resources. └── tests/ └── unit/ ├── __init__.py └── test_handler.py
template.yaml 内容。
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: >
student-api
Sample SAM Template for student-api
# More info about Globals: https://github.com/awslabs/serverless-application-model/blob/master/docs/globals.rst
Globals:
Function:
Timeout: 3
Resources:
HelloWorldFunction:
Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction
Properties:
CodeUri: hello_world/
Handler: app.lambda_handler
Runtime: python3.6
Events:
HelloWorld:
Type: Api # More info about API Event Source: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#api
Properties:
Path: /hello
Method: get
Outputs:
# ServerlessRestApi is an implicit API created out of Events key under Serverless::Function
# Find out more about other implicit resources you can reference within SAM
# https://github.com/awslabs/serverless-application-model/blob/master/docs/internals/generated_resources.rst#api
HelloWorldApi:
Description: "API Gateway endpoint URL for Prod stage for Hello World function"
Value: !Sub "https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/hello/"
HelloWorldFunction:
Description: "Hello World Lambda Function ARN"
Value: !GetAtt HelloWorldFunction.Arn
HelloWorldFunctionIamRole:
Description: "Implicit IAM Role created for Hello World function"
Value: !GetAtt HelloWorldFunctionRole.Arn
End.