AWSのいろいろなサービスを使っていると、リソース毎の料金を把握したくなりました。
- Lambda 1の料金
- Lambda 2の料金
- DynamoDB 1の料金
- DynamoDB 2の料金
- など
このようなとき、コスト配分タグの利用が便利です。 タグの値にリソース名を記載しておけば、リソース毎の料金が把握できます。
設定時に少しでも楽をするため、自分自身のリソース名を参照できるか?を試してみました。
おすすめの方
- CloudFormationでタグを設定したい方
自分自身を参照できなかった(循環参照のため)
CloudFormationテンプレート
DynamoDBをサンプルにして試してみました。タグの値で自分自身を参照しています。
test.yaml
AWSTemplateFormatVersion: '2010-09-09'
Resources:
TagTestTable:
Type: AWS::DynamoDB::Table
Properties:
TableName: tag-test-table
BillingMode: PAY_PER_REQUEST
AttributeDefinitions:
- AttributeName: userId
AttributeType: S
KeySchema:
- AttributeName: userId
KeyType: HASH
Tags:
- Key: This_is_key_name
Value: !Sub DynamoDB-Table-${TagTestTable}
デプロイすると、循環参照だよと怒られる
$ aws cloudformation deploy \
--template-file test.yaml \
--stack-name tag-test-stack \
--no-fail-on-empty-changeset
An error occurred (ValidationError) when calling the CreateChangeSet operation: Circular dependency between resources: [TagTestTable]
それでも参照したい!
ここから先はもはや意味があるのか分かりませんが、意地でも参照してみます。 使いたいリソース名をパラメータ部分に書いてみました。
CloudFormationテンプレート
test.yaml
AWSTemplateFormatVersion: '2010-09-09'
Parameters:
TagTestTableName:
Type: String
Default: tag-test-table
Resources:
TagTestTable:
Type: AWS::DynamoDB::Table
Properties:
TableName: !Ref TagTestTableName
BillingMode: PAY_PER_REQUEST
AttributeDefinitions:
- AttributeName: userId
AttributeType: S
KeySchema:
- AttributeName: userId
KeyType: HASH
Tags:
- Key: This_is_key_name
Value: !Sub DynamoDB-Table-${TagTestTableName}
デプロイ成功する
$ aws cloudformation deploy \
--template-file test.yaml \
--stack-name tag-test-stack \
--no-fail-on-empty-changeset
タグにテーブル名がある
タグの値にパラメータ部分のテーブル名が利用できました。
さいごに
CloudFormationでタグを設定してみました。 自分自身のリソース名は参照できませんが、リソース名をパラメータ化すれば参照可能でした。