gpt4 book ai didi

amazon-web-services - 如何在 CloudFormation 脚本中获取当前日期?

转载 作者:行者123 更新时间:2023-12-04 01:57:09 25 4
gpt4 key购买 nike

我使用 cfn 脚本中的标签来标记我的资源:

"Tags" : [ { "Key" : "Owner",       "Value" : "my name" },
{ "Key" : "Name", "Value" : "instance name" }
{ "Key" : "DateCreated", "Value" : <something goes here> }
],

我想按照上面的示例创建一个包含当前日期的标签。可能吗?

最佳答案

您可以使用“自定义资源”来生成时间戳(或任何其他值)。

Custom resources是 CloudFormation 中的一项新功能(2014 年左右推出),基本上允许您调用 lambda 函数来“创建”、“更新”或“删除”CloudFormation 不提供语言支持的资源(甚至可以是 AWS 外部的资源) .

我大量使用自定义资源只是为了计算一些值以供堆栈其他部分使用,例如创建保存计算值的“变量”(例如使用 !Join 和类似函数)我需要经常使用并且想计算一次。

您可以轻松地使用自定义资源来生成时间戳。下面是一些示例代码,非常接近我在生产中实际使用的代码:

创建“资源”实现

Resources:
ValueFunc:
Type: AWS::Lambda::Function
Properties:
Code:
ZipFile: >
var r = require('cfn-response');
exports.handler = function(ev, ctx) {
ev.ResourceProperties.Time = new Date().toISOString();
r.send(ev, ctx, r.SUCCESS, ev.ResourceProperties);
};
Handler: index.handler
Runtime: nodejs6.10
Timeout: 30
Role: !GetAtt ValueFunctionExecutionRole.Arn

ValueFunctionExecutionRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Principal: { Service: [ lambda.amazonaws.com ] }
Action: sts:AssumeRole
Policies:
- PolicyName:
Fn::Sub: "value-custom-res-${AWS::StackName}-${AWS::Region}"
PolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Action:
- logs:CreateLogGroup
- logs:CreateLogStream
- logs:PutLogEvents
Resource: "arn:aws:logs:*:*:*"
- Effect: Allow
Action: cloudformation:DescribeStacks
Resource: "arn:aws:cloudformation:*:*:*"

然后,无论您想在何处生成时间戳,都可以执行以下操作(计划操作示例取自 here ):

创建计算其创建时间的自定义资源

GetTimeThisTime:
Type: Custom::Value
Properties:
ServiceToken: !GetAtt ValueFunc.Arn

使用Time属性读取创建的时间戳

ScheduledActionUp: 
Type: AWS::AutoScaling::ScheduledAction
Properties:
AutoScalingGroupName: !Ref WebServerGroup
DesiredCapacity: 2
StartTime: !GetAtt GetTimeThisTime.Time
Recurrence: "0 7 * * *"

您可以在堆栈创建的不同时间生成多个时间戳,只需创建一个新的“自定义值”,该值取决于您想要为其创建计时的逻辑实体。

关于amazon-web-services - 如何在 CloudFormation 脚本中获取当前日期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15637947/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com