{CloudFront}オリジンリクエストへのカスタムヘッダーの追加

 

https://docs.aws.amazon.com/ja_jp/AmazonCloudFront/latest/DeveloperGuide/add-origin-custom-headers.html
https://docs.aws.amazon.com/ja_jp/AmazonCloudFront/latest/DeveloperGuide/restrict-access-to-load-balancer.html

https://www.yamamanx.com/cloudfront-customeheader-alb/

 

-- 1. コマンド等のインストール

-- 1.1 aws cli version 2 インストール

curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"
unzip awscliv2.zip
sudo ./aws/install
aws --version

 

-- 1.2 jqインストール
sudo yum -y install jq


-- 2. EC2インスタンス作成


-- ap-northeast-1a


vim a.sh

#!/bin/bash
yum -y update
yum -y install httpd
systemctl start httpd
systemctl enable httpd
echo $(hostname) > /var/www/html/index.html

 

aws ec2 run-instances \
--image-id ami-0404778e217f54308 \
--instance-type t3.nano \
--key-name key1 \
--tag-specifications 'ResourceType=instance,Tags=[{Key=Name,Value=instance01}]' \
--subnet-id subnet-11111111111111111 \
--user-data file://a.sh

 

aws ec2 describe-instances

 


-- 3. ロードバランサーの作成


aws elbv2 create-load-balancer \
--name alb01  \
--subnets subnet-11111111111111111 subnet-22222222222222222 \
--security-groups sg-33333333333333333


aws elbv2 describe-load-balancers
aws elbv2 describe-load-balancers| jq -r .LoadBalancers.LoadBalancerArn

 


aws elbv2 create-target-group \
--name target01 \
--protocol HTTP \
--port 80 \
--vpc-id vpc-44444444444444444 \
--ip-address-type ipv4 \
--target-type instance

aws elbv2 describe-target-groups
aws elbv2 describe-target-groups| jq -r .TargetGroups.TargetGroupArn

aws elbv2 describe-target-group-attributes \
--target-group-arn arn:aws:elasticloadbalancing:ap-northeast-1:999999999999:targetgroup/target01/555555555555555

 

aws elbv2 register-targets \
--target-group-arn arn:aws:elasticloadbalancing:ap-northeast-1:999999999999:targetgroup/target01/555555555555555  \
--targets Id=i-00000000000000000


aws elbv2 describe-target-health \
--target-group-arn arn:aws:elasticloadbalancing:ap-northeast-1:999999999999:targetgroup/target01/555555555555555

 


-- 4. リスナーの作成

aws elbv2 create-listener \
--load-balancer-arn arn:aws:elasticloadbalancing:ap-northeast-1:999999999999:loadbalancer/app/alb01/6666666666666666 \
--protocol HTTP \
--port 80  \
--default-actions Type=forward,TargetGroupArn=arn:aws:elasticloadbalancing:ap-northeast-1:999999999999:targetgroup/target01/555555555555555


aws elbv2 describe-listeners \
--load-balancer-arn arn:aws:elasticloadbalancing:ap-northeast-1:999999999999:loadbalancer/app/alb01/6666666666666666

aws elbv2 describe-listeners \
--load-balancer-arn arn:aws:elasticloadbalancing:ap-northeast-1:999999999999:loadbalancer/app/alb01/6666666666666666 | jq -r .Listeners[].ListenerArn

 


-- 5. ディストリビューションの作成


aws cloudfront create-distribution \
--origin-domain-name alb01-00000000.ap-northeast-1.elb.amazonaws.com


aws cloudfront list-distributions

aws cloudfront get-distribution \
--id AAAAAAAAAAAAAA

aws cloudfront get-distribution-config \
--id AAAAAAAAAAAAAA

 

 


-- 6. カスタムヘッダーの追加

aws cloudfront get-distribution \
--id AAAAAAAAAAAAAA

aws cloudfront get-distribution-config \
--id AAAAAAAAAAAAAA


aws cloudfront get-distribution-config \
--id AAAAAAAAAAAAAA | jq -r .DistributionConfig > distribution.json

vim distribution.json


Origins -> Items -> CustomHeaders を下記のように修正

        "CustomHeaders": {
          "Quantity": 1,
          "Items": [
            {
              "HeaderName": "X-HOGE",
              "HeaderValue": "header01"
            }
          ]
        },

aws cloudfront get-distribution-config \
--id AAAAAAAAAAAAAA | jq -r .ETag

aws cloudfront update-distribution \
--id AAAAAAAAAAAAAA \
--if-match DDDDDDDDDDDDD \
--distribution-config file://distribution.json


-- 7. リスナールール追加


aws elbv2 describe-rules \
--listener-arn arn:aws:elasticloadbalancing:ap-northeast-1:999999999999:listener/app/alb01/6666666666666666/7777777777777777


aws elbv2 create-rule \
--listener-arn arn:aws:elasticloadbalancing:ap-northeast-1:999999999999:listener/app/alb01/6666666666666666/7777777777777777 \
--conditions '[
                {
                    "Field": "http-header",
                    "HttpHeaderConfig": {
                        "HttpHeaderName": "X-HOGE",
                        "Values": [
                            "header01"
                        ]
                    }
                }
            ]' \
--priority 1 \
--actions ' [
                {
                    "Type": "forward",
                    "TargetGroupArn": "arn:aws:elasticloadbalancing:ap-northeast-1:999999999999:targetgroup/target01/555555555555555",
                    "Order": 1,
                    "ForwardConfig": {
                        "TargetGroups": [
                            {
                                "TargetGroupArn": "arn:aws:elasticloadbalancing:ap-northeast-1:999999999999:targetgroup/target01/555555555555555",
                                "Weight": 1
                            }
                        ],
                        "TargetGroupStickinessConfig": {
                            "Enabled": false
                        }
                    }
                }
            ]'

 

aws elbv2 describe-listeners \
--load-balancer-arn arn:aws:elasticloadbalancing:ap-northeast-1:999999999999:loadbalancer/app/alb01/6666666666666666

aws elbv2 modify-listener \
--listener-arn arn:aws:elasticloadbalancing:ap-northeast-1:999999999999:listener/app/alb01/6666666666666666/7777777777777777 \
--default-actions ' [
                {
                    "Type": "fixed-response",
                    "Order": 1,
                    "FixedResponseConfig": {
                        "MessageBody": "Access denied!!!",
                        "StatusCode": "403",
                        "ContentType": "text/plain"
                    }
                }
            ]'

 

 


-- 8. 動作確認


curl -v -X GET https://xxxxxxxxxxxxxx.cloudfront.net/index.html

→ 200

curl -v -X GET http://alb01-00000000.ap-northeast-1.elb.amazonaws.com/index.html

→ 403 Forbidden

curl -v -X GET -H 'X-HOGE:header01' http://alb01-00000000.ap-northeast-1.elb.amazonaws.com/index.html

→ 200

 


-- 9. クリーンアップ

 


-- ディストリビューションの無効化

aws cloudfront get-distribution \
--id AAAAAAAAAAAAAA

aws cloudfront get-distribution-config \
--id AAAAAAAAAAAAAA


※ distribution.jsonはget-distribution-configコマンドのDistributionConfigから取得し、Enabledをfalseに変更する

aws cloudfront get-distribution-config \
--id AAAAAAAAAAAAAA | jq -r .DistributionConfig > distribution.json

sed -i 's/"Enabled": true/"Enabled": false/' distribution.json

 

aws cloudfront get-distribution-config \
--id AAAAAAAAAAAAAA | jq -r .ETag

aws cloudfront update-distribution \
--id AAAAAAAAAAAAAA \
--if-match BBBBBBBBBBBBBB \
--distribution-config file://distribution.json


※ if-matchにはETagの値をセット

無効化されるまで待つ


-- ディストリビューションの削除

aws cloudfront get-distribution \
--id AAAAAAAAAAAAAA

aws cloudfront get-distribution-config \
--id AAAAAAAAAAAAAA

aws cloudfront get-distribution-config \
--id AAAAAAAAAAAAAA | jq -r .ETag

aws cloudfront delete-distribution \
--id AAAAAAAAAAAAAA \
--if-match CCCCCCCCCCCCCC

aws cloudfront list-distributions

 

-- リスナーの削除

aws elbv2 describe-listeners \
--load-balancer-arn arn:aws:elasticloadbalancing:ap-northeast-1:999999999999:loadbalancer/app/alb01/6666666666666666


aws elbv2 delete-listener \
--listener-arn arn:aws:elasticloadbalancing:ap-northeast-1:999999999999:listener/app/alb01/6666666666666666/7777777777777777


-- ターゲットグループの削除

aws elbv2 describe-target-groups

aws elbv2 deregister-targets \
--target-group-arn arn:aws:elasticloadbalancing:ap-northeast-1:999999999999:targetgroup/target01/555555555555555 \
--targets Id=i-00000000000000000

aws elbv2 delete-target-group \
--target-group-arn arn:aws:elasticloadbalancing:ap-northeast-1:999999999999:targetgroup/target01/555555555555555

 


-- ロードバランサーの削除

aws elbv2 describe-load-balancers

aws elbv2 delete-load-balancer \
--load-balancer-arn arn:aws:elasticloadbalancing:ap-northeast-1:999999999999:loadbalancer/app/alb01/6666666666666666

 

-- EC2インスタンスの削除

aws ec2 describe-instances

aws ec2 terminate-instances --instance-ids i-00000000000000000

 

 

 

{CloudFront}CloudFront オリジンフェイルオーバーによる高可用性の最適化

https://docs.aws.amazon.com/ja_jp/AmazonCloudFront/latest/DeveloperGuide/high_availability_origin_failover.html

https://dev.classmethod.jp/articles/cloudfront-origin-failover/


プライマリオリジン: ALB
セカンダリオリジン: S3


-- 1. コマンド等のインストール

-- 1.1 aws cli version 2 インストール

curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"
unzip awscliv2.zip
sudo ./aws/install
aws --version

 

-- 1.2 jqインストール
sudo yum -y install jq


-- 2. EC2インスタンス作成


-- ap-northeast-1a


vim a.sh

#!/bin/bash
yum -y update
yum -y install httpd
systemctl start httpd
systemctl enable httpd
echo $(hostname) > /var/www/html/index.html

 

aws ec2 run-instances \
--image-id ami-0404778e217f54308 \
--instance-type t3.nano \
--key-name key1 \
--tag-specifications 'ResourceType=instance,Tags=[{Key=Name,Value=instance01}]' \
--subnet-id subnet-11111111111111111 \
--user-data file://a.sh

 

aws ec2 describe-instances

 


-- 3. ロードバランサーの作成


aws elbv2 create-load-balancer \
--name alb01  \
--subnets subnet-11111111111111111 subnet-22222222222222222 \
--security-groups sg-33333333333333333


aws elbv2 describe-load-balancers
aws elbv2 describe-load-balancers| jq -r .LoadBalancers.LoadBalancerArn

 


aws elbv2 create-target-group \
--name target01 \
--protocol HTTP \
--port 80 \
--vpc-id vpc-44444444444444444 \
--ip-address-type ipv4 \
--target-type instance

aws elbv2 describe-target-groups
aws elbv2 describe-target-groups| jq -r .TargetGroups.TargetGroupArn

aws elbv2 describe-target-group-attributes \
--target-group-arn arn:aws:elasticloadbalancing:ap-northeast-1:999999999999:targetgroup/target01/5555555555555555

 

aws elbv2 register-targets \
--target-group-arn arn:aws:elasticloadbalancing:ap-northeast-1:999999999999:targetgroup/target01/5555555555555555  \
--targets Id=i-88888888888888888


aws elbv2 describe-target-health \
--target-group-arn arn:aws:elasticloadbalancing:ap-northeast-1:999999999999:targetgroup/target01/5555555555555555

 


-- 4. リスナーの作成

aws elbv2 create-listener \
--load-balancer-arn arn:aws:elasticloadbalancing:ap-northeast-1:999999999999:loadbalancer/app/alb01/6666666666666666 \
--protocol HTTP \
--port 80  \
--default-actions Type=forward,TargetGroupArn=arn:aws:elasticloadbalancing:ap-northeast-1:999999999999:targetgroup/target01/5555555555555555


aws elbv2 describe-listeners \
--load-balancer-arn arn:aws:elasticloadbalancing:ap-northeast-1:999999999999:loadbalancer/app/alb01/6666666666666666

aws elbv2 describe-listeners \
--load-balancer-arn arn:aws:elasticloadbalancing:ap-northeast-1:999999999999:loadbalancer/app/alb01/6666666666666666 | jq -r .Listeners[].ListenerArn

 


-- 5. ディストリビューションの作成


aws cloudfront create-distribution \
--origin-domain-name alb01-0000000000.ap-northeast-1.elb.amazonaws.com

 


aws cloudfront list-distributions

aws cloudfront get-distribution \
--id AAAAAAAAAAAAAA

aws cloudfront get-distribution-config \
--id AAAAAAAAAAAAAA

 

 

-- 6. S3 バケットを作成する

aws s3 ls

aws s3 mb s3://bucket123

 

 

-- 7. パブリックアクセスブロック設定の編集

-- 7.1 アカウントレベル
aws s3control put-public-access-block \
--account-id 999999999999 \
--public-access-block-configuration "BlockPublicAcls=false,IgnorePublicAcls=false,BlockPublicPolicy=false,RestrictPublicBuckets=false"

aws s3control get-public-access-block \
--account-id 999999999999

-- 7.2 バケットレベル
aws s3api put-public-access-block \
--bucket bucket123 \
--public-access-block-configuration "BlockPublicAcls=false,IgnorePublicAcls=false,BlockPublicPolicy=false,RestrictPublicBuckets=false"

aws s3api get-public-access-block \
--bucket bucket123


-- 8. バケットポリシーの設定

vim b.json

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "PublicReadGetObject",
            "Effect": "Allow",
            "Principal": "*",
            "Action": "s3:GetObject",
            "Resource": "arn:aws:s3:::bucket123/*",
            "Condition": {
                "IpAddress": {
                    "aws:SourceIp": "0.0.0.0/0"
                }
            }
        }
    ]
}

 

aws s3api put-bucket-policy \
--bucket bucket123 \
--policy file://b.json


aws s3api get-bucket-policy \
--bucket bucket123


-- 9. インデックスドキュメントの設定

vim index.html

<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    <title>My Website Home Page</title>
</head>
<body>
  <h1>Welcome to my website</h1>
  <p>Now hosted on Amazon S3!</p>
</body>
</html>

aws s3api put-object --bucket bucket123 --key index.html --body index.html --content-type text/html

 


-- 10. セカンドオリジンの追加


aws cloudfront get-distribution \
--id AAAAAAAAAAAAAA

aws cloudfront get-distribution-config \
--id AAAAAAAAAAAAAA


aws cloudfront get-distribution-config \
--id AAAAAAAAAAAAAA | jq -r .DistributionConfig > distribution.json

vim distribution.json


Origins -> Items に下記を追加し、Quantityを1 → 2に修正

      {
        "Id": "bucket123.s3.ap-northeast-1.amazonaws.com",
        "DomainName": "bucket123.s3.ap-northeast-1.amazonaws.com",
        "OriginPath": "",
        "CustomHeaders": {
          "Quantity": 0
        },
        "S3OriginConfig": {
          "OriginAccessIdentity": ""
        },
        "ConnectionAttempts": 3,
        "ConnectionTimeout": 10,
        "OriginShield": {
          "Enabled": false
        }
      },


aws cloudfront get-distribution-config \
--id AAAAAAAAAAAAAA | jq -r .ETag

aws cloudfront update-distribution \
--id AAAAAAAAAAAAAA \
--if-match BBBBBBBBBBBBBB \
--distribution-config file://distribution.json


-- 11. オリジングループの作成


aws cloudfront get-distribution \
--id AAAAAAAAAAAAAA

aws cloudfront get-distribution-config \
--id AAAAAAAAAAAAAA


aws cloudfront get-distribution-config \
--id AAAAAAAAAAAAAA | jq -r .DistributionConfig > distribution.json

vim distribution.json


OriginGroups を下記のように修正

  "OriginGroups": {
    "Quantity": 1,
    "Items": [
      {
        "Id": "og01",
        "FailoverCriteria": {
          "StatusCodes": {
            "Quantity": 8,
            "Items": [
              400,
              403,
              404,
              416,
              500,
              502,
              503,
              504
            ]
          }
        },
        "Members": {
          "Quantity": 2,
          "Items": [
            {
              "OriginId": "alb01-0000000000.ap-northeast-1.elb.amazonaws.com-0000000000-000000"
            },
            {
              "OriginId": "bucket123.s3.ap-northeast-1.amazonaws.com"
            }
          ]
        }
      }
    ]
  },


aws cloudfront get-distribution-config \
--id AAAAAAAAAAAAAA | jq -r .ETag

aws cloudfront update-distribution \
--id AAAAAAAAAAAAAA \
--if-match CCCCCCCCCCCCCC \
--distribution-config file://distribution.json


-- 12. デフォルトビヘイビアの修正


aws cloudfront get-distribution \
--id AAAAAAAAAAAAAA

aws cloudfront get-distribution-config \
--id AAAAAAAAAAAAAA


aws cloudfront get-distribution-config \
--id AAAAAAAAAAAAAA | jq -r .DistributionConfig > distribution.json

vim distribution.json


DefaultCacheBehavior を下記のように修正
※オブジェクトキャッシュの最大TTLと デフォルトTTLを10秒に設定

  "DefaultCacheBehavior": {
    "TargetOriginId": "og01",
    "TrustedSigners": {
      "Enabled": false,
      "Quantity": 0
    },
    "TrustedKeyGroups": {
      "Enabled": false,
      "Quantity": 0
    },
    "ViewerProtocolPolicy": "allow-all",
    "AllowedMethods": {
      "Quantity": 2,
      "Items": [
        "HEAD",
        "GET"
      ],
      "CachedMethods": {
        "Quantity": 2,
        "Items": [
          "HEAD",
          "GET"
        ]
      }
    },
    "SmoothStreaming": false,
    "Compress": false,
    "LambdaFunctionAssociations": {
      "Quantity": 0
    },
    "FunctionAssociations": {
      "Quantity": 0
    },
    "FieldLevelEncryptionId": "",
    "ForwardedValues": {
      "QueryString": false,
      "Cookies": {
        "Forward": "none"
      },
      "Headers": {
        "Quantity": 0
      },
      "QueryStringCacheKeys": {
        "Quantity": 0
      }
    },
    "MinTTL": 0,
    "DefaultTTL": 10,
    "MaxTTL": 10
  },
  

 


aws cloudfront get-distribution-config \
--id AAAAAAAAAAAAAA | jq -r .ETag

aws cloudfront update-distribution \
--id AAAAAAAAAAAAAA \
--if-match DDDDDDDDDDDDDD \
--distribution-config file://distribution.json

 


-- 13. 動作確認


curl -v -X GET https://xxxxxxxxxxxxx.cloudfront.net/index.html


curl -v -X GET http://alb01-0000000000.ap-northeast-1.elb.amazonaws.com/index.html


curl -v -X GET https://bucket123.s3.ap-northeast-1.amazonaws.com/index.html


ALBのEC2を停止してS3にフェイルオーバーを確認

ALBのステータスコードは503 Service Temporarily Unavailable

 


-- 14. クリーンアップ

 


-- ディストリビューションの無効化

aws cloudfront get-distribution \
--id AAAAAAAAAAAAAA

aws cloudfront get-distribution-config \
--id AAAAAAAAAAAAAA


※ distribution.jsonはget-distribution-configコマンドのDistributionConfigから取得し、Enabledをfalseに変更する

aws cloudfront get-distribution-config \
--id AAAAAAAAAAAAAA | jq -r .DistributionConfig > distribution.json

sed -i 's/"Enabled": true/"Enabled": false/' distribution.json

 

aws cloudfront get-distribution-config \
--id AAAAAAAAAAAAAA | jq -r .ETag

aws cloudfront update-distribution \
--id AAAAAAAAAAAAAA \
--if-match EEEEEEEEEEEEEE \
--distribution-config file://distribution.json


※ if-matchにはETagの値をセット

無効化されるまで待つ


-- ディストリビューションの削除

aws cloudfront get-distribution \
--id AAAAAAAAAAAAAA

aws cloudfront get-distribution-config \
--id AAAAAAAAAAAAAA

aws cloudfront get-distribution-config \
--id AAAAAAAAAAAAAA | jq -r .ETag

aws cloudfront delete-distribution \
--id AAAAAAAAAAAAAA \
--if-match FFFFFFFFFFFFF

aws cloudfront list-distributions

 

-- リスナーの削除

aws elbv2 describe-listeners \
--load-balancer-arn arn:aws:elasticloadbalancing:ap-northeast-1:999999999999:loadbalancer/app/alb01/6666666666666666


aws elbv2 delete-listener \
--listener-arn arn:aws:elasticloadbalancing:ap-northeast-1:999999999999:listener/app/alb01/6666666666666666/7777777777777777


-- ターゲットグループの削除

aws elbv2 describe-target-groups

aws elbv2 deregister-targets \
--target-group-arn arn:aws:elasticloadbalancing:ap-northeast-1:999999999999:targetgroup/target01/5555555555555555 \
--targets Id=i-88888888888888888

aws elbv2 delete-target-group \
--target-group-arn arn:aws:elasticloadbalancing:ap-northeast-1:999999999999:targetgroup/target01/5555555555555555

 


-- ロードバランサーの削除

aws elbv2 describe-load-balancers

aws elbv2 delete-load-balancer \
--load-balancer-arn arn:aws:elasticloadbalancing:ap-northeast-1:999999999999:loadbalancer/app/alb01/6666666666666666

 

-- EC2インスタンスの削除

aws ec2 describe-instances

aws ec2 terminate-instances --instance-ids i-88888888888888888

 

 

-- バケットの削除
aws s3 ls

aws s3 rb s3://bucket123 --force

-- アカウントレベルのパブリックアクセスブロックの有効化

aws s3control put-public-access-block \
--account-id 999999999999 \
--public-access-block-configuration "BlockPublicAcls=true,IgnorePublicAcls=true,BlockPublicPolicy=true,RestrictPublicBuckets=true"

aws s3control get-public-access-block \
--account-id 999999999999

 

 

{CloudFront}署名付き Cookie の使用



https://docs.aws.amazon.com/ja_jp/AmazonCloudFront/latest/DeveloperGuide/private-content-signed-cookies.html


https://dev.classmethod.jp/articles/cloudfront-signed-cookie/

 

 

-- 1. コマンド等のインストール

-- 1.1 aws cli version 2 インストール

curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"
unzip awscliv2.zip
sudo ./aws/install
aws --version

 

-- 1.2 jqインストール
sudo yum -y install jq


-- 2. S3 バケットを作成する

aws s3 ls

aws s3 mb s3://bucket123

 

 

-- 3. パブリックアクセスブロック設定の編集

-- 3.1 アカウントレベル
aws s3control put-public-access-block \
--account-id 999999999999 \
--public-access-block-configuration "BlockPublicAcls=false,IgnorePublicAcls=false,BlockPublicPolicy=false,RestrictPublicBuckets=false"

aws s3control get-public-access-block \
--account-id 999999999999

-- 3.2 バケットレベル
aws s3api put-public-access-block \
--bucket bucket123 \
--public-access-block-configuration "BlockPublicAcls=false,IgnorePublicAcls=false,BlockPublicPolicy=false,RestrictPublicBuckets=false"

aws s3api get-public-access-block \
--bucket bucket123


-- 4. バケットポリシーの設定

vim b.json

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "PublicReadGetObject",
            "Effect": "Allow",
            "Principal": "*",
            "Action": "s3:GetObject",
            "Resource": "arn:aws:s3:::bucket123/*",
            "Condition": {
                "IpAddress": {
                    "aws:SourceIp": "0.0.0.0/0"
                }
            }
        }
    ]
}

 

aws s3api put-bucket-policy \
--bucket bucket123 \
--policy file://b.json


aws s3api get-bucket-policy \
--bucket bucket123


-- 5. インデックスドキュメントの設定

vim index.html

<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    <title>My Website Home Page</title>
</head>
<body>
  <h1>Welcome to my website</h1>
  <p>Now hosted on Amazon S3!</p>
</body>
</html>

aws s3api put-object --bucket bucket123 --key index.html --body index.html --content-type text/html

 

 

-- 6. ディストリビューションの作成


aws cloudfront create-distribution \
--origin-domain-name bucket123.s3.ap-northeast-1.amazonaws.com \
--default-root-object index.html

 

aws cloudfront list-distributions

aws cloudfront get-distribution \
--id AAAAAAAAAAAAAA

aws cloudfront get-distribution-config \
--id AAAAAAAAAAAAAA

 


-- 7. 信頼されたキーグループのキーペアを作成する


-- 7.1 パブリックとプライベートのキーペアを作成する

openssl genrsa -out private_key.pem 2048


openssl rsa -pubout -in private_key.pem -out public_key.pem


-- 7.2 パブリックキーを CloudFront にアップロードする

cat public_key.pem

※EncodedKeyの改行部分は\nで置き換える

vim pubkey.json

{
    "CallerReference": "cli-example",
    "Name": "ExampleKey",
    "EncodedKey": "-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAxPMbCA2Ks0lnd7IR+3pw\nwd3H/7jPGwj8bLUmore7bX+oeGpZ6QmLAe/1UOWcmZX2u70dYcSIzB1ofZtcn4cJ\nenHBAzO3ohBY/L1tQGJfS2A+omnN6H16VZE1JCK8XSJyfze7MDLcUyHZETdxuvRb\nA9X343/vMAuQPnhinFJ8Wdy8YBXSPpy7r95ylUQd9LfYTBzVZYG2tSesplcOkjM3\n2Uu+oMWxQAw1NINnSLPinMVsutJy6ZqlV3McWNWe4T+STGtWhrPNqJEn45sIcCx4\nq+kGZ2NQ0FyIyT2eiLKOX5Rgb/a36E/aMk4VoDsaenBQgG7WLTnstb9sr7MIhS6A\nrwIDAQAB\n-----END PUBLIC KEY-----\n",
    "Comment": "example public key"
}


aws cloudfront create-public-key \
--public-key-config file://pubkey.json

aws cloudfront list-public-keys

aws cloudfront get-public-key \
--id DDDDDDDDDDDDDD

 


-- 7.3 キーグループの作成

aws cloudfront create-key-group \
--key-group-config '{
  "Name": "kg01",
  "Items": ["DDDDDDDDDDDDDD"],
  "Comment": "kg01"
}'


aws cloudfront list-key-groups

aws cloudfront get-key-group \
--id 11111111-2222-3333-4444-555555555555

 

--8. ディストリビューションへの署名者の追加


aws cloudfront get-distribution \
--id AAAAAAAAAAAAAA

aws cloudfront get-distribution-config \
--id AAAAAAAAAAAAAA


aws cloudfront get-distribution-config \
--id AAAAAAAAAAAAAA | jq -r .DistributionConfig > distribution.json

vim distribution.json


DefaultCacheBehavior -> TrustedKeyGroups を下記のように修正

    "TrustedKeyGroups": {
      "Enabled": true,
      "Quantity": 1,
      "Items": ["11111111-2222-3333-4444-555555555555"]
    },

 

aws cloudfront get-distribution-config \
--id AAAAAAAAAAAAAA | jq -r .ETag

aws cloudfront update-distribution \
--id AAAAAAAAAAAAAA \
--if-match EEEEEEEEEEEEEE \
--distribution-config file://distribution.json

 


-- 9. 署名付きCookieの生成


date +%s
date -d @1653007998

vim policy.json

{
    "Statement": [
        {
            "Resource": "https://xxxxxxxxxxxxxx.cloudfront.net/*",
            "Condition": {
                "DateLessThan": {
                    "AWS:EpochTime": 1653007998
                }
            }
        }
    ]
}

-- 9.1 CloudFront-Policyの生成

cat policy.json | tr -d "\n" | tr -d " \t\n\r" | openssl base64 | tr '+=/' '-_~'  | xargs | sed 's/ //g'

CloudFrontPolicy=$(cat policy.json | tr -d "\n" | tr -d " \t\n\r" | openssl base64 | tr '+=/' '-_~' | xargs | sed 's/ //g')

echo ${CloudFrontPolicy}

-- 9.2 CloudFrontSignatureの生成

cat policy.json | tr -d "\n" | tr -d " \t\n\r" | openssl sha1 -sign private_key.pem | openssl base64 -A | tr -- '+=/' '-_~'  | xargs | sed 's/ //g'

CloudFrontSignature=$(cat policy.json | tr -d "\n" | tr -d " \t\n\r" | openssl sha1 -sign private_key.pem | openssl base64 -A | tr -- '+=/' '-_~' | xargs | sed 's/ //g')

echo ${CloudFrontSignature}

-- 9.3 Cookieの生成

Cookie="Cookie:CloudFront-Policy=${CloudFrontPolicy};CloudFront-Signature=${CloudFrontSignature};CloudFront-Key-Pair-Id=DDDDDDDDDDDDDD"

echo ${Cookie}

 


-- 10. 動作確認

-- 10.1 署名なしで、S3直アクセス
curl -v -X GET https://bucket123.s3.ap-northeast-1.amazonaws.com/index.html

→ 200


-- 10.2 署名なしで、アクセス
curl -v -X GET https://xxxxxxxxxxxxxx.cloudfront.net/index.html

→ 403 Forbidden


-- 10.3 署名ありで、有効期限内アクセス

curl -v -X GET -H ${Cookie} https://xxxxxxxxxxxxxx.cloudfront.net/index.html

→ 200

-- 10.4 署名ありで、有効期限外アクセス


curl -v -X GET -H ${Cookie} https://xxxxxxxxxxxxxx.cloudfront.net/index.html

→ 403 Forbidden

 


-- 11. クリーンアップ

-- ディストリビューションから署名者の削除

aws cloudfront get-distribution \
--id AAAAAAAAAAAAAA

aws cloudfront get-distribution-config \
--id AAAAAAAAAAAAAA


aws cloudfront get-distribution-config \
--id AAAAAAAAAAAAAA | jq -r .DistributionConfig > distribution.json

vim distribution.json


DefaultCacheBehavior -> TrustedKeyGroups を下記のように修正

    "TrustedKeyGroups": {
      "Enabled": false,
      "Quantity": 0
    },


aws cloudfront get-distribution-config \
--id AAAAAAAAAAAAAA | jq -r .ETag

aws cloudfront update-distribution \
--id AAAAAAAAAAAAAA \
--if-match FFFFFFFFFFFFFF \
--distribution-config file://distribution.json

 


-- ディストリビューションの無効化

aws cloudfront get-distribution \
--id AAAAAAAAAAAAAA

aws cloudfront get-distribution-config \
--id AAAAAAAAAAAAAA


※ distribution.jsonはget-distribution-configコマンドのDistributionConfigから取得し、Enabledをfalseに変更する

aws cloudfront get-distribution-config \
--id AAAAAAAAAAAAAA | jq -r .DistributionConfig > distribution.json

sed -i 's/"Enabled": true/"Enabled": false/' distribution.json

 

aws cloudfront get-distribution-config \
--id AAAAAAAAAAAAAA | jq -r .ETag

aws cloudfront update-distribution \
--id AAAAAAAAAAAAAA \
--if-match GGGGGGGGGGGGG \
--distribution-config file://distribution.json


※ if-matchにはETagの値をセット

無効化されるまで待つ


-- ディストリビューションの削除

aws cloudfront get-distribution \
--id AAAAAAAAAAAAAA

aws cloudfront get-distribution-config \
--id AAAAAAAAAAAAAA

aws cloudfront get-distribution-config \
--id AAAAAAAAAAAAAA | jq -r .ETag

aws cloudfront delete-distribution \
--id AAAAAAAAAAAAAA \
--if-match HHHHHHHHHHHHH

 

aws cloudfront list-distributions


-- キーグループの削除


aws cloudfront list-key-groups

aws cloudfront get-key-group \
--id 11111111-2222-3333-4444-555555555555


aws cloudfront delete-key-group \
--id 11111111-2222-3333-4444-555555555555 \
--if-match IIIIIIIIIIIIII

 

 

-- パブリックキーの削除

aws cloudfront list-public-keys

aws cloudfront get-public-key \
--id DDDDDDDDDDDDDD

aws cloudfront delete-public-key \
--id DDDDDDDDDDDDDD \
--if-match JJJJJJJJJJJJJJ

 


-- バケットの削除
aws s3 ls

aws s3 rb s3://bucket123 --force

-- アカウントレベルのパブリックアクセスブロックの有効化

aws s3control put-public-access-block \
--account-id 999999999999 \
--public-access-block-configuration "BlockPublicAcls=true,IgnorePublicAcls=true,BlockPublicPolicy=true,RestrictPublicBuckets=true"

aws s3control get-public-access-block \
--account-id 999999999999

 

{CloudFront}署名付き URL の使用

 

https://docs.aws.amazon.com/ja_jp/AmazonCloudFront/latest/DeveloperGuide/private-content-signed-urls.html

https://zenn.dev/may_solty/articles/807dbad3a30de8


次のような場合は、署名付き URL を使用します。

個別のファイル (アプリケーションのインストールダウンロード) へのアクセスを制限する場合。
ユーザーが Cookie をサポートしていないクライアント (カスタム HTTP クライアントなど) を使用している場合。

 


-- 1. コマンド等のインストール

-- 1.1 aws cli version 2 インストール

curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"
unzip awscliv2.zip
sudo ./aws/install
aws --version

 

-- 1.2 jqインストール
sudo yum -y install jq


-- 2. S3 バケットを作成する

aws s3 ls

aws s3 mb s3://bucket123

 

 

-- 3. パブリックアクセスブロック設定の編集

-- 3.1 アカウントレベル
aws s3control put-public-access-block \
--account-id 999999999999 \
--public-access-block-configuration "BlockPublicAcls=false,IgnorePublicAcls=false,BlockPublicPolicy=false,RestrictPublicBuckets=false"

aws s3control get-public-access-block \
--account-id 999999999999

-- 3.2 バケットレベル
aws s3api put-public-access-block \
--bucket bucket123 \
--public-access-block-configuration "BlockPublicAcls=false,IgnorePublicAcls=false,BlockPublicPolicy=false,RestrictPublicBuckets=false"

aws s3api get-public-access-block \
--bucket bucket123


-- 4. バケットポリシーの設定

vim b.json

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "PublicReadGetObject",
            "Effect": "Allow",
            "Principal": "*",
            "Action": "s3:GetObject",
            "Resource": "arn:aws:s3:::bucket123/*",
            "Condition": {
                "IpAddress": {
                    "aws:SourceIp": "0.0.0.0/0"
                }
            }
        }
    ]
}

 

aws s3api put-bucket-policy \
--bucket bucket123 \
--policy file://b.json


aws s3api get-bucket-policy \
--bucket bucket123


-- 5. インデックスドキュメントの設定

vim index.html

<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    <title>My Website Home Page</title>
</head>
<body>
  <h1>Welcome to my website</h1>
  <p>Now hosted on Amazon S3!</p>
</body>
</html>

aws s3api put-object --bucket bucket123 --key index.html --body index.html --content-type text/html

 

 

-- 6. ディストリビューションの作成


aws cloudfront create-distribution \
--origin-domain-name bucket123.s3.ap-northeast-1.amazonaws.com \
--default-root-object index.html

 

aws cloudfront list-distributions

aws cloudfront get-distribution \
--id AAAAAAAAAAAAAA

aws cloudfront get-distribution-config \
--id AAAAAAAAAAAAAA

 


-- 7. 信頼されたキーグループのキーペアを作成する


-- 7.1 パブリックとプライベートのキーペアを作成する

openssl genrsa -out private_key.pem 2048


openssl rsa -pubout -in private_key.pem -out public_key.pem


-- 7.2 パブリックキーを CloudFront にアップロードする

cat public_key.pem

※EncodedKeyの改行部分は\nで置き換える

vim pubkey.json

{
    "CallerReference": "cli-example",
    "Name": "ExampleKey",
    "EncodedKey": "-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAxPMbCA2Ks0lnd7IR+3pw\nwd3H/7jPGwj8bLUmore7bX+oeGpZ6QmLAe/1UOWcmZX2u70dYcSIzB1ofZtcn4cJ\nenHBAzO3ohBY/L1tQGJfS2A+omnN6H16VZE1JCK8XSJyfze7MDLcUyHZETdxuvRb\nA9X343/vMAuQPnhinFJ8Wdy8YBXSPpy7r95ylUQd9LfYTBzVZYG2tSesplcOkjM3\n2Uu+oMWxQAw1NINnSLPinMVsutJy6ZqlV3McWNWe4T+STGtWhrPNqJEn45sIcCx4\nq+kGZ2NQ0FyIyT2eiLKOX5Rgb/a36E/aMk4VoDsaenBQgG7WLTnstb9sr7MIhS6A\nrwIDAQAB\n-----END PUBLIC KEY-----\n",
    "Comment": "example public key"
}


aws cloudfront create-public-key \
--public-key-config file://pubkey.json

aws cloudfront list-public-keys

aws cloudfront get-public-key \
--id DDDDDDDDDDDDDD

 


-- 7.3 キーグループの作成

aws cloudfront create-key-group \
--key-group-config '{
  "Name": "kg01",
  "Items": ["DDDDDDDDDDDDDD"],
  "Comment": "kg01"
}'


aws cloudfront list-key-groups

aws cloudfront get-key-group \
--id 11111111-2222-3333-4444-555555555555

 

--8. ディストリビューションへの署名者の追加


aws cloudfront get-distribution \
--id AAAAAAAAAAAAAA

aws cloudfront get-distribution-config \
--id AAAAAAAAAAAAAA


aws cloudfront get-distribution-config \
--id AAAAAAAAAAAAAA | jq -r .DistributionConfig > distribution.json

vim distribution.json


DefaultCacheBehavior -> TrustedKeyGroups を下記のように修正

    "TrustedKeyGroups": {
      "Enabled": true,
      "Quantity": 1,
      "Items": ["11111111-2222-3333-4444-555555555555"]
    },

 

aws cloudfront get-distribution-config \
--id AAAAAAAAAAAAAA | jq -r .ETag

aws cloudfront update-distribution \
--id AAAAAAAAAAAAAA \
--if-match EEEEEEEEEEEEEE \
--distribution-config file://distribution.json

 


-- 9. 署名付きURLの生成


aws cloudfront sign \
--url https://xxxxxxxxxxxxxx.cloudfront.net/index.html \
--key-pair-id DDDDDDDDDDDDDD \
--private-key file://private_key.pem \
--date-less-than 2022-05-22T23:53:00+09:00

 


-- 10. 動作確認

-- 10.1 署名なしで、S3直アクセス
curl -v -X GET https://bucket123.s3.ap-northeast-1.amazonaws.com/index.html

→ 200

-- 10.2 署名なしで、アクセス
curl -v -X GET https://xxxxxxxxxxxxxx.cloudfront.net/index.html

→ 403 Forbidden


-- 10.3 署名ありで、有効期限内アクセス


curl -v -X GET 'https://xxxxxxxxxxxxxx.cloudfront.net/index.html?Expires=1653018380&Signature=12345&Key-Pair-Id=DDDDDDDDDDDDDD'


→ 200

-- 10.4 署名ありで、有効期限外アクセス


curl -v -X GET 'https://xxxxxxxxxxxxxx.cloudfront.net/index.html?Expires=1653018380&Signature=12345&Key-Pair-Id=DDDDDDDDDDDDDD'


→ 403 Forbidden

 

 


-- 11. クリーンアップ

-- ディストリビューションから署名者の削除

aws cloudfront get-distribution \
--id AAAAAAAAAAAAAA

aws cloudfront get-distribution-config \
--id AAAAAAAAAAAAAA


aws cloudfront get-distribution-config \
--id AAAAAAAAAAAAAA | jq -r .DistributionConfig > distribution.json

vim distribution.json


DefaultCacheBehavior -> TrustedKeyGroups を下記のように修正

    "TrustedKeyGroups": {
      "Enabled": false,
      "Quantity": 0
    },


aws cloudfront get-distribution-config \
--id AAAAAAAAAAAAAA | jq -r .ETag

aws cloudfront update-distribution \
--id AAAAAAAAAAAAAA \
--if-match FFFFFFFFFFFFFF \
--distribution-config file://distribution.json

 


-- ディストリビューションの無効化

aws cloudfront get-distribution \
--id AAAAAAAAAAAAAA

aws cloudfront get-distribution-config \
--id AAAAAAAAAAAAAA


※ distribution.jsonはget-distribution-configコマンドのDistributionConfigから取得し、Enabledをfalseに変更する

aws cloudfront get-distribution-config \
--id AAAAAAAAAAAAAA | jq -r .DistributionConfig > distribution.json

sed -i 's/"Enabled": true/"Enabled": false/' distribution.json

 

aws cloudfront get-distribution-config \
--id AAAAAAAAAAAAAA | jq -r .ETag

aws cloudfront update-distribution \
--id AAAAAAAAAAAAAA \
--if-match GGGGGGGGGGGGG \
--distribution-config file://distribution.json


※ if-matchにはETagの値をセット

無効化されるまで待つ


-- ディストリビューションの削除

aws cloudfront get-distribution \
--id AAAAAAAAAAAAAA

aws cloudfront get-distribution-config \
--id AAAAAAAAAAAAAA

aws cloudfront get-distribution-config \
--id AAAAAAAAAAAAAA | jq -r .ETag

aws cloudfront delete-distribution \
--id AAAAAAAAAAAAAA \
--if-match HHHHHHHHHHHHH

 

aws cloudfront list-distributions


-- キーグループの削除


aws cloudfront list-key-groups

aws cloudfront get-key-group \
--id 11111111-2222-3333-4444-555555555555


aws cloudfront delete-key-group \
--id 11111111-2222-3333-4444-555555555555 \
--if-match IIIIIIIIIIIIII

 

 

-- パブリックキーの削除

aws cloudfront list-public-keys

aws cloudfront get-public-key \
--id DDDDDDDDDDDDDD

aws cloudfront delete-public-key \
--id DDDDDDDDDDDDDD \
--if-match JJJJJJJJJJJJJJ

 


-- バケットの削除
aws s3 ls

aws s3 rb s3://bucket123 --force

-- アカウントレベルのパブリックアクセスブロックの有効化

aws s3control put-public-access-block \
--account-id 999999999999 \
--public-access-block-configuration "BlockPublicAcls=true,IgnorePublicAcls=true,BlockPublicPolicy=true,RestrictPublicBuckets=true"

aws s3control get-public-access-block \
--account-id 999999999999

 

{CloudFront}オリジンアクセスアイデンティティ (OAI) を使用して Amazon S3 コンテンツへのアクセスを制限する


https://docs.aws.amazon.com/ja_jp/AmazonCloudFront/latest/DeveloperGuide/private-content-restricting-access-to-s3.html
https://aws.amazon.com/jp/premiumsupport/knowledge-center/cloudfront-serve-static-website/


ウェブサイトエンドポイントとして設定されている Amazon S3 バケットを使用する場合、
CloudFront でカスタムオリジンとして設定する必要があります。
オリジンアクセスアイデンティティ機能を使用することはできません。


-- 1. コマンド等のインストール

-- 1.1 aws cli version 2 インストール

curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"
unzip awscliv2.zip
sudo ./aws/install
aws --version

 

-- 1.2 jqインストール
sudo yum -y install jq


-- 2. S3 バケットを作成する

aws s3 ls

aws s3 mb s3://bucket123

 


-- 3. インデックスドキュメントの設定

vim index.html

<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    <title>My Website Home Page</title>
</head>
<body>
  <h1>Welcome to my website</h1>
  <p>Now hosted on Amazon S3!</p>
</body>
</html>

aws s3api put-object --bucket bucket123 --key index.html --body index.html --content-type text/html

 

 

-- 4. ディストリビューションの作成


aws cloudfront create-distribution \
--origin-domain-name bucket123.s3.ap-northeast-1.amazonaws.com \
--default-root-object index.html

 

aws cloudfront list-distributions

aws cloudfront get-distribution \
--id AAAAAAAAAAAAA

aws cloudfront get-distribution-config \
--id AAAAAAAAAAAAA

 


-- 5. OAIの作成

aws cloudfront create-cloud-front-origin-access-identity \
--cloud-front-origin-access-identity-config '{
    "CallerReference": "caller01",
    "Comment": "oai01"
}'


aws cloudfront list-cloud-front-origin-access-identities

aws cloudfront get-cloud-front-origin-access-identity \
--id BBBBBBBBBBBBBB

 

-- 6. OAIをディストリビューションに追加する

 

aws cloudfront get-distribution \
--id AAAAAAAAAAAAA

aws cloudfront get-distribution-config \
--id AAAAAAAAAAAAA


aws cloudfront get-distribution-config \
--id AAAAAAAAAAAAA | jq -r .DistributionConfig > distribution.json

vim distribution.json

Origins -> Items -> CustomHeaders の下の
CustomOriginConfigを削除して下記S3OriginConfigを追加


        "S3OriginConfig": {
            "OriginAccessIdentity": "origin-access-identity/cloudfront/BBBBBBBBBBBBBB"
        },

 

aws cloudfront get-distribution-config \
--id AAAAAAAAAAAAA | jq -r .ETag

aws cloudfront update-distribution \
--id AAAAAAAAAAAAA \
--if-match CCCCCCCCCCCCC \
--distribution-config file://distribution.json

 


-- 7. OAI に Amazon S3 バケット内のファイルの読み込みアクセス許可を付与する


vim b.json

{
    "Version": "2012-10-17",
    "Id": "PolicyForCloudFrontPrivateContent",
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": {
                "AWS": "arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity BBBBBBBBBBBBBB"
            },
            "Action": [
                "s3:GetObject",
                "s3:PutObject"
            ],
            "Resource": "arn:aws:s3:::bucket123/*"
        }
    ]
}


aws s3api put-bucket-policy \
--bucket bucket123 \
--policy file://b.json


aws s3api get-bucket-policy \
--bucket bucket123

 

 


-- 8. 動作確認

 

curl -v -X GET http://xxxxxxxxxxxxxx.cloudfront.net/index.html

 


-- 9. クリーンアップ

 

 

-- ディストリビューションの無効化

aws cloudfront get-distribution \
--id AAAAAAAAAAAAA

aws cloudfront get-distribution-config \
--id AAAAAAAAAAAAA


※ distribution.jsonはget-distribution-configコマンドのDistributionConfigから取得し、Enabledをfalseに変更する

aws cloudfront get-distribution-config \
--id AAAAAAAAAAAAA | jq -r .DistributionConfig > distribution.json

sed -i 's/"Enabled": true/"Enabled": false/' distribution.json

 

aws cloudfront get-distribution-config \
--id AAAAAAAAAAAAA | jq -r .ETag

aws cloudfront update-distribution \
--id AAAAAAAAAAAAA \
--if-match DDDDDDDDDDDDDD \
--distribution-config file://distribution.json


※ if-matchにはETagの値をセット

無効化されるまで待つ


-- ディストリビューションの削除

aws cloudfront get-distribution \
--id AAAAAAAAAAAAA

aws cloudfront get-distribution-config \
--id AAAAAAAAAAAAA

aws cloudfront get-distribution-config \
--id AAAAAAAAAAAAA | jq -r .ETag

aws cloudfront delete-distribution \
--id AAAAAAAAAAAAA \
--if-match EEEEEEEEEEEEEE

 

aws cloudfront list-distributions


-- OAIの削除

aws cloudfront list-cloud-front-origin-access-identities

aws cloudfront get-cloud-front-origin-access-identity \
--id BBBBBBBBBBBBBB

aws cloudfront delete-cloud-front-origin-access-identity \
--id BBBBBBBBBBBBBB \
--if-match FFFFFFFFFFFFFF


-- バケットの削除
aws s3 ls

aws s3 rb s3://bucket123 --force

 

{CloudFront}コンテンツの地理的ディストリビューションの制限

https://docs.aws.amazon.com/ja_jp/AmazonCloudFront/latest/DeveloperGuide/georestrictions.html

 

-- 1. コマンド等のインストール

-- 1.1 aws cli version 2 インストール

curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"
unzip awscliv2.zip
sudo ./aws/install
aws --version

 

-- 1.2 jqインストール
sudo yum -y install jq


-- 2. S3 バケットを作成する

aws s3 ls

aws s3 mb s3://bucket123

-- 3. 静的ウェブサイトホスティングの有効化

vim a.json

{
    "IndexDocument": {
        "Suffix": "index.html"
    },
    "ErrorDocument": {
        "Key": "index.html"
    }
}

aws s3api put-bucket-website \
--bucket bucket123 \
--website-configuration file://a.json

aws s3api get-bucket-website \
--bucket bucket123

 


-- 4. パブリックアクセスブロック設定の編集

-- 4.1 アカウントレベル
aws s3control put-public-access-block \
--account-id 999999999999 \
--public-access-block-configuration "BlockPublicAcls=false,IgnorePublicAcls=false,BlockPublicPolicy=false,RestrictPublicBuckets=false"

aws s3control get-public-access-block \
--account-id 999999999999

-- 4.2 バケットレベル
aws s3api put-public-access-block \
--bucket bucket123 \
--public-access-block-configuration "BlockPublicAcls=false,IgnorePublicAcls=false,BlockPublicPolicy=false,RestrictPublicBuckets=false"

aws s3api get-public-access-block \
--bucket bucket123


-- 5. バケットポリシーの設定

vim b.json

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "PublicReadGetObject",
            "Effect": "Allow",
            "Principal": "*",
            "Action": "s3:GetObject",
            "Resource": "arn:aws:s3:::bucket123/*",
            "Condition": {
                "IpAddress": {
                    "aws:SourceIp": "0.0.0.0/0"
                }
            }
        }
    ]
}

 

aws s3api put-bucket-policy \
--bucket bucket123 \
--policy file://b.json


aws s3api get-bucket-policy \
--bucket bucket123


-- 6. インデックスドキュメントの設定

vim index.html

<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    <title>My Website Home Page</title>
</head>
<body>
  <h1>Welcome to my website</h1>
  <p>Now hosted on Amazon S3!</p>
</body>
</html>

aws s3api put-object --bucket bucket123 --key index.html --body index.html --content-type text/html

 

 

-- 7. ディストリビューションの作成


aws cloudfront create-distribution \
--origin-domain-name bucket123.s3.ap-northeast-1.amazonaws.com \
--default-root-object index.html

 

aws cloudfront list-distributions

aws cloudfront get-distribution \
--id AAAAAAAAAAAAAA

aws cloudfront get-distribution-config \
--id AAAAAAAAAAAAAA


-- 8. 動作確認(地域制限追加前)

curl -v -X GET http://xxxxxxxxxxxxxx.cloudfront.net/index.html

-- 9. 地域制限追加


aws cloudfront get-distribution \
--id AAAAAAAAAAAAAA

aws cloudfront get-distribution-config \
--id AAAAAAAAAAAAAA


aws cloudfront get-distribution-config \
--id AAAAAAAAAAAAAA | jq -r .DistributionConfig > distribution.json

vim distribution.json

Restrictionsを下記のように修正

  "Restrictions": {
    "GeoRestriction": {
      "RestrictionType": "blacklist",
      "Quantity": 1,
      "Items": ["JP"]
    }
  },

 

aws cloudfront get-distribution-config \
--id AAAAAAAAAAAAAA | jq -r .ETag

aws cloudfront update-distribution \
--id AAAAAAAAAAAAAA \
--if-match BBBBBBBBBBBBB \
--distribution-config file://distribution.json

 

 

-- 10. 動作確認(地域制限追加後)


curl -v -X GET http://xxxxxxxxxxxxxx.cloudfront.net/index.html


→ The Amazon CloudFront distribution is configured to block access from your country.
We can't connect to the server for this app or website at this time. 
There might be too much traffic or a configuration error. 
Try again later, or contact the app or website owner.

 

-- 11. クリーンアップ

-- ディストリビューションの無効化

aws cloudfront get-distribution \
--id AAAAAAAAAAAAAA

aws cloudfront get-distribution-config \
--id AAAAAAAAAAAAAA


※ distribution.jsonはget-distribution-configコマンドのDistributionConfigから取得し、Enabledをfalseに変更する

aws cloudfront get-distribution-config \
--id AAAAAAAAAAAAAA | jq -r .DistributionConfig > distribution.json

sed -i 's/"Enabled": true/"Enabled": false/' distribution.json

 

aws cloudfront get-distribution-config \
--id AAAAAAAAAAAAAA | jq -r .ETag

aws cloudfront update-distribution \
--id AAAAAAAAAAAAAA \
--if-match CCCCCCCCCCCCCC \
--distribution-config file://distribution.json


※ if-matchにはETagの値をセット

無効化されるまで待つ


-- ディストリビューションの削除

aws cloudfront get-distribution \
--id AAAAAAAAAAAAAA

aws cloudfront get-distribution-config \
--id AAAAAAAAAAAAAA

aws cloudfront get-distribution-config \
--id AAAAAAAAAAAAAA | jq -r .ETag

aws cloudfront delete-distribution \
--id AAAAAAAAAAAAAA \
--if-match DDDDDDDDDDDDDD

 

aws cloudfront list-distributions

 


-- バケットの削除
aws s3 ls

aws s3 rb s3://bucket123 --force

-- アカウントレベルのパブリックアクセスブロックの有効化

aws s3control put-public-access-block \
--account-id 999999999999 \
--public-access-block-configuration "BlockPublicAcls=true,IgnorePublicAcls=true,BlockPublicPolicy=true,RestrictPublicBuckets=true"

aws s3control get-public-access-block \
--account-id 999999999999

 

 

 

{CloudFront}CloudFront ディストリビューションの価格クラスを選択する

https://docs.aws.amazon.com/ja_jp/AmazonCloudFront/latest/DeveloperGuide/PriceClass.html

 

 

-- 1. コマンド等のインストール

-- 1.1 aws cli version 2 インストール

curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"
unzip awscliv2.zip
sudo ./aws/install
aws --version

 

-- 1.2 jqインストール
sudo yum -y install jq


-- 2. S3 バケットを作成する

aws s3 ls

aws s3 mb s3://bucket123

-- 3. 静的ウェブサイトホスティングの有効化

vim a.json

{
    "IndexDocument": {
        "Suffix": "index.html"
    },
    "ErrorDocument": {
        "Key": "index.html"
    }
}

aws s3api put-bucket-website \
--bucket bucket123 \
--website-configuration file://a.json

aws s3api get-bucket-website \
--bucket bucket123

 


-- 4. パブリックアクセスブロック設定の編集

-- 4.1 アカウントレベル
aws s3control put-public-access-block \
--account-id 999999999999 \
--public-access-block-configuration "BlockPublicAcls=false,IgnorePublicAcls=false,BlockPublicPolicy=false,RestrictPublicBuckets=false"

aws s3control get-public-access-block \
--account-id 999999999999

-- 4.2 バケットレベル
aws s3api put-public-access-block \
--bucket bucket123 \
--public-access-block-configuration "BlockPublicAcls=false,IgnorePublicAcls=false,BlockPublicPolicy=false,RestrictPublicBuckets=false"

aws s3api get-public-access-block \
--bucket bucket123


-- 5. バケットポリシーの設定

vim b.json

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "PublicReadGetObject",
            "Effect": "Allow",
            "Principal": "*",
            "Action": "s3:GetObject",
            "Resource": "arn:aws:s3:::bucket123/*",
            "Condition": {
                "IpAddress": {
                    "aws:SourceIp": "0.0.0.0/0"
                }
            }
        }
    ]
}

 

aws s3api put-bucket-policy \
--bucket bucket123 \
--policy file://b.json


aws s3api get-bucket-policy \
--bucket bucket123


-- 6. インデックスドキュメントの設定

vim index.html

<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    <title>My Website Home Page</title>
</head>
<body>
  <h1>Welcome to my website</h1>
  <p>Now hosted on Amazon S3!</p>
</body>
</html>

aws s3api put-object --bucket bucket123 --key index.html --body index.html --content-type text/html

 

 

-- 7. ディストリビューションの作成


aws cloudfront create-distribution \
--origin-domain-name bucket123.s3.ap-northeast-1.amazonaws.com \
--default-root-object index.html

 

aws cloudfront list-distributions

aws cloudfront get-distribution \
--id AAAAAAAAAAAAA

aws cloudfront get-distribution-config \
--id AAAAAAAAAAAAA


-- 8. 動作確認(PriceClass_All)

 

time curl -v -X GET http://xxxxxxxxxxxxxx.cloudfront.net/index.html

real    0m0.018s


-- 9. Price Classの設定(PriceClass_All -> PriceClass_100)


aws cloudfront get-distribution \
--id AAAAAAAAAAAAA

aws cloudfront get-distribution-config \
--id AAAAAAAAAAAAA


aws cloudfront get-distribution-config \
--id AAAAAAAAAAAAA | jq -r .DistributionConfig > distribution.json

cat distribution.json
sed -i 's/"PriceClass": "PriceClass_All"/"PriceClass": "PriceClass_100"/' distribution.json
cat distribution.json

 

aws cloudfront get-distribution-config \
--id AAAAAAAAAAAAA | jq -r .ETag

aws cloudfront update-distribution \
--id AAAAAAAAAAAAA \
--if-match BBBBBBBBBBBBBB \
--distribution-config file://distribution.json

 

 

-- 10. 動作確認(PriceClass_100)

 

time curl -v -X GET http://xxxxxxxxxxxxxx.cloudfront.net/index.html

real    0m0.186s


-- 11. クリーンアップ

-- ディストリビューションの無効化

aws cloudfront get-distribution \
--id AAAAAAAAAAAAA

aws cloudfront get-distribution-config \
--id AAAAAAAAAAAAA


※ distribution.jsonはget-distribution-configコマンドのDistributionConfigから取得し、Enabledをfalseに変更する

aws cloudfront get-distribution-config \
--id AAAAAAAAAAAAA | jq -r .DistributionConfig > distribution.json

sed -i 's/"Enabled": true/"Enabled": false/' distribution.json

 

aws cloudfront get-distribution-config \
--id AAAAAAAAAAAAA | jq -r .ETag

aws cloudfront update-distribution \
--id AAAAAAAAAAAAA \
--if-match CCCCCCCCCCCCC \
--distribution-config file://distribution.json


※ if-matchにはETagの値をセット

無効化されるまで待つ


-- ディストリビューションの削除

aws cloudfront get-distribution \
--id AAAAAAAAAAAAA

aws cloudfront get-distribution-config \
--id AAAAAAAAAAAAA

aws cloudfront get-distribution-config \
--id AAAAAAAAAAAAA | jq -r .ETag

aws cloudfront delete-distribution \
--id AAAAAAAAAAAAA \
--if-match DDDDDDDDDDDDDD

 

aws cloudfront list-distributions

 


-- バケットの削除
aws s3 ls

aws s3 rb s3://bucket123 --force

-- アカウントレベルのパブリックアクセスブロックの有効化

aws s3control put-public-access-block \
--account-id 999999999999 \
--public-access-block-configuration "BlockPublicAcls=true,IgnorePublicAcls=true,BlockPublicPolicy=true,RestrictPublicBuckets=true"

aws s3control get-public-access-block \
--account-id 999999999999