CloudFormationでAPI Gatewayを変更しても反映されない
CloudFormationでAWSのAPI Gatewayを使った開発をするときの話。
初めてCloudFormationをデプロイするときには、API Gatewayのデプロイも実行されるので、すぐにAPIが使えるようになります。しかしその後テンプレートファイルを更新してCloudFormationでデプロイしなおしても、API Gatewayに変更が反映されません。正確に言うと、リソースに変更が反映されるけど、API Gatewayのデプロイは実行されないので、APIの挙動は変更されません。
CloudFormationをデプロイすればすべてを反映できることを期待していたので、困りました。
しかし、CloudFormationでAPI Gatewayの再デプロイはできないようです。
参考
- amazon web services - CloudFormation doesn't deploy to API gateway stages on update - Stack Overflow
そのため、API GatewayのリソースポリシーなどをCloudFormationで更新したら、API Gatewayのデプロイ実行が別途必要になります。
aws cloudformation deploy
の実行後にAPI Gatewayのデプロイも実行するシェルスクリプトは次のようになります。
aws cloudformation deploy \ --template-file template.yaml \ --stack-name samplestack restid=$(aws cloudformation describe-stacks \ --stack-name samplestack | jq -r '.Stacks[0].Outputs[0].OutputValue') # jq を使わずに以下でもよい #restid=$(aws cloudformation describe-stacks \ # --stack-name samplestack \ # --query 'Stacks[0].Outputs[0].OutputValue' --output text) aws apigateway create-deployment --rest-api-id $restid --stage-name Prod
上記スクリプトを動かすにはCloudFormationのテンプレートファイルの最後に以下のような Outputs
の記述が必要です。
AWSTemplateFormatVersion: '2010-09-09' Resources: SampleApiGateway: Type: AWS::ApiGateway::RestApi ... SampleApiGatewayDeployment: Type: AWS::ApiGateway::Deployment Properties: RestApiId: !Ref SampleApiGateway StageName: Prod Outputs: RestId: Value: !Ref SampleApiGateway