https://dev.classmethod.jp/articles/update-tag-policies/
https://aws.amazon.com/jp/premiumsupport/knowledge-center/organizations-scp-tag-policies/
既存リソース -> タグポリシー
新規リソース -> SCP
タグポリシーの場合は、リソース作成時はチェックされない
また、タグの削除も可能のため、タグポリシーの使いどころとしては、タグがある場合にタグ設定値を特定の値に制限することぐらいとなる
-- 1. コマンド等のインストール
-- 1.1 aws cli version 2 インストール
curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"
unzip awscliv2.zip
sudo ./aws/install
aws --version
-- 1.2 jqインストール
sudo yum -y install jq
-- 2. タグポリシーの有効化
aws organizations enable-policy-type \
--root-id r-2222 \
--policy-type TAG_POLICY
-- 3. タグポリシーを作成
{
"tags": {
"env": {
"tag_value": {
"@@assign": [
"dev",
"prd"
]
},
"enforced_for": {
"@@assign": [
"ec2:instance"
]
}
}
}
}
aws organizations create-policy \
--name tagpolicy01 \
--description tagpolicy01 \
--content file://tagpolicy01.json \
--type TAG_POLICY
aws organizations list-policies \
--filter TAG_POLICY
aws organizations describe-policy \
--policy-id p-1111111111
-- 4. タグポリシーをアタッチ
aws organizations list-roots
aws organizations attach-policy \
--policy-id p-1111111111 \
--target-id r-2222
aws organizations list-targets-for-policy \
--policy-id p-1111111111
-- 5. 動作確認(リソース作成時)
aws ec2 run-instances \
--image-id ami-0404778e217f54308 \
--instance-type t3.nano \
--key-name key1 \
--tag-specifications 'ResourceType=instance,Tags=[{Key=Name,Value=instance01}]'
→
タグが定義されていない場合も作成可能★
aws ec2 run-instances \
--image-id ami-0404778e217f54308 \
--instance-type t3.nano \
--key-name key1 \
--tag-specifications 'ResourceType=instance,Tags=[{Key=Name,Value=instance02},{Key=env,Value=dev}]'
→
作成可能
-- 6. 動作確認(タグ変更時)
aws ec2 describe-instances \
--instance-ids i-33333333333333333 \
--query Reservations.Instances.{Tags:Tags}
aws ec2 create-tags \
--resources i-33333333333333333 \
--tags Key=env,Value=hoge
→
An error occurred (TagPolicyViolation) when calling the CreateTags operation: The tag policy does not allow the specified value for the following tag key: 'env'.
-- 7. 動作確認(タグ削除時)
aws ec2 describe-instances \
--instance-ids i-33333333333333333 \
--query Reservations.Instances.{Tags:Tags}
aws ec2 delete-tags \
--resources i-33333333333333333 \
--tags Key=env
→
削除可能
-- 8. クリーンアップ
-- タグポリシーをデタッチ
aws organizations detach-policy \
--policy-id p-1111111111 \
--target-id r-2222
aws organizations list-targets-for-policy \
--policy-id p-1111111111
-- タグポリシーを削除
aws organizations delete-policy \
--policy-id p-1111111111
aws organizations list-policies \
--filter TAG_POLICY
-- タグポリシーの無効化
aws organizations disable-policy-type \
--root-id r-2222 \
--policy-type TAG_POLICY