如何使用 AWS Systems Manager Parameter Store 中的参数在 CloudFormation 堆栈之间共享值?

2 分钟阅读
0

当我尝试更新另一个 AWS CloudFormation 堆栈中使用的导出变量时,我收到一条错误消息。错误是:“Cannot update an export variable as it is in use by another stack.”(无法更新导出变量,因为它正在被另一个堆栈使用)

简短描述

要解决此错误,请使用 AWS Systems Manager Parameter Store 中的 SSM 参数在 CloudFormation 堆栈之间共享值。SSM 参数可在一个堆栈(stackA)中存储可由另一个堆栈(stackB)使用的值。

使用 SSM 参数时,两个 CloudFormation 堆栈之间没有依赖关系。这是因为变量存储在 AWS Systems Manager Parameter Store 中。

注意:CloudFormation 支持多种 SSM 参数类型

解决方法

1.    根据以下模板创建一个 CloudFormation 堆栈(例如 stackA):

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

  "Parameters": {

    "AvailabilityZone": {
      "Description": "Amazon EC2 instance Availability Zone",
      "Type": "String"
    },

    "AMIId": {
      "Description": "The Amazon Machine Image id",
      "Type": "String"
    },

    "InstanceType": {
      "Description": "The Type of instance",
      "Type": "String"
    }
  },


  "Resources": {


    "myinstance": {
      "Type": "AWS::EC2::Instance",
      "Properties": {
        "AvailabilityZone": {
          "Fn::GetAtt": ["BasicParameter", "Value"]
        },
        "ImageId": { "Ref": "AMIId" },
        "InstanceType": { "Ref": "InstanceType" }
      }
    },

    "BasicParameter": {
      "Type": "AWS::SSM::Parameter",
      "Properties": {
        "Name": "AvailabilityZone",
        "Type": "String",
        "Value": {
          "Ref": "AvailabilityZone"
        }

      }
    }
  }
}

以上模板创建了一个实例和一个 SSM 参数。该 SSM 参数的值设置为所创建实例的可用区。现在,stackA 会创建一个 SSM 参数仓库,将 Name(名称)设置为 AvailabilityZone,将 Value(值)设置为 us-east-2a

注意:SSM 参数的名称必须唯一。

2.    根据以下模板创建另一个CloudFormation 堆栈(例如 stackB)。

{
  "AWSTemplateFormatVersion": "2010-09-09",
  
  "Parameters": {
    
"AMIId": {
  "Description": "The Amazon Machine Image id",
  "Type": "String"
},

"InstanceType": {
  "Description": "The Type of instance",
  "Type": "String"
}
    
    "AvailabilityZone": {
      "Description": "Amazon EC2 instance Availablity Zone",
      "Type": "AWS::SSM::Parameter::Value<String>",
      "Default": "AvailabilityZone"
    }

  },
  "Mappings": {

  },
  "Conditions": {

  },
  "Resources": {
    "myinstance": {
      "Type": "AWS::EC2::Instance",
      "Properties": {
        "AvailabilityZone": {
          "Ref": "AvailabilityZone"
        },
        "ImageId": { "Ref": "AMIId" },
        "InstanceType": { "Ref": "InstanceType" }
      }
    }
  }
}

以上模板使用由第 1 步中的 stackA 创建的 SSM 参数。

**注意:**要使用此参数,您必须在 stackB 中声明一个参数。将 Type 设置为 AWS::SSM::Parameter::Value<String>。然后,在 us-east-2a 可用区中启动通过 stackB 创建的实例。

3.    要更新 stackA,请将 AvailabilityZone 参数从 us-east-2a 更改为 us-east-2b

4.    在与 stackB 相同的更新可用区中,从 stackA 启动实例。

此时,系统将替换实例并在 us-east-2b 可用区中启动实例。


相关视频

AWS 官方
AWS 官方已更新 2 年前