①Lambdaのソースを記述する

 

import json
import os
from requests_oauthlib import OAuth1Session
from datetime import datetime, timedelta, timezone # 追加

JST = timezone(timedelta(hours=+9), 'JST') # 追加

# API Key, Access Token (本来、ハードコーディングするのは望ましくありません。連載の中で修正していきます。)
consumer_key = '*Input Your API Key*'
client_secret = '*Input Your API Key Secret*'
access_token = '*Input Your Access Token*'
access_token_secret = '*Input Your Access Token Secret*'

oauth = OAuth1Session(consumer_key, client_secret, access_token, access_token_secret)

def lambda_handler(event, context):
    now = datetime.now(JST).strftime("%Y年%-m月%-d日") # 追加
    text = 'おはようございます!今日は ' + now + 'です。頑張っていきましょう!!' # 修正
    
    payload = {'text': text}
    response = oauth.post(
        "https://api.twitter.com/2/tweets",
        json=payload,
    )
    if response.status_code != 201:
        raise Exception(
            "[Error] {} {}".format(response.status_code, response.text)
        )
    

 

※Twitterの開発ツールでAPIキーとアクセスキーを張り付ける

 

 

②EventBridge (CloudWatch Events) を作成する。朝8時にスケジュール作成実施。

 

 

③EventBridge (CloudWatch Events)が作成されたことを確認

 

④Twitterの投稿を確認する

 

 

 

 

 

 

①Lambda関数を作成する

 

  • 関数名 : twitter-bot-hello
  • ランタイム : Python 3.9
  • アーキテクチャ : x86_64
②CloudShellで以下プログラムを実行する。requests_oauthlib パッケージをインストール、空の lambda_function.py を作成、.zip 化したのち、最後に AWS CLI を使って .zip ファイルで Lambda 関数のコードを更新しています。
 
mkdir twitter-bot-hello
cd twitter-bot-hello/
pip3 install -U pip
pip install requests_oauthlib -t ./
touch lambda_function.py
zip -r twitter-bot-hello.zip ./
aws lambda update-function-code --function-name twitter-bot-hello --zip-file fileb://twitter-bot-hello.zip
 
③フォルダが作成されていることを確認する。ツイートプログラムを記入する。
 
  • 手元にメモした API Key と Access Token を利用し、OAuth セッションを作る
  • ツイートテキストを準備 (現段階では固定テキスト) する
  • API Endpoint URL に向けて Post する
 
import json
import os
from requests_oauthlib import OAuth1Session

# API Key, Access Token 
consumer_key = '*Input Your API Key*'
client_secret = '*Input Your API Key Secret*'
access_token = '*Input Your Access Token*'
access_token_secret = '*Input Your Access Token Secret*'

oauth = OAuth1Session(consumer_key, client_secret, access_token, access_token_secret)

def lambda_handler(event, context):
    text = 'これは Lambda からの自動ツイートテストです。'
    
    payload = {'text': text}
    response = oauth.post(
        "https://api.twitter.com/2/tweets",
        json=payload,
    )
    if response.status_code != 201:
        raise Exception(
            "[Error] {} {}".format(response.status_code, response.text)
        )
 
 
※Twitterの開発者画面から、APIキーとアクセスキーを取得し、貼り付けます。
 
 
④Lamda関数を実行し、ツイートを確認する
 
 
 
 
 

①EC2のユーザーデーターの編集で設定。

今回は yum update と Apache のインストール、起動、

および自動起動設定の付与、ドキュメントルートにindex.htmlを生成する設定を実施する。

 

Content-Type: multipart/mixed; boundary="//"
MIME-Version: 1.0

--//
Content-Type: text/cloud-config; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
Content-Disposition: attachment; filename="cloud-config.txt"

#cloud-config
cloud_final_modules:
- [scripts-user, always]

--//
Content-Type: text/x-shellscript; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
Content-Disposition: attachment; filename="userdata.txt"

#!/bin/bash
yum update -y
yum install -y httpd
systemctl start httpd
systemctl enable httpd
touch /var/www/html/index.html
echo "Hello AWS!" | tee -a /var/www/html/index.html

 

②当該EC2に接続し、フォルダが作成されていること、index.htmlを開いて「Hello AWS」を確認する

 

以上

 

 

 

 

 

※ユーザーデーターはEC2作成時にのみ起動するスクリプトであるが、再起動する度に実行する設定を行う

①EC2からユーザーデーターの編集

Content-Type: multipart/mixed; boundary="//"
MIME-Version: 1.0

--//
Content-Type: text/cloud-config; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
Content-Disposition: attachment; filename="cloud-config.txt"

#cloud-config
cloud_final_modules:
- [scripts-user, always]

--//
Content-Type: text/x-shellscript; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
Content-Disposition: attachment; filename="userdata.txt"

#!/bin/bash
あなたのスクリプト内容は以下に記載
--//--
 

 

 

①TargetGroupを二つ作ります。それぞれにEC2をアタッチします。

 

②ALBを作成し、リスナーとルールで送信元IPによって接続先EC2を変える設定を行います。

送信元 IP が 106.0.0.0/32の場合はTarget1へ、送信元 IP が 13.0.0.0/32の場合はTarget2へ接続します。

それ以外はデフォルト設定でエラーメッセージを返します。

 

①認証情報ヘルパーを設定する

②Cloud9で名前とメール設定

③リポジトリのクローンを作成する

④リポジトリにindexファイルをアップロードする

⑤リポジトリにindexファイルがアップロードされたことを確認

 

完了

 

 

 

 

 

 

 

 

 

 

①S3の作成で、フルアクセスを許可する

 

②静的ウエブホスティングの設定

 

③バケットポリシーをjsonで記述

{
  "Version": "2012-10-17",
  "Statement": [
      {
          "Sid": "PublicReadGetObject",
          "Effect": "Allow",
          "Principal": "*",
          "Action": [
              "s3:GetObject"
          ],
          "Resource": [
              "arn:aws:s3:::test-20280828/*"
          ]
      }
  ]
}

 

④indexファイルをアップロードする

 

⑤S3のオブジェクトURLをクリックする

 

⑥index.htmlファイルの表示確認

 

以上