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

CloudFormation で S3 の ARN を !GetAtt ではなく !Sub で取得する

Last updated at Posted at 2026-01-27

概要

CloudFormation のテンプレート内で S3 の ARN を取得したい場合、
普通は !GetAtt を使用すると思いますが、実は !Sub でも ARN が取得できるんだよ。というお話
!Sub の公式ドキュメント ではこの書き方が紹介されていなかったため、備忘録として残しておきます。
(嘘です書いてありました。記述例のところはないけど)

${MyInstance.PublicIp} などのリソース属性を指定すると、CloudFormation は Fn::GetAtt 組み込み関数を使用した場合と同じ値を返します。

書き方

AWSTemplateFormatVersion: "2010-09-09"
Resources:
  # S3
  TestBucket:
    Type: AWS::S3::Bucket
    Properties:
      BucketName: "test-bucket"

  # 適当なリソース (パラメータストア)
  ## GetAtt を使用した場合 (一般的なパターン)
  TestParameterGetAtt:
    Type: AWS::SSM::Parameter
    Properties:
      Type: String
      Value: !GetAtt TestBucket.Arn
      # ↑ には "arn:aws:s3:::test-bucket" が入る

  ## Sub を使用した場合 (通常の Sub)
  TestParameterSubNull:
    Type: AWS::SSM::Parameter
    Properties:
      Type: String
      Value: !Sub TestBucket
      # ↑ には "test-bucket" が入る
      #     (バケット名しか取得されない)

  ## Sub を使用した場合 (本記事で紹介したいポイント)
  TestParameterSub:
    Type: AWS::SSM::Parameter
    Properties:
      Type: String
      Value: !Sub ${TestBucket.Arn}
      # ↑ には "arn:aws:s3:::test-bucket" が入る!!

このように、

  • !GetAtt TestBucket.Arn
  • !Sub ${TestBucket.Arn}
    は同じ結果を返してくれます。

!Sub を使うメリット

!Sub で書けると何が嬉しいかというと、
文字列を連結したい場合、 !GetAtt だと !Join とかを使用しなければいけないが、
!Sub だと↓のようにシンプルに書けます

  TestParameterSub:
    Type: AWS::SSM::Parameter
    Properties:
      Type: String
      Value: !Sub ${TestBucket.Arn}-wasshoi

IAMポリシーを書くとき、バケット末尾に /* とかをつけていると思いますが、
!Sub ${TestBucket.Arn}/* みたいに書きたくなってきませんか?😏

以上、 !Sub の使い方でした。
もちろん S3 以外にも IAM 等々、 !GetAtt を使わないといけなかった他の場面でも使えます。

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