

這是 AWS CDK v2 開發人員指南。較舊的 CDK v1 已於 2022 年 6 月 1 日進入維護，並於 2023 年 6 月 1 日結束支援。

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# 標籤和 AWS CDK
<a name="tagging"></a>

標籤是您可以新增至 AWS CDK 應用程式中建構的資訊鍵/值元素。套用至指定建構的標籤也會套用至其所有可標記的子系。標籤會包含在從您的應用程式合成的 AWS CloudFormation 範本中，並套用至其部署 AWS 的資源。您可以使用標籤來識別和分類 資源，目的如下：
+ 簡化管理
+ 成本分配
+ 存取控制
+ 您設計的任何其他目的

**提示**  
如需如何搭配 AWS 資源使用標籤的詳細資訊，請參閱* AWS 白皮書*中的[標記 AWS 資源的最佳實務](https://docs.aws.amazon.com/whitepapers/latest/tagging-best-practices/tagging-best-practices.html)。

## 使用標籤
<a name="tagging-use"></a>

[標籤](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.Tags.html)類別包含靜態方法 `of()`，您可以透過此方法將標籤新增至指定的建構，或從中移除標籤。
+  [https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.Tags.html#addkey-value-props](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.Tags.html#addkey-value-props) 會將新標籤套用至指定的建構模組及其所有子系。
+  [https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.Tags.html#removekey-props](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.Tags.html#removekey-props) 會從指定的建構模組及其任何子系中移除標籤，包括子建構可能已套用至其本身的標籤。

**注意**  
使用 [Aspects 和 AWS CDK](aspects.md) 實作標記。Aspects 是將 操作 （例如標記） 套用至指定範圍內所有建構體的一種方式。

下列範例會將具有 **值**的標籤**索引鍵**套用至建構。

**Example**  

```
Tags.of(myConstruct).add('key', 'value');
```

```
Tags.of(myConstruct).add('key', 'value');
```

```
Tags.of(my_construct).add("key", "value")
```

```
Tags.of(myConstruct).add("key", "value");
```

```
Tags.Of(myConstruct).Add("key", "value");
```

```
awscdk.Tags_Of(myConstruct).Add(jsii.String("key"), jsii.String("value"), &awscdk.TagProps{})
```

下列範例會從建構中刪除標籤**索引鍵**。

**Example**  

```
Tags.of(myConstruct).remove('key');
```

```
Tags.of(myConstruct).remove('key');
```

```
Tags.of(my_construct).remove("key")
```

```
Tags.of(myConstruct).remove("key");
```

```
Tags.Of(myConstruct).Remove("key");
```

```
awscdk.Tags_Of(myConstruct).Remove(jsii.String("key"), &awscdk.TagProps{})
```

如果您使用的是 `Stage` 建構，請在`Stage`關卡或以下套用標籤。標籤不會跨`Stage`邊界套用。

## 標籤優先順序
<a name="tagging-priorities"></a>

 AWS CDK 會以遞迴方式套用和移除標籤。如果有衝突，具有最高優先順序的標記操作會獲勝。（優先順序是使用選用`priority`屬性設定。) 如果兩個操作的優先順序相同，則最接近建構樹底部的標記操作會獲勝。根據預設，套用標籤的優先順序為 100 （直接新增至 An AWS CloudFormation 資源的標籤除外，其優先順序為 50)。移除標籤的預設優先順序為 200。

下列會將優先順序為 300 的標籤套用至建構。

**Example**  

```
Tags.of(myConstruct).add('key', 'value', {
  priority: 300
});
```

```
Tags.of(myConstruct).add('key', 'value', {
  priority: 300
});
```

```
Tags.of(my_construct).add("key", "value", priority=300)
```

```
Tags.of(myConstruct).add("key", "value", TagProps.builder()
        .priority(300).build());
```

```
Tags.Of(myConstruct).Add("key", "value", new TagProps { Priority = 300 });
```

```
awscdk.Tags_Of(myConstruct).Add(jsii.String("key"), jsii.String("value"), &awscdk.TagProps{
  Priority: jsii.Number(300),
})
```

## 可選屬性
<a name="tagging-props"></a>

標籤支援[https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.TagProps.html](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.TagProps.html)微調標籤套用或移除資源的方式。所有屬性皆是選用。

 `applyToLaunchedInstances` (Python：`apply_to_launched_instances`)  
僅適用於 add()。根據預設，標籤會套用至 Auto Scaling 群組中啟動的執行個體。將此屬性設定為 **false**，以忽略 Auto Scaling 群組中啟動的執行個體。

 `includeResourceTypes`/`excludeResourceTypes` (Python：`include_resource_types`/`exclude_resource_types`)  
根據 AWS CloudFormation 資源類型，使用這些標籤僅在資源子集上操作標籤。根據預設，操作會套用至建構子樹狀結構中的所有資源，但您可以透過包含或排除特定資源類型來變更此操作。如果同時指定兩者，則排除優先於包含。

 `priority`   
使用此項目可設定此操作與其他 `Tags.add()`和 `Tags.remove()`操作的優先順序。較高的值優先於較低的值。新增操作的預設值為 100 （直接套用至 AWS CloudFormation 資源的標籤為 50)，移除操作為 200。

下列範例會將**值**為 且優先順序為 **100** 的標籤**標籤名稱**套用至 建構中的 類型 ** AWS：：Xxx：：Yyy**。它不會將標籤套用至在 Amazon EC2 Auto Scaling 群組中啟動的執行個體，或類型為 ** AWS：：Xxx：：Zzz **的資源。（這些是兩種任意但不同的 AWS CloudFormation 資源類型的預留位置。)

**Example**  

```
Tags.of(myConstruct).add('tagname', 'value', {
  applyToLaunchedInstances: false,
  includeResourceTypes: ['AWS::Xxx::Yyy'],
  excludeResourceTypes: ['AWS::Xxx::Zzz'],
  priority: 100,
});
```

```
Tags.of(myConstruct).add('tagname', 'value', {
  applyToLaunchedInstances: false,
  includeResourceTypes: ['AWS::Xxx::Yyy'],
  excludeResourceTypes: ['AWS::Xxx::Zzz'],
  priority: 100
});
```

```
Tags.of(my_construct).add("tagname", "value",
    apply_to_launched_instances=False,
    include_resource_types=["AWS::Xxx::Yyy"],
    exclude_resource_types=["AWS::Xxx::Zzz"],
    priority=100)
```

```
Tags.of(myConstruct).add("tagname", "value", TagProps.builder()
                .applyToLaunchedInstances(false)
                .includeResourceTypes(Arrays.asList("AWS::Xxx::Yyy"))
                .excludeResourceTypes(Arrays.asList("AWS::Xxx::Zzz"))
                .priority(100).build());
```

```
Tags.Of(myConstruct).Add("tagname", "value", new TagProps
{
    ApplyToLaunchedInstances = false,
    IncludeResourceTypes = ["AWS::Xxx::Yyy"],
    ExcludeResourceTypes = ["AWS::Xxx::Zzz"],
    Priority = 100
});
```

```
awscdk.Tags_Of(myConstruct).Add(jsii.String("tagname"), jsii.String("value"), &awscdk.TagProps{
  ApplyToLaunchedInstances: jsii.Bool(false),
  IncludeResourceTypes:     &[]*string{jsii.String("AWS::Xxx:Yyy")},
  ExcludeResourceTypes:     &[]*string{jsii.String("AWS::Xxx:Zzz")},
  Priority:                 jsii.Number(100),
})
```

下列範例會從建構中類型為 ** AWS：：Xxx：：Yyy **的資源中移除優先順序為 **200** 的標籤**標籤名稱**，但不會從類型為 ** AWS：：Xxx：：Zzz **的資源移除。

**Example**  

```
Tags.of(myConstruct).remove('tagname', {
  includeResourceTypes: ['AWS::Xxx::Yyy'],
  excludeResourceTypes: ['AWS::Xxx::Zzz'],
  priority: 200,
});
```

```
Tags.of(myConstruct).remove('tagname', {
  includeResourceTypes: ['AWS::Xxx::Yyy'],
  excludeResourceTypes: ['AWS::Xxx::Zzz'],
  priority: 200
});
```

```
Tags.of(my_construct).remove("tagname",
    include_resource_types=["AWS::Xxx::Yyy"],
    exclude_resource_types=["AWS::Xxx::Zzz"],
    priority=200,)
```

```
Tags.of((myConstruct).remove("tagname", TagProps.builder()
        .includeResourceTypes(Arrays.asList("AWS::Xxx::Yyy"))
        .excludeResourceTypes(Arrays.asList("AWS::Xxx::Zzz"))
        .priority(100).build());
        )
```

```
Tags.Of(myConstruct).Remove("tagname", new TagProps
{
    IncludeResourceTypes = ["AWS::Xxx::Yyy"],
    ExcludeResourceTypes = ["AWS::Xxx::Zzz"],
    Priority = 100
});
```

```
awscdk.Tags_Of(myConstruct).Remove(jsii.String("tagname"), &awscdk.TagProps{
  IncludeResourceTypes: &[]*string{jsii.String("AWS::Xxx:Yyy")},
  ExcludeResourceTypes: &[]*string{jsii.String("AWS::Xxx:Zzz")},
  Priority:             jsii.Number(200),
})
```

## 範例
<a name="tagging-example"></a>

下列範例會將值為 **TheBest** 的標籤索引鍵 **StackType** 新增至`Stack`名為 的任何資源`MarketingSystem`。然後，它會再次將其從 Amazon EC2 VPC 子網路以外的所有資源中移除。結果是只有子網路已套用 標籤。

**Example**  

```
import { App, Stack, Tags } from 'aws-cdk-lib';

const app = new App();
const theBestStack = new Stack(app, 'MarketingSystem');

// Add a tag to all constructs in the stack
Tags.of(theBestStack).add('StackType', 'TheBest');

// Remove the tag from all resources except subnet resources
Tags.of(theBestStack).remove('StackType', {
  excludeResourceTypes: ['AWS::EC2::Subnet']
});
```

```
const { App, Stack, Tags } = require('aws-cdk-lib');

const app = new App();
const theBestStack = new Stack(app, 'MarketingSystem');

// Add a tag to all constructs in the stack
Tags.of(theBestStack).add('StackType', 'TheBest');

// Remove the tag from all resources except subnet resources
Tags.of(theBestStack).remove('StackType', {
  excludeResourceTypes: ['AWS::EC2::Subnet']
});
```

```
from aws_cdk import App, Stack, Tags

app = App();
the_best_stack = Stack(app, 'MarketingSystem')

# Add a tag to all constructs in the stack
Tags.of(the_best_stack).add("StackType", "TheBest")

# Remove the tag from all resources except subnet resources
Tags.of(the_best_stack).remove("StackType",
    exclude_resource_types=["AWS::EC2::Subnet"])
```

```
import software.amazon.awscdk.App;
import software.amazon.awscdk.Tags;

// Add a tag to all constructs in the stack
Tags.of(theBestStack).add("StackType", "TheBest");

// Remove the tag from all resources except subnet resources
Tags.of(theBestStack).remove("StackType", TagProps.builder()
        .excludeResourceTypes(Arrays.asList("AWS::EC2::Subnet"))
        .build());
```

```
using Amazon.CDK;

var app = new App();
var theBestStack = new Stack(app, 'MarketingSystem');

// Add a tag to all constructs in the stack
Tags.Of(theBestStack).Add("StackType", "TheBest");

// Remove the tag from all resources except subnet resources
Tags.Of(theBestStack).Remove("StackType", new TagProps
{
    ExcludeResourceTypes = ["AWS::EC2::Subnet"]
});
```

```
import "github.com/aws/aws-cdk-go/awscdk/v2"
app := awscdk.NewApp(nil)
theBestStack := awscdk.NewStack(app, jsii.String("MarketingSystem"), &awscdk.StackProps{})

// Add a tag to all constructs in the stack
awscdk.Tags_Of(theBestStack).Add(jsii.String("StackType"), jsii.String("TheBest"), &awscdk.TagProps{})

// Remove the tag from all resources except subnet resources
awscdk.Tags_Of(theBestStack).Add(jsii.String("StackType"), jsii.String("TheBest"), &awscdk.TagProps{
  ExcludeResourceTypes: &[]*string{jsii.String("AWS::EC2::Subnet")},
})
```

下列程式碼達到相同的結果。考慮哪種方法 （包含或排除） 讓您的意圖更清楚。

**Example**  

```
Tags.of(theBestStack).add('StackType', 'TheBest',
  { includeResourceTypes: ['AWS::EC2::Subnet']});
```

```
Tags.of(theBestStack).add('StackType', 'TheBest',
  { includeResourceTypes: ['AWS::EC2::Subnet']});
```

```
Tags.of(the_best_stack).add("StackType", "TheBest",
    include_resource_types=["AWS::EC2::Subnet"])
```

```
Tags.of(theBestStack).add("StackType", "TheBest", TagProps.builder()
        .includeResourceTypes(Arrays.asList("AWS::EC2::Subnet"))
        .build());
```

```
Tags.Of(theBestStack).Add("StackType", "TheBest", new TagProps {
    IncludeResourceTypes = ["AWS::EC2::Subnet"]
});
```

```
awscdk.Tags_Of(theBestStack).Add(jsii.String("StackType"), jsii.String("TheBest"), &awscdk.TagProps{
  IncludeResourceTypes: &[]*string{jsii.String("AWS::EC2::Subnet")},
})
```

## 標記單一建構
<a name="tagging-single"></a>

 `Tags.of(scope).add(key, value)` 是將標籤新增至 AWS CDK 中建構體的標準方法。它的樹行行為，在給定範圍內以遞迴方式標記所有可標記的資源，幾乎總是您想要的。不過，有時您需要標記特定、任意的建構 （或建構）。

這種情況涉及套用標籤，其值衍生自要標記之建構的某些屬性。標準標記方法會以遞迴方式將相同的索引鍵和值套用至範圍內的所有相符資源。不過，此處每個標記建構的值可能不同。

標籤使用 [層面](aspects.md)實作，而 CDK 會在您使用 指定的範圍內呼叫每個建構的標籤`visit()`方法`Tags.of(scope)`。我們可以`Tag.visit()`直接呼叫 ，將標籤套用至單一建構。

**Example**  

```
new cdk.Tag(key, value).visit(scope);
```

```
new cdk.Tag(key, value).visit(scope);
```

```
cdk.Tag(key, value).visit(scope)
```

```
Tag.Builder.create(key, value).build().visit(scope);
```

```
new Tag(key, value).Visit(scope);
```

```
awscdk.NewTag(key, value, &awscdk.TagProps{}).Visit(scope)
```

您可以標記範圍內的所有建構，但讓標籤的值衍生自每個建構的屬性。若要這樣做，請撰寫一個 面向，並在該面向的 `visit()`方法中套用標籤，如上述範例所示。然後，使用 將 面向新增至所需的範圍`Aspects.of(scope).add(aspect)`。

下列範例會將標籤套用至堆疊中包含資源路徑的每個資源。

**Example**  

```
class PathTagger implements cdk.IAspect {
  visit(node: IConstruct) {
    new cdk.Tag("aws-cdk-path", node.node.path).visit(node);
  }
}

stack = new MyStack(app);
cdk.Aspects.of(stack).add(new PathTagger())
```

```
class PathTagger {
  visit(node) {
    new cdk.Tag("aws-cdk-path", node.node.path).visit(node);
  }
}

stack = new MyStack(app);
cdk.Aspects.of(stack).add(new PathTagger())
```

```
@jsii.implements(cdk.IAspect)
class PathTagger:
    def visit(self, node: IConstruct):
        cdk.Tag("aws-cdk-path", node.node.path).visit(node)

stack = MyStack(app)
cdk.Aspects.of(stack).add(PathTagger())
```

```
final class PathTagger implements IAspect {
	public void visit(IConstruct node) {
		Tag.Builder.create("aws-cdk-path", node.getNode().getPath()).build().visit(node);
	}
}

stack stack = new MyStack(app);
Aspects.of(stack).add(new PathTagger());
```

```
public class PathTagger : IAspect
{
    public void Visit(IConstruct node)
    {
        new Tag("aws-cdk-path", node.Node.Path).Visit(node);
    }
}

var stack = new MyStack(app);
Aspects.Of(stack).Add(new PathTagger);
```

**提示**  
有條件標記的邏輯，包括優先順序、資源類型等，都內建在 `Tag`類別中。您可以在將標籤套用至任意資源時使用這些功能；如果不符合條件，則不會套用標籤。此外，`Tag`類別只會標記可標記的資源，因此您不需要在套用標籤之前測試建構是否可標記。