LoginSignup
3
5

More than 3 years have passed since last update.

AWS Lambda で EC2 を起動する。祝日は起動しない。

Posted at

開発用の EC2 を経費削減のため、休日にはインタンスをたちあがらないようにしたい。
コピペでつかえるように、ライブラリなどは使いたくない。
祝日はそれほど多くないし、会社独自の休業日などもあるので、祝日系は配列で持つことにした。
年に2回くらいメンテナンスすれば良いので、これで良い。

require 'json'
require 'date'
require 'aws-sdk'

def lambda_handler(event:, context:)
    today = Date.today.to_s
    if holydays.include?(today)
        msg = "Today is Holyday! Does Not Start Instance."
    else
        msg = start_instance('ここにインスタンスのIDを書く')
    end

    { statusCode: 200, body: JSON.generate("#{today} - #{msg}") }
end

def holydays
  # この配列をメンテナンスする。
  # https://www8.cao.go.jp/chosei/shukujitsu/gaiyou.html
  [
    '2019-10-22', #休日(祝日扱い)
    '2019-11-03', #文化の日
    '2019-11-04', #休日
    '2019-11-23', #勤労感謝の日
    '2019-12-30', #冬季休業
    '2019-12-30', #冬季休業

    '2020-01-01', #元日
    '2020-01-02', #冬季休業
    '2020-01-03', #冬季休業
    '2020-01-13', #成人の日
    '2020-02-11', #建国記念の日
    '2020-02-23', #天皇誕生日
    '2020-02-24', #休日
    '2020-03-20', #春分の日
    '2020-04-29', #昭和の日
    '2020-05-03', #憲法記念日
    '2020-05-04', #みどりの日
    '2020-05-05', #こどもの日
    '2020-05-06', #休日
    '2020-07-23', #海の日
    '2020-07-24', #スポーツの日
    '2020-08-10', #山の日
    '2020-09-21', #敬老の日
    '2020-09-22', #秋分の日
    '2020-11-03', #文化の日
    '2020-11-23', #勤労感謝の日
  ]
end

def start_instance(instance_id)
    ec2 = Aws::EC2::Resource.new(region: 'ap-northeast-1') # 東京限定...
    i = ec2.instance(instance_id)
    # https://docs.aws.amazon.com/ja_jp/sdk-for-ruby/v3/developer-guide/ec2-example-start-instance.html
    # からコピペ
    msg = "Instance:#{instance_id} is "
    if i.exists?
      case i.state.code
      when 0  # pending
        msg = msg + "pending, so it will be running in a bit."
      when 16  # started
        msg = msg + "already started."
      when 48  # terminated
        msg = msg + "terminated, so you cannot start it."
      else
        msg = msg + "stopped."
        i.start
      end
    else
      msg = msg + "not exists."
    end
    msg
end

「国民の祝日」について

以下に、内閣府が CSV を置いてくれている。
https://www8.cao.go.jp/chosei/shukujitsu/gaiyou.html

参考

https://qiita.com/kknd/items/da6a0970803bc035a870
https://dev.classmethod.jp/cloud/aws/ec2-lambda-auto-startstop-java/

3
5
1

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
3
5