今日もCloudFormationの操作を勉強してました。
コードでAWS環境作れる感覚が楽しいですね。
良い感じに参考になるCLoudFormationのテンプレート見つける->自分のローカル環境から実行して動くか確認する->テンプレートの内容1行する理解して自分で応用できるようにする、の流れでAWSのスキルだいぶ上げていきそうな気がしてます。
以下は今日勉強した内容のメモです。
vpc0130.ymlを作成し、以下のテンプレートでVPCとサブネットが作成できる。
AWSTemplateFormatVersion: '2010-09-09' Description: VPC created at 20210130 Resources: VPC: Type: 'AWS::EC2::VPC' Properties: CidrBlock: '10.0.0.0/16' EnableDnsSupport: true EnableDnsHostnames: true InstanceTenancy: default Tags: - Key: "Name" Value: "VPC0130-2" Subnet1: Type: AWS::EC2::Subnet Properties: VpcId: !Ref VPC CidrBlock: '10.0.0.0/24' MapPublicIpOnLaunch: true
ポイント: 同じスタックのVPCのIDをサブネットに紐づけるには!Ref関数でVPCを指定する
Ref関数のドキュメントは以下。 docs.aws.amazon.com
上記テンプレートを準備してAWS CLIからCloudFormationスタックの作成を実行します。
aws cloudformation create-stack --template-body file://$PWD/infra0130/vpc0130.yml --stack-name vpc0130
マネジメントコンソールからCloudFormationスタックが生成したリソースにVPCとサブネットがひとつあることを確認できます。
!refを使えば他のAWSリソースのIDに依存するリソースも同じテンプレートで作ることができるっぽい。
CLoudFormationでAWSリソースの作り方がだいたいわかってきたので、インターネットゲートウェイやルートテーブルまで加えた以下のテンプレートを実行してみました。
AWSTemplateFormatVersion: '2010-09-09' Description: VPC created at 20210130 Resources: VPC: Type: 'AWS::EC2::VPC' Properties: CidrBlock: '10.0.0.0/16' EnableDnsSupport: true EnableDnsHostnames: true InstanceTenancy: default Tags: - Key: "Name" Value: "VPC0130-2" Subnet1: Type: AWS::EC2::Subnet Properties: VpcId: !Ref VPC CidrBlock: '10.0.1.0/24' MapPublicIpOnLaunch: true Subnet2: Type: AWS::EC2::Subnet Properties: VpcId: !Ref VPC CidrBlock: '10.0.2.0/24' MapPublicIpOnLaunch: true InternetGateway: Type: 'AWS::EC2::InternetGateway' VPCGatewayAttachment: Type: 'AWS::EC2::VPCGatewayAttachment' Properties: InternetGatewayId: !Ref InternetGateway VpcId: !Ref VPC RouteTable: Type: 'AWS::EC2::RouteTable' Properties: VpcId: !Ref VPC RouteTableAssociation1: Type: 'AWS::EC2::SubnetRouteTableAssociation' Properties: SubnetId: !Ref Subnet1 RouteTableId: !Ref RouteTable RouteTableAssociation2: Type: 'AWS::EC2::SubnetRouteTableAssociation' Properties: SubnetId: !Ref Subnet2 RouteTableId: !Ref RouteTable InternetRoute: Type: 'AWS::EC2::Route' DependsOn: VPCGatewayAttachment Properties: GatewayId: !Ref InternetGateway RouteTableId: !Ref RouteTable DestinationCidrBlock: '0.0.0.0/0' Outputs: VPC: Description: VPC Value: !Ref VPC Export: Name: 'VPC' Subnet1: Description: 'Subnet 1 on AZ1' Value: !Ref Subnet1 Export: Name: 'Subnet1' Subnet2: Description: 'Subnet 2 on AZ2' Value: !Ref Subnet2 Export: Name: 'Subnet2'
ルートテーブルをサブネットに関連付けるのもテンプレートでは一つのリソースとして表現されるんですかね。ルートテーブルが一つのリソースで上記テンプレートで言うところのRouteTable内でSubnetAssociationとかも指定できるのかとイメージしてましたがそういうことではないみたいで、サブネットを関連づけるにはAWS::EC2::SubnetRouteTableAssociationというTypeが用意されているようです。
ここらへんは変に頭硬く考えすぎず、とにかく想定通りに動くテンプレートを読みまくって、それらを正解パターンとして自分の中に成功体験を増やしていくことが大事かなと思います。
上記テンプレートを実行すると想定通りにリソースがずらりと作成されていました。
うーん、楽しいですね。どんどん手を動かしながら自分の中に馴染ませていきたいと思います。