LoginSignup
0
1

More than 1 year has passed since last update.

【AWS】RDSを7日以上停止するステートマシン

Posted at

最初に

RDSを停止していたと思ったらいつの間にか起動している何てこと結構あると思います!
対策としてよくあるのは、EventBridgeでスケジューリングして、7日間経ったタイミングで起動して停止するというパターンだと思いますが、
StepFunctions使えばそこだけで完結するやんってことに気づいたのです。

StepFunctions ステートマシン

フロー

フローは下図の通りです!停止して6日間待ってステータス確認して、停止済みなら一時的に起動してもう一度。それ以外のステータスならSuccessに逃げます。
6日間のところは、ちょっとチキってますw

stepfunctions_graph (4).png

ステートマシン定義

ステートマシンの定義は下記の通りです!

{
  "Comment": "A description of my state machine",
  "StartAt": "RDSクラスターを停止",
  "States": {
    "RDSクラスターを停止": {
      "Type": "Task",
      "Next": "Wait - 6日間",
      "Parameters": {
        "DbClusterIdentifier.$": "$.db_identifer"
      },
      "Resource": "arn:aws:states:::aws-sdk:rds:stopDBCluster",
      "ResultPath": null
    },
    "Wait - 6日間": {
      "Type": "Wait",
      "Seconds": 518400,
      "Next": "DescribeDBClusters"
    },
    "DescribeDBClusters": {
      "Type": "Task",
      "Parameters": {
        "DbClusterIdentifier.$": "$.db_identifer"
      },
      "Resource": "arn:aws:states:::aws-sdk:rds:describeDBClusters",
      "Next": "Choice - クラスターステータス",
      "ResultSelector": {
        "db_identifer.$": "$.DbClusters[0].DbClusterIdentifier",
        "status.$": "$.DbClusters[0].Status"
      }
    },
    "Choice - クラスターステータス": {
      "Type": "Choice",
      "Choices": [
        {
          "Variable": "$.status",
          "StringMatches": "stopped",
          "Next": "RDSクラスターを一時的に起動"
        }
      ],
      "Default": "Success - クラスターが別の要因で起動または削除されました"
    },
    "RDSクラスターを一時的に起動": {
      "Type": "Task",
      "Parameters": {
        "DbClusterIdentifier.$": "$.db_identifer"
      },
      "Resource": "arn:aws:states:::aws-sdk:rds:startDBCluster",
      "ResultPath": null,
      "Next": "Wait - 5分"
    },
    "Wait - 5分": {
      "Type": "Wait",
      "Seconds": 300,
      "Next": "RDSクラスターを停止"
    },
    "Success - クラスターが別の要因で起動または削除されました": {
      "Type": "Succeed"
    }
  }
}

入力はこんな感じ!

{
  "db_identifer": "データベース識別子"
}

最後に

同じデータベースに対して、ステートマシンの実行が重ならないように注意してください!
ご紹介したステートマシンはクラスター用ですが、インスタンスでもAPIをインスタンス用のに変えれば同じようにできます!

以上!ありがとうございました!

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