モーダルを閉じる工作HardwareHub ロゴ画像

工作HardwareHubは、ロボット工作や電子工作に関する情報やモノが行き交うコミュニティサイトです。さらに詳しく

利用規約プライバシーポリシー に同意したうえでログインしてください。

目次目次を開く/閉じる

Amazon Comprehend を GCP VPC 内から実行する設定の例 (Public Internet 接続なし)

モーダルを閉じる

ステッカーを選択してください

お支払い手続きへ
モーダルを閉じる

お支払い内容をご確認ください

購入商品
」ステッカーの表示権
メッセージ
料金
(税込)
決済方法
GooglePayマーク
決済プラットフォーム
確認事項

利用規約をご確認のうえお支払いください

※カード情報はGoogleアカウント内に保存されます。本サイトやStripeには保存されません

※記事の執筆者は購入者のユーザー名を知ることができます

※購入後のキャンセルはできません

作成日作成日
2021/09/03
最終更新最終更新
2023/12/12
記事区分記事区分
一般公開

目次

    インフラ構築と自動化が得意。TerraformとAnsibleでインフラを自動構築するお仕事が多め

    GCP DLP に相当する AWS サービスに Amazon Comprehend が存在します。GCP VPC 内から Public Internet を経由せずに利用する設定の例を記載します。

    AWS VPC と GCP VPC の作成

    クラウド 項目
    AWS VPC region ap-northeast-1
    AWS VPC CIDR 10.2.0.0/16
    AWS ap-northeast-1b 10.2.2.0/24
    AWS ap-northeast-1c 10.2.3.0/24
    AWS DNS hostnames Disabled/Enabled (どちらでも可)
    GCP asia-northeast1 10.1.1.0/24
    GCP asia-northeast1 10.8.0.0/28 (Serverless VPC access を利用する場合)
    GCP Private Google Access On

    GCP Firewall 設定

    Priority Direction of traffic Action on match IP ranges
    65534 Ingress Deny 0.0.0.0/0
    65534 Egress Deny 0.0.0.0/0
    1000 Ingress Allow 35.235.240.0/20
    1000 Egress Allow 199.36.153.4/30
    1000 Egress Allow 10.2.0.0/16

    gcloud のための GCP DNS 設定

    項目
    DNS 種別 Response policy
    DNS type A
    *.googleapis.com 199.36.153.4
    *.googleapis.com 199.36.153.5
    *.googleapis.com 199.36.153.6
    *.googleapis.com 199.36.153.7

    VPN 設定、AWS セキュリティグループ作成

    クラウド 項目
    AWS VPC route propagation Yes (応答するパケットを返すときにはルートが必要です)
    AWS EC2 security group Allow Inbound 10.1.1.0/24
    AWS VPCE security group Allow Inbound 10.1.1.0/24, 10.8.0.0/28, 10.2.0.0/16

    AWS IAM User の作成

    項目 チェック
    Programmatic access O
    AWS Management Console access X
    AmazonS3FullAccess O
    iam:PassRole 下記参照
    comprehend:* 下記参照

    Inline Poliy 等によって付与

    {
      "Version": "2012-10-17",
      "Statement": [
        {
          "Effect": "Allow",
          "Resource": "*",
          "Action": [
            "comprehend:DetectEntities",
            "comprehend:BatchDetectEntities",
            "comprehend:StartEntitiesDetectionJob",
            "comprehend:ListEntitiesDetectionJobs",
            "comprehend:DescribeEntitiesDetectionJob",
            "comprehend:StopEntitiesDetectionJob",
            "comprehend:DetectPiiEntities",
            "comprehend:ContainsPiiEntities",
            "comprehend:StopPiiEntitiesDetectionJob",
            "comprehend:ListPiiEntitiesDetectionJobs",
            "comprehend:DescribePiiEntitiesDetectionJob",
            "comprehend:StartPiiEntitiesDetectionJob",
            "comprehend:DetectDominantLanguage"
          ]
        },
        {
          "Effect": "Allow",
          "Resource": "arn:aws:iam::123412341234:role/my-comprehend-role",
          "Action": [
            "iam:PassRole"
          ],
          "Condition": {
            "StringEquals": {
              "iam:PassedToService": "comprehend.amazonaws.com"
            }
          }
        }
      ]
    }
    

    AWS IAM Role の作成

    Comprehend が S3 にアクセスする際に利用する IAM Role を作成します。

    項目
    ARN arn:aws:iam::123412341234:role/my-comprehend-role
    Trust Relationship 下記参照
    Permissions 下記参照

    Trust Relationship

    {
      "Version": "2012-10-17",
      "Statement": [
        {
          "Effect": "Allow",
          "Principal": {
            "Service": "comprehend.amazonaws.com"
          },
          "Action": "sts:AssumeRole"
        }
      ]
    }
    

    Permissions

    {
      "Version": "2012-10-17",
      "Statement": [
        {
          "Effect": "Allow",
          "Action": [
            "s3:GetObject",
            "s3:ListBucket",
            "s3:PutObject"
          ],
          "Resource": [
            "arn:aws:s3:::my-comprehend-bucket-20210905",
            "arn:aws:s3:::my-comprehend-bucket-20210905/*"
          ]
        },
        {
          "Effect": "Allow",
          "Action": [
            "ec2:CreateNetworkInterface",
            "ec2:CreateNetworkInterfacePermission",
            "ec2:DeleteNetworkInterface",
            "ec2:DeleteNetworkInterfacePermission",
            "ec2:DescribeNetworkInterfaces",
            "ec2:DescribeVpcs",
            "ec2:DescribeDhcpOptions",
            "ec2:DescribeSubnets",
            "ec2:DescribeSecurityGroups"
          ],
          "Resource": "*"
        }
      ]
    }
    

    参照資料:

    GCP Secret Manager 設定

    簡単のため、以下の設定で作成します。AWS IAM User の Secret access key を格納します。

    項目
    Replication policy asia-northeast1, asia-northeast2
    Encryption google-managed
    Rotation None
    Notifications None
    Expiration Never
    Permissions roles/secretmanager.secretAccessor (GCE および Cloud Functions の Service Account)

    参考資料:

    • Managing secret versions
      • 理想的には、production においては latest を使わずに特定の version を指すようにします。
    • Access control (IAM)
      • アプリケーションから secret 値を参照するためには roles/secretmanager.secretAccessor を利用します。
      • roles/editorroles/viewer は secret 値を参照できません。
    • Secret Manager Audit Logging
      • "Admin Write" 以外の Audit Logs は既定では無効になっています。
    • Choosing a Replication Policy
      • secret 値が保存されるリージョンを指定できます。

    VM 作成

    クラウド 項目
    GCP Region asia-northeast1
    GCP Access scopes Allow full access to all Cloud APIs (cloud-platform)
    GCP External IP None
    AWS Public IP address None
    AWS security group 10.1.1.0/24 からの通信を許可

    参考資料:

    • OAuth scopes
      • GCP Compute Engine (GCE) には scope という概念があります。
      • cloud-platform を選択することで IAM による制御のみに切り換えます。

    AWS VPC Endpoint (PrivateLink) 作成

    項目
    com.amazonaws.ap-northeast-1.comprehend Interface
    com.amazonaws.ap-northeast-1.s3 Interface
    ap-northeast-1b O
    ap-northeast-1c O
    Enable DNS name O/X (どちらでも可)
    security group 10.1.1.0/24, 10.8.0.0/28, 10.2.0.0/16 からの通信を許可
    Policy 下記参照

    AWS VPC Endpoint Policy の設定

    {
      "Statement": [
        {
          "Effect": "Allow",
          "Principal": "*",
          "Action": [
              "comprehend:*",
              "iam:PassRole"
          ],
          "Resource": "*",
          "Condition": {
            "StringEquals": {
              "aws:PrincipalAccount": "123412341234"
            }
          }
        }
      ]
    }
    
    {
      "Statement": [
        {
          "Effect": "Allow",
          "Principal": "*",
          "Action": "s3:*",
          "Resource": [
            "arn:aws:s3:::my-comprehend-bucket-20210905",
            "arn:aws:s3:::my-comprehend-bucket-20210905/*"
          ],
          "Condition": {
            "StringEquals": {
              "aws:PrincipalAccount": "123412341234"
            }
          }
        }
      ]
    }
    

    参考資料:

    • Endpoints for Amazon S3
      • Source IP は Security Group で制御します。
      • IAM に関する制御を追加したい場合は VPC Endpoint Policy を設定します。
      • Identity-based policy と Resource-based policy で Allow されていたとしても、VPC Endpoint Policy における明示的な Allow が存在しない限りは Deny されます。
      • "Principal" ではなく "Condition" で Principal を制限します。
    • Policy の Allow と Deny 判定について
      • VPC Endpoint 自体も resource-based policy ですが、Action が対象とする Resource は Comprehend や S3 であり VPC Endpoint ではありません。
    • IAM ARNs
    • AWS global condition context keys
      • "aws:PrincipalAccount" は ARN operators には対応していません。
    • Creating a VPC endpoint policy for Amazon S3
    • Granting a user permissions to pass a role to an AWS service
      • Comprehend サービスに IAM Role を pass する Action も VPCE Policy で許可します。

    AWS S3 Gateway VPC Endpoint 作成

    項目
    com.amazonaws.ap-northeast-1.s3 Gateway
    Route Tables O
    Policy 下記参照
    {
      "Version": "2008-10-17",
      "Statement": [
        {
          "Effect": "Allow",
          "Principal": "*",
          "Action": "s3:*",
          "Resource": [
            "arn:aws:s3:::my-comprehend-bucket-20210905",
            "arn:aws:s3:::my-comprehend-bucket-20210905/*"
          ],
          "Condition": {
            "StringEquals": {
              "aws:PrincipalAccount": "123412341234"
            }
          }
        }
      ]
    }
    

    参考資料:

    S3 バケットの作成

    項目
    バケット名 my-comprehend-bucket-20210905
    Policy 下記参照
    {
      "Statement": [
        {
          "Effect": "Deny",
          "Principal": "*",
          "Action": "s3:*",
          "Resource": [
            "arn:aws:s3:::my-comprehend-bucket-20210905",
            "arn:aws:s3:::my-comprehend-bucket-20210905/*"
          ],
          "Condition": {
            "StringNotEquals": {
              "aws:sourceVpce": [
                "vpce-xxxxxxxxxxxxxxxxx",
                "vpce-yyyyyyyyyyyyyyyyy"
              ],
              "aws:PrincipalArn": "arn:aws:iam::123412341234:user/myadmin"
            }
          }
        }
      ]
    }
    

    参照資料:

    • Endpoints for Amazon S3
      • バケットと同じアカウントについて、myadmin ユーザ、または VPCE 経由でのアクセスを Allow (より正確には Implicit Allow) しています。
      • バケットと異なるアカウントからのアクセスが必要な場合は、別途 Explicit Allow する必要があります。
    • "aws:sourceVpce" には Interface type S3 VPCE と Gateway type S3 VPCE の ID を記載します。

    VM から VPC Endpoint の利用

    export AWS_DEFAULT_REGION=ap-northeast-1
    export AWS_ACCESS_KEY_ID=XXXXXXXXXXXXXXXXXXXX
    export AWS_SECRET_ACCESS_KEY=$(gcloud secrets versions access latest --secret my-aws-iam)
    
    aws --endpoint-url https://vpce-xxxxxxxxxxxxxxxxx-xxxxxxxx.comprehend.ap-northeast-1.vpce.amazonaws.com \
    comprehend detect-dominant-language --text "It is raining today in Seattle."
    
    aws --endpoint-url https://vpce-xxxxxxxxxxxxxxxxx-xxxxxxxx.comprehend.ap-northeast-1.vpce.amazonaws.com \
    comprehend detect-entities --text "私は田中です。こんにちは" \
    --language-code ja
    
    aws --endpoint-url https://vpce-xxxxxxxxxxxxxxxxx-xxxxxxxx.comprehend.ap-northeast-1.vpce.amazonaws.com \
    comprehend detect-pii-entities --text "My Phone number is 090-1111-2222" \
    --language-code en
    
    aws --endpoint-url https://bucket.vpce-xxxxxxxxxxxxxxxxx-xxxxxxxx.s3.ap-northeast-1.vpce.amazonaws.com \
    s3 ls s3://my-comprehend-bucket-20210905/
    
    python3 sample.py
    

    sample.py

    import boto3
    import json
    
    comprehend = boto3.client(service_name='comprehend', endpoint_url='https://vpce-xxxxxxxxxxxxxxxxx-xxxxxxxx.comprehend.ap-northeast-1.vpce.amazonaws.com')
    text = "It is raining today in Seattle"
    
    print('Calling DetectDominantLanguage')
    print(json.dumps(comprehend.detect_dominant_language(Text = text), sort_keys=True, indent=4))
    print("End of DetectDominantLanguage\n")
    

    参考資料:

    VPC Service Control の設定

    項目
    Project myproject-20210411
    Restricted Services All
    VPC Accessible Services RESTRICTED-SERVICES
    Access Levels my-dev-machine-ip
    Ingress policy From Identities xxxxxxxxxxxx@cloudbuild.gserviceaccount.com
    Ingress policy From Source All sources allowed
    Ingress policy To Projects myproject-20210411
    Ingress policy To Services All services

    参考資料:

    • VPC Service Controls に関する雑多な事項の整理
      • "RESTRICTED-SERVICES" を指定することで、GCP VPC からアクセス可能な googleapis を VPC-SC で指定されたものに制限できます。
    • Supported products and limitations
      • Cloud Functions で利用される container image の build 時に対しては VPC-SC は機能しません。
        • Cloud Build は pip や npm を利用するために Internet Access が許可されています。
        • VPC-SC が Cloud Build API に対して有効になっていたとしても許可されます。
      • Build 時に利用可能なデータの exfiltration に注意します。

    Serverless VPC access の作成

    項目
    Region asia-northeast1
    Subnet 10.8.0.0/28
    Minimum instances 2
    Maximum instances 10
    Instance type e2-micro

    参考資料:

    Organization policies の設定 (Project Level 設定)

    Organization Policy Administrator (roles/orgpolicy.policyAdmin) で設定します。Cloud Functions 動作時の通信を VPC 内に閉じ込めるための設定です。

    項目
    cloudfunctions.allowedIngressSettings ALLOW_INTERNAL_ONLY
    cloudfunctions.requireVPCConnector Enforce
    cloudfunctions.allowedVpcConnectorEgressSettings ALL_TRAFFIC

    参考資料:

    • Set up organization policies
      • HTTP について、VPC-SC 内の VPC からの通信に制限したデプロイのみを許可します。
      • VPC Connector を指定した関数のデプロイのみを許可します。
      • すべての egress 通信を VPC connector 経由に制限したデプロイのみを許可します。

    Cloud Functions 作成

    項目
    Region asia-northeast1
    AWS_DEFAULT_REGION ap-northeast-1
    AWS_ACCESS_KEY_ID XXXXXXXXXXXXXXXXXXXX
    Ingress settings Allow internal traffic only
    Egress settings Route all traffic through the VPC connector
    Reference a Secret AWS_SECRET_ACCESS_KEY
    Runtime Python 3.9

    main.py

    import boto3
    import json
    
    def hello_world(request):
    
        s3 = boto3.resource('s3', endpoint_url='https://bucket.vpce-xxxxxxxxxxxxxxxxx-xxxxxxxx.s3.ap-northeast-1.vpce.amazonaws.com')
        my_bucket = s3.Bucket('my-comprehend-bucket-20210905')
        for my_bucket_object in my_bucket.objects.all():
            print(my_bucket_object)
    
        comprehend = boto3.client(service_name='comprehend', endpoint_url='https://vpce-xxxxxxxxxxxxxxxxx-xxxxxxxx.comprehend.ap-northeast-1.vpce.amazonaws.com')
        text = "It is raining today in Seattle"
        return json.dumps(comprehend.detect_dominant_language(Text = text), sort_keys=True, indent=4)
    

    requirements.txt

    boto3==1.18.36
    

    出力例

    {
        "Languages": [
            {
                "LanguageCode": "en",
                "Score": 0.9925304651260376
            }
        ],
        "ResponseMetadata": {
            "HTTPHeaders": {
                "content-length": "64",
                "content-type": "application/x-amz-json-1.1",
                "date": "Sun, 05 Sep 2021 14:21:50 GMT",
                "x-amzn-requestid": "8c1561be-ac8f-4591-b9c9-e3e7f9efe594"
            },
            "HTTPStatusCode": 200,
            "RequestId": "8c1561be-ac8f-4591-b9c9-e3e7f9efe594",
            "RetryAttempts": 0
        }
    }
    

    参考資料:

    Amazon Comprehend Asynchronous API の実行例

    s3://my-comprehend-bucket-20210905/input/sample.txt

    こんにちは。私の名前は田中です。
    

    実行例

    aws --endpoint-url https://vpce-xxxxxxxxxxxxxxxxx-xxxxxxxx.comprehend.ap-northeast-1.vpce.amazonaws.com \
    comprehend start-entities-detection-job \
    --input-data-config S3Uri=s3://my-comprehend-bucket-20210905/input/ \
    --output-data-config S3Uri=s3://my-comprehend-bucket-20210905/output/ \
    --data-access-role-arn arn:aws:iam::123412341234:role/my-comprehend-role \
    --job-name reviews-entities-analysis \
    --language-code ja \
    --vpc-config SecurityGroupIds=sg-0cd4e94d4c206acdc,Subnets=subnet-07820d34f9d239941,subnet-04b91b3ac40ebe829
    
    aws --endpoint-url https://vpce-xxxxxxxxxxxxxxxxx-xxxxxxxx.comprehend.ap-northeast-1.vpce.amazonaws.com \
    comprehend describe-entities-detection-job \
    --job-id 2425a650c688f62dfbeffe1a966e736b
    

    出力例

    cat output | jq .
    {
      "Entities": [
        {
          "BeginOffset": 11,
          "EndOffset": 13,
          "Score": 0.9976550619896744,
          "Text": "田中",
          "Type": "PERSON"
        }
      ],
      "File": "sample.txt",
      "Line": 0
    }
    

    参考資料:

    AI サービス品質向上のためのデータ提供に関するオプトアウト

    AWS Organizations を利用した opt-out policy の設定、またはサポートに問い合わせることで、AI サービス品質向上のためのデータ提供に関してオプトアウトの設定が可能です。

    参考資料: Easily manage your content policies for AI services with AWS Organizations

    Likeボタン(off)0
    詳細設定を開く/閉じる
    アカウント プロフィール画像

    インフラ構築と自動化が得意。TerraformとAnsibleでインフラを自動構築するお仕事が多め

    記事の執筆者にステッカーを贈る

    有益な情報に対するお礼として、またはコメント欄における質問への返答に対するお礼として、 記事の読者は、執筆者に有料のステッカーを贈ることができます。

    >>さらに詳しくステッカーを贈る
    ステッカーを贈る コンセプト画像

    Feedbacks

    Feedbacks コンセプト画像

      ログインするとコメントを投稿できます。

      ログインする

      関連記事

      • GKE における Node および Pod の autoscaling
        サムネイル画像-7d7ee7c7aa
        Google Kubernetes Engine (GKE) における autoscaling について、用語の意味を整理します。 GKE の機能による Node の autoscaling GKE のクラスタには Standard と Autopilot の二種類が存在します。 Autopilot の場合は Node は Google によって管理されるため、自動で autoscaling され...
        junjun2/18/2024に更新
        いいねアイコン画像0
      • Snowflake におけるネットワーク関連の設定
        サムネイル画像-8ec2ac140d
        本ページではネットワーク関連の設定について記載します。 Network Policy によるアクセス元 IP 制限 IPv4 で指定します。IPv6 は 2021/9/21 時点では利用できません。 allowed list で許可されていない IP は block されます。 allowed list が /24 等で指定されており、その一部を
      • VPC Service Controls に関する雑多な事項の整理
        サムネイル画像-bb464b77f2
        VPC Service Controls (VPC-SC) に関する雑多な事項を記載します。 Private Google Access の基本形 Private Google Access は外部 IP を持たない VM のための機能です。VPC の機能ですが、VPC-SC と関連するため基本事項を記載します。 [Private Google Access](ht
        kentakenta3/18/2024に更新
        いいねアイコン画像0
      • AWS IAM Role を GCP から STS 認証で利用する設定例
        サムネイル画像-30f7c61cfa
        GCP から AWS IAM Role を利用するための設定例を記載します。 GCP Service Account の作成 Service Account を作成して Unique ID を確認します。 AWS IAM Role の作成 Trust relationship の設定は Web Identity を選択します。Identity Provider
        AWS NinjaAWS Ninja11/29/2024に更新
        いいねアイコン画像0
      • GCP IAP tunnel を HTTP プロキシを通して利用する場合の注意点
        サムネイル画像-fd7e826326
        IAP tunnel は、HTTPS トンネル内で TCP パケットを forward するための技術です。 この HTTPS トンネルは、ユーザと tunnel.cloudproxy.app の間で確立される WebSocket です。 そのため、IAP tunnel を HTTP プロキシ環境下で利用する際には、以下の二つに注意する必要があります。 tunnel.cloudproxy.app ...
        AWS NinjaAWS Ninja11/18/2023に更新
        いいねアイコン画像0