継続は力なり

タイトル通り定期的な更新を心掛けるブログです。

Amazon OpenSearch Service でスローログを有効化しているのにログがでない...?時の解決方法を試した

タダです.

Amazon OpenSearch Service でスローログを有効化しているのに何もログがないって思ったことはありませんか?自分はあります.これでは遅いクエリの分析ができない...そんな状況からログを出すことができたので対処法をまとめていきます.

Amazon OpenSearch Service のログ有効化する方法

そもそも Amazon OpenSearch Service でログを有効化する方法はどのようにするかというと,ドキュメントにコンソール利用の方法と AWS CLI,AWS SDKの記載があり,これに従って設定していきます.

スローログの閾値を設定する

本題ですが,スローログを有効化してもログが出てこないのは閾値を設定してないからです.閾値の設定の仕方はドキュメントに記載があります.つまり,Amazon OpenSearch Service に対して PUT リクエストを送り閾値を設定するということですね.以下,curl でリクエストを送った場合の例になりますが,1秒以上かかるリクエストを WARN ログとして出力する例です.

$ curl -XPUT 'domain-endpoint/index-name/_settings' -H 'Content-Type: application/json' -d '{
"index.search.slowlog.threshold.query.warn": "1s"
}'

関連ドキュメント docs.aws.amazon.com

これで curl domain-endpoint/index-name/_settings?pretty を叩いて slowlog のセクションが出ていれば CloudWatch Logs にスローログが出力されます.

$ curl domain-endpoint/index-name/_settings?pretty
{
  "index-name" : {
    "settings" : {
      "index" : {
        "search" : {
          "slowlog" : {
            "threshold" : {
              "query" : {
                "warn" : "1s"
              }
            }
          }
        }
  ~中略~
}

なお,スローログのフィールド情報は下記ページに日本語記事の解説があり,大変勉強になりました.

www.elastic.co

まとめ

Amazon OpenSearch Service でスローログに何も出ない場合の理由とその対処をまとめました.

CloudWatch Logs のログから秒,分,時間ごとの件数を集計する時にむちゃくちゃ重宝した構文の紹介

タダです.

CloudWatch Logs から時間ごとのログの件数を集計することがあったのを今回の調査で初めて知ったのでまとめておきます.

stas 構文

それは stats 構文で名前の通りログのパターン分析に役立つ役割のようです.下記のクエリでは Exception の件数を5分ごとに集計して降順で表示することができます.

filter @message like /Exception/
| stats count(*) as exceptionCount by bin(5m)
| sort exceptionCount desc

docs.aws.amazon.com

この bin(5m) の値は例えば,1秒毎であれば bin(1s) とできるし,1時間毎であれば bin(60m) とすれば時間の間隔を調整して集計できます.今回自分は,膨大な CloudWatch Logs の中から特定のログパターンで発生したリクエストの件数を集計しレポートする役割を持っていたので,この stats 構文を使っての集計はとても役立ちました.

まとめ

今回は時間毎のログ集計で役立った stats 構文の紹介でした.

SecurityHub の違反してるリソースの検出されたリストを出力する方法をまとめる

タダです.

先日SecurityHub を運用していて違反しているリソースを通知することはやっていてアラートを放置してしまっていたので,その違反の修正を方針を決めてやりました.その際に,違反してるリソースを一覧で出す時の方法を実践して学んだのでまとめておきます.

AWS マネジメントコンソールから出力する場合

マネジメントコンソールから出力する場合は検出ルールの詳細からDownload ボタンを押すと CSV ファイルをダウンロードできます.Compliance Status,Severity,ID, Title, Failed checks , Unknown checks , Not available checks , Passed checks , Custom parameters の順番のカラムで出力されます.

ただ,この段階ではどの AWS リソースで違反が発生しているかはわからないため,個別のチェックツールを詳細で見て Failedステータスのルールを確認すると違反したリソース一覧を確認できるため,これで修正対応をしていくことができました.

AWS CLI から出力する場合

既に検索したら多くの記事が公開されていたのですが,下記の記事を参照させてもらいました.「5. 以下の条件に合致したコントロール数を取得」で利用しているコマンド の部分のコマンドでほしい結果を得られました.

blog.serverworks.co.jp

まとめ

SecurityHub の違反してるリソースを一覧で出す時の方法をまとめました.

The next-generation Slack platform に入門する[ローカルからデプロイ編]

タダです.

前回からの続きです.ローカルで The next-generation Slack platform のローカル開発するのをやってみました.この記事では開発したのをデプロイしてみます.

sadayoshi-tada.hatenablog.com

ローカルからデプロイする

slack deploy で Slack platform にデプロイできました.

❯ slack deploy
? Choose a deployed environment taddyteam hogehoge hogehoge

📚 App Manifest
   Updated app manifest for "hello-world-app" in "taddyteam"

🏠 App Install
   Installing "hello-world-app" app to "taddyteam"
   Updated app icon: assets/default_new_app_icon.png
   Finished in 4.0s

⚡ Listing triggers installed to the app...
   There are no triggers installed for the app

⚡ Create a trigger
   Searching for trigger definition files under 'triggers/*'...
   Found 1 trigger definition file

? Choose a trigger definition file: triggers/greeting_trigger.ts

⚡ Trigger successfully created!

   Send a greeting ABCDEFG (shortcut)
   Created: 2024-01-17 22:48:47 +09:00 (0 seconds ago)
   Collaborators:
     Sadayoshi Tada @tada hoge
   Can be found and used by:
     everyone in the workspace
   https://slack.com/shortcuts/ABCDEFG/hogeghogehoge


🎁 App packaged and ready to deploy
   0.016MB was packaged in 0.5s

🚀 hello-world-app deployed in 8.6s
   Dashboard:  https://slack.com/apps/hoge
   App Owner:  tada (hoge)
   Workspace:  taddyteam (hogehoge)

🌩  Visit Slack to try out your live app!
   When you make any changes, update your app by re-running slack deploy

💌 We would love to know how things are going
   Survey your development experience with slack feedback --name platform-improvements

超簡単に Slack App ができました 🎊

動作確認

slack deploy 時に出ていたショートカット用のURL( https://slack.com/shortcuts/ABCDEFG/hogeghogehoge ) をポストするとローカル開発と同じように hello world app が起動してきました.その後,Start Workflow からメッセージの投稿もできたので動作確認ができました.

まとめ

一旦この記事までで Slack CLI からテンプレートで Slack App を作りそこから App をSlack platform 上にデプロイして使うことができました.引き続き慣れるためにいろんな学習コンテンツをさらった内容を備忘録に記録してきます.

The next-generation Slack platform に入門する[ローカルで動作編]

タダです.

タイトルの通り The next-generation Slack platform を使ってみたいというモチベーションから試してみた内容を備忘録で何回かに分けて記録していきます.今回はチュートリアルにある Hello World App の開発をやってみます.なお,他にもサンプルはありドキュメントから確認できます.

api.slack.com

事前準備

事前準備として有料の Slack のプランを契約している環境を用意する必要がありますが,加えて Slack の CLI を準備します.インストール後に対象のワークスペースとの認証を完了させ,slack auth listで対象のワークスペースが表示されれば事前準備完了です.

❯ slack version
Using slack v2.16.0
$ slack auth list

taddyteam (Team ID: hogehogehoge)
User ID: hogehoge
Last Updated: 2024-01-13 16:27:37 +09:00
Authorization Level: Workspace
❯ slack       
✨ CLI to create, run, and deploy Slack apps

📚 Get started by reading the docs:
    https://api.slack.com/automation

USAGE
  $ slack <command> <subcommand> [flags]

COMMANDS
  app
    delete      Delete the app
    install     Install the app to a team
    list        List all teams that have installed the app
    uninstall   Uninstall the app from a team
  auth
    list        List all authorized accounts
    login       Log in to a Slack account
    logout      Log out of a team
    revoke      Revoke an authentication token
    token       Collect a service token
  collaborator
    add         Add a collaborator to your app
    list        List all collaborators of an app
    remove      Remove a collaborator from an app
  datastore
    delete      Delete an item from a datastore
    get         Get an item from a datastore
    put         Create or replace an item in a datastore
    query       Query a datastore for items
    update      Create or update an item in a datastore
  env
    add         Add an environment variable to the app
    list        List all environment variables for the app
    remove      Remove an environment variable from the app
  external-auth
    add         Initiate the OAuth2 flow for a provider in your app
    add-secret  Add the client secret for a provider in your app
    remove      Remove provider token(s) from your app
    select-auth Set developer authentication to be used for a specific workflow
  function
    distribute  Manage who can view functions published by your app
  manifest
    info        Display the app manifest when run in a project directory
    validate    Validate the app manifest generated by a project
  platform
    activity    Display the app activity logs from the Slack Platform
    deploy      Deploy the app to the Slack Platform
    run         Start a local server to develop and run the app locally
  trigger
    access      Manage who can use your triggers
    create      Create a trigger for a workflow
    delete      Delete an existing trigger
    info        Get details for a specific trigger
    list        List details of existing triggers
    update      Updates an existing trigger
  create            Create a Slack project
  doctor            Check and report on system and app information
  feedback          Share feedback about your experience or project
  help              Help about any command
  samples           List available sample apps
  upgrade           Checks for available updates to the CLI or SDK
  version           Print the version number

FLAGS
  -a, --app string           use a specific app ID or environment
      --config-dir string    use a custom path for system config directory
  -e, --experiment strings   use the experiment(s) in the command
  -f, --force                ignore warnings and continue executing command
  -h, --help                 help for slack
      --no-color             remove styles and formatting from outputs
  -s, --skip-update          skip checking for latest version of CLI
  -w, --team string          select workspace or organization by team name or ID
      --token string         set the access token associated with a team
  -v, --verbose              print debug logging and additional info
      --version              version for slack

GLOBAL ALIASES
  activity           platform > activity
  delete             app   > delete
  deploy             platform > deploy
  install            app   > install
  list               auth  > list
  login              auth  > login
  logout             auth  > logout
  run                platform > run
  uninstall          app   > uninstall

EXAMPLE
  $ slack login   # Log in to your Slack account
  $ slack create  # Create a new Slack app
  $ slack run     # Start a local development server
  $ slack deploy  # Deploy to the Slack Platform

EXPERIMENTS
  None

ADDITIONAL HELP
  For more information about a specific command, run:
  $ slack <command> <subcommand> --help

  For guides and documentation, head over to https://api.slack.com/automation

インストールのドキュメント

api.slack.com

ローカルのプロジェクト環境構築

slack create hello-world-app --template https://github.com/slack-samples/deno-blank-template でローカルに空のプロジェクトを作ることができます.slack create hello-world-app --template https://github.com/slack-samples/deno-hello-world で pre-built の app も作れるようですが,今回は空のプロジェクトにしました.

❯ slack create hello-world-app --template https://github.com/slack-samples/deno-blank-template
⚙️  Creating a new Slack app in ~/tmp/hello-world-app

📦 Installed project dependencies

✨ hello-world-app successfully created

🧭 Explore the documentation to learn more
   Read the README.md or peruse the docs over at api.slack.com/automation
   Find available commands and usage info with slack help

📋 Follow the steps below to begin development
   Change into your project directory with cd hello-world-app/
   Develop locally and see changes in real-time with slack run
   When you're ready to deploy for production use slack deploy
❯ cd hello-world-app;ls -l
total 56
-rw-r--r--@ 1 tady  staff  1090 Jan 13 16:42 LICENSE
-rw-r--r--@ 1 tady  staff  6280 Jan 13 16:42 README.md
drwxr-xr-x@ 3 tady  staff    96 Jan 13 16:42 assets
-rw-r--r--@ 1 tady  staff   624 Jan 13 16:42 deno.jsonc
-rw-r--r--@ 1 tady  staff   158 Jan 13 16:42 import_map.json
-rw-r--r--@ 1 tady  staff   505 Jan 13 16:42 manifest.ts
-rw-r--r--@ 1 tady  staff   127 Jan 13 16:42 slack.json

まず確認するのは functions, triggers, workflowsディレクトリです.役割は公式記事に解説があったのでそちらのリンクを貼ります.

qiita.com

Slack App のトリガーを作る

Slack App を実行するトリガーを作っていきます.slack trigger create --triger-def "triggers/greeting_trigger.ts" を実行すると事前準備で認証しているワークスペースhello-world-app (local) が表示されます.

❯ slack trigger create --trigger-def "triggers/greeting_trigger.ts"
? Select a team Install to a new team
? Install to a new team taddyteam hogehogehoge

🔔 If you leave this team, you can no longer manage the installed apps
   Installed apps will belong to the team if you leave the workspace

? Choose an app environment Local 
📚 App Manifest
   Created app manifest for "hello-world-app (local)" in "taddyteam"

🏠 App Install
   Installing "hello-world-app (local)" app to "taddyteam"
   Finished in 2.8s

⚡ Trigger successfully created!

   Send a greeting (local) Ft06E4V2M2HF (shortcut)
   Created: 2024-01-13 17:04:06 +09:00 (1 second ago)
   Collaborators:
     Sadayoshi Tada @tada hogehoge
   Can be found and used by:
     everyone in the workspace
   https://slack.com/shortcuts/ABCD1234EFGH/01d8db3db6ea1a9e05012a90028ed678

また, https://slack.com/shortcuts/ABCD1234EFGH/01d8db3db6ea1a9e05012a90028ed678(これは偽のURLです) の URL をコピーしてワークスペースのパブリックチャンネルにポストするとアプリが反応します.

Start Window でメッセージを送る相手とその内容を選べるのですが,この段階でローカル側で slack run コマンドを実行してローカルのサーバーを立ち上げます.メッセージと送る相手を選択して実行するとメッセージが返ってきました.

レスポンスの内容を変えてみる

固定のレスポンスになっている箇所で追加のメッセージを入れてみました.オハヨウ って返すだけですが,追加のメッセージを返してくれるようになりました.

export default SlackFunction(
  GreetingFunctionDefinition,
  ({ inputs }) => {
    const { recipient, message } = inputs;
    const salutations = ["Hello", "Hi", "Howdy", "Hola", "Salut", "オハヨウ"];
    const salutation =
      salutations[Math.floor(Math.random() * salutations.length)];
    const greeting =
      `${salutation}, <@${recipient}>! :wave: Someone sent the following greeting: \n\n>${message}`;
    return { outputs: { greeting } };
  },
);

まとめ

ローカルで Slack App を動かしてみてました.次はデプロイをしてみたり,修正をいれてからの反映をやってみます.