LoginSignup
4
3

More than 1 year has passed since last update.

aws-cdkでリソースにタグを追加・上書きしたい

Posted at

cdkを使ってリソース定義しようとしたらメソッドにtagsが用意されてない!でもCloudformationでは対応してるよ〜っていうときにタグを入れる方法
リソース名が気に入らないときの上書きにも使える

①Aspects.ofを使う

ネットワークACLにNameタグをつける例

stack.py
# vpcの定義は省略
nacl = ec2.NetworkAcl(self, 'id',
    vpc=vpc,
    subnet_selection=ec2.SubnetSelection(
    subnet_type=ec2.SubnetType.PUBLIC
    ),
    network_acl_name='nacl'
    )
core.Aspects.of(nacl).add(core.Tag("Name", 'your-public-nacl'))

サブネットにまとめてNameタグをつける例

stack.py
vpc = ec2.Vpc(self, 'vpc',
                max_azs=2,
                cidr='10.0.0.0/24',
                subnet_configuration=[ec2.SubnetConfiguration(
                    subnet_type=ec2.SubnetType.PRIVATE,
                    name="Private",
                    cidr_mask=27
                ), ec2.SubnetConfiguration(
                    subnet_type=ec2.SubnetType.ISOLATED,
                    name="Isolated",
                    cidr_mask=27
                ), ec2.SubnetConfiguration(
                    subnet_type=ec2.SubnetType.PUBLIC,
                    name='Public',
                    cidr_mask=27,
                )
                ],
                )
subnets_list = [vpc.public_subnets, vpc.private_subnets, vpc.isolated_subnets]
for subnets in subnets_list:
    for isubnet in subnets:
        core.Aspects.of(isubnet).add(core.Tag("Name", 'your-subnet-name'))

②apply_aspectを使う (古いversionの人向け)

ネットワークACLにNameタグをつける例

stack.py
# vpcの定義は省略
nacl = ec2.NetworkAcl(self, 'id',
    vpc=vpc,
    subnet_selection=ec2.SubnetSelection(
    subnet_type=ec2.SubnetType.PUBLIC
    ),
    network_acl_name='nacl'
    )
nacl.node.apply_aspect(core.Tag("Name", 'your-public-nacl'))

サブネットにまとめてNameタグをつける例

stack.py
vpc = ec2.Vpc(self, 'vpc',
                max_azs=2,
                cidr='10.0.0.0/24',
                subnet_configuration=[ec2.SubnetConfiguration(
                    subnet_type=ec2.SubnetType.PRIVATE,
                    name="Private",
                    cidr_mask=27
                ), ec2.SubnetConfiguration(
                    subnet_type=ec2.SubnetType.ISOLATED,
                    name="Isolated",
                    cidr_mask=27
                ), ec2.SubnetConfiguration(
                    subnet_type=ec2.SubnetType.PUBLIC,
                    name='Public',
                    cidr_mask=27,
                )
                ],
                )
subnets_list = [vpc.public_subnets, vpc.private_subnets, vpc.isolated_subnets]
for subnets in subnets_list:
    for isubnet in subnets:
        isubnet.node.apply_aspect(core.Tag("Name", "your-subnet-name"))
4
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
3