Cloudformation 是AWS的一个非常重要的工具,主要通过Json或者Yaml中申明应用程序所需要资源以及各资源之间的关联。只需要简单几行命令解决程序部署,升级,删除整个资源栈的工作。
以下是通过CloudFormation创建一个S3的Bucket,然后修改CloudFormation,最后删除CloudFormation,同时Bucket也会被自动删除。
1. 创建 cloudformation.template 文件
{
"Resources": {
"DeploymentBucket": {
"Type": "AWS::S3::Bucket",
"Properties": {
"AccessControl":"PublicRead"
}
}
}
}
使用 cloudformation.template 创建一个S3的bucket,并设置访问权限为PublicRead(公共可读)
2. 创建 CloudFormation
aws cloudformation create-stack \
--region us-east-2 \
--stack-name test-stack \
--template-body file://${PWD}/cloudformation.template
运行以上命令成功后返回一个资源栈ID类似:
{
"StackId": "arn:aws:cloudformation:us-east-2:083845954230:stack/test-stack/f7523e60-a4cc-11ea-a7c9-0a76b6c12f42"
}
检查Bucket 是否创建
// 查看S3的文件
aws s3 ls
运行成功后可以看到类似的bucket:test-stack-deploymentbucket-1r6lhwc92du29 ,命名规则:stack-name+deploymentbucket+RANDOM_ID
检查CloudFormation是否创建
访问https://console.aws.amazon.com/cloudformation/home 查看刚才创建的栈信息。
3. 更新 CloudFormation
{
"Resources": {
"DeploymentBucket": {
"Type": "AWS::S3::Bucket",
"Properties": {
"AccessControl":"PublicRead",
"WebsiteConfiguration":{
"IndexDocument":"index.html",
"ErrorDocument":"error.html"
}
}
}
}
}
aws cloudformation update-stack \
--region us-east-2 \
--stack-name test-stack \
--template-body file://${PWD}/cloudformation.template
4. 删除 CloudFormation
aws cloudformation delete-stack \
--region us-east-2 \
--stack-name test-stack
删除资源栈并清除全部资源(即刚才创建的Bucket也会删除,可以通过 aws s3 ls 命令查看),可以通过模版文件中为希望保留的资源加“DeletionPolicy”,“Retain”属性防止AWS删除stack时一并删除resources。
网友评论