如何使用 AWS Systems Manager Parameter Store 中的參數在 CloudFormation 堆疊之間共用值?

2 分的閱讀內容
0

當我嘗試更新另一個 AWS CloudFormation 堆疊使用的匯出變數時,收到錯誤訊息。錯誤是: 「無法更新匯出變數,因為正在被另一堆疊使用。」

簡短描述

若要解決此錯誤,請利用 AWS Systems Manager Parameter Store 中的 SSM 參數在 CloudFormation 堆疊之間共用值。SSM 參數儲存在另一堆疊 (stackB) 可以使用的一個堆疊 (stackA) 中。

當您使用 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 Parameter Store,其 Name 設定為 AvailabilityZoneValue 設定為 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"
        }
      }
    }
  }
}

此範本使用 stackA 在步驟 1 中建立的 SSM 參數。

**注意:**若要使用此參數,您必須在 stackB 宣告參數。將 Type 設定為 AWS::SSM::Parameter::Value<String>。由 stackB 建立的執行個體接著會在 us-east-2a 可用區域中啟動。

3.    若要更新 stackA,請將 AvailabilityZone 參數從 us-east-2a 變更為 us-east-2b

4.    在與 stackB 相同的更新可用區域中從 stackA 啟動執行個體。執行個體會被取代並在 us-east-2b 可用區域中啟動。

AWS 官方
AWS 官方已更新 9 個月前