# 模板标签和版本化
<subtitle>使用标签对模板进行版本控制和管理基于环境的部署</subtitle>

模板版本化允许您使用标签维护同一模板的多个版本。这支持语义版本控制、基于环境的部署和渐进式发布等工作流。

## 标签格式

标签遵循 `name:tag` 格式，其中 `name` 是您的模板标识符，`tag` 是版本标签。

```
my-template:v1.0.0              // 在您的团队内
my-template:production          // 在您的团队内
acme/my-template:v1.0.0         // 完整的命名空间引用
```

## 默认标签

当您构建或引用模板而不指定标签时，UCloud Sandbox 会自动使用 `default` 标签。这意味着：

- `my-template` 等同于 `my-template:default`
- 没有标签的现有模板继续无缝工作

```python
# 这些是等效的
sandbox1 = Sandbox.create('my-template')
sandbox2 = Sandbox.create('my-template:default')
```

## 引用特定构建

除了使用命名标签，您还可以通过直接传递其 `build_id` 从特定构建启动沙箱。当您需要将沙箱固定到确切的构建工件时，这很有用——例如，在调试期间或从已知构建重现问题时。

格式遵循与标签相同的冒号语法：`<template>:<build_id>` 或 `<namespace>/<template>:<build_id>`。

您可以从 `Template.build()` 的返回值或通过使用 `Template.get_tags()` 列出标签找到 `build_id`。

```python
from ucloud_sandbox import Sandbox

# 从特定构建 ID 启动沙箱
sandbox = Sandbox.create('my-template:f47ac10b-58cc-4372-a567-0e02b2c3d479')

# 使用命名空间
sandbox2 = Sandbox.create('acme/my-template:f47ac10b-58cc-4372-a567-0e02b2c3d479')
```

## 使用标签构建

您可以使用一个或多个标签构建模板以创建版本化构建。

### 单个标签

```python
from ucloud_sandbox import Template

# 使用特定版本标签构建
Template.build(template, 'my-template:v1.0.0')
```

### 多个标签

使用多个标签构建，将多个版本标签分配给同一构建工件。

```python
from ucloud_sandbox import Template

# 使用多个指向同一工件的标签构建
Template.build(template, 'my-template', tags=['v1.2.0', 'latest'])
```

## 管理标签

您可以在现有模板构建上管理标签，而无需重新构建。

### 分配标签

将新标签分配给现有构建。当将经过测试的版本提升到生产环境或将版本标记为稳定时，这很有用。

```python
from ucloud_sandbox import Template

# 分配单个标签
Template.assign_tags('my-template:v1.2.0', 'production')

# 一次分配多个标签
Template.assign_tags('my-template:v1.2.0', tags=['production', 'stable'])
```

### 删除标签

从模板中删除标签。底层构建工件仍可通过其他标签访问。

```python
from ucloud_sandbox import Template

# 删除标签
Template.remove_tags('my-template', 'staging')
```

> 删除标签不会删除构建工件。指向同一构建的其他标签将继续工作。

### 列出标签

检索模板的所有标签。每个标签包括标签名称、关联的构建 ID 以及分配标签的时间。

```python
from ucloud_sandbox import Template

tags = Template.get_tags('my-template')
for tag in tags:
    print(f"标签: {tag.tag}, 构建: {tag.build_id}, 创建时间: {tag.created_at}")
```

## 用例

### 语义版本控制

使用语义版本标签跟踪发布并启用回滚。

```python
# 发布版本
Template.build(template, 'api-server:v1.0.0')
Template.build(template, 'api-server:v1.1.0')
Template.build(template, 'api-server:v2.0.0')

# 从特定版本创建沙箱
sandbox = Sandbox.create('api-server:v1.1.0')
```

### 环境标签

为部署管道使用环境标签。

```python
import os

# 构建新版本
Template.build(template, 'my-app:v1.5.0')

# 在环境中推广
Template.assign_tags('my-app:v1.5.0', 'staging')

# 测试后，推广到生产环境
Template.assign_tags('my-app:v1.5.0', 'production')

# 在应用程序中使用
env = os.environ.get('ENV', 'staging')
sandbox = Sandbox.create(f'my-app:{env}')
```

### 最新和稳定标签

维护始终指向特定版本的滚动标签。

```python
# 使用版本和最新标签构建
Template.build(template, 'my-tool', tags=['v3.0.0', 'latest'])

# 将经过测试的版本标记为稳定
Template.assign_tags('my-tool:v2.9.0', 'stable')

# 您可以选择风险承受能力
latest_sandbox = Sandbox.create('my-tool:latest')  # 最新
stable_sandbox = Sandbox.create('my-tool:stable')  # 经过测试
```
