LoginSignup
8
0

AWS SSO PortalにサインインしたことをSlackに通知したい

Last updated at Posted at 2023-12-15

この記事はツクリンク プロダクト部 Advent Calendar 2023 16日目の記事です。

はじめに

ツクリンクのエンジニアのkariyaです!!
インフラ領域を担当しています!最近インフラをAWSに移行したのですがAWSはまだまだ初心者で日々キャッチアップに勤しんでいます。。。


AWSに移行してアカウント増えたのでIdentity Center(旧AWS SSO)を導入検討中で、
SSOポータルのサインインをSlackに通知するようにしてみました。

もともと弊社のインフラはHerokuでしたが、今年AWSへ移行しました。
移行する前からSNSやS3など一部AWSを利用していたので、ログイン通知はSlackにすでに連携していました。
AWS移行後はSTG,本番とAWSアカウントを複数管理することになったのでIdentity Center検証中で、
ポータルへのログイン通知も行えるか確認したらできそうだったのでやってみました。

使用したサービス

  • Slack Incoming Webhook
  • Lambda
  • Cloud Watch
  • CloudTrail

流れ

スクリーンショット 2023-12-12 12.51.51.png

  1. CloudTrailからCloudWatch Logsへの配信を行う
  2. サブスクリプションフィルターから条件を指定しLambdaにログを転送
  3. LambdaでSlackのwebhookを叩く

サブスクリプションフィルターのフィルターパターンに下記検索文字列、送信先にLambdaのarnを指定。

{ $.eventName = "UserAuthentication" }

Lambdaは以下

lambda_function.rb
require 'json'
require 'aws-sdk'
require 'zlib'
require 'base64'
require 'net/http'
require 'uri'

def lambda_handler(event:, context:)
    aws_account_name = ENV["awsaccountname"]
    gzip = Zlib::Inflate.new(Zlib::MAX_WBITS + 32) 
    event_gzip = Base64.decode64(event['awslogs']['data'].to_s)
    event_json = JSON.parse(gzip.inflate(event_gzip))
    event_json['logEvents'].each do |log|
      event_message_json = JSON.parse(log['message'])
      if event_message_json['eventName'] == "UserAuthentication"
        message = <<EOS
#{aws_account_name} のAWSアカウントにログイン処理が発生しました。
発生日時: #{event_message_json['eventTime']}
アカウント名: #{event_message_json['userIdentity']['userName']}
EOS
      else
        message = event_message_json.to_s
      end
        
      # webhookURLは環境変数から取得
      webhook_url = ENV["webhookURL"]
      uri = URI.parse(webhook_url)
      http = Net::HTTP.new(uri.host, uri.port)
      http.use_ssl = true
      
      request = Net::HTTP::Post.new(uri.path, {'Content-Type' => 'application/json'})
      request.body = { text: message }.to_json
    
      response = http.request(request)
      {
        statusCode: response.code.to_i,
        body: response.body
      }
    end
end

※webhookURLとaws_account_nameは環境変数に外出しします。

実際の通知はこんな感じ
スクリーンショット 2023-12-11 20.20.40.png

おわりに

またIdentity Centerや運用周りで気づきがあれば記事にしたいと思います。
ツクリンク プロダクト部 Advent Calendar 2023

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