我如何替换CloudFormation AWS中的某些字符串

时间:2019-07-04 06:33:28

标签: amazon-web-services amazon-cloudformation

我有cloudformation模板,其中我从上一步传递了一个参数,其值像这样

 "test1.example.org"

 "example.org"

 "org"

现在我想基本上从该参数中删除.org部分并获取

test1.example

example

也可以有很多子域,例如

test1.test2.test3.test4.example.org

我只需要从最后删除.org

4 个答案:

答案 0 :(得分:10)

通过警告您可以实现您想要的-假设.org仅出现在字符串的末尾。

这是一个完整的模板(test.cfn.yaml),显示了此方法的工作原理:

AWSTemplateFormatVersion: 2010-09-09

Parameters:
  Input:
    Type: String

Resources:
  DummyBucket:
    Type: AWS::S3::Bucket


Outputs:
  TheOutput:
    Value: !Join [ '', !Split [ '.org', !Ref Input ] ]

您可以通过运行以下命令使用aws cli进行测试:

aws cloudformation deploy --template-file test.cfn.yaml --stack-name test1 --parameter-overrides Input=apples.bananas.org

此堆栈的输出将包含apples.bananas

在脚本中,您可以使用!Join [ '', !Split [ '.org', !Ref Input ] ]根据需要删除字符串,将 Input 替换为您需要更改的值。

请注意,堆栈中有一个DummyBucket,因为您需要至少一个用于cloudformation的资源才能部署脚本。

答案 1 :(得分:0)

CloudFormation模板中没有字符串处理功能。

最坏的情况是,您可以创建一个由Lambda支持的自定义资源,它可以转换参数。

答案 2 :(得分:0)

如果我正确地理解了您的查询,则可以采用的一种方法是使用Fn :: Split函数以冒号分隔字符串并使用要使用的数组元素。

答案 3 :(得分:0)

我认为您不能为此目的使用任何现有的Cloudformation method。 您可以利用AWS提供的cloudformation模板示例。这是示例模板String manipulation,提供了字符串转换实用程序功能。您可以轻松地将python method扩展到所需的任何操作。

CLI命令创建堆栈(在本地下载堆栈之后)

aws cloudformation create-stack --stack-name testString --template-body file://string.yaml  --profile your_profile --capabilities CAPABILITY_IAM
arn:aws:cloudformation:us-east-1:1234:stack/testString/ec34d8c0-9fc9-11e9-a0ed-0aa1af63e98c

aws cloudformation create-stack --stack-name testStringExample --template-body file://string_example.yaml  --profile your_profile --capabilities CAPABILITY_AUTO_EXPAND
arn:aws:cloudformation:us-east-1:1234:stack/testStringExample/2047d720-9fca-11e9-ab63-12989ba5c57e

它创建一个s3存储桶并添加各种转换后的标签。验证命令。

aws s3api get-bucket-tagging --bucket teststringexample-s3bucket-1dgnx05oslymu --profile your_profile --output json

{
    "TagSet": [
        {
            "Value": "ring",
            "Key": "ShortenLeft"
        },
        {
            "Value": "his is a test input strin",
            "Key": "Strip"
        },
        {
            "Value": "THIS IS A TEST INPUT STRING",
            "Key": "Upper"
        },
        {
            "Value": "This_is_a_test_input_string",
            "Key": "Replace"
        },
        {
            "Value": "testStringExample",
            "Key": "aws:cloudformation:stack-name"
        },
        {
            "Value": "this is a test input string",
            "Key": "Lower"
        },
        {
            "Value": "This is a test input string",
            "Key": "Capitalize"
        },
        {
            "Value": "This Is A Test Input String",
            "Key": "Title"
        },
        {
            "Value": "S3Bucket",
            "Key": "aws:cloudformation:logical-id"
        },
        {
            "Value": "This",
            "Key": "ShortenRight"
        }
    ]
}