3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

!Refや!GetAttを!Subで代替する

Posted at

!Refと!Subの使い分けについて

以下のように!Refと!GetAttは!Subで代替可能なので、全部!Subで記載する場合について考えてみる。

# !Refと!GetAtt (結果は同じ)
!Ref S3Bucket
!Sub ${S3Bucket}
# !Subと!GetAtt (結果は同じ)
!GetAtt S3Bucket.Arn 
!Sub ${S3Bucket.Arn}

!Subで記載するメリット

  • !Ref !GetAtt !Sub の使い分けを意識する必要がなくなる
  • !Subだけになるのでコピペしやすい

!Subで記載するデメリット

  • ${}を書く必要がある
    • ただ、基本的に手入力する機会はほとんどなく結局コピペすることを考えると、!Ref !GetAttの使い分けを気にする方が高コストだと感じる

!Joinの場合

ImportValueした値と文字列を結合して値を作成したい時がある。
例えばIAMポリシーのResourceセクションで {BucketArn}/prefix/{Region}/* などを指定する場合など。
ことのき!Subで以下のように代替できる。

# !Joinの場合
Resource:
- !Join
  - ''
  - - Fn::ImportValue: !Sub output-s3-arn
    - '/prefix/'
    - !Ref AWS::Region
    - '/*'
# !Subの場合
Resource:
  - !Sub
    - ${BucketArn}/prefix/${AWS::Region}/*
    - BucketArn:
        Fn::ImportValue: !Sub output-s3-arn

これで!Joinも不要になるのでほとんど!Subでなんとかなる。

まとめ

個人的には全部!Subで代替した方が楽だと感じた。
AWS公式や一般的な記法ではしっかり使い分けて記載されていることが多いので、再利用性を考えると多数派に合わせるのが吉ではありそうだが、!Sub代替の知られざるデメリットなどがあればぜひ知りたい。

参考

AWS CloudFormation の Fn:: Sub 関数を Fn::FindInMap、Fn::ImportValue、またはその他のサポートされている関数と組み合わせて使用する方法を教えてください。

個人的によくやるCloudFormationテンプレート小技と+α

3
0
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
3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?