こちらの記事の祝日対応版です。
Google Calendar APIを使って起動日が祝日の場合は処理を行わないように。
また、Google Calendar APIだと正月や会社の休日に対応できないので、環境変数に別途例外休日を設定できるようにしています。
記事のコードにimport文と祝日判定のためのロジックを追加。
app.py
import datetime
import urllib.request
import json
app.py
def change_instances_state(event, target='ec2', state='Start', dryrun=True):
if is_holiday():
return # 休日なら処理終了
if state == 'Stop': # 停止させる条件
app.py
def is_holiday():
now = datetime.datetime.now()
app.log.debug(now)
# 環境変数で設定した休日と比較
days = now.strftime('%m/%d')
env_holidays = os.environ['HOLIDAYS'].split(',')
if days in env_holidays:
app.log.info("%s is env holiday." % days)
return True
# Google Calendar APIから祝日判定
url = 'https://www.googleapis.com/calendar/v3/calendars/japanese__ja@holiday.calendar.google.com/events'
query = {
'key': os.environ['GOOGLE_CALENDER_API_KEY'],
'timeMin': now.strftime('%Y-%m-%d') + 'T00:00:00Z',
'timeMax': now.strftime('%Y-%m-%d') + 'T23:59:59Z'
}
try:
with urllib.request.urlopen('{}?{}'.format(url, urllib.parse.urlencode(query))) as r:
response = json.loads(r.read())
app.log.info(response)
if r.getcode() != 200:
app.log.error("Google Calendar API response not OK.")
return True
if 'items' in response and len(response['items']) > 0:
summary = response['items'][0]['summary']
app.log.info("{} is {}.".format(days, summary))
return True
except urllib.error.URLError as e:
app.log.error(e.reason)
return True
return False
Google CloudのコンソールからGoogle Calendar APIを有効にしてAPIキーを発行します。
発行したAPIキーでこんな感じの呼び出しで祝日が取れればOK。
https://www.googleapis.com/calendar/v3/calendars/japanese__ja@holiday.calendar.google.com/events?key=[API_KEY]&timeMin=2021-04-29T00:00:00Z&timeMax=2021-04-29T23:59:59Z
発行したAPIキーと例外休日の設定を追加します。
.chalice/config.json
{
"version": "2.0",
"app_name": "schedule-startstop",
"stages": {
"dev": {
"lambda_timeout": 20,
"environment_variables": {
"DRYRUN": "True",
"TZ": "Asia/Tokyo",
"HOLIDAYS": "01/01,01/02,01/03,12/31",
"GOOGLE_CALENDER_API_KEY": "**********************************"
}
}
}
}
これでデプロイすれば祝日、例外休日判定付きで同じように使うことができます。