Y_Yamashitaのブログ

勉強したことのアウトプット・メモが中心。記事の内容は個人の見解であり、所属組織を代表するものではありません。

(小ネタ)MFA Deleteを有効化したS3なのにMFA無しで削除が出来ると思ったら勘違いだった話

先日、初めてS3のMFA Deleteを有効化してみました。その時にタイトルの勘違いをしたので、備忘のためにメモを残しておきます。

お断り

本ブログではMFA Deleteの有効化方法については記載しません。以下の記事が参考になると思いますので、こちらをご参照ください。

repost.aws

qiita.com

はじめにまとめ

  • MFA Deleteは、バージョニングが有効になっているS3でのみサポートされている
  • MFA Deleteを有効化していても、オブジェクトに削除マーカーを付ける際にはMFAは要求されない
  • バージョンを指定してオブジェクトを完全削除する場合は、MFAが要求される
  • バージョニングを無効化する際にもMFAが要求される

まとめの少し詳しい説明

下記の公式ドキュメントで説明されている通り、MFA Deleteは、バージョニングが有効化されたバケットに追加の認証を加えることで、偶発的に(あるいは悪意を持って)オブジェクトの特定バージョンが完全削除されたり、バージョニング自体が無効にされることを防ぐ、というコンセプトになっています。

docs.aws.amazon.com

Amazon S3 バケットで S3 バージョニングを行うときに、MFA (多要素認証) Delete が有効になるようにバケットを設定すれば、セキュリティをさらに強化できます。この設定を行うと、バケット所有者は、特定のバージョンを削除したりバケットのバージョニング状態を変更したりするリクエストに、2 つの認証形式を含めることが必要になります。
MFA Delete では、以下のいずれかの操作で追加の認証が必要になります。
バケットのバージョニング状態を変更する
・オブジェクトバージョンを完全に削除する

S3でバージョニングが有効になっている場合、バージョンを指定せずにオブジェクトを削除しても、削除マーカーが付くだけで、オブジェクトは完全には削除されません。オブジェクトを完全に削除する場合は、オブジェクトのバージョンを指定する必要があります。詳細は下記公式ドキュメントを参照ください。

docs.aws.amazon.com

「バージョニングに追加の認証をかけて、削除リスクをさらに軽減する」というコンセプトが理解できると、「バージョンを指定しない削除」を防止しない仕様も腑に落ちました。

(おまけ)実際に動作を確認してみる

最後におまけで、実際に動作を確認してみます。
まず、バージョニングとMFA Deleteが有効化されているバケットを用意します。


次に、ルートユーザーではない通常のIAMユーザーで、MFAなしで対象S3のオブジェクトを削除してみます。ちなみに、このオブジェクトは、バージョニング・MFA Deleteを有効化する前から存在していたものです。MFA Delete有効化前から存在していたオブジェクトに対しても、MFA Deleteが適用されるか確認したかったため、このオブジェクトを選択してみました。

一見すると普通に削除されたように見えますね。実際には削除マーカーがついただけなので、オブジェクトは残っています。そのため、ストレージ容量が減ることもありません。

オブジェクト一覧で、「バージョンを表示」にチェックを入れると、削除マーカーと、削除前のオブジェクトが見えました。削除マーカーの方はサイズが0バイトになっていますが、削除前の方は元のサイズのままですね。


ここで、削除前のオブジェクトを指定して、再度削除を試みます。

今度は、ちゃんと怒られました。ちなみに、削除マーカーの方を消そうとしても、同様にエラーとなりました。
MFA Deleteを有効化する前から存在していたオブジェクトに対しても、ちゃんと効果を発揮しているようです。

おまけの補足

MFA Deleteは、ライフサイクルポリシーと併用することが出来ません。ライフサイクルポリシーが存在する状態でMFA Deleteを有効化しようとすると下記のようなエラーが発生するため、先にライフサイクルポリシーを削除する必要があります。

[cloudshell-user@ip-10-130-39-90 ~]$ aws s3api put-bucket-versioning \
> --bucket aws-cloudtrail-logs-XXXXXXXXXXXX \
> --versioning-configuration Status=Enabled,MFADelete=Enabled \
> --mfa 'arn:aws:iam::XXXXXXXXXXXX:mfa/root-account-mfa-device XXXXXX'

An error occurred (InvalidBucketState) when calling the PutBucketVersioning operation: Mfa Authentication is not supported on a bucket with lifecycle configuration. Delete lifecycle configuration before enabling Mfa Authentication.
[cloudshell-user@ip-10-130-39-90 ~]$ 

また、上述通り、MFA Deleteを有効化する前から存在していたオブジェクトに対しても、MFA Delete は効果を発揮します。

つまり、MFA Deleteを有効化すると、その時点でバケットに存在するオブジェクト、および、それ以降に作成されたオブジェクトは全て、ルートユーザーのMFAを利用しない限り完全削除できない、ということになります。

もともとバージョニングしているものに追加の認証をかけるくらいなので、そもそも削除する想定のないものに適用する機能だと考えた方が良さそうです。ログファイルのようにローテートすることが前提のものに適用する機能では無いように感じました。

今回は以上となります。このブログが少しでも誰かの参考になれば幸いです。

AWSアップデートをLangChain+BedRockで要約させてメール通知してみた

以前のブログで、LangChainとBedRockを利用し、AWSアップデートの要約をさせてみました。 今回は、EventBridgeとStep Functions を活用し、要約内容を定期的にメール通知する仕組みを実装してみたいと思います。

はじめにお断り(というか言い訳)

今回は Step Functions の入出力を扱う練習もしたかったので、やたらと細かくLambda関数を分割し、直列で繋いだワークフローになっています。また、コードにエラーハンドリングなどは組み込んでいません。個人用途だし、とりあえず動かしてみたくて試行錯誤しながら実装したので、全体的に洗練されておりません。。そのあたりをご容赦いただければと思います。

より洗練された同様の仕組みについては、AWS公式のGitHubリポジトリや記事で公開・紹介されておりますので、こちらも是非ご参照ください。

github.com

aws.amazon.com

全体構成

全体構成は下図のようになっています。

ワークフローの各ステップの概要について簡単に記載します。詳細は後述します。

No. ステップ名 概要
1 aws-update-check AWSアップデートのRSSから最新記事のタイトルとリンクを取得する
2 Choice 最新の記事が存在するかどうか判断する
3 aws-update-description 最新記事の内容を取得する
4 aws-update-summarize 最新記事の内容を要約する
5 aws-update-make-mail-text 通知メールの本文を作成する
6 メール通知(アップデートあり) アップデート情報をメール通知する
7 メール通知(アップデートなし) アップデートが無かった旨をメール通知する

各ステップの詳細について

ここからは各ステップの詳細について記載します。

1. aws-update-check

Lambda関数

このLambda関数は、AWSアップデートのRSSから最新記事のタイトルとリンクを取得します。最新記事については、Lambdaを実行した日付と同日のものとします。

ランタイムはPython3.12です。具体的なコードは以下です。

クリックすると展開します

import datetime
from rss_parser import RSSParser
import requests

def lambda_handler(event, context):

    # AWSアップデートのRSS情報を取得
    rss_url = "https://aws.amazon.com/about-aws/whats-new/recent/feed/"
    response = requests.get(rss_url)
    rss = RSSParser.parse(response.text)
    items = rss.channel.items

    # 本日の日付をUTCで取得し、YYYY-MM-DD型の文字列に変換
    today = datetime.date.today()
    todaystr = today.strftime('%Y-%m-%d')

    # 最新のアップデートを格納するための空のリストを作成
    newupdate = []
    result_update = []

    # RSS情報の時刻(GMT)を取得。本日の日付と一致しているもののみリストに追加
    for item in items:
        gmtdatestr = datetime.datetime.strptime(item.pub_date.content, '%a, %d %b %Y %H:%M:%S %Z').strftime('%Y-%m-%d')
    
        if gmtdatestr == todaystr:
            newupdate.append(item)

    # 本日の日付と一致しているアップデートの一覧から、タイトルとリンクだけを取り出し、別のリストに追加
    for update in newupdate:
        update_dict = dict(title=update.title.content, link=update.link.content)
        result_update.append(update_dict)
        
    return {
        'statusCode': 200,
        'body': result_update
    }

rss_parser と requests は標準関数ではないので、パッケージをLambdaレイヤーで追加しています。
RSSの日付が「Mon, 15 Jul 2024 03:16:05 GMT」といった書式なので、これを「2024-07-15」の「YYYY-MM-DD」型に変換してから比較しています。 Lambda関数のreturnは以下のようになります。

クリックすると展開します

{
  "statusCode": 200,
  "body": [
    {
      "title": "Announcing IDE workspace context awareness in Q Developer chat",
      "link": "https://aws.amazon.com/about-aws/whats-new/2024/07/ide-workspace-context-awareness-q-developer-chat"
    },
    {
      "title": "AWS Secrets Manager announces open source release of Secrets Manager Agent",
      "link": "https://aws.amazon.com/about-aws/whats-new/2024/07/aws-secrets-manager-open-source-secrets-manager-agent"
    },
    {
      "title": "Amazon ECS now enforces software version consistency for containerized applications",
      "link": "https://aws.amazon.com/about-aws/whats-new/2024/07/amazon-ecs-software-version-consistency-containerized-applications"
    },
    {
      "title": "Amazon RDS for SQL Server supports minor version 2019 CU27",
      "link": "https://aws.amazon.com/about-aws/whats-new/2024/07/amazon-rds-sql-server-minor-version-2019-cu27"
    },
    {
      "title": "Announcing availability of AWS Outposts in Senegal",
      "link": "https://aws.amazon.com/about-aws/whats-new/2024/07/availability-aws-outposts-senegal"
    },
    {
      "title": "AWS Batch now supports gang-scheduling on Amazon EKS using multi-node parallel jobs",
      "link": "https://aws.amazon.com/about-aws/whats-new/2024/07/aws-batch-gang-scheduling-eks-multi-node-parallel-jobs/"
    },
    {
      "title": "Chatting about your AWS resources is now generally available for Amazon Q Developer",
      "link": "https://aws.amazon.com/about-aws/whats-new/2024/07/chatting-aws-resources-generally-available-amazon-q-developer"
    },
    {
      "title": "AWS Neuron introduces Flash Attention kernel enabling high performance and large sequence lengths",
      "link": "https://aws.amazon.com/about-aws/whats-new/2024/07/aws-neuron-flash-kernel-performance-sequence-lengths/"
    },
    {
      "title": "Amazon ECS now provides enhanced stopped task error messages for easier troubleshooting",
      "link": "https://aws.amazon.com/about-aws/whats-new/2024/07/amazon-ecs-stopped-task-error-messages-troubleshooting/"
    },
    {
      "title": "RDS Performance Insights provides support for AWS PrivateLink and IPv6",
      "link": "https://aws.amazon.com/about-aws/whats-new/2024/07/rds-performance-insights-privatelink-ipv6/"
    }
  ]
}

Step Functions

このLambda関数は入力値を必要としないので、Step Functions の入力には何も指定しません。
出力では、ResultSelectorを使用し、Lambda関数のreturnのbody部分のみを取得します。その際、キーを「TitleLinkTest」に変換してます。

Step Functionsの出力としては以下のようになります。

クリックすると展開します

{
  "TitleLinkList": [
    {
      "title": "Announcing IDE workspace context awareness in Q Developer chat",
      "link": "https://aws.amazon.com/about-aws/whats-new/2024/07/ide-workspace-context-awareness-q-developer-chat"
    },
    {
      "title": "AWS Secrets Manager announces open source release of Secrets Manager Agent",
      "link": "https://aws.amazon.com/about-aws/whats-new/2024/07/aws-secrets-manager-open-source-secrets-manager-agent"
    },
    {
      "title": "Amazon ECS now enforces software version consistency for containerized applications",
      "link": "https://aws.amazon.com/about-aws/whats-new/2024/07/amazon-ecs-software-version-consistency-containerized-applications"
    },
    {
      "title": "Amazon RDS for SQL Server supports minor version 2019 CU27",
      "link": "https://aws.amazon.com/about-aws/whats-new/2024/07/amazon-rds-sql-server-minor-version-2019-cu27"
    },
    {
      "title": "Announcing availability of AWS Outposts in Senegal",
      "link": "https://aws.amazon.com/about-aws/whats-new/2024/07/availability-aws-outposts-senegal"
    },
    {
      "title": "Chatting about your AWS resources is now generally available for Amazon Q Developer",
      "link": "https://aws.amazon.com/about-aws/whats-new/2024/07/chatting-aws-resources-generally-available-amazon-q-developer"
    },
    {
      "title": "AWS Batch now supports gang-scheduling on Amazon EKS using multi-node parallel jobs",
      "link": "https://aws.amazon.com/about-aws/whats-new/2024/07/aws-batch-gang-scheduling-eks-multi-node-parallel-jobs/"
    },
    {
      "title": "AWS Neuron introduces Flash Attention kernel enabling high performance and large sequence lengths",
      "link": "https://aws.amazon.com/about-aws/whats-new/2024/07/aws-neuron-flash-kernel-performance-sequence-lengths/"
    },
    {
      "title": "Amazon ECS now provides enhanced stopped task error messages for easier troubleshooting",
      "link": "https://aws.amazon.com/about-aws/whats-new/2024/07/amazon-ecs-stopped-task-error-messages-troubleshooting/"
    },
    {
      "title": "RDS Performance Insights provides support for AWS PrivateLink and IPv6",
      "link": "https://aws.amazon.com/about-aws/whats-new/2024/07/rds-performance-insights-privatelink-ipv6/"
    }
  ]
}


アップデートが無かった場合は、出力は以下のようになります。

{
  "TitleLinkList": []
}

2. Choice

このステップでは、最新のAWSアップデートが存在したかどうかで処理を分岐します。AWSアップデートが存在しなかった場合、前ステップの出力の「TitleLinkList」が空になるので、その場合はアップデートなしのメール通知に分岐させます。それ以外の場合は次のLambda関数に進みます。

3. aws-update-description

Lambda関数

このLambda関数は、WEBスクレイピングで最新記事のページから本文の内容を取得します。ランタイムはPython3.12です。具体的なコードは以下です。

クリックすると展開します

import requests
from bs4 import BeautifulSoup

def lambda_handler(event, context):
    
    # 最新記事のタイトルとリンクのリストを取得
    TitleLinkList = event["TitleLinkList"]

    # 最新記事の内容を格納する新規のリストを作成
    description_list = []
    
    # 最新記事の内容を取得し、リストに追加
    for x in TitleLinkList:
        url = x['link'] # 最新記事のURLを取得
        response = requests.get(url) # 最新記事のHTMLを取得
        soup = BeautifulSoup(response.text, features="html.parser")
        main = soup.find("main") # 最新記事の内容を取得
        description_dict = dict(description=main.text) # 最新記事の内容を辞書に格納
        description_list.append(description_dict) # 辞書の内容をリストに追加
        
    return {
        'statusCode': 200,
        'body': description_list
    }

requests と BeautifulSoup はパッケージをLambdaレイヤーで追加しています。また、この関数の実行は3秒では終わらないため、タイムアウト値を30秒に設定しています(実際には10秒もかかりませんが)。Lambda関数のreturnは以下のようになります。

クリックすると展開します

{
  "statusCode": 200,
  "body": [
    {
      "description": "\n\n\n\n\n\n\n\nAnnouncing IDE workspace context awareness in Q Developer chat\n\n           Posted on: \n          Jul 11, 2024 \n         \n\nToday, AWS announces IDE workspace context awareness in Amazon Q Developer chat. Users can now add @workspace to their chat message to Amazon Q Developer to ask questions about the code in the project they currently have open in the integrated development environment (IDE). Developers can ask questions like “@workspace what does this codebase do?” or “how does this @workspace implement authentication and authorization?”.  Previously, Amazon Q Developer chat in the IDE could only answer questions about your currently opened code file. Now, Q Developer automatically ingests and indexes all code files, configurations, and project structure, giving the chat comprehensive context across your entire application within the IDE. The index is stored locally and is created the first time you mention @workspace.  To get started, make sure you are using the most up-to-date version of the Amazon Q Developer IDE extension, open the Q chat in your IDE, and just ask a question that includes @workspace.\n\n\n\n\n\n\n"
    },
    {
      "description": "\n\n\n\n\n\n\n\nAWS Secrets Manager announces open source release of Secrets Manager Agent\n\n           Posted on: \n          Jul 11, 2024 \n         \n\nAWS Secrets Manager today announces Secrets Manager Agent - a language agnostic local HTTP service that you can install and use in your compute environments to read secrets from Secrets Manager and cache them in memory. With this launch, you can now simplify and standardize the way you read secrets across compute environments without the need for custom code.  Secrets Manager Agent is an open source release that your applications can use to retrieve secrets from a local HTTP service instead of making a network call to Secrets Manager. With customizable configuration options such as time to live, cache size, maximum connections, and HTTP port, you can adapt the agent based on your application needs. The agent also offers built-in protection against Server Side Request Forgery (SSRF) to ensure security when calling the agent within your compute environment.  The Secrets Manager Agent open source code is available on GitHub and can be used in all AWS Regions where AWS Secrets Manager is available. To learn more about how to use Secrets Manager Agent, visit our documentation.\n\n\n\n\n\n\n"
    },
    {
      "description": "\n\n\n\n\n\n\n\nAmazon ECS now enforces software version consistency for containerized applications\n\n           Posted on: \n          Jul 11, 2024 \n         \n\nAmazon Elastic Container Service (Amazon ECS) now enforces software version consistency for your containerized applications, helping you ensure all tasks in your application are identical and that all code changes go through the safeguards defined in your deployment pipeline.  Customers deploy long-running applications such as HTTP-based microservices as Amazon ECS services and often use container image tags to configure these services. Although container images are immutable, image tags aren’t immutable by default and there is no standard mechanism to prevent different versions from being unintentionally deployed when you configure a containerized application using image tags. To prevent such inconsistencies, Amazon ECS now resolves container image tags to the image digest (SHA256 hash of the image manifest) when you deploy an update to your Amazon ECS service and enforces that all tasks in the service are identical and launched with this image digest(s). This means, even if you use a mutable image tag like ‘LATEST’ in your task definition and your service scales out after the deployment, the correct image (which was used when deploying the service) is used for launching new tasks.  \n\n\nAmazon ECS automatically enforces software version consistency for services created or updated after June 25 2024, running on AWS Fargate platform version 1.4.0 or higher and/or version v1.70.0 or higher of the Amazon ECS Agent in all commercial and the AWS GovCloud (US) Regions. To learn more, please read this blog post or visit our documentation.\n\n\n\n\n\n\n"
    },
    {
      "description": "\n\n\n\n\n\n\n\nAmazon RDS for SQL Server supports minor version 2019 CU27\n\n           Posted on: \n          Jul 11, 2024 \n         \n\nA new minor version of Microsoft SQL Server is now available on Amazon RDS for SQL Server, providing performance enhancements and security fixes. Amazon RDS for SQL Server now supports the latest minor version of SQL Server 2019 across the Express, Web, Standard, and Enterprise editions.  We encourage you to upgrade your Amazon RDS for SQL Server database instances at your convenience. You can upgrade with just a few clicks in the Amazon RDS Management Console or by using the AWS CLI. Learn more about upgrading your database instances from the Amazon RDS User Guide. The new minor version include SQL Server 2019 CU27 - 15.0.4375.4.  The minor version is available in all AWS regions where Amazon RDS for SQL Server databases are available, including the AWS GovCloud (US) Regions.  Amazon RDS for SQL Server makes it simple to set up, operate, and scale SQL Server deployments in the cloud. See Amazon RDS for SQL Server Pricing for pricing details and regional availability.\n\n\n\n\n\n\n"
    },
    {
      "description": "\n\n\n\n\n\n\n\nAnnouncing availability of AWS Outposts in Senegal\n\n           Posted on: \n          Jul 11, 2024 \n         \n\nAWS Outposts can now be shipped and installed at your data center and on-premises locations in Senegal.  AWS Outposts is a family of fully managed solutions that extends AWS infrastructure, AWS services, APIs, and tools to virtually any on-premises or edge location for a truly consistent hybrid experience. Outposts is ideal for workloads that require low latency access to on-premises systems, local data processing, and migration of applications with local system interdependencies. Outposts can also help meet data residency requirements. Outposts is available in a variety of form factors, from 1U and 2U Outposts servers to 42U Outposts racks, and multiple rack deployments.  With the availability of Outposts in Senegal, you can use AWS services to run your workloads and data in country in your on-premises facilities and connect to your nearest AWS Region for management and operations.  To learn more about Outposts, read the product overview and user guide. For the most updated list of countries and territories where Outposts is supported, check out the Outposts rack FAQs page and the Outposts servers FAQs page.\n\n\n\n\n\n\n"
    },
    {
      "description": "\n\n\n\n\n\n\n\nChatting about your AWS resources is now generally available for Amazon Q Developer\n\n           Posted on: \n          Jul 11, 2024 \n         \n\nToday, AWS announces the general availability of Amazon Q Developer’s capability to chat about your AWS account resources. With this capability, you can use natural language prompts to list resources in your AWS account, get specific resource details, and ask about related resources.  From the Amazon Q Developer chat panel in the AWS Management Console, you can ask Q to “list my S3 buckets” or “show my running EC2 instances in us-east-1” and Amazon Q returns a list of resource details, along with a summary. You can ask what Amazon EC2 instances an Amazon CloudWatch alarm is monitoring or ask “what related resources does my ec2 instance <id> have?” and Amazon Q Developer shows attached Amazon EBS volumes, configured Amazon VPCs, and AWS IAM roles for Amazon EC2 instances automatically.  To learn more, visit Amazon Q Developer or the documentation.\n\n\n\n\n\n\n"
    },
    {
      "description": "\n\n\n\n\n\n\n\nAWS Batch now supports gang-scheduling on Amazon EKS using multi-node parallel jobs\n\n           Posted on: \n          Jul 11, 2024 \n         \n\nToday, AWS announces the general availability of Multi-Node Parallel (MNP) jobs in AWS Batch on Amazon Elastic Kubernetes Service (Amazon EKS). With AWS Batch MNP jobs you can run tightly-coupled High Performance Computing (HPC) applications like training multi-layer AI/ML models. AWS Batch helps you to launch, configure, and manage nodes in your Amazon EKS cluster without manual intervention.  You can configure MNP jobs using the RegisterJobsDefinition API or via job definitions sections of AWS Batch Management Console. With MNP jobs you can run AWS Batch on Amazon EKS workloads that span multiple Amazon Elastic Compute Cloud (Amazon EC2) instances. AWS Batch MNP jobs support any IP-based inter-instance communications framework, such as NVIDIA Collective Communications Library (NCCL), Gloo, Message Passing Interface (MPI), or Unified Collective Communication (UCC) as well as machine learning and parallel computing libraries such as PyTorch and Dask. For more information, see Multi-Node Parallel jobs page in the AWS Batch User Guide.  AWS Batch supports developers, scientists, and engineers in running efficient batch processing for ML model training, simulations, and analysis at any scale. Multi-Node Parallel jobs are available in any AWS Region where AWS Batch is available.  \n\n\n\n\n\n\n"
    },
    {
      "description": "\n\n\n\n\n\n\n\nAWS Neuron introduces Flash Attention kernel enabling high performance and large sequence lengths\n\n           Posted on: \n          Jul 11, 2024 \n         \n\nToday, AWS announces the release of Neuron 2.19, introducing support for flash attention kernel to enable performant LLM model training and inference with large sequence lengths.  AWS Neuron is the SDK for AWS Inferentia and Trainium based instances purpose-built for generative AI. Neuron integrates with popular ML frameworks like PyTorch. It includes a compiler, runtime, tools, and libraries to support high performance training and inference of AI models on Trn1 and Inf2 instances.  This release adds new features and performance improvements for both training and inference and new Ubuntu 22 Neuron DLAMIs for PyTorch 2.1 and PyTorch 1.13. Neuron 2.19 adds support for Flash Attention kernel to enable training for large sequence lengths (greater than or equal to 8K), Llama3 model training, and interleaved pipeline parallelism to enhance training efficiency and resource utilization. For inference, this release adds Flash Attention kernel support to enable LLM inference for context lengths of up to 32k. Neuron 2.19 additionally adds support for Llama3 model inference and adds beta support for continuous batching with Mistral-7B-v0.2 models. Neuron 2.19 introduces new tools: Neuron Node Problem Detector and Recovery plugin in EKS and Neuron Monitor for EKS to enable enhanced Neuron metrics monitoring in Kubernetes.  You can use AWS Neuron SDK to train and deploy models on Trn1 and Inf2 instances, available in AWS Regions as On-Demand Instances, Reserved Instances, Spot Instances, or part of Savings Plan.  For a list of features in Neuron 2.19, visit Neuron Release Notes. To get started with Neuron, see: AWS Neuron Inf2 Instances Trn1 Instances  \n\n\n\n\n\n\n"
    },
    {
      "description": "\n\n\n\n\n\n\n\nAmazon ECS now provides enhanced stopped task error messages for easier troubleshooting\n\n           Posted on: \n          Jul 11, 2024 \n         \n\nAmazon Elastic Container Services (Amazon ECS) now makes it easier to troubleshoot task launch failures with enhanced stopped task error messages. When your Amazon ECS task fails to launch, you see the stopped task error messages in the AWS Management Console or in the ECS DescribeTasks API response. With today’s launch, Amazon ECS stopped task error messages are now more specific and actionable.  Amazon ECS is designed to help easily launch and scale your applications. When your Amazon ECS task fails to launch, you can use the Amazon ECS stopped task error message to identify the failure reason and resolve the failure. With this launch, stopped task error messages from common task launch failures now include more specific failure reasons and remediation recommendations. Amazon ECS documentation for these failures additionally provides in-depth root cause details and steps to mitigate the failure. If you manage your applications running on Amazon ECS using the AWS Management Console, error messages now include a direct link to the relevant Amazon ECS troubleshooting documentation page such as this Troubleshooting Amazon ECS ResourceInitializationError errors page, making it easier for you to access detailed information and resolve failures faster.  The new experience is now automatically enabled in all AWS Regions. See more details in Amazon ECS stopped task error messages updates.  \n\n\n\n\n\n\n"
    },
    {
      "description": "\n\n\n\n\n\n\n\nRDS Performance Insights provides support for AWS PrivateLink and IPv6\n\n           Posted on: \n          Jul 11, 2024 \n         \n\nAmazon RDS (Relational Database Service) Performance Insights now provides support for AWS PrivateLink and Internet Protocol Version 6 (IPv6). Customers can now access Performance Insights API/CLI privately, without going through the public Internet. Additionally, Performance Insights includes support for IPv6 connectivity and for a dual stack configuration (IPv4 and IPv6).  AWS PrivateLink provides private, secure, and scalable connectivity between virtual private clouds (VPCs) and AWS services. Customers can now prevent sensitive data, such as SQL text, from traversing the Internet to maintain compliance with regulations such as HIPAA and PCI . With IPv6 support, scaling an application on AWS is no longer constrained by the number of IPv4 addresses in the VPC. This eliminates the need for complex architectures to work around the limits of public IPv4 addresses.  Amazon RDS Performance Insights is a database performance tuning and monitoring feature of RDS that allows you to visually assess the load on your database and determine when and where to take action. With one click in the Amazon RDS Management Console, you can add a fully-managed performance monitoring solution to your Amazon RDS database.  To learn more about RDS Performance Insights, read the Amazon RDS User Guide and visit Performance Insights pricing for pricing details and region availability.  \n\n\n\n\n\n\n"
    }
  ]
}

Step Functions

入力は、ステップ1の出力をそのまま使います。出力では、ResultSelectorを使用し、body部分を「description_list」として取得します。また、ResultPathを使用し、入力値(ステップ1の出力値)も合わせて出力します。

結果的に、Step Functionsの出力は以下のようになります。

クリックすると展開します

{
  "TitleLinkList": [
    {
      "title": "Announcing IDE workspace context awareness in Q Developer chat",
      "link": "https://aws.amazon.com/about-aws/whats-new/2024/07/ide-workspace-context-awareness-q-developer-chat"
    },
    {
      "title": "AWS Secrets Manager announces open source release of Secrets Manager Agent",
      "link": "https://aws.amazon.com/about-aws/whats-new/2024/07/aws-secrets-manager-open-source-secrets-manager-agent"
    },
    {
      "title": "Amazon ECS now enforces software version consistency for containerized applications",
      "link": "https://aws.amazon.com/about-aws/whats-new/2024/07/amazon-ecs-software-version-consistency-containerized-applications"
    },
    {
      "title": "Amazon RDS for SQL Server supports minor version 2019 CU27",
      "link": "https://aws.amazon.com/about-aws/whats-new/2024/07/amazon-rds-sql-server-minor-version-2019-cu27"
    },
    {
      "title": "Announcing availability of AWS Outposts in Senegal",
      "link": "https://aws.amazon.com/about-aws/whats-new/2024/07/availability-aws-outposts-senegal"
    },
    {
      "title": "Chatting about your AWS resources is now generally available for Amazon Q Developer",
      "link": "https://aws.amazon.com/about-aws/whats-new/2024/07/chatting-aws-resources-generally-available-amazon-q-developer"
    },
    {
      "title": "AWS Batch now supports gang-scheduling on Amazon EKS using multi-node parallel jobs",
      "link": "https://aws.amazon.com/about-aws/whats-new/2024/07/aws-batch-gang-scheduling-eks-multi-node-parallel-jobs/"
    },
    {
      "title": "AWS Neuron introduces Flash Attention kernel enabling high performance and large sequence lengths",
      "link": "https://aws.amazon.com/about-aws/whats-new/2024/07/aws-neuron-flash-kernel-performance-sequence-lengths/"
    },
    {
      "title": "Amazon ECS now provides enhanced stopped task error messages for easier troubleshooting",
      "link": "https://aws.amazon.com/about-aws/whats-new/2024/07/amazon-ecs-stopped-task-error-messages-troubleshooting/"
    },
    {
      "title": "RDS Performance Insights provides support for AWS PrivateLink and IPv6",
      "link": "https://aws.amazon.com/about-aws/whats-new/2024/07/rds-performance-insights-privatelink-ipv6/"
    }
  ],
  "DescriptionResult": {
    "description_list": [
      {
        "description": "\n\n\n\n\n\n\n\nAnnouncing IDE workspace context awareness in Q Developer chat\n\n           Posted on: \n          Jul 11, 2024 \n         \n\nToday, AWS announces IDE workspace context awareness in Amazon Q Developer chat. Users can now add @workspace to their chat message to Amazon Q Developer to ask questions about the code in the project they currently have open in the integrated development environment (IDE). Developers can ask questions like “@workspace what does this codebase do?” or “how does this @workspace implement authentication and authorization?”.  Previously, Amazon Q Developer chat in the IDE could only answer questions about your currently opened code file. Now, Q Developer automatically ingests and indexes all code files, configurations, and project structure, giving the chat comprehensive context across your entire application within the IDE. The index is stored locally and is created the first time you mention @workspace.  To get started, make sure you are using the most up-to-date version of the Amazon Q Developer IDE extension, open the Q chat in your IDE, and just ask a question that includes @workspace.\n\n\n\n\n\n\n"
      },
      {
        "description": "\n\n\n\n\n\n\n\nAWS Secrets Manager announces open source release of Secrets Manager Agent\n\n           Posted on: \n          Jul 11, 2024 \n         \n\nAWS Secrets Manager today announces Secrets Manager Agent - a language agnostic local HTTP service that you can install and use in your compute environments to read secrets from Secrets Manager and cache them in memory. With this launch, you can now simplify and standardize the way you read secrets across compute environments without the need for custom code.  Secrets Manager Agent is an open source release that your applications can use to retrieve secrets from a local HTTP service instead of making a network call to Secrets Manager. With customizable configuration options such as time to live, cache size, maximum connections, and HTTP port, you can adapt the agent based on your application needs. The agent also offers built-in protection against Server Side Request Forgery (SSRF) to ensure security when calling the agent within your compute environment.  The Secrets Manager Agent open source code is available on GitHub and can be used in all AWS Regions where AWS Secrets Manager is available. To learn more about how to use Secrets Manager Agent, visit our documentation.\n\n\n\n\n\n\n"
      },
      {
        "description": "\n\n\n\n\n\n\n\nAmazon ECS now enforces software version consistency for containerized applications\n\n           Posted on: \n          Jul 11, 2024 \n         \n\nAmazon Elastic Container Service (Amazon ECS) now enforces software version consistency for your containerized applications, helping you ensure all tasks in your application are identical and that all code changes go through the safeguards defined in your deployment pipeline.  Customers deploy long-running applications such as HTTP-based microservices as Amazon ECS services and often use container image tags to configure these services. Although container images are immutable, image tags aren’t immutable by default and there is no standard mechanism to prevent different versions from being unintentionally deployed when you configure a containerized application using image tags. To prevent such inconsistencies, Amazon ECS now resolves container image tags to the image digest (SHA256 hash of the image manifest) when you deploy an update to your Amazon ECS service and enforces that all tasks in the service are identical and launched with this image digest(s). This means, even if you use a mutable image tag like ‘LATEST’ in your task definition and your service scales out after the deployment, the correct image (which was used when deploying the service) is used for launching new tasks.  \n\n\nAmazon ECS automatically enforces software version consistency for services created or updated after June 25 2024, running on AWS Fargate platform version 1.4.0 or higher and/or version v1.70.0 or higher of the Amazon ECS Agent in all commercial and the AWS GovCloud (US) Regions. To learn more, please read this blog post or visit our documentation.\n\n\n\n\n\n\n"
      },
      {
        "description": "\n\n\n\n\n\n\n\nAmazon RDS for SQL Server supports minor version 2019 CU27\n\n           Posted on: \n          Jul 11, 2024 \n         \n\nA new minor version of Microsoft SQL Server is now available on Amazon RDS for SQL Server, providing performance enhancements and security fixes. Amazon RDS for SQL Server now supports the latest minor version of SQL Server 2019 across the Express, Web, Standard, and Enterprise editions.  We encourage you to upgrade your Amazon RDS for SQL Server database instances at your convenience. You can upgrade with just a few clicks in the Amazon RDS Management Console or by using the AWS CLI. Learn more about upgrading your database instances from the Amazon RDS User Guide. The new minor version include SQL Server 2019 CU27 - 15.0.4375.4.  The minor version is available in all AWS regions where Amazon RDS for SQL Server databases are available, including the AWS GovCloud (US) Regions.  Amazon RDS for SQL Server makes it simple to set up, operate, and scale SQL Server deployments in the cloud. See Amazon RDS for SQL Server Pricing for pricing details and regional availability.\n\n\n\n\n\n\n"
      },
      {
        "description": "\n\n\n\n\n\n\n\nAnnouncing availability of AWS Outposts in Senegal\n\n           Posted on: \n          Jul 11, 2024 \n         \n\nAWS Outposts can now be shipped and installed at your data center and on-premises locations in Senegal.  AWS Outposts is a family of fully managed solutions that extends AWS infrastructure, AWS services, APIs, and tools to virtually any on-premises or edge location for a truly consistent hybrid experience. Outposts is ideal for workloads that require low latency access to on-premises systems, local data processing, and migration of applications with local system interdependencies. Outposts can also help meet data residency requirements. Outposts is available in a variety of form factors, from 1U and 2U Outposts servers to 42U Outposts racks, and multiple rack deployments.  With the availability of Outposts in Senegal, you can use AWS services to run your workloads and data in country in your on-premises facilities and connect to your nearest AWS Region for management and operations.  To learn more about Outposts, read the product overview and user guide. For the most updated list of countries and territories where Outposts is supported, check out the Outposts rack FAQs page and the Outposts servers FAQs page.\n\n\n\n\n\n\n"
      },
      {
        "description": "\n\n\n\n\n\n\n\nChatting about your AWS resources is now generally available for Amazon Q Developer\n\n           Posted on: \n          Jul 11, 2024 \n         \n\nToday, AWS announces the general availability of Amazon Q Developer’s capability to chat about your AWS account resources. With this capability, you can use natural language prompts to list resources in your AWS account, get specific resource details, and ask about related resources.  From the Amazon Q Developer chat panel in the AWS Management Console, you can ask Q to “list my S3 buckets” or “show my running EC2 instances in us-east-1” and Amazon Q returns a list of resource details, along with a summary. You can ask what Amazon EC2 instances an Amazon CloudWatch alarm is monitoring or ask “what related resources does my ec2 instance <id> have?” and Amazon Q Developer shows attached Amazon EBS volumes, configured Amazon VPCs, and AWS IAM roles for Amazon EC2 instances automatically.  To learn more, visit Amazon Q Developer or the documentation.\n\n\n\n\n\n\n"
      },
      {
        "description": "\n\n\n\n\n\n\n\nAWS Batch now supports gang-scheduling on Amazon EKS using multi-node parallel jobs\n\n           Posted on: \n          Jul 11, 2024 \n         \n\nToday, AWS announces the general availability of Multi-Node Parallel (MNP) jobs in AWS Batch on Amazon Elastic Kubernetes Service (Amazon EKS). With AWS Batch MNP jobs you can run tightly-coupled High Performance Computing (HPC) applications like training multi-layer AI/ML models. AWS Batch helps you to launch, configure, and manage nodes in your Amazon EKS cluster without manual intervention.  You can configure MNP jobs using the RegisterJobsDefinition API or via job definitions sections of AWS Batch Management Console. With MNP jobs you can run AWS Batch on Amazon EKS workloads that span multiple Amazon Elastic Compute Cloud (Amazon EC2) instances. AWS Batch MNP jobs support any IP-based inter-instance communications framework, such as NVIDIA Collective Communications Library (NCCL), Gloo, Message Passing Interface (MPI), or Unified Collective Communication (UCC) as well as machine learning and parallel computing libraries such as PyTorch and Dask. For more information, see Multi-Node Parallel jobs page in the AWS Batch User Guide.  AWS Batch supports developers, scientists, and engineers in running efficient batch processing for ML model training, simulations, and analysis at any scale. Multi-Node Parallel jobs are available in any AWS Region where AWS Batch is available.  \n\n\n\n\n\n\n"
      },
      {
        "description": "\n\n\n\n\n\n\n\nAWS Neuron introduces Flash Attention kernel enabling high performance and large sequence lengths\n\n           Posted on: \n          Jul 11, 2024 \n         \n\nToday, AWS announces the release of Neuron 2.19, introducing support for flash attention kernel to enable performant LLM model training and inference with large sequence lengths.  AWS Neuron is the SDK for AWS Inferentia and Trainium based instances purpose-built for generative AI. Neuron integrates with popular ML frameworks like PyTorch. It includes a compiler, runtime, tools, and libraries to support high performance training and inference of AI models on Trn1 and Inf2 instances.  This release adds new features and performance improvements for both training and inference and new Ubuntu 22 Neuron DLAMIs for PyTorch 2.1 and PyTorch 1.13. Neuron 2.19 adds support for Flash Attention kernel to enable training for large sequence lengths (greater than or equal to 8K), Llama3 model training, and interleaved pipeline parallelism to enhance training efficiency and resource utilization. For inference, this release adds Flash Attention kernel support to enable LLM inference for context lengths of up to 32k. Neuron 2.19 additionally adds support for Llama3 model inference and adds beta support for continuous batching with Mistral-7B-v0.2 models. Neuron 2.19 introduces new tools: Neuron Node Problem Detector and Recovery plugin in EKS and Neuron Monitor for EKS to enable enhanced Neuron metrics monitoring in Kubernetes.  You can use AWS Neuron SDK to train and deploy models on Trn1 and Inf2 instances, available in AWS Regions as On-Demand Instances, Reserved Instances, Spot Instances, or part of Savings Plan.  For a list of features in Neuron 2.19, visit Neuron Release Notes. To get started with Neuron, see: AWS Neuron Inf2 Instances Trn1 Instances  \n\n\n\n\n\n\n"
      },
      {
        "description": "\n\n\n\n\n\n\n\nAmazon ECS now provides enhanced stopped task error messages for easier troubleshooting\n\n           Posted on: \n          Jul 11, 2024 \n         \n\nAmazon Elastic Container Services (Amazon ECS) now makes it easier to troubleshoot task launch failures with enhanced stopped task error messages. When your Amazon ECS task fails to launch, you see the stopped task error messages in the AWS Management Console or in the ECS DescribeTasks API response. With today’s launch, Amazon ECS stopped task error messages are now more specific and actionable.  Amazon ECS is designed to help easily launch and scale your applications. When your Amazon ECS task fails to launch, you can use the Amazon ECS stopped task error message to identify the failure reason and resolve the failure. With this launch, stopped task error messages from common task launch failures now include more specific failure reasons and remediation recommendations. Amazon ECS documentation for these failures additionally provides in-depth root cause details and steps to mitigate the failure. If you manage your applications running on Amazon ECS using the AWS Management Console, error messages now include a direct link to the relevant Amazon ECS troubleshooting documentation page such as this Troubleshooting Amazon ECS ResourceInitializationError errors page, making it easier for you to access detailed information and resolve failures faster.  The new experience is now automatically enabled in all AWS Regions. See more details in Amazon ECS stopped task error messages updates.  \n\n\n\n\n\n\n"
      },
      {
        "description": "\n\n\n\n\n\n\n\nRDS Performance Insights provides support for AWS PrivateLink and IPv6\n\n           Posted on: \n          Jul 11, 2024 \n         \n\nAmazon RDS (Relational Database Service) Performance Insights now provides support for AWS PrivateLink and Internet Protocol Version 6 (IPv6). Customers can now access Performance Insights API/CLI privately, without going through the public Internet. Additionally, Performance Insights includes support for IPv6 connectivity and for a dual stack configuration (IPv4 and IPv6).  AWS PrivateLink provides private, secure, and scalable connectivity between virtual private clouds (VPCs) and AWS services. Customers can now prevent sensitive data, such as SQL text, from traversing the Internet to maintain compliance with regulations such as HIPAA and PCI . With IPv6 support, scaling an application on AWS is no longer constrained by the number of IPv4 addresses in the VPC. This eliminates the need for complex architectures to work around the limits of public IPv4 addresses.  Amazon RDS Performance Insights is a database performance tuning and monitoring feature of RDS that allows you to visually assess the load on your database and determine when and where to take action. With one click in the Amazon RDS Management Console, you can add a fully-managed performance monitoring solution to your Amazon RDS database.  To learn more about RDS Performance Insights, read the Amazon RDS User Guide and visit Performance Insights pricing for pricing details and region availability.  \n\n\n\n\n\n\n"
      }
    ]
  }
}

4. aws-update-summarize

Lambda関数

このLambda関数では、BedRockを使って、AWSアップデートの内容を日本語で要約させます。BedRockはLangChain経由で使います。基盤モデルはAnturopicのClaude2.1を利用しています。ランタイムはPython3.10です(前回のブログでLangChainを使った時のPythonバージョンが3.10だったので、合わせました)。具体的なコードは以下です。

クリックすると展開します

from langchain_aws import BedrockLLM

def lambda_handler(event, context):
    
    # 基盤モデルにClaude2.1を指定し、LLMオブジェクトを作成
    llm = BedrockLLM(
        model_id="anthropic.claude-v2:1"
    )
    
    # 記事の内容のリストを取得
    description_list = event["DescriptionResult"]["description_list"]
    
    # 記事の要約を格納するリストを新規作成
    summarize_list = []
    
    # リストから記事の内容を取り出し、要約させた結果を新規リストに追加
    for x in description_list:
        description = x['description']
        
        prompt = f"""
        下記の内容を150文字以内で日本語で要約してください。誰にどのようなメリットがあるのかという点を必ず含めるようにしてください。
        {description}
        """

        result = llm.generate(
            [prompt],
            {
                "temperature":0.7,
                "maxTokens": 300,
                "topP": 1
            }
        )

        summarize = result.generations[0][0].text.strip()
        summarize_dict = dict(summarize=summarize)
        summarize_list.append(summarize_dict)
    
    return {
        'statusCode': 200,
        'body': summarize_list
    }

langchain_aws はLambdaレイヤーでパッケージを追加しています。また、この関数の実行はそれなりに時間がかかり、3秒では終わらないため、タイムアウト値を3分0秒に設定しています。Lambda関数のreturnは以下のようになります。

クリックすると展開します

{
  "statusCode": 200,
  "body": [
    {
        "summarize": "AWSのQ Developerチャット機能が、IDE上で開発者が現在作業しているプロジェクトのコンテキストを理解できるようになりました。開発者は「@workspaceこのコードは何をしているか」などと質問でき、チャットボットがプロジェクト全体のコードや設定ファイルの内容を参照して回答することができます。これにより開発効率の向上や開発生産性の改善などのメリットが期待できます。"
    },
    {
        "summarize": "AWS Secrets Managerが、シークレットをローカルでキャッシュするSecrets Manager Agentをオープンソースで公開しました。これにより、お客様はカスタムコードなしに、コンピューティング環境間でのシークレットの読み取りを標準化できるようになります。Secrets Manager Agentを利用することで、アプリケーションはネットワークコールを行うことなく、ローカルHTTPサービスからシークレットを取得できるため、運用コストとセキュリティの両面でメリットがあります。"
    },
    {
        "summarize": "Amazon ECSがコンテナ化されたアプリケーションのバージョンの整合性を強制することで、お客様のアプリケーション内のすべてのタスクが同一であることと、すべてのコード変更がデプロイメントパイプラインで定義された安全保護を経ることを確実にすることができます。これによりアプリケーションの信頼性が向上し、お客様の運用が容易になります。"
    },
    {
        "summarize": "Amazon RDS for SQL Serverが、パフォーマンス向上とセキュリティ修正を含むSQL Server 2019の最新マイナーバージョンCU27をサポートするようになりました。これにより、RDS for SQL Serverのユーザーは、わずか数クリックでデータベースインスタンスをアップグレードでき、パフォーマンスとセキュリティの改善を実現できます。"
    },
    {
        "summarize": "AWS Outposts はオンプレミスのデータセンターや施設へAWSのインフラ、サービス、API、ツールを展開できるハイブリッドクラウドソリューションです。セネガルで Outposts の利用が可能になり、オンプレミスでの低レイテンシーなワークロード実行、ローカルデータ処理、依存関係のあるアプリの移行などにメリットがあります。データresidency要件を満たせるほか、1Uから42Uラックまでさまざまな規模の導入が可能です。"
    },
    {
        "summarize": "AWSのチャットボット機能「Amazon Q Developer」が、AWSアカウント内のリソースについての自然言語での問い合わせに対応する一般提供を開始しました。この機能により、S3バケットやEC2インスタンスなどのAWSリソースの一覧表示や詳細情報の取得、関連リソースの表示などが可能になります。AWS管理コンソール内のチャット機能を利用することで、AWSリソースの確認や操作が容易になるなど、AWSユーザーにメリットがあります。"
    },
    {
        "summarize": "AWS BatchがAmazon EKS上でガングスケジューリングをサポートするようになりました。これにより、マルチノードパラレルジョブを使用して、AI/MLモデルのトレーニングなどの密結合型ハイパフォーマンスコンピューティング(HPC)アプリケーションを実行できます。 開発者はマルチノードパラレルジョブを利用することで、複数のAmazon EC2インスタンスにまたがるAWS Batch on Amazon EKSのワークロードを手間なく実行できるようになります。"
    },
    {
        "summarize": "AWS Neuron 2.19では、長いシーケンス長での高速なLLMモデルの学習と推論を可能にするFlash Attentionカーネルのサポートが追加されました。これにより、Trn1とInf2インスタンス上で、最大32kのコンテキスト長での高速なLLM推論が可能になります。ユーザーは、これらの目的製インスタンスを利用して、大規模な言語モデルの学習と推論を高速に実行できるようになり、生産性とコストパフォーマンスの向上が期待できます。"
    },
    {
        "summarize": "Amazon ECSが提供する停止したタスクのエラーメッセージが拡張され、トラブルシューティングがより簡単になりました。新しいエラーメッセージは、より具体的でアクション可能な内容になっており、ユーザーは失敗の理由と対処法をすぐに特定できるようになりました。これにより、Amazon ECSでアプリケーションを管理するユーザーは、障害をより迅速に解決できるメリットがあります。"
    },
    {
        "summarize": "RDS Performance InsightsがAWS PrivateLinkとIPv6に対応した。これにより、パフォーマンスインサイトのAPI/CLIをパブリックインターネットを通さずにプライベートにアクセスできる。IPv6接続とIPv4/IPv6デュアルスタック構成にも対応した。これらの機能により、顧客はセンシティブデータをインターネット上に流さずに済み、コンプライアンス面でのメリットがある。またIPv6対応により、IPv4アドレスの制限によるアプリケーションスケーリングの制約がなくなる。"
    }
  ]
}

Step Functions

入力は、前のステップの出力をそのまま使います。出力は、ResultSelectorを使用し、body部分を「summarize_list」として出力します。また、ResultPathを使用して、入力値(=前のステップの出力値)もそのまま出力します。

結果的に、このステップの出力は以下のようになります。

クリックすると展開します

{
  "TitleLinkList": [
    {
      "title": "Announcing IDE workspace context awareness in Q Developer chat",
      "link": "https://aws.amazon.com/about-aws/whats-new/2024/07/ide-workspace-context-awareness-q-developer-chat"
    },
    {
      "title": "AWS Secrets Manager announces open source release of Secrets Manager Agent",
      "link": "https://aws.amazon.com/about-aws/whats-new/2024/07/aws-secrets-manager-open-source-secrets-manager-agent"
    },
    {
      "title": "Amazon ECS now enforces software version consistency for containerized applications",
      "link": "https://aws.amazon.com/about-aws/whats-new/2024/07/amazon-ecs-software-version-consistency-containerized-applications"
    },
    {
      "title": "Amazon RDS for SQL Server supports minor version 2019 CU27",
      "link": "https://aws.amazon.com/about-aws/whats-new/2024/07/amazon-rds-sql-server-minor-version-2019-cu27"
    },
    {
      "title": "Announcing availability of AWS Outposts in Senegal",
      "link": "https://aws.amazon.com/about-aws/whats-new/2024/07/availability-aws-outposts-senegal"
    },
    {
      "title": "Chatting about your AWS resources is now generally available for Amazon Q Developer",
      "link": "https://aws.amazon.com/about-aws/whats-new/2024/07/chatting-aws-resources-generally-available-amazon-q-developer"
    },
    {
      "title": "AWS Batch now supports gang-scheduling on Amazon EKS using multi-node parallel jobs",
      "link": "https://aws.amazon.com/about-aws/whats-new/2024/07/aws-batch-gang-scheduling-eks-multi-node-parallel-jobs/"
    },
    {
      "title": "AWS Neuron introduces Flash Attention kernel enabling high performance and large sequence lengths",
      "link": "https://aws.amazon.com/about-aws/whats-new/2024/07/aws-neuron-flash-kernel-performance-sequence-lengths/"
    },
    {
      "title": "Amazon ECS now provides enhanced stopped task error messages for easier troubleshooting",
      "link": "https://aws.amazon.com/about-aws/whats-new/2024/07/amazon-ecs-stopped-task-error-messages-troubleshooting/"
    },
    {
      "title": "RDS Performance Insights provides support for AWS PrivateLink and IPv6",
      "link": "https://aws.amazon.com/about-aws/whats-new/2024/07/rds-performance-insights-privatelink-ipv6/"
    }
  ],
  "DescriptionResult": {
    "description_list": [
      {
        "description": "\n\n\n\n\n\n\n\nAnnouncing IDE workspace context awareness in Q Developer chat\n\n           Posted on: \n          Jul 11, 2024 \n         \n\nToday, AWS announces IDE workspace context awareness in Amazon Q Developer chat. Users can now add @workspace to their chat message to Amazon Q Developer to ask questions about the code in the project they currently have open in the integrated development environment (IDE). Developers can ask questions like “@workspace what does this codebase do?” or “how does this @workspace implement authentication and authorization?”.  Previously, Amazon Q Developer chat in the IDE could only answer questions about your currently opened code file. Now, Q Developer automatically ingests and indexes all code files, configurations, and project structure, giving the chat comprehensive context across your entire application within the IDE. The index is stored locally and is created the first time you mention @workspace.  To get started, make sure you are using the most up-to-date version of the Amazon Q Developer IDE extension, open the Q chat in your IDE, and just ask a question that includes @workspace.\n\n\n\n\n\n\n"
      },
      {
        "description": "\n\n\n\n\n\n\n\nAWS Secrets Manager announces open source release of Secrets Manager Agent\n\n           Posted on: \n          Jul 11, 2024 \n         \n\nAWS Secrets Manager today announces Secrets Manager Agent - a language agnostic local HTTP service that you can install and use in your compute environments to read secrets from Secrets Manager and cache them in memory. With this launch, you can now simplify and standardize the way you read secrets across compute environments without the need for custom code.  Secrets Manager Agent is an open source release that your applications can use to retrieve secrets from a local HTTP service instead of making a network call to Secrets Manager. With customizable configuration options such as time to live, cache size, maximum connections, and HTTP port, you can adapt the agent based on your application needs. The agent also offers built-in protection against Server Side Request Forgery (SSRF) to ensure security when calling the agent within your compute environment.  The Secrets Manager Agent open source code is available on GitHub and can be used in all AWS Regions where AWS Secrets Manager is available. To learn more about how to use Secrets Manager Agent, visit our documentation.\n\n\n\n\n\n\n"
      },
      {
        "description": "\n\n\n\n\n\n\n\nAmazon ECS now enforces software version consistency for containerized applications\n\n           Posted on: \n          Jul 11, 2024 \n         \n\nAmazon Elastic Container Service (Amazon ECS) now enforces software version consistency for your containerized applications, helping you ensure all tasks in your application are identical and that all code changes go through the safeguards defined in your deployment pipeline.  Customers deploy long-running applications such as HTTP-based microservices as Amazon ECS services and often use container image tags to configure these services. Although container images are immutable, image tags aren’t immutable by default and there is no standard mechanism to prevent different versions from being unintentionally deployed when you configure a containerized application using image tags. To prevent such inconsistencies, Amazon ECS now resolves container image tags to the image digest (SHA256 hash of the image manifest) when you deploy an update to your Amazon ECS service and enforces that all tasks in the service are identical and launched with this image digest(s). This means, even if you use a mutable image tag like ‘LATEST’ in your task definition and your service scales out after the deployment, the correct image (which was used when deploying the service) is used for launching new tasks.  \n\n\nAmazon ECS automatically enforces software version consistency for services created or updated after June 25 2024, running on AWS Fargate platform version 1.4.0 or higher and/or version v1.70.0 or higher of the Amazon ECS Agent in all commercial and the AWS GovCloud (US) Regions. To learn more, please read this blog post or visit our documentation.\n\n\n\n\n\n\n"
      },
      {
        "description": "\n\n\n\n\n\n\n\nAmazon RDS for SQL Server supports minor version 2019 CU27\n\n           Posted on: \n          Jul 11, 2024 \n         \n\nA new minor version of Microsoft SQL Server is now available on Amazon RDS for SQL Server, providing performance enhancements and security fixes. Amazon RDS for SQL Server now supports the latest minor version of SQL Server 2019 across the Express, Web, Standard, and Enterprise editions.  We encourage you to upgrade your Amazon RDS for SQL Server database instances at your convenience. You can upgrade with just a few clicks in the Amazon RDS Management Console or by using the AWS CLI. Learn more about upgrading your database instances from the Amazon RDS User Guide. The new minor version include SQL Server 2019 CU27 - 15.0.4375.4.  The minor version is available in all AWS regions where Amazon RDS for SQL Server databases are available, including the AWS GovCloud (US) Regions.  Amazon RDS for SQL Server makes it simple to set up, operate, and scale SQL Server deployments in the cloud. See Amazon RDS for SQL Server Pricing for pricing details and regional availability.\n\n\n\n\n\n\n"
      },
      {
        "description": "\n\n\n\n\n\n\n\nAnnouncing availability of AWS Outposts in Senegal\n\n           Posted on: \n          Jul 11, 2024 \n         \n\nAWS Outposts can now be shipped and installed at your data center and on-premises locations in Senegal.  AWS Outposts is a family of fully managed solutions that extends AWS infrastructure, AWS services, APIs, and tools to virtually any on-premises or edge location for a truly consistent hybrid experience. Outposts is ideal for workloads that require low latency access to on-premises systems, local data processing, and migration of applications with local system interdependencies. Outposts can also help meet data residency requirements. Outposts is available in a variety of form factors, from 1U and 2U Outposts servers to 42U Outposts racks, and multiple rack deployments.  With the availability of Outposts in Senegal, you can use AWS services to run your workloads and data in country in your on-premises facilities and connect to your nearest AWS Region for management and operations.  To learn more about Outposts, read the product overview and user guide. For the most updated list of countries and territories where Outposts is supported, check out the Outposts rack FAQs page and the Outposts servers FAQs page.\n\n\n\n\n\n\n"
      },
      {
        "description": "\n\n\n\n\n\n\n\nChatting about your AWS resources is now generally available for Amazon Q Developer\n\n           Posted on: \n          Jul 11, 2024 \n         \n\nToday, AWS announces the general availability of Amazon Q Developer’s capability to chat about your AWS account resources. With this capability, you can use natural language prompts to list resources in your AWS account, get specific resource details, and ask about related resources.  From the Amazon Q Developer chat panel in the AWS Management Console, you can ask Q to “list my S3 buckets” or “show my running EC2 instances in us-east-1” and Amazon Q returns a list of resource details, along with a summary. You can ask what Amazon EC2 instances an Amazon CloudWatch alarm is monitoring or ask “what related resources does my ec2 instance <id> have?” and Amazon Q Developer shows attached Amazon EBS volumes, configured Amazon VPCs, and AWS IAM roles for Amazon EC2 instances automatically.  To learn more, visit Amazon Q Developer or the documentation.\n\n\n\n\n\n\n"
      },
      {
        "description": "\n\n\n\n\n\n\n\nAWS Batch now supports gang-scheduling on Amazon EKS using multi-node parallel jobs\n\n           Posted on: \n          Jul 11, 2024 \n         \n\nToday, AWS announces the general availability of Multi-Node Parallel (MNP) jobs in AWS Batch on Amazon Elastic Kubernetes Service (Amazon EKS). With AWS Batch MNP jobs you can run tightly-coupled High Performance Computing (HPC) applications like training multi-layer AI/ML models. AWS Batch helps you to launch, configure, and manage nodes in your Amazon EKS cluster without manual intervention.  You can configure MNP jobs using the RegisterJobsDefinition API or via job definitions sections of AWS Batch Management Console. With MNP jobs you can run AWS Batch on Amazon EKS workloads that span multiple Amazon Elastic Compute Cloud (Amazon EC2) instances. AWS Batch MNP jobs support any IP-based inter-instance communications framework, such as NVIDIA Collective Communications Library (NCCL), Gloo, Message Passing Interface (MPI), or Unified Collective Communication (UCC) as well as machine learning and parallel computing libraries such as PyTorch and Dask. For more information, see Multi-Node Parallel jobs page in the AWS Batch User Guide.  AWS Batch supports developers, scientists, and engineers in running efficient batch processing for ML model training, simulations, and analysis at any scale. Multi-Node Parallel jobs are available in any AWS Region where AWS Batch is available.  \n\n\n\n\n\n\n"
      },
      {
        "description": "\n\n\n\n\n\n\n\nAWS Neuron introduces Flash Attention kernel enabling high performance and large sequence lengths\n\n           Posted on: \n          Jul 11, 2024 \n         \n\nToday, AWS announces the release of Neuron 2.19, introducing support for flash attention kernel to enable performant LLM model training and inference with large sequence lengths.  AWS Neuron is the SDK for AWS Inferentia and Trainium based instances purpose-built for generative AI. Neuron integrates with popular ML frameworks like PyTorch. It includes a compiler, runtime, tools, and libraries to support high performance training and inference of AI models on Trn1 and Inf2 instances.  This release adds new features and performance improvements for both training and inference and new Ubuntu 22 Neuron DLAMIs for PyTorch 2.1 and PyTorch 1.13. Neuron 2.19 adds support for Flash Attention kernel to enable training for large sequence lengths (greater than or equal to 8K), Llama3 model training, and interleaved pipeline parallelism to enhance training efficiency and resource utilization. For inference, this release adds Flash Attention kernel support to enable LLM inference for context lengths of up to 32k. Neuron 2.19 additionally adds support for Llama3 model inference and adds beta support for continuous batching with Mistral-7B-v0.2 models. Neuron 2.19 introduces new tools: Neuron Node Problem Detector and Recovery plugin in EKS and Neuron Monitor for EKS to enable enhanced Neuron metrics monitoring in Kubernetes.  You can use AWS Neuron SDK to train and deploy models on Trn1 and Inf2 instances, available in AWS Regions as On-Demand Instances, Reserved Instances, Spot Instances, or part of Savings Plan.  For a list of features in Neuron 2.19, visit Neuron Release Notes. To get started with Neuron, see: AWS Neuron Inf2 Instances Trn1 Instances  \n\n\n\n\n\n\n"
      },
      {
        "description": "\n\n\n\n\n\n\n\nAmazon ECS now provides enhanced stopped task error messages for easier troubleshooting\n\n           Posted on: \n          Jul 11, 2024 \n         \n\nAmazon Elastic Container Services (Amazon ECS) now makes it easier to troubleshoot task launch failures with enhanced stopped task error messages. When your Amazon ECS task fails to launch, you see the stopped task error messages in the AWS Management Console or in the ECS DescribeTasks API response. With today’s launch, Amazon ECS stopped task error messages are now more specific and actionable.  Amazon ECS is designed to help easily launch and scale your applications. When your Amazon ECS task fails to launch, you can use the Amazon ECS stopped task error message to identify the failure reason and resolve the failure. With this launch, stopped task error messages from common task launch failures now include more specific failure reasons and remediation recommendations. Amazon ECS documentation for these failures additionally provides in-depth root cause details and steps to mitigate the failure. If you manage your applications running on Amazon ECS using the AWS Management Console, error messages now include a direct link to the relevant Amazon ECS troubleshooting documentation page such as this Troubleshooting Amazon ECS ResourceInitializationError errors page, making it easier for you to access detailed information and resolve failures faster.  The new experience is now automatically enabled in all AWS Regions. See more details in Amazon ECS stopped task error messages updates.  \n\n\n\n\n\n\n"
      },
      {
        "description": "\n\n\n\n\n\n\n\nRDS Performance Insights provides support for AWS PrivateLink and IPv6\n\n           Posted on: \n          Jul 11, 2024 \n         \n\nAmazon RDS (Relational Database Service) Performance Insights now provides support for AWS PrivateLink and Internet Protocol Version 6 (IPv6). Customers can now access Performance Insights API/CLI privately, without going through the public Internet. Additionally, Performance Insights includes support for IPv6 connectivity and for a dual stack configuration (IPv4 and IPv6).  AWS PrivateLink provides private, secure, and scalable connectivity between virtual private clouds (VPCs) and AWS services. Customers can now prevent sensitive data, such as SQL text, from traversing the Internet to maintain compliance with regulations such as HIPAA and PCI . With IPv6 support, scaling an application on AWS is no longer constrained by the number of IPv4 addresses in the VPC. This eliminates the need for complex architectures to work around the limits of public IPv4 addresses.  Amazon RDS Performance Insights is a database performance tuning and monitoring feature of RDS that allows you to visually assess the load on your database and determine when and where to take action. With one click in the Amazon RDS Management Console, you can add a fully-managed performance monitoring solution to your Amazon RDS database.  To learn more about RDS Performance Insights, read the Amazon RDS User Guide and visit Performance Insights pricing for pricing details and region availability.  \n\n\n\n\n\n\n"
      }
    ]
  },
  "SummarizeResult": {
    "summarize_list": [
      {
        "summarize": "AWSのQ Developerチャット機能が、IDE上で開発者が現在作業しているプロジェクトのコンテキストを理解できるようになりました。開発者は「@workspaceこのコードは何をしているか」などと質問でき、チャットボットがプロジェクト全体のコードや設定ファイルの内容を参照して回答することができます。これにより開発効率の向上や開発生産性の改善などのメリットが期待できます。"
      },
      {
        "summarize": "AWS Secrets Managerが、シークレットをローカルでキャッシュするSecrets Manager Agentをオープンソースで公開しました。これにより、お客様はカスタムコードなしに、コンピューティング環境間でのシークレットの読み取りを標準化できるようになります。Secrets Manager Agentを利用することで、アプリケーションはネットワークコールを行うことなく、ローカルHTTPサービスからシークレットを取得できるため、運用コストとセキュリティの両面でメリットがあります。"
      },
      {
        "summarize": "Amazon ECSがコンテナ化されたアプリケーションのバージョンの整合性を強制することで、お客様のアプリケーション内のすべてのタスクが同一であることと、すべてのコード変更がデプロイメントパイプラインで定義された安全保護を経ることを確実にすることができます。これによりアプリケーションの信頼性が向上し、お客様の運用が容易になります。"
      },
      {
        "summarize": "Amazon RDS for SQL Serverが、パフォーマンス向上とセキュリティ修正を含むSQL Server 2019の最新マイナーバージョンCU27をサポートするようになりました。これにより、RDS for SQL Serverのユーザーは、わずか数クリックでデータベースインスタンスをアップグレードでき、パフォーマンスとセキュリティの改善を実現できます。"
      },
      {
        "summarize": "AWS Outposts はオンプレミスのデータセンターや施設へAWSのインフラ、サービス、API、ツールを展開できるハイブリッドクラウドソリューションです。セネガルで Outposts の利用が可能になり、オンプレミスでの低レイテンシーなワークロード実行、ローカルデータ処理、依存関係のあるアプリの移行などにメリットがあります。データresidency要件を満たせるほか、1Uから42Uラックまでさまざまな規模の導入が可能です。"
      },
      {
        "summarize": "AWSのチャットボット機能「Amazon Q Developer」が、AWSアカウント内のリソースについての自然言語での問い合わせに対応する一般提供を開始しました。この機能により、S3バケットやEC2インスタンスなどのAWSリソースの一覧表示や詳細情報の取得、関連リソースの表示などが可能になります。AWS管理コンソール内のチャット機能を利用することで、AWSリソースの確認や操作が容易になるなど、AWSユーザーにメリットがあります。"
      },
      {
        "summarize": "AWS BatchがAmazon EKS上でガングスケジューリングをサポートするようになりました。これにより、マルチノードパラレルジョブを使用して、AI/MLモデルのトレーニングなどの密結合型ハイパフォーマンスコンピューティング(HPC)アプリケーションを実行できます。 開発者はマルチノードパラレルジョブを利用することで、複数のAmazon EC2インスタンスにまたがるAWS Batch on Amazon EKSのワークロードを手間なく実行できるようになります。"
      },
      {
        "summarize": "AWS Neuron 2.19では、長いシーケンス長での高速なLLMモデルの学習と推論を可能にするFlash Attentionカーネルのサポートが追加されました。これにより、Trn1とInf2インスタンス上で、最大32kのコンテキスト長での高速なLLM推論が可能になります。ユーザーは、これらの目的製インスタンスを利用して、大規模な言語モデルの学習と推論を高速に実行できるようになり、生産性とコストパフォーマンスの向上が期待できます。"
      },
      {
        "summarize": "Amazon ECSが提供する停止したタスクのエラーメッセージが拡張され、トラブルシューティングがより簡単になりました。新しいエラーメッセージは、より具体的でアクション可能な内容になっており、ユーザーは失敗の理由と対処法をすぐに特定できるようになりました。これにより、Amazon ECSでアプリケーションを管理するユーザーは、障害をより迅速に解決できるメリットがあります。"
      },
      {
        "summarize": "RDS Performance InsightsがAWS PrivateLinkとIPv6に対応した。これにより、パフォーマンスインサイトのAPI/CLIをパブリックインターネットを通さずにプライベートにアクセスできる。IPv6接続とIPv4/IPv6デュアルスタック構成にも対応した。これらの機能により、顧客はセンシティブデータをインターネット上に流さずに済み、コンプライアンス面でのメリットがある。またIPv6対応により、IPv4アドレスの制限によるアプリケーションスケーリングの制約がなくなる。"
      }
    ]
  }
}

5. aws-update-make-mail-text

Lambda関数

このLambda関数では、これまでに取得した最新記事のタイトル・リンク・要約を使って、メール本文の内容を作成します。ランタイムはPython3.12です。具体的なコードは以下です。

クリックすると展開します

import datetime

def lambda_handler(event, context):
    
    # 最新記事のタイトルとリンク、要約をリストから取得
    TitleLinkList = event["TitleLinkList"]
    summarize_list = event["SummarizeResult"]["summarize_list"]

    # 日付をUTCで取得し、「YYYY-MM-DD」の文字列に変換
    today = datetime.date.today()
    todaystr = today.strftime('%Y-%m-%d')

    # メール本文の冒頭を作成
    mail_text = f"おはようございます!{todaystr}のAWSアップデートをお送りします!\n\n"
    
    # 最新記事のタイトルとリンク、要約をメール本文に追加
    for a, b in zip(TitleLinkList, summarize_list):
        mail_text += f"■ {a['title']}\n"
        mail_text += f"・{a['link']}\n"
        mail_text += f"・{b['summarize']}\n\n"
    
    return {
        'statusCode': 200,
        'body': mail_text
    }

Lambda関数のリターンは以下のようになります。

クリックすると展開します

{
  "statusCode": 200,
  "body": "おはようございます!2024-07-15のAWSアップデートをお送りします!\n\n■ Announcing IDE workspace context awareness in Q Developer chat\n・https://aws.amazon.com/about-aws/whats-new/2024/07/ide-workspace-context-awareness-q-developer-chat\n・AWSのQ Developerチャット機能が、IDE上で開発者が現在作業しているプロジェクトのコンテキストを理解できるようになりました。開発者は「@workspaceこのコードは何をしているか」などと質問でき、チャットボットがプロジェクト全体のコードや設定ファイルの内容を参照して回答することができます。これにより開発効率の向上や開発生産性の改善などのメリットが期待できます。\n\n■ AWS Secrets Manager announces open source release of Secrets Manager Agent\n・https://aws.amazon.com/about-aws/whats-new/2024/07/aws-secrets-manager-open-source-secrets-manager-agent\n・AWS Secrets Managerが、シークレットをローカルでキャッシュするSecrets Manager Agentをオープンソースで公開しました。これにより、お客様はカスタムコードなしに、コンピューティング環境間でのシークレットの読み取りを標準化できるようになります。Secrets Manager Agentを利用することで、アプリケーションはネットワークコールを行うことなく、ローカルHTTPサービスからシークレットを取得できるため、運用コストとセキュリティの両面でメリットがあります。\n\n■ Amazon ECS now enforces software version consistency for containerized applications\n・https://aws.amazon.com/about-aws/whats-new/2024/07/amazon-ecs-software-version-consistency-containerized-applications\n・Amazon ECSがコンテナ化されたアプリケーションのバージョンの整合性を強制することで、お客様のアプリケーション内のすべてのタスクが同一であることと、すべてのコード変更がデプロイメントパイプラインで定義された安全保護を経ることを確実にすることができます。これによりアプリケーションの信頼性が向上し、お客様の運用が容易になります。\n\n■ Amazon RDS for SQL Server supports minor version 2019 CU27\n・https://aws.amazon.com/about-aws/whats-new/2024/07/amazon-rds-sql-server-minor-version-2019-cu27\n・Amazon RDS for SQL Serverが、パフォーマンス向上とセキュリティ修正を含むSQL Server 2019の最新マイナーバージョンCU27をサポートするようになりました。これにより、RDS for SQL Serverのユーザーは、わずか数クリックでデータベースインスタンスをアップグレードでき、パフォーマンスとセキュリティの改善を実現できます。\n\n■ Announcing availability of AWS Outposts in Senegal\n・https://aws.amazon.com/about-aws/whats-new/2024/07/availability-aws-outposts-senegal\n・AWS Outposts はオンプレミスのデータセンターや施設へAWSのインフラ、サービス、API、ツールを展開できるハイブリッドクラウドソリューションです。セネガルで Outposts の利用が可能になり、オンプレミスでの低レイテンシーなワークロード実行、ローカルデータ処理、依存関係のあるアプリの移行などにメリットがあります。データresidency要件を満たせるほか、1Uから42Uラックまでさまざまな規模の導入が可能です。\n\n■ Chatting about your AWS resources is now generally available for Amazon Q Developer\n・https://aws.amazon.com/about-aws/whats-new/2024/07/chatting-aws-resources-generally-available-amazon-q-developer\n・AWSのチャットボット機能「Amazon Q Developer」が、AWSアカウント内のリソースについての自然言語での問い合わせに対応する一般提供を開始しました。この機能により、S3バケットやEC2インスタンスなどのAWSリソースの一覧表示や詳細情報の取得、関連リソースの表示などが可能になります。AWS管理コンソール内のチャット機能を利用することで、AWSリソースの確認や操作が容易になるなど、AWSユーザーにメリットがあります。\n\n■ AWS Batch now supports gang-scheduling on Amazon EKS using multi-node parallel jobs\n・https://aws.amazon.com/about-aws/whats-new/2024/07/aws-batch-gang-scheduling-eks-multi-node-parallel-jobs/\n・AWS BatchがAmazon EKS上でガングスケジューリングをサポートするようになりました。これにより、マルチノードパラレルジョブを使用して、AI/MLモデルのトレーニングなどの密結合型ハイパフォーマンスコンピューティング(HPC)アプリケーションを実行できます。 開発者はマルチノードパラレルジョブを利用することで、複数のAmazon EC2インスタンスにまたがるAWS Batch on Amazon EKSのワークロードを手間なく実行できるようになります。\n\n■ AWS Neuron introduces Flash Attention kernel enabling high performance and large sequence lengths\n・https://aws.amazon.com/about-aws/whats-new/2024/07/aws-neuron-flash-kernel-performance-sequence-lengths/\n・AWS Neuron 2.19では、長いシーケンス長での高速なLLMモデルの学習と推論を可能にするFlash Attentionカーネルのサポートが追加されました。これにより、Trn1とInf2インスタンス上で、最大32kのコンテキスト長での高速なLLM推論が可能になります。ユーザーは、これらの目的製インスタンスを利用して、大規模な言語モデルの学習と推論を高速に実行できるようになり、生産性とコストパフォーマンスの向上が期待できます。\n\n■ Amazon ECS now provides enhanced stopped task error messages for easier troubleshooting\n・https://aws.amazon.com/about-aws/whats-new/2024/07/amazon-ecs-stopped-task-error-messages-troubleshooting/\n・Amazon ECSが提供する停止したタスクのエラーメッセージが拡張され、トラブルシューティングがより簡単になりました。新しいエラーメッセージは、より具体的でアクション可能な内容になっており、ユーザーは失敗の理由と対処法をすぐに特定できるようになりました。これにより、Amazon ECSでアプリケーションを管理するユーザーは、障害をより迅速に解決できるメリットがあります。\n\n■ RDS Performance Insights provides support for AWS PrivateLink and IPv6\n・https://aws.amazon.com/about-aws/whats-new/2024/07/rds-performance-insights-privatelink-ipv6/\n・RDS Performance InsightsがAWS PrivateLinkとIPv6に対応した。これにより、パフォーマンスインサイトのAPI/CLIをパブリックインターネットを通さずにプライベートにアクセスできる。IPv6接続とIPv4/IPv6デュアルスタック構成にも対応した。これらの機能により、顧客はセンシティブデータをインターネット上に流さずに済み、コンプライアンス面でのメリットがある。またIPv6対応により、IPv4アドレスの制限によるアプリケーションスケーリングの制約がなくなる。\n\n"
}

Step Functions

入力は前ステップの出力をそのまま使います。出力は、OutputPathでbody部分のみを最終出力させます。

結果的に、このステップの出力は以下のようになります。

クリックすると展開します

"おはようございます!2024-07-11のAWSアップデートをお送りします!\n\n■ Announcing IDE workspace context awareness in Q Developer chat\n・https://aws.amazon.com/about-aws/whats-new/2024/07/ide-workspace-context-awareness-q-developer-chat\n・AWSのQ Developerチャット機能が、IDE上で開発者が現在作業しているプロジェクトのコンテキストを理解できるようになりました。開発者は「@workspaceこのコードは何をしているか」などと質問でき、チャットボットがプロジェクト全体のコードや設定ファイルの内容を参照して回答することができます。これにより開発効率の向上や開発生産性の改善などのメリットが期待できます。\n\n■ AWS Secrets Manager announces open source release of Secrets Manager Agent\n・https://aws.amazon.com/about-aws/whats-new/2024/07/aws-secrets-manager-open-source-secrets-manager-agent\n・AWS Secrets Managerが、シークレットをローカルでキャッシュするSecrets Manager Agentをオープンソースで公開しました。これにより、お客様はカスタムコードなしに、コンピューティング環境間でのシークレットの読み取りを標準化できるようになります。Secrets Manager Agentを利用することで、アプリケーションはネットワークコールを行うことなく、ローカルHTTPサービスからシークレットを取得できるため、運用コストとセキュリティの両面でメリットがあります。\n\n■ Amazon ECS now enforces software version consistency for containerized applications\n・https://aws.amazon.com/about-aws/whats-new/2024/07/amazon-ecs-software-version-consistency-containerized-applications\n・Amazon ECSがコンテナ化されたアプリケーションのバージョンの整合性を強制することで、お客様のアプリケーション内のすべてのタスクが同一であることと、すべてのコード変更がデプロイメントパイプラインで定義された安全保護を経ることを確実にすることができます。これによりアプリケーションの信頼性が向上し、お客様の運用が容易になります。\n\n■ Amazon RDS for SQL Server supports minor version 2019 CU27\n・https://aws.amazon.com/about-aws/whats-new/2024/07/amazon-rds-sql-server-minor-version-2019-cu27\n・Amazon RDS for SQL Serverが、パフォーマンス向上とセキュリティ修正を含むSQL Server 2019の最新マイナーバージョンCU27をサポートするようになりました。これにより、RDS for SQL Serverのユーザーは、わずか数クリックでデータベースインスタンスをアップグレードでき、パフォーマンスとセキュリティの改善を実現できます。\n\n■ Announcing availability of AWS Outposts in Senegal\n・https://aws.amazon.com/about-aws/whats-new/2024/07/availability-aws-outposts-senegal\n・AWS Outposts はオンプレミスのデータセンターや施設へAWSのインフラ、サービス、API、ツールを展開できるハイブリッドクラウドソリューションです。セネガルで Outposts の利用が可能になり、オンプレミスでの低レイテンシーなワークロード実行、ローカルデータ処理、依存関係のあるアプリの移行などにメリットがあります。データresidency要件を満たせるほか、1Uから42Uラックまでさまざまな規模の導入が可能です。\n\n■ Chatting about your AWS resources is now generally available for Amazon Q Developer\n・https://aws.amazon.com/about-aws/whats-new/2024/07/chatting-aws-resources-generally-available-amazon-q-developer\n・AWSのチャットボット機能「Amazon Q Developer」が、AWSアカウント内のリソースについての自然言語での問い合わせに対応する一般提供を開始しました。この機能により、S3バケットやEC2インスタンスなどのAWSリソースの一覧表示や詳細情報の取得、関連リソースの表示などが可能になります。AWS管理コンソール内のチャット機能を利用することで、AWSリソースの確認や操作が容易になるなど、AWSユーザーにメリットがあります。\n\n■ AWS Batch now supports gang-scheduling on Amazon EKS using multi-node parallel jobs\n・https://aws.amazon.com/about-aws/whats-new/2024/07/aws-batch-gang-scheduling-eks-multi-node-parallel-jobs/\n・AWS BatchがAmazon EKS上でガングスケジューリングをサポートするようになりました。これにより、マルチノードパラレルジョブを使用して、AI/MLモデルのトレーニングなどの密結合型ハイパフォーマンスコンピューティング(HPC)アプリケーションを実行できます。 開発者はマルチノードパラレルジョブを利用することで、複数のAmazon EC2インスタンスにまたがるAWS Batch on Amazon EKSのワークロードを手間なく実行できるようになります。\n\n■ AWS Neuron introduces Flash Attention kernel enabling high performance and large sequence lengths\n・https://aws.amazon.com/about-aws/whats-new/2024/07/aws-neuron-flash-kernel-performance-sequence-lengths/\n・AWS Neuron 2.19では、長いシーケンス長での高速なLLMモデルの学習と推論を可能にするFlash Attentionカーネルのサポートが追加されました。これにより、Trn1とInf2インスタンス上で、最大32kのコンテキスト長での高速なLLM推論が可能になります。ユーザーは、これらの目的製インスタンスを利用して、大規模な言語モデルの学習と推論を高速に実行できるようになり、生産性とコストパフォーマンスの向上が期待できます。\n\n■ Amazon ECS now provides enhanced stopped task error messages for easier troubleshooting\n・https://aws.amazon.com/about-aws/whats-new/2024/07/amazon-ecs-stopped-task-error-messages-troubleshooting/\n・Amazon ECSが提供する停止したタスクのエラーメッセージが拡張され、トラブルシューティングがより簡単になりました。新しいエラーメッセージは、より具体的でアクション可能な内容になっており、ユーザーは失敗の理由と対処法をすぐに特定できるようになりました。これにより、Amazon ECSでアプリケーションを管理するユーザーは、障害をより迅速に解決できるメリットがあります。\n\n■ RDS Performance Insights provides support for AWS PrivateLink and IPv6\n・https://aws.amazon.com/about-aws/whats-new/2024/07/rds-performance-insights-privatelink-ipv6/\n・RDS Performance InsightsがAWS PrivateLinkとIPv6に対応した。これにより、パフォーマンスインサイトのAPI/CLIをパブリックインターネットを通さずにプライベートにアクセスできる。IPv6接続とIPv4/IPv6デュアルスタック構成にも対応した。これらの機能により、顧客はセンシティブデータをインターネット上に流さずに済み、コンプライアンス面でのメリットがある。またIPv6対応により、IPv4アドレスの制限によるアプリケーションスケーリングの制約がなくなる。\n\n"

6. メール通知(アップデートあり)

このステップでは、アップデート内容をSNSトピックに送ります。SNSのトピック・サブスクリプションは予め作成済みです(本ブログでは記載を省略します)。今回は、統合タイプに「AWS SDK」を選択します(メールのタイトルも指定できるため)。TopicにSNSトピックを指定し、Messageには前のステップの出力をそのまま指定します。Subjectは「AWSアップデート通知」としました。

このステップが実行されると、以下のようなメールが届きます。

7. メール通知(アップデートなし)

このステップでは、アップデートが無かった際に、その旨をSNSトピックに送ります。対象のSNSトピックはステップ6と同じです。こちらも統合タイプに「AWS SDK」を選択し、Topic・Message・Subjectを指定します。Messageには直接テキストを書き込みます。

このステップが実行されると、以下のようなメールが届きます。

EventBridge

Step Functionsが完成したため、これをEventBridgeで定期実行させます。1日1回、日本時間のAM8:50(GMTでは前日の23:50)に実行させています。このタイミングにしているのは、RSSの時刻がGMTのため、前日分の日付のアップデートを全て拾うためです。今回の実装は、最新のアップデートをリアルタイムで通知するわけではなく、前日分のアップデートを翌朝まとめて通知するものになっています。

参考記事

最後に、今回の実装にあたって参考にさせていただいた記事を記載します。

RSS情報の取得については、以下の記事を参考にさせていただきました。

qiita.com


Step Functionsの入出力については、以下の記事を参考にさせていただきました。

zenn.dev

www.distant-view.co.jp



本ブログの内容は以上となります。何か少しでも参考になることがあれば幸いです。

Flask・PynamoDBを使いDynamoDB localのテーブルを作成しようとしてつまづいた話

現在、下記の書籍でサーバレスアプリについて学習中です。

動かして学ぶ!Pythonサーバレスアプリ開発入門

この本の Chapter.7 で、Flask・PynamoDBを使用してDynamoDB localのテーブルを作成する手順があるのですが、少々詰まってしまったので、備忘のために経緯をメモに残しておきたいと思います。

はじめにお断り

アプリケーションのフォルダ構成・ファイル構成やコードの中身などの説明は割愛します。そのため、書籍を読んでない方には何のことか分からない部分が一部あるかと思いますが、ご容赦ください。

今回利用したライブラリやサービスに関する簡単な紹介

はじめに、今回利用したライブラリやサービスについて、ごく簡単に触れておきます。

Flask

PythonのWEBアプリケーションフレームワークです。同じくPythonのWEBフレームワークとしては「Django」が有名ですが、Flaskの方が初心者にはとっつきやすいようです。
下記のページの説明・チュートリアルが分かりやすかったです。

qiita.com

PynamoDB

ORMのようにDynamoDBを操作可能なPythonのパッケージです。Boto3でDynamoDBを操作する場合と比較して、よりシンプルなコードで操作が可能なようです。
下記ページにサンプルコード付きの解説が載っています。

dev.classmethod.jp

DynamoDB local

自身のPCなどのローカル環境にダウンロードして使用できるDynamoDBです。アプリの開発段階でのテスト用途などで利用します。
詳細は下記公式ドキュメントをご参照ください。

docs.aws.amazon.com

経緯・原因・対策

ここからは、私が詰まった経緯・原因・対策について記載していきます。

経緯1:flask-script を使ったところ、エラーが発生

この書籍では、flask-script というFlaskの関連ライブラリを使ってDynamoDBのテーブルを作成する手順となっています。しかし、手順通りに実行したところ、以下のエラーが発生してしまいました。

ModuleNotFoundError: No module named 'flask._compat'

原因:Flaskのバージョン2.0以降ではflask-scriptが使えなくなっていた

原因については、下記の記事で詳しく解説されていました。それによると、Flask2.0以降では、flask-script をサポートしていないようです。

note.com


改めて確認してみると、私はFlaskの3.0.3(※2024年6月時点での最新バージョン)をインストールしていました。

なお、書籍では、冒頭で動作環境について明記されており、Flaskについてはバージョン1.1.2で動作確認済みである旨が記載されています。そのため、書籍に不備があるわけではないことは申し添えておきます。

今回は pipenv を使って本書籍専用の環境を作っていたし、作ったアプリを外部公開するわけでもないので、書籍に合わせて古いバージョンを入れても良かったかも、と思いました。

対策:flask-script を使わず、単体でテーブルを作成するコードを用意

Flaskを入れ直すことも少し考えたのですが、flask-script を使わず、単体でテーブルを作成するコードを用意すれば事足りそうなので、以下のコードを「applicaiton」フォルダに用意しました。

from flask_blog.models.entries import Entry

if not Entry.exists():
    Entry.create_table(read_capacity_units=5, write_capacity_units=2)

「DynamoDBにテーブルが存在しない場合、テーブルを作成する」という非常に簡便なコードです。ここでは、読み込みキャパシティユニットと書き込みキャパシティユニットを指定しています。

「Entry」というのは、別のコードでPynamoDBを使用して作成したテーブル定義クラスです。そちらのコードは以下です。

from datetime import datetime
from pynamodb.models import Model
from pynamodb.attributes import UnicodeAttribute, NumberAttribute, UTCDateTimeAttribute
from flask_blog import app

class Entry(Model):
    class Meta:
        table_name = "serverless_blog_entries"
        region = app.config.get('DYNAMODB_REGION')
        aws_access_key_id = app.config.get('AWS_ACCESS_KEY_ID')
        aws_secret_access_key = app.config.get('AWS_SECRET_ACCESS_KEY')
        host = app.config.get('DYNAMODB_ENDPOINT_URL')
    id = NumberAttribute(hash_key=True, null=False)
    title = UnicodeAttribute(null=True)
    text = UnicodeAttribute(null=True)
    created_at = UTCDateTimeAttribute(default=datetime.now)

所々、app.config.get というメソッドが使われていますが、これは、別に用意した「config.py」でリージョンやアクセスキー等の設定値を指定しており、その設定値を読み取っています。

経緯2:セキュリティトークンに関するエラーが発生

これで問題なく動作するかと思いきや、テーブルを作成するコードを実行したところ、以下のエラーが発生しました。

pynamodb.exceptions.VerboseClientError: An error occurred (UnrecognizedClientException) on request (DFO4H41N2VT25S3U8Q7LMGANIRVV4KQNSO5AEMVJF66Q9ASUAAJG) on table (serverless_blog_entries) when calling the DescribeTable operation: The security token included in the request is invalid.

「セキュリティトークンが無効」という内容ですが、DynamoDB localではアクセスキー・シークレットキーはダミーの値で良いはずなので、最初、なぜこのエラーが出たのか分かりませんでした。

原因:DynamoDB localのダミー用のアクセスキー・シークレットキーの指定方法が間違っていた

DynamoDB local用の設定値については、書籍に従い、以下のように設定していました。(前述の「config.py」の中身)
上述通り、アクセスキー・シークレットキーはダミーの値を入れています。

DYNAMODB_REGION='ap-northeast-1'
AWS_ACCESS_KEY_ID='AWS_ACCSESS_KEY_ID'
AWS_SECRET_ACCESS_KEY='AWS_SECRET_ACCESS_KEY'
DYNAMODB_ENDPONT_URL='http://localhost:8000'

しかし、DynamoDB local のバージョン2.0.0以降では、アクセスキーに英数字しか使えないようになっていました。私がインストールしたバージョンは2.5.1でした。

repost.aws

The resolution to this problem is straightforward: adhere to the new naming convention for the Access Key ID when using DynamoDB Local version greater than 1.23.0 or 2.0.0. The updated convention specifies that the AWS_ACCESS_KEY_ID can only contain letters (A–Z, a–z) and numbers (0–9).

(日本語訳)この問題の解決策は簡単です。1.23.0 または 2.0.0 以降の DynamoDB ローカル バージョンを使用する場合は、アクセス キー ID の新しい命名規則に従ってください。更新された規則では、AWS_ACCESS_KEY_ID には文字 (A ~ Z、a ~ z) と数字 (0 ~ 9) のみを含めることが指定されています。

対策:アクセスキーのダミー値を修正

アクセスキーにアンダースコアを入れていたのが原因だったので、以下の通り、英数字だけの値に変更しました。

DYNAMODB_REGION='ap-northeast-1'
AWS_ACCESS_KEY_ID='dummy123'  #英数字のみの値に修正
AWS_SECRET_ACCESS_KEY='dummy123'  #アクセスキーに合わせて修正
DYNAMODB_ENDPOINT_URL='http://localhost:8000'

シークレットキーは特殊文字を入れても問題なさそうでしたが、アクセスキーに合わせて修正しました。

経緯3:ハッシュキーが存在しないというエラーが発生

これでもう大丈夫と思い、再度テーブル作成のコードを実行したところ、今度は以下のエラーが発生してしまいました。

pynamodb.exceptions.TableError: Failed to create table: An error occurred (ValidationException) on request (25ad3382-8297-49e4-b2c8-2989adc4d2bb) on table (serverless_blog_entries) when calling the CreateTable operation: No Hash Key specified in schema.  All Dynamo DB tables must have exactly one hash key

「DynamoDBのテーブルにはハッシュキーが一つ必要だが、指定されていない。」と言われてしまいました。

原因:PynamoDB のモデル作成時のインデントが誤っていた

改めてテーブル定義を指定したコードを確認したところ、テーブル定義の部分のインデントが誤っていました。以下が、修正前の誤ったコードです。

from datetime import datetime
from pynamodb.models import Model
from pynamodb.attributes import UnicodeAttribute, NumberAttribute, UTCDateTimeAttribute
from flask_blog import app

class Entry(Model):
    class Meta:
        table_name = "serverless_blog_entries"
        region = app.config.get('DYNAMODB_REGION')
        aws_access_key_id = app.config.get('AWS_ACCESS_KEY_ID')
        aws_secret_access_key = app.config.get('AWS_SECRET_ACCESS_KEY')
        host = app.config.get('DYNAMODB_ENDPOINT_URL')
        id = NumberAttribute(hash_key=True, null=False)  #インデント誤り
        title = UnicodeAttribute(null=True)  #インデント誤り
        text = UnicodeAttribute(null=True)  #インデント誤り
        created_at = UTCDateTimeAttribute(default=datetime.now)  #インデント誤り

テーブル名・リージョン・アクセスキー・シークレットキー・エンドポイントURLなどの、DBに関するステータスは「Meta」クラス内に記述するのですが、テーブルに関する定義はMetaクラス内ではなく、モデルクラス直下に記載するのが正しい書き方でした。

対策:インデントを修正

以下のようにテーブル定義の部分のインデントを修正しました。

from datetime import datetime
from pynamodb.models import Model
from pynamodb.attributes import UnicodeAttribute, NumberAttribute, UTCDateTimeAttribute
from flask_blog import app

class Entry(Model):
    class Meta:
        table_name = "serverless_blog_entries"
        region = app.config.get('DYNAMODB_REGION')
        aws_access_key_id = app.config.get('AWS_ACCESS_KEY_ID')
        aws_secret_access_key = app.config.get('AWS_SECRET_ACCESS_KEY')
        host = app.config.get('DYNAMODB_ENDPOINT_URL')
    id = NumberAttribute(hash_key=True, null=False)  #インデント修正
    title = UnicodeAttribute(null=True)  #インデント修正
    text = UnicodeAttribute(null=True)  #インデント修正
    created_at = UTCDateTimeAttribute(default=datetime.now)  #インデント修正

この後、再度テーブル作成のコードを実行したところ、問題なくテーブルが作成されました。

まとめ:バージョンを合わせる事・開発環境を分ける事の重要性が理解できた

私はアプリケーション開発の経験がほとんど無かったため、pipenv等で開発環境を分ける事について、理屈は分かるものの、「実際、ライブラリのバージョンを上げただけで、そんなにコードが動かなくなるものなのだろうか?」という気持ちが少しありました。

しかし、今回、まさにそういった体験をして、非常に腹落ちしました。個人開発でたった一つのWEBアプリを作るだけでこうなんだから、組織的にいくつものアプリを開発している状況下で共通環境なんて使っていたら、そりゃあ大変ですよね。。
若干遠回りにはなったものの、結果的に、非常に良い勉強になったので良しとします。

もし私と同じ箇所でつまづいている方がいれば、このブログが少しでも参考になれば幸いです。

【読書感想文】Amazon Bedrock 超入門

本日、下記の書籍を読了しました。(ほぼ全編ハンズオン形式なので、読んだというよりハンズオンをやり終えたといった方が正しいかもしれません。)

Amazon Bedrock 超入門


せっかくなので、読んだ感想などを記しておきたいと思います。(個人の感想ですので、予めご了承いただければ幸いです。)

必要となる前提知識など

本書では、冒頭で、想定読者について以下のように記載しています。(原文ママ

  • Pythonという言語を一通り使える人。本書ではPythonの使い方などは特に説明をしません。Pythonそのものに関する問題を自力で解決できる人を対象としています。
  • AWSの基本的な使い方がわかっている人。本書ではAWSのアカウント作成から説明をしていますが、全くの知識がない人は理解が難しいでしょう。
  • 「AIを利用するためにはある程度の費用がかかるのは構わない」と考える人。タダでAIを使いたいという人は、Bedrockは使えません。

Pythonについては、入門書レベルの知識があれば大丈夫でした。具体的には、import、print、変数へのデータの格納、関数の作成方法、リスト・辞書の基本的な扱い方、などが分かっていれば十分でした。コードも10~20行程度の短いものがほとんどでした。

AWSについては、実質ほとんど利用することがありませんでした。大部分がJupyterノートブックでPythonコードを実行する手順となっており、AWSを使うのは、Bedrockでモデルを有効化する時・Bedrockのプレイグラウンドを利用する時・SageMakerノートブックを利用する時くらいでした。(※ノートブックについても、SageMakerノートブックを使うのは少しだけで、ほとんどGoogle Colaboratoryを利用する手順になっていました。)

費用についてですが、私の場合、本書の実施によるAWS利用料は 2.65USD でした。本日(2024年6月25日)のレートが1ドル159円くらいなので、大体400円くらいですね。

AWS利用料は使用するモデルや使用量によって異なります。詳細は以下の公式ドキュメントを参照ください。

aws.amazon.com

良かった点

本書の特に良かったと感じた点は、以下3点です。

  1. 生成AIに関する用語などについて、平易な言葉で分かりやすく説明されている。
  2. 手順が詳細に分かりやすく記載されている。
  3. テキスト生成・画像生成・チャット・セマンティック検索など、幅広いユースケースを試すことができる。


それぞれ、もう少し詳しく記載します。

生成AIに関する用語などについて、平易な言葉で分かりやすく説明されている

最初の章で、生成AIとは何か、これまでの機械学習モデルと何が違うのか、代表的なモデルにはどのようなものがあるのか等の説明があり、生成AIの現状についてまとめてザックリキャッチアップすることが出来ました。

また、Embeddingモデル や セマンティック検索などについても、専門用語をなるべく使わず平易な言葉で説明されており、概要が理解しやすかったです。

私は生成AIの波にすっかり乗り遅れてしまっていましたが、用語やモデルについての基礎の基礎が一気にキャッチアップできて、大変助かりました。

手順が詳細に分かりやすく記載されている

マネジメントコンソール等のGUIの手順は画像がふんだんに使われており、迷いにくくなっていました。また、Pythonのコードについても、変な省略をすることなく、毎回必要な部分がすべて記載されており、分かりやすかったです。加えて、初めて出てくる処理については、行毎に何をしているのか解説されており、プログラミング初級者にも分かりやすい作りになっていました。

Jupyterノートブックを使っていることもありますが、一つ一つのコードを短く区切っていることも、理解のしやすさに一役買っていたように思います。(上述通り、長くても一つのブロックで10~20行くらい)

テキスト生成・画像生成・チャット・セマンティック検索など、幅広いユースケースを試すことができる

「超入門」と銘打ってはいるものの、定番のテキスト生成・画像生成・チャットに加えて、Embeddingモデルを活用したセマンティック検索や、テキストプロンプトに最も近い画像を表示するマルチモーダルの処理など、色々なユースケースを試すことができました。

また、LangChainの利用方法や、curlJavaScript でBedrockを利用する方法も紹介されており、入門書としては十分過ぎるくらい幅広いユースケースが押さえられていると感じました。

気になった点

個人的に気になった点は以下2点です。

  1. AWSのルートユーザーでアクセスキーを発行させる手順がある
  2. アクセスキー・シークレットキーをハードコーディングしている箇所がある

いずれも、セキュリティリスクがあるためAWS公式で非推奨とされています。詳しくは下記公式ドキュメントをご参照ください。

docs.aws.amazon.com

docs.aws.amazon.com

「Bedrockを利用する」という本筋から外れる部分については、出来るだけ手順を簡便にしたかったのかな?と想像しましたが、せめて専用のIAMユーザーを作成する手順くらいはあっても良かったのでは、という気がしました。

もし書籍通りにルートユーザーでアクセスキーを発行された方がいらっしゃった場合は、ルートユーザーのアクセスキーは無効化・削除し、代わりにIAMユーザーを作成してアクセスキーを発行されることをお勧めします。 また、書籍のハンズオン実施後も引き続きアクセスキーを利用する場合は、下記ドキュメントを参考に、一度アクセスキーを更新されることをお勧めします。

docs.aws.amazon.com

まとめと次のステップ

上述の気になった点はあったものの、読みやすく非常に勉強になりました。買って良かったです。

ただ、本書では基本的にBedrockを単体で利用しており、他のAWSサービスと連携したアプリ開発については触れられていませんでした。せっかくAWSサービスを利用するのであれば、やはり他のAWSサービスと上手く連携させたアプリを作りたいところです。
そういった点については、下記の書籍を読みつつ、自分でも試行錯誤して実装していきたいと思います。

Amazon Bedrock 生成AIアプリ開発入門 [AWS深掘りガイド]

LangChain経由でBedrockを使って、AWSのアップデート情報を要約してみた

最近、LangChainを初めて触りました。まだ初歩的な使い方しか試していないですが、少ないコードで簡単に実装が出来るし、異なるモデルでもコードの流用が出来て、便利だなと思いました。もう少し使い慣れるために、練習として、AWSのアップデート情報を要約してみたいと思います。

参考書籍

今回は、以下の書籍の内容を参考にしています。モデルやパラメータ、実際のコードについても丁寧に説明されており、とても分かりやすい良書でした。

Amazon Bedrock 超入門

LangChainとは

大規模言語モデル(LLM)によるアプリケーション開発を簡素化するための、オープンソースフレームワークです。異なるモデルであっても同じように扱えることが大きなメリットかと思います。

下記のBedrock公式ドキュメントを見ると分かりますが、モデル毎に、リクエストで渡すパラメータも、レスポンスで返ってくるパラメータも書式が異なるので、LangChainを使わない場合、モデル毎にパラメータの違いを意識してコードを書く必要があります。LangChainを使うと、そういった違いを意識しないで済むので、コードを書くのが多少楽になるかと思います。(※最近ではConvers APIというものが出てきて、異なるモデルでも用途によっては同様に扱えるようになったようです。)

docs.aws.amazon.com

docs.aws.amazon.com


LangChainについての詳細は、以下ドキュメントにも記載があります。

aws.amazon.com

SageMakerノートブックで試してみる

それではLangChainを実際に使ってみます。今回は、SageMakerノートブックのJupyterLab環境を使ってみます。「conda_pytorch_p310」を使います。

要約方法

今回は、AWSアップデートの内容をテキストファイル化し、ファイルの内容を読み込ませて要約させることにします。
また、LangChainのテンプレート機能を利用し、プロンプトをテンプレート化します。テンプレートには変数を埋め込むことができるので、テンプレートの呼び出しと変数の指定をするだけで、簡単にプロンプトを完成させることができます。

LangChain関連のモジュールをインストール~BedrockChat用のオブジェクトを作成

それでは実際にコードを実行していきます。まずはLangChain関連のモジュールをインストールします。

pip install langchain


続いて、BedrockChat用のオブジェクトを作成します。今回、モデルは Anthropic のClaudeバージョン2を使用します。

from langchain.chat_models import BedrockChat

chat = BedrockChat(
    model_id="anthropic.claude-v2:1"
)


すると、以下のエラーが出てしまいました。

---------------------------------------------------------------------------
ModuleNotFoundError                       Traceback (most recent call last)
Cell In[5], line 1
----> 1 from langchain.chat_models import BedrockChat
      3 chat = BedrockChat(
      4     model_id="anthropic.claude-v2:1"
      5 )

File ~/anaconda3/envs/pytorch_p310/lib/python3.10/site-packages/langchain/chat_models/__init__.py:28, in __getattr__(name)
     27 def __getattr__(name: str) -> None:
---> 28     from langchain_community import chat_models
     30     # If not in interactive env, raise warning.
     31     if not is_interactive_env():

ModuleNotFoundError: No module named 'langchain_community'


langchain_communityというモジュールが必要だとメッセージが出ています。 なので、追加でモジュールをインストールします。

pip install langchain-community


そのうえで、再度BedrockChat用のオブジェクトを作成しましたが、今度は違うエラーが出てしまいました。

/home/ec2-user/anaconda3/envs/pytorch_p310/lib/python3.10/site-packages/langchain_core/_api/deprecation.py:139: LangChainDeprecationWarning: The class `BedrockChat` was deprecated in LangChain 0.0.34 and will be removed in 0.3. An updated version of the class exists in the langchain-aws package and should be used instead. To use it run `pip install -U langchain-aws` and import as `from langchain_aws import ChatBedrock`.
  warn_deprecated(


エラーの日本語訳は以下です。どうもBedrockChatの新バージョンが新しいパッケージに含まれており、今後はそちらを使う必要があるようです。

クラス `BedrockChat` は LangChain 0.0.34 で非推奨となり、0.3 で削除される予定です。クラスの更新バージョンは langchain-aws パッケージに存在するため、代わりに使用する必要があります。これを使用するには、「pip install -U langchain-aws」を実行し、「from langchain_aws import ChatBedrock」としてインポートします。


指示に従って、langchain-awsをインストールします。

pip install -U langchain-aws


そのうえで、改めてBedrockChat用のオブジェクトを作成します。リージョンも指定しておきます。

from langchain_aws import ChatBedrock

chat = BedrockChat(
    model_id="anthropic.claude-v2:1",
    region_name="us-east-1"
)

今度はエラーが出ませんでした。

テンプレートの作成

続いて、プロンプトのテンプレートを作成します。

# チャットテンプレート用モジュールのインストール
from langchain.prompts import ChatPromptTemplate

# テンプレートの作成
template_prompt = ChatPromptTemplate.from_template(
    """以下のテキストを日本語で要約しなさい:
    
    {content}
    
    要約:"""
)

{content} の部分が変数となります。この後モデルにプロンプトを渡す際には、contentの中身を指定するだけでプロンプトを完成させることができます。



続いてRunnableSequenceを作成します。RunnableSequenceはLinuxのパイプのようなもので、前に記載した処理の出力結果を、次の処理の入力として渡すことができるものです。最終的にオブジェクトには、最後に実行した処理の出力結果が格納されます。

# RunnableSequenceの作成
runnable = template_prompt | chat

テキストファイルの準備とアップロード

続いて、テキストファイルを準備します。 今回は以下のAWSアップデートの内容をテキストファイルにします。

aws.amazon.com

本文の内容をテキストファイルにコピペして保存します。文字コードUTF-8にしています。 ファイルをJupyterLabにアップロードします。

アップロードした結果が以下です。

テキストファイルの読み込みと要約の実行

次に、テキストファイルからテキストを読み込んで、変数に格納します。そして最後にRunnableSequenceを実行します。その時に、変数の内容をテンプレートに渡して、プロンプトを完成させます。

# テキストファイル名の指定
file_name = "AWS_Billing_and_Cost_Management_now_provides_Data_Exports_for_Cost_Optimization_Hub.txt"

# テキストファイルからテキストを読み込み
with open(file_name, 'r') as f:
    data_txt = f.read()
    
# RunnableSequenceの実行
response = runnable.invoke({"content": data_txt}) #テンプレートの{content}部分に、data_txt(テキストファイルの中身)を指定

# 実行結果の表示
print(response.content)

実行結果

実行結果が以下です。ちゃんと日本語訳されましたが、あまり要約された感がありませんね。

Data Exports for Cost Optimization Hubは、コスト最適化の推奨事項をAmazon S3にエクスポートできるようになりました。 コスト最適化Hubの推奨事項は、EC2インスタンスのRIGHTSIZING、Graviton移行、Savings Plan購入など、15種類以上のAWSコスト最適化推奨事項を統合したものです。 エクスポートは、ParquetやCSV形式で毎日Amazon S3に配信されます。

Data Exports for Cost Optimization Hubを使用すると、レポートやダッシュボードの作成が簡単になるように、推奨事項が容易に取り込めるデータファイルで提供されます。 顧客は、コスト最適化Hubで使用しているのと同じフィルタや設定をエクスポートに適用して、節約を重複除去できます。 基本的なSQL列選択や行フィルタを使用して、エクスポートされるデータを制御することもできます。 Data Exports for Cost Optimization Hubを使用すると、重要なステークホルダーと節約機会を共有するために、推奨データを分析ツールやBIツールに簡単に取り込むことができます。

Data Exports for Cost Optimization Hubは米国東部(バージニア北部)リージョンで利用できますが、AWS GovCloud(米国)リージョンとAWS中国(北京および寧夏)リージョンを除くすべてのAWSリージョンの推奨事項が含まれます。

詳細は、Data Exportsユーザーガイド、Data Exports製品の詳細ページを参照してください。 Cost Optimization Hubの詳細は、Cost Optimization Hubユーザーガイドを参照してください。 AWS Billing and Cost Managementコンソールの「Data Exports」または「Cost Optimization Hub」機能にアクセスし、「Cost Optimization Recommendations」テーブルのエクスポートを作成することから始めてください。

テンプレートのプロンプトを少し変更してみる

もう少し簡潔にまとめてほしいので、テンプレートのプロンプトを少しだけ変更して、150文字以内で要約するように指示してみます。

# チャットテンプレート用モジュールのインストール
from langchain.prompts import ChatPromptTemplate

# テンプレートの作成(※150文字以内で要約するよう、プロンプトの内容を変更)
template_prompt = ChatPromptTemplate.from_template(
    """以下のテキストを日本語で150文字以内で要約しなさい:
    
    {content}
    
    要約:"""
)

# RunnableSequenceの作成
runnable = template_prompt | chat


そのうえで、改めて要約してみた結果が以下です。先ほどよりシンプルになりましたね。

コスト最適化Hubのデータエクスポート機能により、顧客はコスト最適化の推奨事項をAmazon S3にエクスポートできるようになった。これらの推奨事項は、EC2インスタンスのサイズ調整、Gravitonへの移行、節約プランの購入など、AWSアカウントとリージョン全体で15種類以上の推奨事項から統合される。エクスポートはParquetやCSV形式で毎日Amazon S3に配信される。このデータエクスポートにより、顧客は容易に取り込めるデータファイルで推奨事項を取得でき、レポートやダッシュボードの作成が簡略化される。顧客はHubと同じフィルタや設定をエクスポートに適用でき、節減額の重複を除外できる。 データエクスポート機能により、顧客は推奨事項データを分析ツールに取り込みやすく、追跡、優先順位付け、重要ステークホルダーとの共有が容易になる。

あと、「です・ます調」だった文章が「だ・である調」に変わりました。少しでも字数を節約するための涙ぐましい努力が垣間見えましたw

さらに、文字数を100文字以内と指定した場合の結果が以下です。

コスト最適化Hubのデータエクスポートにより、お客様はコスト最適化の推奨事項をAmazon S3にエクスポートできるようになりました。推奨事項はEC2インスタンスのサイズ調整、Gravitonへの移行、Savings Planの購入など15種類以上のAWSコスト最適化の推奨事項が統合されています。エクスポートは毎日ParquetまたはCSVフォーマットでAmazon S3に配信されます。

かなりシンプルになりましたね。ただ、150文字で要約した時の後半部分で説明されていた、顧客にとっての具体的なメリットの部分がゴッソリ無くなってしまいました。
まだ一つのアップデートで試しただけなので断言はできませんが、アップデート内容だけを簡潔に知りたい場合は100文字、顧客のメリットやユースケースまで知りたい場合は150文字程度はあった方が良いのかもしれません。



以上、LangChain+BedrockによるAWSアップデート情報の要約でした。今回は手動でテキストファイルを用意してそれを要約させましたが、出来ればWEBスクレイピングで内容を読み込んで要約し、それを通知する所まで自動化してみたいなと思いました。いずれ挑戦してみたいと思います。

極めて個人的な、AWS Summit 2024の感想と反省

6/20(木)、21(金)の両日、AWS Summit 2024に一般参加者として参加してきました。

昨年の2023年に初めて参加し、今回が2回目の参加だったのですが、個人的に色々と反省点がありました。 1年に1回しかないイベントのため、このままだと次回も同じ過ちを犯すかもしれないので、反省点をブログに残しておこうと思います。ついでに個人的な感想も書いておこうと思います。

はじめにお断り

AWS Summit 2024 でどのような出し物があったかということや、当日のオペレーション・ルールなどについては触れません。その辺は、下記の emi さんのブログでとてつもなく分かりやすく説明されていますので、そちらをご参照ください。

dev.classmethod.jp

また、感想については個人的な所感で、かなり感覚的な話が多いです。キチンとした調査や分析に基づいた意見ではありませんので、予めご了承ください。

個人的な感想

まずは参加してみての個人的な感想を記載します。

生成AIに関するブース・セッションが非常に多かった

世間は生成AIブーム一色ですし、生成AIに関するトピックスに特化した「週刊生成AI with AWS」が公式ブログで発表されるくらいですから、もちろん生成AIが中心になるとは思っていましたが、想像以上に生成AIに関するブース・セッションの割合が多かったです。

AWSの人が事例や展示を直接説明してくれる「AWS Village」というエリアがあるのですが、 体感的に、7~8割くらいのブースが生成AI絡みなんじゃ?と感じるほどでした。(あくまで体感なので、実際の正確な割合は分かりませんが。。)

それに比べると、ネットワークやストレージなどのインフラ周りのブースに関しては、昨年と比べてもかなり縮小されたような気がしました。(これも体感ですが)

サーバレス構成はもはやデフォ

昨年のSummitの時点でも既に、事例のアーキテクチャではサーバレス構成が多く見受けられたように思いますが、今年は更にそれが顕著になり、Summit中に見たアーキテクチャ図はほぼ全てサーバレス構成で、EC2を立てている構成は見なかった気がします。

もちろん世の中ではEC2を使っているケースはたくさんあるでしょうし、あえてEC2を選択するようなケースもあるとは思いますが、作る側としてはサーバレス構成のノウハウもしっかり押さえておく必要があるなと感じました。私はサーバレスの経験・知見があまり無いため、キャッチアップを加速させねばという危機感を覚えました。

リアルで知り合いに会えて嬉しかった

6月に転職して新しい会社に入社したため、まだ社内に知り合いがほとんどおらず、少し寂しい思いをしているのですがw、そんなタイミングで前職の仲間や知り合いに会って話が出来て、非常に嬉しかったですし、良い刺激ももらえました。

前職がブースを出していたので行ってみたのですが、概ね温かく迎えていただけたようで、大変ありがたかったです。

パートナー企業の表彰が羨ましい。。w

AWS Summitに合わせて、以下の表彰が行われますが、受賞資格があるのはAWS Partner Network (APN) 参加企業に所属しているエンジニアとなります。

2024 Japan AWS Jr. Champions の発表 | AWS JAPAN APN ブログ

2024 Japan AWS All Certifications Engineers の発表 | AWS JAPAN APN ブログ

2024 Japan AWS Top Engineers の発表 | AWS JAPAN APN ブログ

2024 Japan AWS Ambassadors の発表 | AWS JAPAN APN ブログ


私は先月までAPN参加企業に所属していたのですが、今は違うため、応募資格がありません。しかし、X(旧Twitter)のタイムラインで「受賞しました!」というツイートがたくさん流れてきたり、当日の発表時の盛り上がりを見ていると、ちょっと羨ましいなと思ってしまいました。。w

個人的な反省点

ここからは、来年に向けた個人的な反省点を記載します。

申し込みをもっと早くするべきだった

Summitへ申し込んだのが、開催1週間前の6/14だったのですが、その時点で、かなりのセッションがすでに満席となってしまっていました。 6月に転職をして新しい会社に入社したため、Summitへ参加できるか不透明だったこともあったのですが、もう少し早く申し込むべきでした。

時間配分を事前に考慮すべきだった

今回、事前に時間配分を十分考慮しなかった結果、いくつか気になっていたブースで話を聞く時間が取れませんでした。。また、気になっていたブースセッションもいくつか見逃してしまいました。

メインセッションに関しては後でオンデマンド配信されるものも結構あるので、ブースで直接色々な話を聞く時間をもう少し多く取っても良かったかな、と思いました。特に人気のあるブースでは説明者の方の手がなかなか空かず、話を聞くのに少し待つ必要があるケースもあるので、時間に余裕を持っておけば良かったです。

また、偶然知り合いにあった時は、せっかくなら色々と話をしたいので、ある程度ゆとりを持った計画にしておくべきだなと思いました。

事前の技術的なキャッチアップが不十分だった

生成AIやそれを活用したアプリケーションに関する話題が多いことは、ある程度は予想できたことでした。(上述通り、実際には予想以上でしたが。。)しかし、生成AIやアプリケーション開発、サーバレスに関するキャッチアップが十分とはいえず、せっかくAWSの人に直接あれこれ聞ける貴重な機会を十分に活かしきることができませんでした。

サービスの概要や一般的なユースケースについては、公式ドキュメントや公式ブログでもある程度説明されているので、せっかく直接質問できるのであれば、実際に設計・構築・運用していく中でぶつかった障壁や悩み等、もう一段深い話が出来れば理想的だったなと思いました。

終わりに

色々と反省点はありましたが、知見が増えたり、色々な刺激をもらえてモチベーションが上がった事は間違いないですし、会いたかった人たちにリアルで会えましたし、行って本当に良かったと思っています。だからこそ、来年はもっと「行って良かった」と思えるように、今回の反省を活かして臨みたいと思います。

【Amazon Bedrock】AWS SDK for Python(Boto3)で、SDXLモデルのパラメータを指定してイメージ生成してみた

最近、Amazon Bedrockを勉強中です。AWS SDK等でInvokeModel APIをコールしSDXLモデルのイメージ生成を行う場合、マネジメントコンソールのプレイグラウンドと比べて、より多くのパラメータを指定可能であることを知ったので、試してみました。

マネジメントコンソールのプレイグラウンドで指定可能なパラメータ

マネジメントコンソールのプレイグラウンドでは、以下のパラメータが指定可能です。

パラメータ 内容
負のプロンプト 生成してほしくないものを記述する。
画像サイズ 画像のサイズを指定する。ランドスケープポートレートは横長か縦長かの指定に利用する。
プロンプト強度 プロンプトにどれだけ厳密に従うかを決める値。
生成ステップ イメージ生成の処理を繰り返すサイクル数。値が大きいほど精密で正確なイメージが作成される。
シード 乱数生成のシード。プロンプトとシード値が同じ場合、同じイメージが生成される。プロンプトが同じでも、シード値が異なると違うイメージとなる。

もし、イメージ生成の際に画風を指定したい場合、そのようなパラメータは存在しないので、プロンプトで「anime style」などと指定する必要があります。

InvokeModel APIで指定可能なパラメータ

InvokeModel APIを使用する場合、上記のプレイグラウンドで指定可能なパラメータに加えて、更に色々なパラメータを指定可能です。詳細は下記の公式ドキュメントを参照してください。

docs.aws.amazon.com

今回は、マネジメントコンソールのプレイグラウンドに存在しないパラメータの内、「style_preset」を使用してみます。このパラメータは、画像モデルを特定のスタイルに導くためのもので、3d-model, analog-film, anime, cinematic, comic-book等、複数のスタイルがあらかじめ用意されています。

Boto3でパラメータを指定しイメージ生成してみた

それでは実際にBoto3でパラメータを指定しイメージ生成してみます。今回はAmazon SageMakerノートブックインスタンスのJupyterLabを利用します。

ノートブックでコードを順番に実行していきます。まずはBedrockのランタイムにアクセスします。

import boto3

runtime_client = boto3.client(
    service_name='bedrock-runtime',
    region_name='us-east-1'
)


続いて、プロンプト・style_preset・シード値用の変数に値を格納します。シード値はランダムな値を格納します。今回はプロンプトには「anime style」といった画風を指定する文言を入れずに、代わりにstyle_presetを「anime」にします。

import random

prompt_data = "A dog running in the park."
style_data = "anime" # ["3d-model", "analog-film", "anime", "cinematic", "comic-book", "digital-art", "enhance", "fantasy-art", "isometric", "line-art", "low-poly", "modeling-compound", "neon-punk", "origami", "photographic", "pixel-art", "tile-texture"]

seed = random.randint(0,4294967295)


続いて、モデルに渡すためのbody部分とモデルIDを変数に格納します。

import json

modelId = "stability.stable-diffusion-xl-v1"
body = json.dumps({
    "text_prompts": [
        {
            "text": prompt_data,
            "weight": 1.0
        },
        {
            "text": "artifact",
            "weight": -0.5
        }
    ],
    "samples": 1,
    "cfg_scale": 7,
    "seed": seed,
    "steps": 30,
    "style_preset": style_data,
    "height": 512,
    "width": 512,
})

プロンプトはリスト型になっており、複数指定することが可能です。また、プレイグラウンドには無かった要素として、「weight(重み)」があります。weightは-1.0~1.0の範囲で指定可能で、負の値にすることで上述の「負のプロンプト」にすることが可能です。weightが-1.0の場合、そのプロンプトは生成されません。-0.5等の値にすると、完全に生成されないわけではないようです。このように、プレイグラウンドと比べてより柔軟な制御が可能となっています。今回は「artifact(人工物)」というプロンプトを-0.5のweightで設定してみました。


続いて、bodyとモデルIDを指定して、モデルを呼び出します。

response = runtime_client.invoke_model(
    body=body,
    modelId=modelId
)

responseの中身を見ると、下図のようにjson形式となっており、body部分はbotocore.response.StreamingBodyとなっています。

このStreamingBodyから実際のデータを取り出すにはread()というメソッドを使用します。詳細は以下ドキュメントを参照ください。

botocore.amazonaws.com

実際に取り出したレスポンスは、SDXLモデルの場合、以下の書式となっています。

{
    "result": string,
    "artifacts": [
        {
            "seed": int,
            "base64": string,
            "finishReason": string
        }
    ]
}

Stability.ai Diffusion 1.0 によるテキストからの画像生成 - Amazon Bedrock


上記の「base64」の部分に、Base64エンコードされた画像データが入っています。そのため、このデータをデコードし、ファイルとして保存します。また、Jupyterノートブック上で画像を表示するために、HTMLコードも記載します。具体的なコードは以下です。

import base64
from datetime import datetime
from IPython.display import display, HTML

# StreamingBodyからbodyコンテンツを取得し、JSONをPythonオブジェクトに変換
response_body = json.loads(response.get("body").read())

# Pythonオブジェクトから、Base64エンコードされた画像データを取り出し
base64_data = response_body.get("artifacts")[0]['base64']

# 画像データをBase64デコード
binary_data = base64.b64decode(base64_data)

# 現在時刻のファイル名でファイル保存
dt_str = str(datetime.now())
with open(f"{dt_str}.png", "wb") as f:
  f.write(binary_data)

# Jupyterノートブック上に画像を表示
html_code = f'<img src="data:image/png;base64,{base64_data}">'
display(HTML(html_code))

実行結果が下図です。プロンプトでは特に何も指定していませんが、アニメ調の画像となりました。また、負のプロンプトで指定した人工物の表現はやや控えめになったかと思います。(街灯が無くなったので。まあ道も人工物といえば人工物ですが。。)ファイルが保存されていることも確認できました。

プロンプトでの画風指定とstyle_presetを併用してみる

今度は、プロンプトで画風を指定したうえで、style_presetで全く別の画風を指定し、どうなるのか試してみます。

import random

prompt_data = "A dog running in the park, anime style."
style_data = "origami" # ["3d-model", "analog-film", "anime", "cinematic", "comic-book", "digital-art", "enhance", "fantasy-art", "isometric", "line-art", "low-poly", "modeling-compound", "neon-punk", "origami", "photographic", "pixel-art", "tile-texture"]

seed = random.randint(0,4294967295)

プロンプトではアニメ調を指定しつつ、style_presetには折り紙を指定します。それ以外のパラメータは先ほどと同じです。

結果は下図のようになりました。

見事に折り紙調ですね。style_presetの指定の方が強く反映されているように見えます。

今度はパラメータを少し変更してみます。「cfg_scale」という、プロンプトにどれだけ忠実に従うかを決めるパラメータを変更します。(値が大きいほどプロンプトに忠実になる)デフォルト値は7ですが、最大の35にしてみます。

import json

modelId = "stability.stable-diffusion-xl-v1"
body = json.dumps({
    "text_prompts": [
        {
            "text": prompt_data,
            "weight": 1.0
        },
        {
            "text": "artifact",
            "weight": -0.5
        }
    ],
    "samples": 1,
    "cfg_scale": 35,  #最大値に変更
    "seed": seed,
    "steps": 30,
    "style_preset": style_data,
    "height": 512,
    "width": 512,
})

実行結果が下図です。

やっぱり折り紙調ですね。というか、なんかカオスになってしまいました。。公園感もどっかにいっちゃったし。。

折り紙だとクセが強すぎるのかもしれないので、style_presetを変えてみることにします。まずはphotographic。

続いて、pixel-art。

どんどんおかしな感じになってますね。。もはやどこに犬の要素があるのかも分かりません。。

(結論)スタイルはケンカさせない方がよい

今回はプロンプトが非常に単純でしたし、パラメータも大雑把にしか変えていないので、かなり雑な検証ではあるのですが、今回試した限りでは、以下の所感を持ちました。

  • プロンプトでの画風指定とstyle_presetでは、style_presetの方が強く反映されているように感じた。
  • プロンプトとstyle_presetはケンカさせない方がよい

正直、画像生成に関する実践的なノウハウはあまり身に付きませんでしたがw、とりあえずBoto3でBedrockを扱う練習は出来たので良しとします。
あまり参考になるような内容の無いブログになってしまいましたが、誰かの参考になれば幸いです。