Todos os produtos
Search
Central de documentação

Resource Orchestration Service:ALIYUN::KMS::Secret

Última atualização: Oct 09, 2026

O tipo ALIYUN::KMS::Secret cria um segredo e armazena seu valor na versão inicial.

Sintaxe

{
  "Type": "ALIYUN::KMS::Secret",
  "Properties": {
    "VersionId": String,
    "SecretName": String,
    "Description": String,
    "SecretDataType": String,
    "SecretData": String,
    "VersionStages": List,
    "EncryptionKeyId": String,
    "RecoveryWindowInDays": Integer,
    "ForceDeleteWithoutRecovery": Boolean,
    "SecretType": String,
    "EnableAutomaticRotation": Boolean,
    "RotationInterval": String,
    "ExtendedConfig": Map,
    "DKMSInstanceId": String,
    "Policy": Map,
    "Tags": List
  }
}

Propriedades

Propriedade

Tipo

Obrigatório

Editável

Descrição

Restrições

SecretData

String

Sim

Sim

O valor do segredo recém-criado. O Secrets Manager criptografa e armazena esse valor na versão inicial.

Nenhuma.

SecretName

String

Sim

Não

O nome do segredo.

Nenhuma.

VersionId

String

Sim

Sim

O número da versão inicial.

O número da versão é único dentro do segredo.

Description

String

Não

Sim

A descrição do segredo.

Nenhuma.

DKMSInstanceId

String

Não

Não

O ID da instância do Dedicated KMS.

Nenhuma.

EnableAutomaticRotation

Boolean

Não

Não

Especifica se a rotação automática do segredo será ativada.

Valores válidos:

  • true: ative a rotação automática do segredo.

  • false (padrão): Desativa a rotação automática do segredo.

EncryptionKeyId

String

Não

Não

O identificador da chave mestra do KMS usada para criptografar e proteger o valor do segredo.

Se você não especificar esta propriedade, o Secrets Manager usará uma chave criada pelo sistema para criptografar e proteger os dados do segredo.

Nota

A chave mestra do KMS deve ser uma chave simétrica.

ExtendedConfig

Map

Não

Não

A configuração estendida do segredo.

Nenhuma.

ForceDeleteWithoutRecovery

Boolean

Não

Sim

Especifica se o segredo será excluído à força, sem permitir recuperação.

Valores válidos:

  • true: exclua o segredo à força e não permita a recuperação.

  • false (padrão): não exclua o segredo à força e permita a recuperação.

Policy

Map

Não

Não

A política da chave.

O valor está no formato json e pode ter até 32.768 bytes. Para obter mais informações sobre políticas de chave, consulte Key policy overview. Se você não especificar esta propriedade, a política de segredo padrão será usada. Uma política de chave inclui:

  • Version: a versão da política da chave. Somente a versão 1 é suportada.

  • Statement: as declarações da política da chave. Cada política de chave contém uma ou mais declarações.

O formato da política da chave é:

{
    "Version": "1",
    "Statement": [
        {
            "Sid": "Enable RAM User Permissions",
            "Effect": "Allow",
            "Principal": {
              "RAM": "acs:ram::112890462****:root"
            }
            "Action": [
                "kms:*"
            ],
            "Resource": [
                "*"
            ]
        }
    ]
}

RecoveryWindowInDays

Integer

Não

Sim

Exclui o segredo de forma recuperável e especifica a janela de recuperação.

Valor padrão: 30.

Unidade: dias.

RotationInterval

String

Não

Não

O intervalo para rotação automática do segredo.

O formato é integer[unit], em que integer especifique a duração e unit especifique a unidade de tempo. O único valor aceito para unit é s (segundos). Por exemplo, um intervalo de rotação de sete dias é 604800s.

Nota

Esta propriedade é retornada quando a rotação automática está ativada.

SecretDataType

String

Não

Não

O tipo do valor do segredo.

Valores válidos:

  • text

  • binary

SecretType

String

Não

Não

O tipo do segredo.

Valores válidos:

  • Generic: Um segredo genérico.

  • Rds: Um segredo gerenciado do RDS.

  • RAMCredentials: Um segredo gerenciado do ram.

  • ECS: Um segredo gerenciado do ECS.

Tags

List

Não

Sim

Tags.

É possível adicionar até 20 tags. Para obter mais informações, consulte Tags properties.

VersionStages

List

Não

Sim

Os rótulos de status da versão.

Rótulo padrão: ACSCurrent.

É possível especificar até sete rótulos.

Sintaxe das tags

"Tags": [
  {
    "Key": String,
    "Value": String
  }
]

Propriedades das tags

Propriedade

Tipo

Obrigatório

Editável

Descrição

Restrições

Key

String

Sim

Não

A chave da tag.

A chave da tag tem de 1 a 128 caracteres. Não pode começar com aliyun ou acs:, e não pode conter http:// ou https://.

Value

String

Não

Não

O valor da tag.

O valor da tag tem de 0 a 128 caracteres. Não pode começar com aliyun ou acs:, e não pode conter http:// ou https://.

Valores de retorno

Fn::GetAtt

  • SecretName: O nome do segredo.

  • Arn: O Alibaba Cloud Resource Name (ARN).

Exemplos

Cenário 1: crie um segredo genérico do KMS

# Scenario 1: Create a simple generic KMS secret to store sensitive configuration information.
# Create a simple KMS generic secret for storing sensitive configuration
ROSTemplateFormatVersion: '2015-09-01'
Description:
  zh-cn: Create a simple generic KMS secret to store sensitive configuration information.
  en: Create a simple KMS generic secret for storing sensitive configuration.
Parameters:
  SecretName:
    Type: String
    Label:
      zh-cn: Secret name
      en: Secret Name
    Description:
      zh-cn: The name of the secret.
      en: The name of the secret.
    Default: my-app-secret
  SecretData:
    Type: String
    Label:
      zh-cn: Secret value
      en: Secret Data
    Description:
      zh-cn: The plaintext content of the secret. Secrets Manager encrypts it and stores it in the initial version.
      en: The plaintext content of the secret. Secrets Manager encrypts it and stores it in the initial version.
    NoEcho: true
    Default: my-secret-password-123
  VersionId:
    Type: String
    Label:
      zh-cn: Version number
      en: Version ID
    Description:
      zh-cn: The version number of the initial version. It is unique within the secret.
      en: The version number of the initial secret version. Unique within the secret.
    Default: v1
Resources:
  Secret:
    Type: ALIYUN::KMS::Secret
    Properties:
      SecretName:
        Ref: SecretName
      SecretData:
        Ref: SecretData
      VersionId:
        Ref: VersionId
Outputs:
  SecretName:
    Description:
      zh-cn: The name of the secret.
      en: Secret name.
    Label:
      zh-cn: Secret name
      en: Secret Name
    Value:
      Fn::GetAtt:
        - Secret
        - SecretName
  Arn:
    Description:
      zh-cn: The Alibaba Cloud Resource Name (ARN) of the secret.
      en: The Alibaba Cloud Resource Name (ARN) of the secret.
    Label:
      zh-cn: Secret ARN
      en: Secret ARN
    Value:
      Fn::GetAtt:
        - Secret
        - Arn
Metadata:
  ALIYUN::ROS::Interface:
    ParameterGroups:
      - Parameters:
          - SecretName
          - SecretData
          - VersionId
{
  "ROSTemplateFormatVersion": "2015-09-01",
  "Description": {
    "zh-cn": "Create a simple generic KMS secret to store sensitive configuration information.",
    "en": "Create a simple KMS generic secret for storing sensitive configuration."
  },
  "Parameters": {
    "SecretName": {
      "Type": "String",
      "Label": {
        "zh-cn": "Secret name",
        "en": "Secret Name"
      },
      "Description": {
        "zh-cn": "The name of the secret.",
        "en": "The name of the secret."
      },
      "Default": "my-app-secret"
    },
    "SecretData": {
      "Type": "String",
      "Label": {
        "zh-cn": "Secret value",
        "en": "Secret Data"
      },
      "Description": {
        "zh-cn": "The plaintext content of the secret. Secrets Manager encrypts it and stores it in the initial version.",
        "en": "The plaintext content of the secret. Secrets Manager encrypts it and stores it in the initial version."
      },
      "NoEcho": true,
      "Default": "my-secret-password-123"
    },
    "VersionId": {
      "Type": "String",
      "Label": {
        "zh-cn": "Version number",
        "en": "Version ID"
      },
      "Description": {
        "zh-cn": "The version number of the initial version. It is unique within the secret.",
        "en": "The version number of the initial secret version. Unique within the secret."
      },
      "Default": "v1"
    }
  },
  "Resources": {
    "Secret": {
      "Type": "ALIYUN::KMS::Secret",
      "Properties": {
        "SecretName": {
          "Ref": "SecretName"
        },
        "SecretData": {
          "Ref": "SecretData"
        },
        "VersionId": {
          "Ref": "VersionId"
        }
      }
    }
  },
  "Outputs": {
    "SecretName": {
      "Description": {
        "zh-cn": "The name of the secret.",
        "en": "Secret name."
      },
      "Label": {
        "zh-cn": "Secret name",
        "en": "Secret Name"
      },
      "Value": {
        "Fn::GetAtt": [
          "Secret",
          "SecretName"
        ]
      }
    },
    "Arn": {
      "Description": {
        "zh-cn": "The Alibaba Cloud Resource Name (ARN) of the secret.",
        "en": "The Alibaba Cloud Resource Name (ARN) of the secret."
      },
      "Label": {
        "zh-cn": "Secret ARN",
        "en": "Secret ARN"
      },
      "Value": {
        "Fn::GetAtt": [
          "Secret",
          "Arn"
        ]
      }
    }
  },
  "Metadata": {
    "ALIYUN::ROS::Interface": {
      "ParameterGroups": [
        {
          "Parameters": [
            "SecretName",
            "SecretData",
            "VersionId"
          ]
        }
      ]
    }
  }
}

Cenário 2: crie uma chave personalizada do KMS (CMK) para criptografar um segredo e configure a rotação automática, uma janela de recuperação e tags

# Scenario 2: Create a KMS custom key (CMK) to encrypt a secret and configure automatic rotation, a recovery window, and tags.
# Create a KMS customer master key (CMK) to encrypt a secret with automatic rotation, recovery window and tags
ROSTemplateFormatVersion: '2015-09-01'
Description:
  zh-cn: Create a KMS custom key (CMK), use it to encrypt a secret, and configure automatic rotation, a recovery window, and tags for custom encryption and lifecycle management of the secret.
  en: Create a KMS customer master key (CMK), use it to encrypt a secret with automatic rotation, recovery window and tags for custom encryption and lifecycle management of the secret.
Parameters:
  CommonName:
    Type: String
    Label:
      zh-cn: Resource name prefix
      en: Resource Name Prefix
    Description:
      zh-cn: The common prefix for all resource names.
      en: Unified name prefix for all resources.
    Default: kms-demo
  SecretData:
    Type: String
    Label:
      zh-cn: Secret value
      en: Secret Data
    Description:
      zh-cn: The plaintext content of the secret. Structured data in JSON format is supported.
      en: The plaintext content of the secret. Supports structured data in JSON format.
    NoEcho: true
    Default: '{"username":"app_admin","password":"P@ssw0rd123"}'
  RotationInterval:
    Type: String
    Label:
      zh-cn: Rotation interval
      en: Rotation Interval
    Description:
      zh-cn: The automatic secret rotation interval in the `integer[unit]` format. For example, seven days is 604800s.
      en: The automatic rotation period in the format integer[unit], e.g. 604800s for 7 days.
    Default: 604800s
  RecoveryWindowInDays:
    Type: Number
    Label:
      zh-cn: Recovery window (days)
      en: Recovery Window (Days)
    Description:
      zh-cn: The recovery window in days when you delete the secret in a recoverable manner.
      en: The recovery window in days when deleting the secret in a recoverable manner.
    Default: 30
    MinValue: 1
    MaxValue: 366
Resources:
  KmsKey:
    Type: ALIYUN::KMS::Key
    Properties:
      Description:
        Fn::Sub: Encryption key for ${CommonName} secrets
      KeySpec: Aliyun_AES_256
      KeyUsage: ENCRYPT/DECRYPT
      Enable: true
      EnableAutomaticRotation: true
      RotationInterval: 365d
      PendingWindowInDays: 30
      Tags:
        - Key: Purpose
          Value: SecretEncryption
        - Key: CreatedBy
          Value: ROS
  Secret:
    Type: ALIYUN::KMS::Secret
    DependsOn: KmsKey
    Properties:
      SecretName:
        Fn::Sub: ${CommonName}-app-credential
      SecretData:
        Ref: SecretData
      SecretDataType: text
      VersionId: v1
      VersionStages:
        - ACSCurrent
      EncryptionKeyId:
        Fn::GetAtt:
          - KmsKey
          - KeyId
      Description: Application credential encrypted by custom CMK
      EnableAutomaticRotation: true
      RotationInterval:
        Ref: RotationInterval
      RecoveryWindowInDays:
        Ref: RecoveryWindowInDays
      ForceDeleteWithoutRecovery: false
      SecretType: Generic
      Tags:
        - Key: Environment
          Value: Production
        - Key: ManagedBy
          Value: ROS
Outputs:
  KeyId:
    Description:
      zh-cn: KMS key ID.
      en: KMS key ID.
    Label:
      zh-cn: Key ID
      en: Key ID
    Value:
      Fn::GetAtt:
        - KmsKey
        - KeyId
  SecretName:
    Description:
      zh-cn: The name of the secret.
      en: Secret name.
    Label:
      zh-cn: Secret name
      en: Secret Name
    Value:
      Fn::GetAtt:
        - Secret
        - SecretName
  SecretArn:
    Description:
      zh-cn: The Alibaba Cloud Resource Name (ARN) of the secret.
      en: The ARN of the secret.
    Label:
      zh-cn: Secret ARN
      en: Secret ARN
    Value:
      Fn::GetAtt:
        - Secret
        - Arn
Metadata:
  ALIYUN::ROS::Interface:
    ParameterGroups:
      - Parameters:
          - CommonName
          - SecretData
      - Parameters:
          - RotationInterval
          - RecoveryWindowInDays
{
  "ROSTemplateFormatVersion": "2015-09-01",
  "Description": {
    "zh-cn": "Create a KMS custom key (CMK), use it to encrypt a secret, and configure automatic rotation, a recovery window, and tags for custom encryption and lifecycle management of the secret.",
    "en": "Create a KMS customer master key (CMK), use it to encrypt a secret with automatic rotation, recovery window and tags for custom encryption and lifecycle management of the secret."
  },
  "Parameters": {
    "CommonName": {
      "Type": "String",
      "Label": {
        "zh-cn": "Resource name prefix",
        "en": "Resource Name Prefix"
      },
      "Description": {
        "zh-cn": "The common prefix for all resource names.",
        "en": "Unified name prefix for all resources."
      },
      "Default": "kms-demo"
    },
    "SecretData": {
      "Type": "String",
      "Label": {
        "zh-cn": "Secret value",
        "en": "Secret Data"
      },
      "Description": {
        "zh-cn": "The plaintext content of the secret. Structured data in JSON format is supported.",
        "en": "The plaintext content of the secret. Supports structured data in JSON format."
      },
      "NoEcho": true,
      "Default": "{\"username\":\"app_admin\",\"password\":\"P@ssw0rd123\"}"
    },
    "RotationInterval": {
      "Type": "String",
      "Label": {
        "zh-cn": "Rotation interval",
        "en": "Rotation Interval"
      },
      "Description": {
        "zh-cn": "The automatic secret rotation interval in the `integer[unit]` format. For example, seven days is 604800s.",
        "en": "The automatic rotation period in the format integer[unit], e.g. 604800s for 7 days."
      },
      "Default": "604800s"
    },
    "RecoveryWindowInDays": {
      "Type": "Number",
      "Label": {
        "zh-cn": "Recovery window (days)",
        "en": "Recovery Window (Days)"
      },
      "Description": {
        "zh-cn": "The recovery window in days when you delete the secret in a recoverable manner.",
        "en": "The recovery window in days when deleting the secret in a recoverable manner."
      },
      "Default": 30,
      "MinValue": 1,
      "MaxValue": 366
    }
  },
  "Resources": {
    "KmsKey": {
      "Type": "ALIYUN::KMS::Key",
      "Properties": {
        "Description": {
          "Fn::Sub": "Encryption key for ${CommonName} secrets"
        },
        "KeySpec": "Aliyun_AES_256",
        "KeyUsage": "ENCRYPT/DECRYPT",
        "Enable": true,
        "EnableAutomaticRotation": true,
        "RotationInterval": "365d",
        "PendingWindowInDays": 30,
        "Tags": [
          {
            "Key": "Purpose",
            "Value": "SecretEncryption"
          },
          {
            "Key": "CreatedBy",
            "Value": "ROS"
          }
        ]
      }
    },
    "Secret": {
      "Type": "ALIYUN::KMS::Secret",
      "DependsOn": "KmsKey",
      "Properties": {
        "SecretName": {
          "Fn::Sub": "${CommonName}-app-credential"
        },
        "SecretData": {
          "Ref": "SecretData"
        },
        "SecretDataType": "text",
        "VersionId": "v1",
        "VersionStages": [
          "ACSCurrent"
        ],
        "EncryptionKeyId": {
          "Fn::GetAtt": [
            "KmsKey",
            "KeyId"
          ]
        },
        "Description": "Application credential encrypted by custom CMK",
        "EnableAutomaticRotation": true,
        "RotationInterval": {
          "Ref": "RotationInterval"
        },
        "RecoveryWindowInDays": {
          "Ref": "RecoveryWindowInDays"
        },
        "ForceDeleteWithoutRecovery": false,
        "SecretType": "Generic",
        "Tags": [
          {
            "Key": "Environment",
            "Value": "Production"
          },
          {
            "Key": "ManagedBy",
            "Value": "ROS"
          }
        ]
      }
    }
  },
  "Outputs": {
    "KeyId": {
      "Description": {
        "zh-cn": "KMS key ID.",
        "en": "KMS key ID."
      },
      "Label": {
        "zh-cn": "Key ID",
        "en": "Key ID"
      },
      "Value": {
        "Fn::GetAtt": [
          "KmsKey",
          "KeyId"
        ]
      }
    },
    "SecretName": {
      "Description": {
        "zh-cn": "The name of the secret.",
        "en": "Secret name."
      },
      "Label": {
        "zh-cn": "Secret name",
        "en": "Secret Name"
      },
      "Value": {
        "Fn::GetAtt": [
          "Secret",
          "SecretName"
        ]
      }
    },
    "SecretArn": {
      "Description": {
        "zh-cn": "The Alibaba Cloud Resource Name (ARN) of the secret.",
        "en": "The ARN of the secret."
      },
      "Label": {
        "zh-cn": "Secret ARN",
        "en": "Secret ARN"
      },
      "Value": {
        "Fn::GetAtt": [
          "Secret",
          "Arn"
        ]
      }
    }
  },
  "Metadata": {
    "ALIYUN::ROS::Interface": {
      "ParameterGroups": [
        {
          "Parameters": [
            "CommonName",
            "SecretData"
          ]
        },
        {
          "Parameters": [
            "RotationInterval",
            "RecoveryWindowInDays"
          ]
        }
      ]
    }
  }
}

Cenário 3: crie uma solução completa de gerenciamento de segredos de aplicação (chave do KMS, vários segredos de negócios e uma função de acesso somente leitura do ram) para armazenamento criptografado centralizado de informações confidenciais e controle de acesso com privilégio mínimo

# Scenario 3: Create a complete application secret management solution (KMS key, multiple business secrets, and a RAM read-only access role) for centralized encrypted storage of sensitive information and least privilege access control.
# Create a complete application credential management solution (KMS key + multiple secrets + RAM read-only role) for unified encrypted storage with least-privilege access control
ROSTemplateFormatVersion: '2015-09-01'
Description:
  zh-cn: Create a complete application secret management solution that includes a KMS custom key, multiple business secrets (application configuration, database account, and API key), and a RAM read-only access role for centralized encrypted storage of sensitive information and least privilege access control.
  en: Create a complete application credential management solution including a KMS custom key, multiple business secrets (app config, database account, API key), and a RAM read-only access role, achieving unified encrypted storage of sensitive information with least-privilege access control.
Parameters:
  CommonName:
    Type: String
    Label:
      zh-cn: Resource name prefix
      en: Resource Name Prefix
    Description:
      zh-cn: The common prefix for all resource names.
      en: Unified name prefix for all resources.
    Default: secret-center
  DbUsername:
    Type: String
    Label:
      zh-cn: Database username
      en: Database Username
    Description:
      zh-cn: The username of the database account.
      en: The database account username.
    Default: db_admin
  DbPassword:
    Type: String
    Label:
      zh-cn: Database password
      en: Database Password
    Description:
      zh-cn: The password of the database account.
      en: The database account password.
    NoEcho: true
  ApiKeyValue:
    Type: String
    Label:
      zh-cn: Third-party API key
      en: Third-party API Key
    Description:
      zh-cn: The API key of a third-party service.
      en: The API key of a third-party service.
    NoEcho: true
  RotationInterval:
    Type: String
    Label:
      zh-cn: Rotation interval
      en: Rotation Interval
    Description:
      zh-cn: The automatic secret rotation interval in the `integer[unit]` format.
      en: The automatic rotation period in the format integer[unit].
    Default: 2592000s
Resources:
  KmsKey:
    Type: ALIYUN::KMS::Key
    Properties:
      Description:
        Fn::Sub: Central encryption key for ${CommonName}
      KeySpec: Aliyun_AES_256
      KeyUsage: ENCRYPT/DECRYPT
      Enable: true
      EnableAutomaticRotation: true
      RotationInterval: 365d
      PendingWindowInDays: 30
      DeletionProtection: false
      Tags:
        - Key: Purpose
          Value: CentralSecretEncryption
        - Key: CreatedBy
          Value: ROS
  AppConfigSecret:
    Type: ALIYUN::KMS::Secret
    DependsOn: KmsKey
    Properties:
      SecretName:
        Fn::Sub: ${CommonName}-app-config
      SecretData:
        Fn::Sub: '{"env":"production","log_level":"info","feature_flags":{"new_ui":true,"beta_api":false}}'
      SecretDataType: text
      VersionId: v1
      VersionStages:
        - ACSCurrent
      EncryptionKeyId:
        Fn::GetAtt:
          - KmsKey
          - KeyId
      Description: Application runtime configuration
      EnableAutomaticRotation: false
      RecoveryWindowInDays: 30
      SecretType: Generic
      Tags:
        - Key: SecretCategory
          Value: AppConfig
        - Key: Environment
          Value: Production
  DbCredentialSecret:
    Type: ALIYUN::KMS::Secret
    DependsOn: KmsKey
    Properties:
      SecretName:
        Fn::Sub: ${CommonName}-db-credential
      SecretData:
        Fn::Sub:
          - '{"username":"${User}","password":"${Pass}"}'
          - User:
              Ref: DbUsername
            Pass:
              Ref: DbPassword
      SecretDataType: text
      VersionId: v1
      VersionStages:
        - ACSCurrent
      EncryptionKeyId:
        Fn::GetAtt:
          - KmsKey
          - KeyId
      Description: Database account credential
      EnableAutomaticRotation: true
      RotationInterval:
        Ref: RotationInterval
      RecoveryWindowInDays: 30
      SecretType: Generic
      Tags:
        - Key: SecretCategory
          Value: Database
        - Key: Environment
          Value: Production
  ApiKeySecret:
    Type: ALIYUN::KMS::Secret
    DependsOn: KmsKey
    Properties:
      SecretName:
        Fn::Sub: ${CommonName}-api-key
      SecretData:
        Fn::Sub:
          - '{"api_key":"${ApiKey}","provider":"third-party-service"}'
          - ApiKey:
              Ref: ApiKeyValue
      SecretDataType: text
      VersionId: v1
      VersionStages:
        - ACSCurrent
      EncryptionKeyId:
        Fn::GetAtt:
          - KmsKey
          - KeyId
      Description: Third-party API key credential
      EnableAutomaticRotation: true
      RotationInterval:
        Ref: RotationInterval
      RecoveryWindowInDays: 30
      SecretType: Generic
      Tags:
        - Key: SecretCategory
          Value: ApiKey
        - Key: Environment
          Value: Production
  SecretReaderRole:
    Type: ALIYUN::RAM::Role
    Properties:
      RoleName:
        Fn::Sub: ${CommonName}-secret-reader
      Description: Read-only role for accessing business secrets
      AssumeRolePolicyDocument:
        Version: '1'
        Statement:
          - Action: sts:AssumeRole
            Effect: Allow
            Principal:
              Service:
                - ecs.aliyuncs.com
      Policies:
        - PolicyName: SecretReadOnlyAccess
          PolicyDocument:
            Version: '1'
            Statement:
              - Action:
                  - kms:GetSecretValue
                  - kms:DescribeSecret
                  - kms:ListSecrets
                  - kms:ListSecretVersionIds
                Resource:
                  - Fn::GetAtt:
                      - AppConfigSecret
                      - Arn
                  - Fn::GetAtt:
                      - DbCredentialSecret
                      - Arn
                  - Fn::GetAtt:
                      - ApiKeySecret
                      - Arn
                Effect: Allow
              - Action:
                  - kms:Decrypt
                Resource:
                  - Fn::Sub: acs:kms:${ALIYUN::Region}:${ALIYUN::TenantId}:key/*
                Effect: Allow
                Condition:
                  StringEquals:
                    kms:EncryptionContextKey:
                      - secret
Outputs:
  KeyId:
    Description:
      zh-cn: KMS key ID.
      en: KMS key ID.
    Label:
      zh-cn: Key ID
      en: Key ID
    Value:
      Fn::GetAtt:
        - KmsKey
        - KeyId
  AppConfigSecretArn:
    Description:
      zh-cn: Application configuration secret ARN.
      en: App config secret ARN.
    Label:
      zh-cn: Application configuration secret ARN
      en: App Config Secret ARN
    Value:
      Fn::GetAtt:
        - AppConfigSecret
        - Arn
  DbCredentialSecretArn:
    Description:
      zh-cn: Database secret ARN.
      en: Database credential secret ARN.
    Label:
      zh-cn: Database secret ARN
      en: DB Credential Secret ARN
    Value:
      Fn::GetAtt:
        - DbCredentialSecret
        - Arn
  ApiKeySecretArn:
    Description:
      zh-cn: API key secret ARN.
      en: API key secret ARN.
    Label:
      zh-cn: API key secret ARN
      en: API Key Secret ARN
    Value:
      Fn::GetAtt:
        - ApiKeySecret
        - Arn
  SecretReaderRoleArn:
    Description:
      zh-cn: Read-only access role ARN for secrets.
      en: Secret reader role ARN.
    Label:
      zh-cn: Read-only role ARN
      en: Secret Reader Role ARN
    Value:
      Fn::GetAtt:
        - SecretReaderRole
        - Arn
Metadata:
  ALIYUN::ROS::Interface:
    ParameterGroups:
      - Parameters:
          - CommonName
          - RotationInterval
      - Parameters:
          - DbUsername
          - DbPassword
          - ApiKeyValue
{
  "ROSTemplateFormatVersion": "2015-09-01",
  "Description": {
    "zh-cn": "Create a complete application secret management solution that includes a KMS custom key, multiple business secrets (application configuration, database account, and API key), and a RAM read-only access role for centralized encrypted storage of sensitive information and least privilege access control.",
    "en": "Create a complete application credential management solution including a KMS custom key, multiple business secrets (app config, database account, API key), and a RAM read-only access role, achieving unified encrypted storage of sensitive information with least-privilege access control."
  },
  "Parameters": {
    "CommonName": {
      "Type": "String",
      "Label": {
        "zh-cn": "Resource name prefix",
        "en": "Resource Name Prefix"
      },
      "Description": {
        "zh-cn": "The common prefix for all resource names.",
        "en": "Unified name prefix for all resources."
      },
      "Default": "secret-center"
    },
    "DbUsername": {
      "Type": "String",
      "Label": {
        "zh-cn": "Database username",
        "en": "Database Username"
      },
      "Description": {
        "zh-cn": "The username of the database account.",
        "en": "The database account username."
      },
      "Default": "db_admin"
    },
    "DbPassword": {
      "Type": "String",
      "Label": {
        "zh-cn": "Database password",
        "en": "Database Password"
      },
      "Description": {
        "zh-cn": "The password of the database account.",
        "en": "The database account password."
      },
      "NoEcho": true
    },
    "ApiKeyValue": {
      "Type": "String",
      "Label": {
        "zh-cn": "Third-party API key",
        "en": "Third-party API Key"
      },
      "Description": {
        "zh-cn": "The API key of a third-party service.",
        "en": "The API key of a third-party service."
      },
      "NoEcho": true
    },
    "RotationInterval": {
      "Type": "String",
      "Label": {
        "zh-cn": "Rotation interval",
        "en": "Rotation Interval"
      },
      "Description": {
        "zh-cn": "The automatic secret rotation interval in the `integer[unit]` format.",
        "en": "The automatic rotation period in the format integer[unit]."
      },
      "Default": "2592000s"
    }
  },
  "Resources": {
    "KmsKey": {
      "Type": "ALIYUN::KMS::Key",
      "Properties": {
        "Description": {
          "Fn::Sub": "Central encryption key for ${CommonName}"
        },
        "KeySpec": "Aliyun_AES_256",
        "KeyUsage": "ENCRYPT/DECRYPT",
        "Enable": true,
        "EnableAutomaticRotation": true,
        "RotationInterval": "365d",
        "PendingWindowInDays": 30,
        "DeletionProtection": false,
        "Tags": [
          {
            "Key": "Purpose",
            "Value": "CentralSecretEncryption"
          },
          {
            "Key": "CreatedBy",
            "Value": "ROS"
          }
        ]
      }
    },
    "AppConfigSecret": {
      "Type": "ALIYUN::KMS::Secret",
      "DependsOn": "KmsKey",
      "Properties": {
        "SecretName": {
          "Fn::Sub": "${CommonName}-app-config"
        },
        "SecretData": {
          "Fn::Sub": "{\"env\":\"production\",\"log_level\":\"info\",\"feature_flags\":{\"new_ui\":true,\"beta_api\":false}}"
        },
        "SecretDataType": "text",
        "VersionId": "v1",
        "VersionStages": [
          "ACSCurrent"
        ],
        "EncryptionKeyId": {
          "Fn::GetAtt": [
            "KmsKey",
            "KeyId"
          ]
        },
        "Description": "Application runtime configuration",
        "EnableAutomaticRotation": false,
        "RecoveryWindowInDays": 30,
        "SecretType": "Generic",
        "Tags": [
          {
            "Key": "SecretCategory",
            "Value": "AppConfig"
          },
          {
            "Key": "Environment",
            "Value": "Production"
          }
        ]
      }
    },
    "DbCredentialSecret": {
      "Type": "ALIYUN::KMS::Secret",
      "DependsOn": "KmsKey",
      "Properties": {
        "SecretName": {
          "Fn::Sub": "${CommonName}-db-credential"
        },
        "SecretData": {
          "Fn::Sub": [
            "{\"username\":\"${User}\",\"password\":\"${Pass}\"}",
            {
              "User": {
                "Ref": "DbUsername"
              },
              "Pass": {
                "Ref": "DbPassword"
              }
            }
          ]
        },
        "SecretDataType": "text",
        "VersionId": "v1",
        "VersionStages": [
          "ACSCurrent"
        ],
        "EncryptionKeyId": {
          "Fn::GetAtt": [
            "KmsKey",
            "KeyId"
          ]
        },
        "Description": "Database account credential",
        "EnableAutomaticRotation": true,
        "RotationInterval": {
          "Ref": "RotationInterval"
        },
        "RecoveryWindowInDays": 30,
        "SecretType": "Generic",
        "Tags": [
          {
            "Key": "SecretCategory",
            "Value": "Database"
          },
          {
            "Key": "Environment",
            "Value": "Production"
          }
        ]
      }
    },
    "ApiKeySecret": {
      "Type": "ALIYUN::KMS::Secret",
      "DependsOn": "KmsKey",
      "Properties": {
        "SecretName": {
          "Fn::Sub": "${CommonName}-api-key"
        },
        "SecretData": {
          "Fn::Sub": [
            "{\"api_key\":\"${ApiKey}\",\"provider\":\"third-party-service\"}",
            {
              "ApiKey": {
                "Ref": "ApiKeyValue"
              }
            }
          ]
        },
        "SecretDataType": "text",
        "VersionId": "v1",
        "VersionStages": [
          "ACSCurrent"
        ],
        "EncryptionKeyId": {
          "Fn::GetAtt": [
            "KmsKey",
            "KeyId"
          ]
        },
        "Description": "Third-party API key credential",
        "EnableAutomaticRotation": true,
        "RotationInterval": {
          "Ref": "RotationInterval"
        },
        "RecoveryWindowInDays": 30,
        "SecretType": "Generic",
        "Tags": [
          {
            "Key": "SecretCategory",
            "Value": "ApiKey"
          },
          {
            "Key": "Environment",
            "Value": "Production"
          }
        ]
      }
    },
    "SecretReaderRole": {
      "Type": "ALIYUN::RAM::Role",
      "Properties": {
        "RoleName": {
          "Fn::Sub": "${CommonName}-secret-reader"
        },
        "Description": "Read-only role for accessing business secrets",
        "AssumeRolePolicyDocument": {
          "Version": "1",
          "Statement": [
            {
              "Action": "sts:AssumeRole",
              "Effect": "Allow",
              "Principal": {
                "Service": [
                  "ecs.aliyuncs.com"
                ]
              }
            }
          ]
        },
        "Policies": [
          {
            "PolicyName": "SecretReadOnlyAccess",
            "PolicyDocument": {
              "Version": "1",
              "Statement": [
                {
                  "Action": [
                    "kms:GetSecretValue",
                    "kms:DescribeSecret",
                    "kms:ListSecrets",
                    "kms:ListSecretVersionIds"
                  ],
                  "Resource": [
                    {
                      "Fn::GetAtt": [
                        "AppConfigSecret",
                        "Arn"
                      ]
                    },
                    {
                      "Fn::GetAtt": [
                        "DbCredentialSecret",
                        "Arn"
                      ]
                    },
                    {
                      "Fn::GetAtt": [
                        "ApiKeySecret",
                        "Arn"
                      ]
                    }
                  ],
                  "Effect": "Allow"
                },
                {
                  "Action": [
                    "kms:Decrypt"
                  ],
                  "Resource": [
                    {
                      "Fn::Sub": "acs:kms:${ALIYUN::Region}:${ALIYUN::TenantId}:key/*"
                    }
                  ],
                  "Effect": "Allow",
                  "Condition": {
                    "StringEquals": {
                      "kms:EncryptionContextKey": [
                        "secret"
                      ]
                    }
                  }
                }
              ]
            }
          }
        ]
      }
    }
  },
  "Outputs": {
    "KeyId": {
      "Description": {
        "zh-cn": "KMS key ID.",
        "en": "KMS key ID."
      },
      "Label": {
        "zh-cn": "Key ID",
        "en": "Key ID"
      },
      "Value": {
        "Fn::GetAtt": [
          "KmsKey",
          "KeyId"
        ]
      }
    },
    "AppConfigSecretArn": {
      "Description": {
        "zh-cn": "Application configuration secret ARN.",
        "en": "App config secret ARN."
      },
      "Label": {
        "zh-cn": "Application configuration secret ARN",
        "en": "App Config Secret ARN"
      },
      "Value": {
        "Fn::GetAtt": [
          "AppConfigSecret",
          "Arn"
        ]
      }
    },
    "DbCredentialSecretArn": {
      "Description": {
        "zh-cn": "Database secret ARN.",
        "en": "Database credential secret ARN."
      },
      "Label": {
        "zh-cn": "Database secret ARN",
        "en": "DB Credential Secret ARN"
      },
      "Value": {
        "Fn::GetAtt": [
          "DbCredentialSecret",
          "Arn"
        ]
      }
    },
    "ApiKeySecretArn": {
      "Description": {
        "zh-cn": "API key secret ARN.",
        "en": "API key secret ARN."
      },
      "Label": {
        "zh-cn": "API key secret ARN",
        "en": "API Key Secret ARN"
      },
      "Value": {
        "Fn::GetAtt": [
          "ApiKeySecret",
          "Arn"
        ]
      }
    },
    "SecretReaderRoleArn": {
      "Description": {
        "zh-cn": "Read-only access role ARN for secrets.",
        "en": "Secret reader role ARN."
      },
      "Label": {
        "zh-cn": "Read-only role ARN",
        "en": "Secret Reader Role ARN"
      },
      "Value": {
        "Fn::GetAtt": [
          "SecretReaderRole",
          "Arn"
        ]
      }
    }
  },
  "Metadata": {
    "ALIYUN::ROS::Interface": {
      "ParameterGroups": [
        {
          "Parameters": [
            "CommonName",
            "RotationInterval"
          ]
        },
        {
          "Parameters": [
            "DbUsername",
            "DbPassword",
            "ApiKeyValue"
          ]
        }
      ]
    }
  }
}