LoginSignup
4
0

More than 1 year has passed since last update.

CircleCIでAWS NAT Gatewayの起動・停止を実現してみた

Last updated at Posted at 2021-12-11

はじめに

こちらはCircleCI Advent Calendar 2021の第12日目の記事です。
前日はinokappaさんのCircleCI でワークフロージョブの処理時間を可視化する試みでした。

昨年はデプロイパイプラインの話をしました。今年はスケジューラーを使ってみようと思います。

概要

検証環境の費用削減として、下記を参考にAWS LambdaでAWS NAT Gatewayの削減をやってみました。

しかし、AWS CloudFormationやTerraformなどを利用して構成管理していると、AWS Lambdaで削除するやり方では差分が発生してしまいます。
そこで、差分が出ないように構成管理を維持した状態で起動・停止を実現してみようと思います。

本文

テンプレート準備

まずはAWS CloudFormationのテンプレートを用意しておきましょう。
今回のテンプレートはAWS NAT Gatewayだけを管理するようにします。

natGateway.yaml
AWSTemplateFormatVersion: 2010-09-09
Description: Nat Gateway

# 流用する際は、デフォルト値にパラメータを設定するか、CIで渡すようにしましょう
Parameters:
  SubnetPublic:
    Description: Subnet Public.
    Type: String
  EIP:
    Description: Elastic IP ADDR
    Type: String

Resources:
  NatGateway:
    Type: AWS::EC2::NatGateway
    Properties:
      AllocationId: !Ref EIP
      SubnetId: !Ref SubnetPublic

スケジューラー設定

スケジューラーはワークフローを使用したジョブのスケジュール - CircleCIを参考にしていきます。
Contextの設定方法が書いていないので苦戦しましたが、他と同様にJobに設定すればよかったです。

.circleci/config.yml
version: 2.1

orbs:
  aws-cli: circleci/aws-cli@2.0

jobs:
  create:
    executor: aws-cli/default
    working_directory: ~/work
    steps:
      - checkout
      - aws-cli/setup:
          profile-name: default
      - run:
          name: create AWS NAT Gateway
          command: |
             aws cloudformation deploy --template-file ./natGateway.yaml --stack-name firstNATGateway --no-fail-on-empty-changeset
  destroy:
    executor: aws-cli/default
    working_directory: ~/work
    steps:
      - checkout
      - aws-cli/setup:
          profile-name: default
      - run:
          name: destroy AWS NAT Gateway
          command: |
             aws cloudformation delete-stack --stack-name firstNATGateway

workflows:
  version: 2
  create-work:
    triggers:
      - schedule:
          cron: "0 23 * * 0-4"
          filters:
            branches:
              only: main
    jobs:
      - create:
          context: aws
  destroy-work:
    triggers:
      - schedule:
          cron: "0 12 * * 1-5"
          filters:
            branches:
              only: main
    jobs:
      - destroy:
          context: aws

まとめ

CircleCIを使うことで構成管理をしているリソースのコスト削減ができました。
アドベントカレンダーはまだまだ続きます。

以上、最後まで読んでいただきありがとうございました。

余談

今まで下記のように default 配下に記載していました。今回の実装で default と同一階層に記載できることが知ることができ、他の実装で役に立てることができました。

workflows:
  version: 2
  default:
    jobs:
      - hoge:

参考資料

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