サブスクリプションフィルターポリシーを適用する - Amazon Simple Notification Service

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

サブスクリプションフィルターポリシーを適用する

Amazon SNS コンソールを使用して、Amazon SNS サブスクリプションにフィルターポリシーを適用できます。または、ポリシーをプログラム的に適用するには、Amazon SNS API、 AWS Command Line Interface (AWS CLI)、または Amazon SNS をサポートする任意の AWS SDK を使用できます。を使用することもできます。 AWS CloudFormation

重要

AWS IAM や Amazon SNS などのサービスは、結果整合性と呼ばれる分散コンピューティングモデルを使用します。サブスクリプションフィルターポリシーへの追加または変更は、完全に有効になるまでに最大 15 分かかります。

AWS Management Console

  1. Amazon SNS コンソールにサインインします。

  2. ナビゲーションパネルで、[サブスクリプション] を選択します。

  3. サブスクリプションを選択したら、[編集] を選択します。

  4. [Edit](編集) ページで、[Subscription filter policy](サブスクリプションフィルターポリシーセクション) を展開します。

  5. 属性ベースのフィルタリングまたはペイロードベースのフィルタリングのいずれかを選択します。

  6. [JSON editor](JSON エディタ) フィールドで、フィルターポリシーの [JSON body](JSON 本文) を提供します。

  7. [変更を保存] をクリックします。

    Amazon SNS により、フィルターポリシーがサブスクリプションに適用されます。

AWS CLI

AWS Command Line Interface (AWS CLI) を使用してフィルタポリシーを適用するには、set-subscription-attributes以下の例のようにコマンドを使用します。--attribute-name オプションで、FilterPolicy を指定します。--attribute-value で、JSON ポリシーを指定します。

$ aws sns set-subscription-attributes --subscription-arn arn:aws:sns: ... --attribute-name FilterPolicy --attribute-value '{"store":["example_corp"],"event":["order_placed"]}'

ポリシーに有効な JSON を提供するには、属性名と値を二重引用符で囲みます。また、ポリシーの引数全体を引用符で囲む必要があります。引用符のエスケープを避けるため、上に示した例のように、一重引用符を使用してポリシーを囲み、二重引用符を使用して JSON 名と値を囲みます。

属性ベース (デフォルト) からペイロードベースのメッセージフィルタリングに切り替える場合は、コマンドを使用することもできます。set-subscription-attributes--attribute-name オプションで、FilterPolicyScope を指定します。--attribute-value の場合、MessageBody を指定します。

$ aws sns set-subscription-attributes --subscription-arn arn:aws:sns: ... --attribute-name FilterPolicyScope --attribute-value MessageBody

フィルターポリシーが適用されたことを確認するには、get-subscription-attributes コマンドを使用します。ターミナル出力の属性には、以下の例に示すように、FilterPolicy キーのフィルターポリシーが表示されます。

$ aws sns get-subscription-attributes --subscription-arn arn:aws:sns: ... { "Attributes": { "Endpoint": "endpoint . . .", "Protocol": "https", "RawMessageDelivery": "false", "EffectiveDeliveryPolicy": "delivery policy . . .", "ConfirmationWasAuthenticated": "true", "FilterPolicy": "{\"store\": [\"example_corp\"], \"event\": [\"order_placed\"]}", "FilterPolicyScope": "MessageAttributes", "Owner": "111122223333", "SubscriptionArn": "arn:aws:sns: . . .", "TopicArn": "arn:aws:sns: . . ." } }

AWS SDK

SetSubscriptionAttributes次のコード例は使用方法を示しています。

重要

SDK for Java 2.x の例を使用している場合、クラス SNSMessageFilterPolicy はそのままでは使用できません。このクラスのインストール方法については、 GitHub Web サイトの例を参照してください

CLI
AWS CLI

サブスクリプション属性を設定するには

次の set-subscription-attributes の例では、RawMessageDelivery 属性を SQS サブスクリプションに設定します。

aws sns set-subscription-attributes \ --subscription-arn arn:aws:sns:us-east-1:123456789012:mytopic:f248de18-2cf6-578c-8592-b6f1eaa877dc \ --attribute-name RawMessageDelivery \ --attribute-value true

このコマンドでは何も出力されません。

次の set-subscription-attributes の例では、FilterPolicy 属性を SQS サブスクリプションに設定します。

aws sns set-subscription-attributes \ --subscription-arn arn:aws:sns:us-east-1:123456789012:mytopic:f248de18-2cf6-578c-8592-b6f1eaa877dc \ --attribute-name FilterPolicy \ --attribute-value "{ \"anyMandatoryKey\": [\"any\", \"of\", \"these\"] }"

このコマンドでは何も出力されません。

次の set-subscription-attributes の例では、FilterPolicy 属性を SQS サブスクリプションから削除します。

aws sns set-subscription-attributes \ --subscription-arn arn:aws:sns:us-east-1:123456789012:mytopic:f248de18-2cf6-578c-8592-b6f1eaa877dc \ --attribute-name FilterPolicy \ --attribute-value "{}"

このコマンドでは何も出力されません。

  • API の詳細については、「AWS CLI コマンドリファレンスSetSubscriptionAttributesのを参照してください。

Java
SDK for Java 2.x
注記

にはまだまだあります GitHub。AWS コード例リポジトリ で全く同じ例を見つけて、設定と実行の方法を確認してください。

import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.sns.SnsClient; import software.amazon.awssdk.services.sns.model.SnsException; import java.util.ArrayList; /** * Before running this Java V2 code example, set up your development * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html */ public class UseMessageFilterPolicy { public static void main(String[] args) { final String usage = """ Usage: <subscriptionArn> Where: subscriptionArn - The ARN of a subscription. """; if (args.length != 1) { System.out.println(usage); System.exit(1); } String subscriptionArn = args[0]; SnsClient snsClient = SnsClient.builder() .region(Region.US_EAST_1) .build(); usePolicy(snsClient, subscriptionArn); snsClient.close(); } public static void usePolicy(SnsClient snsClient, String subscriptionArn) { try { SNSMessageFilterPolicy fp = new SNSMessageFilterPolicy(); // Add a filter policy attribute with a single value fp.addAttribute("store", "example_corp"); fp.addAttribute("event", "order_placed"); // Add a prefix attribute fp.addAttributePrefix("customer_interests", "bas"); // Add an anything-but attribute fp.addAttributeAnythingBut("customer_interests", "baseball"); // Add a filter policy attribute with a list of values ArrayList<String> attributeValues = new ArrayList<>(); attributeValues.add("rugby"); attributeValues.add("soccer"); attributeValues.add("hockey"); fp.addAttribute("customer_interests", attributeValues); // Add a numeric attribute fp.addAttribute("price_usd", "=", 0); // Add a numeric attribute with a range fp.addAttributeRange("price_usd", ">", 0, "<=", 100); // Apply the filter policy attributes to an Amazon SNS subscription fp.apply(snsClient, subscriptionArn); } catch (SnsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } }
  • API の詳細については、AWS SDK for Java 2.x API SetSubscriptionAttributesリファレンスのを参照してください

Python
SDK for Python (Boto3)
注記

にはまだまだあります GitHub。AWS コード例リポジトリ で全く同じ例を見つけて、設定と実行の方法を確認してください。

class SnsWrapper: """Encapsulates Amazon SNS topic and subscription functions.""" def __init__(self, sns_resource): """ :param sns_resource: A Boto3 Amazon SNS resource. """ self.sns_resource = sns_resource @staticmethod def add_subscription_filter(subscription, attributes): """ Adds a filter policy to a subscription. A filter policy is a key and a list of values that are allowed. When a message is published, it must have an attribute that passes the filter or it will not be sent to the subscription. :param subscription: The subscription the filter policy is attached to. :param attributes: A dictionary of key-value pairs that define the filter. """ try: att_policy = {key: [value] for key, value in attributes.items()} subscription.set_attributes( AttributeName="FilterPolicy", AttributeValue=json.dumps(att_policy) ) logger.info("Added filter to subscription %s.", subscription.arn) except ClientError: logger.exception( "Couldn't add filter to subscription %s.", subscription.arn ) raise
  • API の詳細については、AWS SDK for Python (Boto3) API リファレンスのを参照してくださいSetSubscriptionAttributes

Amazon SNS API

Amazon SNS API を使用してフィルターポリシーを適用するには、SetSubscriptionAttributes アクションへのリクエストを作成します。AttributeName パラメータを FilterPolicy に設定し、AttributeValue パラメータをフィルターポリシーの JSON に設定します。

メッセージフィルタリングを属性ベース (デフォルト) からペイロードベースのメッセージフィルタリングに切り替える場合は、SetSubscriptionAttributes アクションも使用できます。AttributeName パラメータを FilterPolicyScope に設定し、AttributeValue パラメータを MessageBody に設定します。

AWS CloudFormation

を使用してフィルターポリシーを適用するには AWS CloudFormation、JSON または YAML テンプレートを使用してスタックを作成します。 AWS CloudFormation 詳細については、『AWS CloudFormation ユーザーガイド』FilterPolicyAWS::SNS::Subscription AWS CloudFormation のリソースのプロパティとサンプルテンプレートを参照してください

  1. AWS CloudFormation コンソール にサインインします。

  2. [スタックの作成] を選択します。

  3. [テンプレートの選択] ページで、[テンプレートを Amazon S3 にアップロード] を選択してから、ファイルを選択して [次へ] をクリックします。

  4. [詳細の指定] ページで、以下の作業を行います。

    1. [スタックの名前] に「MyFilterPolicyStack」と入力します。

    2. にはmyHttpEndpoint、トピックに登録する HTTP エンドポイントを入力します。

      ヒント

      HTTP エンドポイントがない場合は作成します。

  5. [オプション] ページで、[次へ] をクリックします。

  6. [Review] ページで、[作成] を選択します。