id
stringlengths
8
78
source
stringclasses
743 values
chunk_id
int64
1
5.05k
text
stringlengths
593
49.7k
AmazonCloudFront_DevGuide-250
AmazonCloudFront_DevGuide.pdf
250
at rest and during transit (when reading or writing to the key value stores) when you call the CloudFront KeyValueStore API operations. • When the function is run, CloudFront decrypts each key-value pair in memory at the CloudFront edge locations. To get started with CloudFront KeyValueStore, see the following topics. CloudFront KeyValueStore 694 Amazon CloudFront Topics • Work with key value store • Work with key value data Developer Guide • For more information about getting started with CloudFront KeyValueStore, see the Introducing Amazon CloudFront KeyValueStore AWS blog post. Work with key value store You must create a key value store to hold the key-value pairs that you want to use in CloudFront Functions. After you create the key value stores and added key-value pairs, you can use the key values in your CloudFront function code. To get started, see the following topics: Topics • Create a key value store • Associate a key value store with a function • Update a key value store • Get a reference to a key value store • Delete a key value store • File format for key-value pairs Note The JavaScript runtime 2.0 includes some helper methods for working with key values in the function code. For more information, see the section called “Helper methods for key value stores”. Create a key value store You can create a key value store and its key-value pairs at the same time. You can also create an empty key value store now and then add the key-value pairs later. CloudFront KeyValueStore 695 Amazon CloudFront Note Developer Guide If you specify your data source from an Amazon S3 bucket, you must have the s3:GetObject and s3:GetBucketLocation permissions to that bucket. If you don't have these permissions, CloudFront can't successfully create your key value store. Decide if you want to add key-value pairs at the same time when you create the key value store. You can import your key-value pairs by using the CloudFront console, CloudFront API, or AWS SDKs. However, you can only import your file of key-value pairs when you initially create the key value store. To create a file of key-value pairs, see File format for key-value pairs. Console To create a key value store 1. Sign in to the AWS Management Console and open the Functions page in the CloudFront console at https://console.aws.amazon.com/cloudfront/v4/home#/functions. 2. Choose the KeyValueStores tab, and then choose Create KeyValueStore. 3. Enter a name and optional description for the key value store. 4. Complete S3 URI: • If you have a file of key-value pairs, enter the path to the Amazon S3 bucket where you stored the file. • Leave this field blank if you plan to enter the key-value pairs manually. 5. Choose Create. The key value store now exists. The details page for the new key value store appears. The information on the page includes the ID and the ARN of the key value store. • The ID is a random string of characters that is unique in your AWS account. • The ARN has this syntax: AWS account:key-value-store/the key value stores ID 6. Look at the Key value pairs section. If you imported a file, this section shows some key- value pairs. You can do the following: CloudFront KeyValueStore 696 Amazon CloudFront Developer Guide • If you imported a file, you can also add more values manually. • If you didn't import a file from an Amazon S3 bucket, and if you want to add key-value pairs now, you can complete the next step. • You can skip this step and add the key-value pairs later. 7. To add the pairs now: a. Choose Add key-value pairs. b. Choose Add pair and enter a name and value. Repeat this step to add more pairs. c. When you're finished, choose Save changes to save all the key-value pairs in the key value store. On the dialog box that appears, choose Done. 8. To associate the key value store with a function now, complete the Associated functions section. For more information, see ??? or ???. You can also associate the function later, either from this key value store details page, or from the function's details page. AWS CLI To create a key value store • Run the following command to create a key value store and import the key-value pairs from an Amazon S3 bucket. aws cloudfront create-key-value-store \ --name=keyvaluestore1 \ --comment="This is my key value store file" \ --import-source=SourceType=S3,SourceARN=arn:aws:s3:::amzn-s3-demo- bucket1/kvs-input.json Response { "ETag": "ETVABCEXAMPLE", "Location": "https://cloudfront.amazonaws.com/2020-05-31/key-value-store/ arn:aws:cloudfront::123456789012:key-value-store/8aa76c93-3198-462c-aaf6- example", "KeyValueStore": { CloudFront KeyValueStore 697 Amazon CloudFront Developer Guide "Name": "keyvaluestore1", "Id": "8aa76c93-3198-462c-aaf6-example", "Comment": "This is my key value store file", "ARN": "arn:aws:cloudfront::123456789012:key-value- store/8aa76c93-3198-462c-aaf6-example", "Status": "PROVISIONING", "LastModifiedTime": "2024-08-06T22:19:10.813000+00:00" } } API To create a key value store 1. Use the CloudFront CreateKeyValueStore operation. The operation takes several parameters: • A
AmazonCloudFront_DevGuide-251
AmazonCloudFront_DevGuide.pdf
251
create a key value store • Run the following command to create a key value store and import the key-value pairs from an Amazon S3 bucket. aws cloudfront create-key-value-store \ --name=keyvaluestore1 \ --comment="This is my key value store file" \ --import-source=SourceType=S3,SourceARN=arn:aws:s3:::amzn-s3-demo- bucket1/kvs-input.json Response { "ETag": "ETVABCEXAMPLE", "Location": "https://cloudfront.amazonaws.com/2020-05-31/key-value-store/ arn:aws:cloudfront::123456789012:key-value-store/8aa76c93-3198-462c-aaf6- example", "KeyValueStore": { CloudFront KeyValueStore 697 Amazon CloudFront Developer Guide "Name": "keyvaluestore1", "Id": "8aa76c93-3198-462c-aaf6-example", "Comment": "This is my key value store file", "ARN": "arn:aws:cloudfront::123456789012:key-value- store/8aa76c93-3198-462c-aaf6-example", "Status": "PROVISIONING", "LastModifiedTime": "2024-08-06T22:19:10.813000+00:00" } } API To create a key value store 1. Use the CloudFront CreateKeyValueStore operation. The operation takes several parameters: • A name of the key value store. • A comment parameter that includes a comment. • An import-source parameter that lets you import key-value pairs from a file that is stored in an Amazon S3 bucket. You can import from a file only when you first create the key value store. For information about the file structure, see the section called “File format for key-value pairs”. The operation response includes the following information: • The values passed in the request, including the name that you assigned. • Data such as the creation time. • An ETag (for example, ETVABCEXAMPLE), the ARN that includes the name of the key value store (for example, arn:aws:cloudfront::123456789012:key-value-store/ keyvaluestore1). You will use some combination of the ETag, the ARN, and the name to work with the key value store programmatically. Key value store statuses When you create a key value store, the data store can have the following status values. CloudFront KeyValueStore 698 Amazon CloudFront Developer Guide Value Description Provisioning The key value store was created and CloudFront is processing the data source that you specified. Ready The key value store was created and CloudFront successfully processed the data source that you specified. Import failed CloudFront wasn't able to process the data source that you specified. This status can appear if your file format isn't valid or that it exceeds the size limit. For more information, see File format for key-value pairs. Associate a key value store with a function After you create your key value store, you can update your function to associate it with your key value store. You must make this association to use the key-value pairs from that store in that function. The following rules apply: • A function can have only one key value store • You can associate the same key value store with multiple functions Console To associate a key value store with a function 1. Sign in to the CloudFront console at https://console.aws.amazon.com/cloudfront/v4/ home#/functions and choose the Functions page. 2. Choose the function name. 3. Go to the Associate KeyValueStore section and choose Associate existing KeyValueStore. 4. Select the key value store that contains the key-value pairs in the function, and then choose Associate KeyValueStore. CloudFront immediately associates the store with the function. You don't need to save the function. 5. To specify a different key value store, choose Update associated KeyValueStore, select another key value store name, and then choose Associate KeyValueStore. CloudFront KeyValueStore 699 Amazon CloudFront Developer Guide For more information, see the section called “Update functions”. AWS CLI To associate a key value store with a function • Run the following command to update the MaxAge function and associate a key value store resource. aws cloudfront update-function \ --name MaxAge \ --function-config '{"Comment":"Max Age 2 years","Runtime":"cloudfront- js-2.0","KeyValueStoreAssociations":{"Quantity":1,"Items": [{"KeyValueStoreARN":"arn:aws:cloudfront::123456789012:key-value- store/8aa76c93-3198-462c-aaf6-example"}]}}' \ --function-code fileb://function-max-age-v1.js \ --if-match ETVABCEXAMPLE • To associate a key value store with a function, specify the KeyValueStoreAssociations parameter and the key value store ARN. • To change the association, specify another key value store ARN. • To remove the association, remove the KeyValueStoreAssociations parameter. For more information, see the section called “Update functions”. API To associate a key value store with a function • Use the UpdateFunction API operation. For more information, see the section called “Update functions”. Notes • If you modify a key value store without changing the key-value pairs, or if you only modify the key-value pairs in the key value store, you don't need to associate the key value store again. You also don't need to republish the function. CloudFront KeyValueStore 700 Amazon CloudFront Developer Guide However, we recommend that you test the function to verify that it works as expected. For more information, see Test functions. • You can view all the functions that use specific key value stores. On the CloudFront console, choose the key value store details page. Update a key value store When you update a key value store, you can change the key-value pairs, or change the association between the key value store and the function. Console To update a key value store 1. Sign in to the AWS Management Console and open the Functions page in the CloudFront console at https://console.aws.amazon.com/cloudfront/v4/home#/functions. 2. Choose the
AmazonCloudFront_DevGuide-252
AmazonCloudFront_DevGuide.pdf
252
you test the function to verify that it works as expected. For more information, see Test functions. • You can view all the functions that use specific key value stores. On the CloudFront console, choose the key value store details page. Update a key value store When you update a key value store, you can change the key-value pairs, or change the association between the key value store and the function. Console To update a key value store 1. Sign in to the AWS Management Console and open the Functions page in the CloudFront console at https://console.aws.amazon.com/cloudfront/v4/home#/functions. 2. Choose the KeyValueStores tab. 3. Select the key value store that you want to update. • • To update the key-value pairs, choose Edit in the Key value pairs section. You can add or delete any key-value pairs. You can also change the value for an existing key-value pair. When you're finished, choose Save changes. To update the association for this key value store, choose Go to functions. For more information, see the section called “Associate a key value store with a function”. AWS CLI To update a key value store 1. Change the key-value pairs – You can add more key-value pairs, delete one or more key- value pairs, and change the value of an existing key-value pair. For more information, see Work with key value data. 2. Change the function association for the key value store – To update the function the association for the key value store, see Associate a key value store with a function. CloudFront KeyValueStore 701 Amazon CloudFront Developer Guide Tip You will need the ARN of the key value store. For more information, see the section called “Get a reference to a key value store”. API To update a key value store 1. Change the key-value pairs – You can add more key-value pairs, delete one or more key- value pairs, and change the value of an existing key-value pair. For more information, see Work with key value data. 2. Change the function association for the key value store – To update the function association for the key value store, use the UpdateFunction API operation. For more information, see the section called “Update functions”. Tip You will need the ARN of the key value store. For more information, see the section called “Get a reference to a key value store”. Get a reference to a key value store To work with the key value stores programmatically, you need the ETag and the name of the key value store. To get both values, you can use the AWS Command Line Interface (AWS CLI) or the CloudFront API. AWS CLI To get the key value store reference 1. To return a list of key value stores, run the following command Find the name of the key value store that you want to change. aws cloudfront list-key-value-stores CloudFront KeyValueStore 702 Amazon CloudFront Developer Guide 2. From the response, find the name of the key value store that you want. Response { "KeyValueStoreList": { "Items": [ { "Name": "keyvaluestore3", "Id": "37435e19-c205-4271-9e5c-example3", "ARN": "arn:aws:cloudfront::123456789012:key-value- store/37435e19-c205-4271-9e5c-example3", "Status": "READY", "LastModifiedTime": "2024-05-08T14:50:18.876000+00:00" }, { "Name": "keyvaluestore2", "Id": "47970d59-6408-474d-b850-example2", "ARN": "arn:aws:cloudfront::123456789012:key-value- store/47970d59-6408-474d-b850-example2", "Status": "READY", "LastModifiedTime": "2024-05-30T21:06:22.113000+00:00" }, { "Name": "keyvaluestore1", "Id": "8aa76c93-3198-462c-aaf6-example", "ARN": "arn:aws:cloudfront::123456789012:key-value- store/8aa76c93-3198-462c-aaf6-example", "Status": "READY", "LastModifiedTime": "2024-08-06T22:19:30.510000+00:00" } ] } } 3. Run the following command to return the ETag for the specified key value store. aws cloudfront describe-key-value-store \ --name=keyvaluestore1 Response CloudFront KeyValueStore 703 Amazon CloudFront Developer Guide { "ETag": "E3UN6WX5RRO2AG", "KeyValueStore": { "Name": "keyvaluestore1", "Id": "8aa76c93-3198-462c-aaf6-example", "Comment": "This is an example KVS", "ARN": "arn:aws:cloudfront::123456789012:key-value- store/8aa76c93-3198-462c-aaf6-example", "Status": "READY", "LastModifiedTime": "2024-08-06T22:19:30.510000+00:00" } } API To get the key value store reference 1. Use the CloudFront ListKeyValueStores API operation to return a list of key value stores. Find the name of the key value store that you want to change. 2. Use the CloudFront DescribeKeyValueStore API operation and specify the name of the key value store that you returned from the previous step. The response includes a UUID, the ARN of the key value store, and the ETag of the key value store. • An ETag, such as E3UN6WX5RRO2AG • The UUID is 128 bits, such as 8aa76c93-3198-462c-aaf6-example • The ARN includes the AWS account number, the constant key-value-store, and the UUID, like the following example: arn:aws:cloudfront::123456789012:key-value-store/8aa76c93-3198-462c-aaf6- example For more information about the DescribeKeyValueStore operation, see the section called “About the CloudFront KeyValueStore”. Delete a key value store You can delete your key value store by using the Amazon CloudFront console or API. CloudFront KeyValueStore 704 Amazon CloudFront Console To delete a key value store Developer Guide 1. Sign in to the AWS Management Console and open the Functions page in the CloudFront console at https://console.aws.amazon.com/cloudfront/v4/home#/functions. 2. Choose the function name. 3. Under the Associated KeyValueStore section, verify if a key value store
AmazonCloudFront_DevGuide-253
AmazonCloudFront_DevGuide.pdf
253
AWS account number, the constant key-value-store, and the UUID, like the following example: arn:aws:cloudfront::123456789012:key-value-store/8aa76c93-3198-462c-aaf6- example For more information about the DescribeKeyValueStore operation, see the section called “About the CloudFront KeyValueStore”. Delete a key value store You can delete your key value store by using the Amazon CloudFront console or API. CloudFront KeyValueStore 704 Amazon CloudFront Console To delete a key value store Developer Guide 1. Sign in to the AWS Management Console and open the Functions page in the CloudFront console at https://console.aws.amazon.com/cloudfront/v4/home#/functions. 2. Choose the function name. 3. Under the Associated KeyValueStore section, verify if a key value store is associated with the function. If it is, remove the association by choosing Disassociate KeyValueStore and then choose Remove association. 4. In the navigation pane, choose the Functions page and then choose the KeyValueStores tab. 5. Select the key value store that you want to delete and then choose Delete. AWS CLI To delete a key value store 1. Get the ETag and the name of the key value stores. For more information, see the section called “Get a reference to a key value store”. 2. Verify if the key value stores is associated with a function. If it is, remove the association. For more information on both these steps, see ???. 3. After you have the name and ETag of the key value store and it's no longer associated with a function, you can delete it. Run the following command to delete the specified key value store. aws cloudfront delete-key-value-store \ --name=keyvaluestore1 \ --if-match=E3UN6WX5RRO2AG API To delete a key value store 1. Get the ETag and the name of the key value stores. For more information, see the section called “Get a reference to a key value store”. CloudFront KeyValueStore 705 Amazon CloudFront Developer Guide 2. Verify if the key value stores is associated with a function. If it is, remove the association. For more information on both these steps, see ???. 3. To delete the key value store, use the CloudFront DeleteKeyValueStore API operation. File format for key-value pairs When you create a UTF-8 encoded file, use the following JSON format: { "data":[ { "key":"key1", "value":"value" }, { "key":"key2", "value":"value" } ] } Your file can't include duplicate keys. If you specified an invalid file in your Amazon S3 bucket, you can update the file to remove any duplicates and then try creating your key value store again. For more information, see Create a key value store. Note The file for your data source and its key-value pairs have the following limits: • File size – 5 MB • Key size – 512 characters • Value size – 1024 characters Work with key value data This topic describes how to add key-value pairs to an existing key value store. To include key- value pairs when you initially create the key value stores, see the section called “Create a key value store”. CloudFront KeyValueStore 706 Amazon CloudFront Topics • Work with key-value pairs (console) • About the CloudFront KeyValueStore • Work with key-value pairs (AWS CLI) • Work with key-value pairs (API) Work with key-value pairs (console) Developer Guide You can use the CloudFront console to work with your key-value pairs. To work with key-value pairs 1. Sign in to the AWS Management Console and open the Functions page in the CloudFront console at https://console.aws.amazon.com/cloudfront/v4/home#/functions. 2. Choose the KeyValueStores tab. 3. 4. Select the key value store that you want to change. In the Key value pairs section, choose Edit. 5. You can add a key-value pair, delete a key-value pair, or change the value for an existing key- value pair. 6. When you're finished, choose Save changes. About the CloudFront KeyValueStore Tip The CloudFront KeyValueStore API is a global service that uses Signature Version 4A (SigV4A) for authentication. Using temporary credentials with SigV4A requires version 2 session tokens. For more information, see Using temporary credentials with the CloudFront KeyValueStore API. If you're using the AWS Command Line Interface (AWS CLI) or your own code to call the CloudFront KeyValueStore API, see the following sections. When you work with a key value store and its key-value pairs, the service that you call depends on your use case: CloudFront KeyValueStore 707 Amazon CloudFront Developer Guide • To work with key-value pairs in an existing key value store, use the CloudFront KeyValueStore service. • To include key-value pairs in the key value store when you initially create the key value store, use the CloudFront service. Both the CloudFront API and the CloudFront KeyValueStore API have a DescribeKeyValueStore operation. You call them for different reasons. To understand the differences, see the following table. Data about the key value store Data that identifies the key value store CloudFront DescribeK eyValueStore API CloudFront KeyValueS tore DescribeK eyValueStore API Returns data, such as the status
AmazonCloudFront_DevGuide-254
AmazonCloudFront_DevGuide.pdf
254
707 Amazon CloudFront Developer Guide • To work with key-value pairs in an existing key value store, use the CloudFront KeyValueStore service. • To include key-value pairs in the key value store when you initially create the key value store, use the CloudFront service. Both the CloudFront API and the CloudFront KeyValueStore API have a DescribeKeyValueStore operation. You call them for different reasons. To understand the differences, see the following table. Data about the key value store Data that identifies the key value store CloudFront DescribeK eyValueStore API CloudFront KeyValueS tore DescribeK eyValueStore API Returns data, such as the status and the date that Returns data about the contents of the storage the key value store itself resource – the key-value was last modified. pairs in the store, and the size of the contents. Returns an ETag, the UUID, and the ARN of the Returns an ETag and the ARN of the key value key value store. store. Notes • Each DescribeKeyValueStore operation returns a different ETag. The ETags aren't interchangeable. • When you call an API operation to complete an action, you must specify the ETag from the appropriate API. For example, in the CloudFront KeyValueStore DeleteKey operation, you specify the ETag that you returned from the CloudFront KeyValueStore DescribeKeyValueStore operation. • When you invoke your CloudFront Functions by using CloudFront KeyValueStore, the values in the key value store aren't updated or changed during the invocation of the function. Updates are processed in between invocations of a function. CloudFront KeyValueStore 708 Amazon CloudFront Developer Guide Work with key-value pairs (AWS CLI) You can run the following AWS Command Line Interface commands for CloudFront KeyValueStore. Contents • List key-value pairs • Get key-value pairs • Describe a key value store • Create a key-value pair • Delete a key-value pair • Update key-value pairs List key-value pairs To list key-value pairs in your key value store, run the following command. aws cloudfront-keyvaluestore list-keys \ --kvs-arn=arn:aws:cloudfront::123456789012:key-value-store/37435e19-c205-4271-9e5c- example Response { "Items": [ { "Key": "key1", "Value": "value1" } ] } Get key-value pairs To get a key-value pair in your key value store, run the following command. aws cloudfront-keyvaluestore get-key \ --key=key1 \ CloudFront KeyValueStore 709 Amazon CloudFront Developer Guide --kvs-arn=arn:aws:cloudfront::123456789012:key-value-store/37435e19-c205-4271-9e5c- example Response { "Key": "key1", "Value": "value1", "ItemCount": 1, "TotalSizeInBytes": 11 } Describe a key value store To describe a key value store, run the following command. aws cloudfront-keyvaluestore describe-key-value-store \ --kvs-arn=arn:aws:cloudfront::123456789012:key-value-store/37435e19-c205-4271-9e5c- example Response { "ETag": "KV1F83G8C2ARO7P", "ItemCount": 1, "TotalSizeInBytes": 11, "KvsARN": "arn:aws:cloudfront::123456789012:key-value-store/37435e19- c205-4271-9e5c-example", "Created": "2024-05-08T07:48:45.381000-07:00", "LastModified": "2024-08-05T13:50:58.843000-07:00", "Status": "READY" } Create a key-value pair To create a key-value pair in your key value store, run the following command. aws cloudfront-keyvaluestore put-key \ --if-match=KV1PA6795UKMFR9 \ --key=key2 \ CloudFront KeyValueStore 710 Amazon CloudFront --value=value2 \ Developer Guide --kvs-arn=arn:aws:cloudfront::123456789012:key-value-store/37435e19-c205-4271-9e5c- example Response { "ETag": "KV13V1IB3VIYZZH", "ItemCount": 3, "TotalSizeInBytes": 31 } Delete a key-value pair To delete a key-value pair, run the following command. aws cloudfront-keyvaluestore delete-key \ --if-match=KV13V1IB3VIYZZH \ --key=key1 \ --kvs-arn=arn:aws:cloudfront::123456789012:key-value-store/37435e19-c205-4271-9e5c- example Output { "ETag": "KV1VC38T7YXB528", "ItemCount": 2, "TotalSizeInBytes": 22 } Update key-value pairs You can use the update-keys command to update more than one key-value pair. For example, to delete an existing key-value pair and create another one, run the following command. aws cloudfront-keyvaluestore update-keys \ --if-match=KV2EUQ1WTGCTBG2 \ --kvs-arn=arn:aws:cloudfront::123456789012:key-value-store/37435e19-c205-4271-9e5c- example \ --deletes '[{"Key":"key2"}]' \ CloudFront KeyValueStore 711 Amazon CloudFront Developer Guide --puts '[{"Key":"key3","Value":"value3"}]' Response { "ETag": "KV3AEGXETSR30VB", "ItemCount": 3, "TotalSizeInBytes": 28 } Work with key-value pairs (API) Follow this section to work with your key-value pairs programatically. Contents • Get a reference to a key value store • Change key-value pairs in a key value store • Example code for CloudFront KeyValueStore Get a reference to a key value store When you use the CloudFront KeyValueStore API to call a write operation, you need to specify the ARN and the ETag of the key value store. To get this data, do the following: To get a reference to a key value store 1. Use the CloudFront ListKeyValueStores API operation to get a list of key value stores. Find the key value store that you want to change. 2. Use the CloudFrontKeyValueStore DescribeKeyValueStore API operation and specify the key value store from the previous step. The response includes the ARN and the ETag of the key value store. • The ARN includes the AWS account number, the constant key-value-store, and the UUID, such as the following example: arn:aws:cloudfront::123456789012:key-value-store/a1b2c3d4-5678-90ab- cdef-EXAMPLE11111 • An ETag that looks like the following example: CloudFront KeyValueStore 712 Amazon CloudFront ETVABCEXAMPLE2 Change key-value pairs in a key value store Developer Guide You can specify the key value store that contains the key-value pair that you want to update. See the following CloudFront KeyValueStore API operations: • CloudFrontKeyValueStore DeleteKey – Deletes a key-value pair • CloudFrontKeyValueStore GetKey – Returns a key-value pair • CloudFrontKeyValueStore ListKeys – Returns a list of key-value
AmazonCloudFront_DevGuide-255
AmazonCloudFront_DevGuide.pdf
255
of the key value store. • The ARN includes the AWS account number, the constant key-value-store, and the UUID, such as the following example: arn:aws:cloudfront::123456789012:key-value-store/a1b2c3d4-5678-90ab- cdef-EXAMPLE11111 • An ETag that looks like the following example: CloudFront KeyValueStore 712 Amazon CloudFront ETVABCEXAMPLE2 Change key-value pairs in a key value store Developer Guide You can specify the key value store that contains the key-value pair that you want to update. See the following CloudFront KeyValueStore API operations: • CloudFrontKeyValueStore DeleteKey – Deletes a key-value pair • CloudFrontKeyValueStore GetKey – Returns a key-value pair • CloudFrontKeyValueStore ListKeys – Returns a list of key-value pairs • CloudFrontKeyValueStore PutKey – You can perform the following tasks: • Create a key-value pair in one key value store by specifying a new key name and value. • Set a different value in an existing key-value pair by specifying an existing key name, and a new key value. • CloudFrontKeyValueStore UpdateKeys – You can perform one or more of the following actions in one all-or-nothing operation: • Delete one or more key-value pairs • Create one or more new key-value pairs • Set a different value in one or more existing key-value pairs Example code for CloudFront KeyValueStore Example The following code shows you how to call the DescribeKeyValueStore API operation for a key value store. const { CloudFrontKeyValueStoreClient, DescribeKeyValueStoreCommand, } = require("@aws-sdk/client-cloudfront-keyvaluestore"); require("@aws-sdk/signature-v4-crt"); (async () => { CloudFront KeyValueStore 713 Amazon CloudFront try { const client = new CloudFrontKeyValueStoreClient({ region: "us-east-1" }); const input = { Developer Guide KvsARN: "arn:aws:cloudfront::123456789012:key-value-store/a1b2c3d4-5678-90ab- cdef-EXAMPLE11111", }; const command = new DescribeKeyValueStoreCommand(input); const response = await client.send(command); } catch (e) { console.log(e); } })(); Customize at the edge with Lambda@Edge Lambda@Edge is an extension of AWS Lambda. Lambda@Edge is a compute service that lets you execute functions that customize the content that Amazon CloudFront delivers. You can author Node.js or Python functions in the Lambda console in one AWS Region, US East (N. Virginia). After you create the function, you can add triggers using the Lambda console or CloudFront console so that the functions run in AWS locations that are closer to the viewer, without provisioning or managing servers. Optionally, you can use Lambda and CloudFront API operations to set up your functions and triggers programmatically. Lambda@Edge scales automatically, from a few requests per day to thousands per second. Processing requests at AWS locations closer to the viewer instead of on origin servers significantly reduces latency and improves the user experience. Note Lambda@Edge isn't supported with gRPC requests. For more information. see Using gRPC with CloudFront distributions. Topics • How Lambda@Edge works with requests and responses Customize with Lambda@Edge 714 Developer Guide Amazon CloudFront • Ways to use Lambda@Edge • Get started with Lambda@Edge functions (console) • Set up IAM permissions and roles for Lambda@Edge • Write and create a Lambda@Edge function • Add triggers for a Lambda@Edge function • Test and debug Lambda@Edge functions • Delete Lambda@Edge functions and replicas • Lambda@Edge event structure • Work with requests and responses • Lambda@Edge example functions How Lambda@Edge works with requests and responses When you associate a CloudFront distribution with a Lambda@Edge function, CloudFront intercepts requests and responses at CloudFront edge locations. You can execute Lambda functions when the following CloudFront events occur: • When CloudFront receives a request from a viewer (viewer request) • Before CloudFront forwards a request to the origin (origin request) • When CloudFront receives a response from the origin (origin response) • Before CloudFront returns the response to the viewer (viewer response) If you're using AWS WAF, the Lambda@Edge viewer request is executed after any AWS WAF rules are applied. For more information, see Work with requests and responses and Lambda@Edge event structure. Ways to use Lambda@Edge There are many uses for Lambda@Edge processing with your Amazon CloudFront distribution, such as the following examples: • A Lambda function can inspect cookies and rewrite URLs so that users see different versions of a site for A/B testing. How Lambda@Edge works with requests and responses 715 Amazon CloudFront Developer Guide • CloudFront can return different objects to viewers based on the device they're using by checking the User-Agent header, which includes information about the devices. For example, CloudFront can return different images based on the screen size of their device. Similarly, the function could consider the value of the Referer header and cause CloudFront to return the images to bots that have the lowest available resolution. • Or you could check cookies for other criteria. For example, on a retail website that sells clothing, if you use cookies to indicate which color a user chose for a jacket, a Lambda function can change the request so that CloudFront returns the image of a jacket in the selected color. • A Lambda function can generate HTTP responses when CloudFront viewer request
AmazonCloudFront_DevGuide-256
AmazonCloudFront_DevGuide.pdf
256
different images based on the screen size of their device. Similarly, the function could consider the value of the Referer header and cause CloudFront to return the images to bots that have the lowest available resolution. • Or you could check cookies for other criteria. For example, on a retail website that sells clothing, if you use cookies to indicate which color a user chose for a jacket, a Lambda function can change the request so that CloudFront returns the image of a jacket in the selected color. • A Lambda function can generate HTTP responses when CloudFront viewer request or origin request events occur. • A function can inspect headers or authorization tokens, and insert a header to control access to your content before CloudFront forwards the request to your origin. • A Lambda function can also make network calls to external resources to confirm user credentials, or fetch additional content to customize a response. For more information, including example code, see Lambda@Edge example functions. For more information about setting up Lambda@Edge in the console, see Tutorial: Create a basic Lambda@Edge function (console). Get started with Lambda@Edge functions (console) With Lambda@Edge, you can use CloudFront triggers to invoke a Lambda function. When you associate a CloudFront distribution with a Lambda function, CloudFront intercepts requests and responses at CloudFront edge locations and runs the function. Lambda functions can improve security or customize information close to your viewers to improve performance. The following list provides a basic overview of how to create and use Lambda functions with CloudFront. Overview: Creating and using Lambda functions with CloudFront 1. Create a Lambda function in the US East (N. Virginia) Region. 2. Save and publish a numbered version of the function. If you want to change the function, you must edit the $LATEST version of the function in the US East (N. Virginia) Region. Then, before you set it up to work with CloudFront, you publish a new numbered version. Get started with Lambda@Edge 716 Amazon CloudFront Developer Guide 3. Associate the function with a CloudFront distribution and cache behavior. Then specify one or more CloudFront events (triggers) that cause the function to execute. For example, you can create a trigger for the function to execute when CloudFront receives a request from a viewer. 4. When you create a trigger, Lambda creates replicas of the function at AWS locations around the world. Tip For more information, see creating and updating functions, the event structure, and adding CloudFront triggers. You can also find more ideas and get code samples in Lambda@Edge example functions. For a step-by-step tutorial, see the following topic: Topics • Tutorial: Create a basic Lambda@Edge function (console) Tutorial: Create a basic Lambda@Edge function (console) This tutorial shows you how to get started with Lambda@Edge by creating and configuring an example Node.js function that runs in CloudFront. This example adds HTTP security headers to a response when CloudFront retrieves a file. (This can improve security and privacy for a website.) You don't need your own website for this tutorial. However, when you choose to create your own Lambda@Edge solution, you follow similar steps and select from the same options. Topics • Step 1: Sign up for an AWS account • Step 2: Create a CloudFront distribution • Step 3: Create your function • Step 4: Add a CloudFront trigger to run the function • Step 5: Verify that the function runs • Step 6: Troubleshoot issues • Step 7: Clean up your example resources Get started with Lambda@Edge 717 Amazon CloudFront • Related information Step 1: Sign up for an AWS account Developer Guide If you haven't already done so, sign up for an AWS account. For more information, see Sign up for an AWS account. Step 2: Create a CloudFront distribution Before you create the example Lambda@Edge function, you must have a CloudFront environment to work with that includes an origin to serve content from. For this example, you create a CloudFront distribution that uses an Amazon S3 bucket as the origin for the distribution. If you already have an environment to use, you can skip this step. To create a CloudFront distribution with an Amazon S3 origin 1. Create an Amazon S3 bucket with a file or two, such as image files, for sample content. For help, follow the steps in Upload your content to Amazon S3. Make sure that you set permissions to grant public read access to the objects in your bucket. 2. Create a CloudFront distribution and add your S3 bucket as an origin, by following the steps in Create a CloudFront web distribution. If you already have a distribution, you can add the bucket as an origin for that distribution instead. Tip Make a note of your distribution ID. Later in this tutorial when you add a
AmazonCloudFront_DevGuide-257
AmazonCloudFront_DevGuide.pdf
257
S3 bucket with a file or two, such as image files, for sample content. For help, follow the steps in Upload your content to Amazon S3. Make sure that you set permissions to grant public read access to the objects in your bucket. 2. Create a CloudFront distribution and add your S3 bucket as an origin, by following the steps in Create a CloudFront web distribution. If you already have a distribution, you can add the bucket as an origin for that distribution instead. Tip Make a note of your distribution ID. Later in this tutorial when you add a CloudFront trigger for your function, you must choose the ID for your distribution in a dropdown list—for example, E653W22221KDDL. Step 3: Create your function In this step, you create a Lambda function from a blueprint template in the Lambda console. The function adds code to update security headers in your CloudFront distribution. To create a Lambda function 1. Sign in to the AWS Management Console and open the AWS Lambda console at https:// console.aws.amazon.com/lambda/. Get started with Lambda@Edge 718 Amazon CloudFront Developer Guide Important Make sure that you're in the US-East-1 (N. Virginia) AWS Region (us-east-1). You must be in this Region to create Lambda@Edge functions. 2. Choose Create function. 3. On the Create function page, choose Use a blueprint, and then filter for the CloudFront blueprints by entering cloudfront in the search field. Note CloudFront blueprints are available only in the US-East-1 (N. Virginia) Region (us- east-1). 4. Choose the Modify HTTP response header blueprint as the template for your function. 5. Enter the following information about your function: • Function name – Enter a name for your function. • Execution role – Choose how to set the permissions for your function. To use the recommended basic Lambda@Edge permissions policy template, choose Create a new role from AWS policy templates. • Role name – Enter a name for the role that the policy template creates. • Policy templates – Lambda automatically adds the policy template Basic Lambda@Edge permissions because you chose a CloudFront blueprint as the basis for your function. This policy template adds execution role permissions that allow CloudFront to run your Lambda function for you in CloudFront locations around the world. For more information, see Set up IAM permissions and roles for Lambda@Edge. 6. Choose Create function at the bottom of the page. 7. In the Deploy to Lambda@Edge pane that appears, choose Cancel. (For this tutorial, you must modify the function code before deploying the function to Lambda@Edge.) 8. Scroll down to the Code source section of the page. 9. Replace the template code with a function that modifies the security headers that your origin returns. For example, you could use code similar to the following: 'use strict'; Get started with Lambda@Edge 719 Amazon CloudFront Developer Guide export const handler = (event, context, callback) => { //Get contents of response const response = event.Records[0].cf.response; const headers = response.headers; //Set new headers headers['strict-transport-security'] = [{key: 'Strict-Transport-Security', value: 'max-age= 63072000; includeSubdomains; preload'}]; headers['content-security-policy'] = [{key: 'Content-Security-Policy', value: "default-src 'none'; img-src 'self'; script-src 'self'; style-src 'self'; object- src 'none'"}]; headers['x-content-type-options'] = [{key: 'X-Content-Type-Options', value: 'nosniff'}]; headers['x-frame-options'] = [{key: 'X-Frame-Options', value: 'DENY'}]; headers['x-xss-protection'] = [{key: 'X-XSS-Protection', value: '1; mode=block'}]; headers['referrer-policy'] = [{key: 'Referrer-Policy', value: 'same-origin'}]; //Return modified response callback(null, response); }; 10. Choose File, Save to save your updated code. 11. Choose Deploy. Proceed to the next section to add a CloudFront trigger to run the function. Step 4: Add a CloudFront trigger to run the function Now that you have a Lambda function to update security headers, configure the CloudFront trigger to run your function to add the headers in any response that CloudFront receives from the origin for your distribution. To configure the CloudFront trigger for your function 1. 2. In the Lambda console, on the Function overview page for your function, choose Add trigger. For Trigger configuration, choose CloudFront. 3. Choose Deploy to Lambda@Edge. 4. In the Deploy to Lambda@Edge pane, under Configure CloudFront trigger, enter the following information: Get started with Lambda@Edge 720 Amazon CloudFront Developer Guide • Distribution – The CloudFront distribution ID to associate with your function. In the dropdown list, choose the distribution ID. • Cache behavior – The cache behavior to use with the trigger. For this example, leave the value set to *, which means your distribution's default cache behavior. For more information, see Cache behavior settings in the Distribution settings reference topic. • CloudFront event – The trigger that specifies when your function runs. We want the security headers function to run whenever CloudFront returns a response from the origin. In the dropdown list, choose Origin response. For more information, see Add triggers for a Lambda@Edge function. 5. Select the Confirm deploy to Lambda@Edge check box. 6. Choose Deploy to
AmazonCloudFront_DevGuide-258
AmazonCloudFront_DevGuide.pdf
258
ID. • Cache behavior – The cache behavior to use with the trigger. For this example, leave the value set to *, which means your distribution's default cache behavior. For more information, see Cache behavior settings in the Distribution settings reference topic. • CloudFront event – The trigger that specifies when your function runs. We want the security headers function to run whenever CloudFront returns a response from the origin. In the dropdown list, choose Origin response. For more information, see Add triggers for a Lambda@Edge function. 5. Select the Confirm deploy to Lambda@Edge check box. 6. Choose Deploy to add the trigger and replicate the function to AWS locations worldwide. 7. Wait for the function to replicate. This typically takes several minutes. You can check to see if replication is finished by going to the CloudFront console and viewing your distribution. Wait for the distribution status to change from Deploying to a date and time, which means that your function has been replicated. To verify that the function works, follow the steps in the next section. Step 5: Verify that the function runs Now that you've created your Lambda function and configured a trigger to run it for a CloudFront distribution, check to make sure that the function is accomplishing what you expect it to. In this example, we check the HTTP headers that CloudFront returns, to make sure that the security headers are added. To verify that your Lambda@Edge function adds security headers 1. In a browser, enter the URL for a file in your S3 bucket. For example, you might use a URL similar to https://d111111abcdef8.cloudfront.net/image.jpg. For more information about the CloudFront domain name to use in the file URL, see Customize the URL format for files in CloudFront. 2. Open your browser's Web Developer toolbar. For example, in your browser window in Chrome, open the context (right-click) menu, and then choose Inspect. 3. Choose the Network tab. Get started with Lambda@Edge 721 Amazon CloudFront Developer Guide 4. Reload the page to view your image, and then choose an HTTP request on the left pane. You see the HTTP headers displayed in a separate pane. 5. Look through the list of HTTP headers to verify that the expected security headers are included in the list. For example, you might see headers similar to those shown in the following screenshot. If the security headers are included in your headers list, great! You've successfully created your first Lambda@Edge function. If CloudFront returns errors or there are other issues, continue to the next step to troubleshoot the issues. Step 6: Troubleshoot issues If CloudFront returns errors or doesn't add the security headers as expected, you can investigate your function's execution by looking at CloudWatch Logs. Be sure to use the logs stored in the AWS location that is closest to the location where the function is executed. For example, if you view the file from London, try changing the Region in the CloudWatch console to Europe (London). Get started with Lambda@Edge 722 Amazon CloudFront Developer Guide To examine CloudWatch logs for your Lambda@Edge function 1. Sign in to the AWS Management Console and open the CloudWatch console at https:// console.aws.amazon.com/cloudwatch/. 2. Change Region to the location that is shown when you view the file in your browser. This is where the function is executing. 3. In the left pane, choose Logs to view the logs for your distribution. For more information, see Monitor CloudFront metrics with Amazon CloudWatch. Step 7: Clean up your example resources If you created an Amazon S3 bucket and CloudFront distribution just for this tutorial, delete the AWS resources that you allocated so that you no longer accrue charges. After you delete your AWS resources, any content that you added is no longer available. Tasks • Delete the S3 bucket • Delete the Lambda function • Delete the CloudFront distribution Delete the S3 bucket Before you delete your Amazon S3 bucket, make sure that logging is disabled for the bucket. Otherwise, AWS continues to write logs to your bucket as you delete it. To disable logging for a bucket 1. Open the Amazon S3 console at https://console.aws.amazon.com/s3/. 2. 3. Select your bucket, and then choose Properties. From Properties, choose Logging. 4. Clear the Enabled check box. 5. Choose Save. Now, you can delete your bucket. For more information, see Deleting a bucket in the Amazon Simple Storage Service Console User Guide. Get started with Lambda@Edge 723 Amazon CloudFront Delete the Lambda function Developer Guide For instructions to delete the Lambda function association and optionally the function itself, see Delete Lambda@Edge functions and replicas. Delete the CloudFront distribution Before you delete a CloudFront distribution, you must disable it. A disabled distribution is no longer functional and does not accrue charges. You can enable a disabled distribution at
AmazonCloudFront_DevGuide-259
AmazonCloudFront_DevGuide.pdf
259
From Properties, choose Logging. 4. Clear the Enabled check box. 5. Choose Save. Now, you can delete your bucket. For more information, see Deleting a bucket in the Amazon Simple Storage Service Console User Guide. Get started with Lambda@Edge 723 Amazon CloudFront Delete the Lambda function Developer Guide For instructions to delete the Lambda function association and optionally the function itself, see Delete Lambda@Edge functions and replicas. Delete the CloudFront distribution Before you delete a CloudFront distribution, you must disable it. A disabled distribution is no longer functional and does not accrue charges. You can enable a disabled distribution at any time. After you delete a disabled distribution, it's no longer available. To disable and delete a CloudFront distribution 1. Open the CloudFront console at https://console.aws.amazon.com/cloudfront/v4/home. 2. Select the distribution that you want to disable, and then choose Disable. 3. When prompted for confirmation, choose Yes, Disable. 4. Select the disabled distribution, and then choose Delete. 5. When prompted for confirmation, choose Yes, Delete. Related information Now that you have a basic idea of how Lambda@Edge functions work, learn more by reading the following: • Lambda@Edge example functions • Lambda@Edge Design Best Practices • Reducing Latency and Shifting Compute to the Edge with Lambda@Edge Set up IAM permissions and roles for Lambda@Edge To configure Lambda@Edge, you must have the following IAM permissions and roles for AWS Lambda: • IAM permissions – These permissions allow you to create your Lambda function and associate it with your CloudFront distribution. • A Lambda function execution role (IAM role) – The Lambda service principals assume this role to execute your function. Set up IAM permissions and roles 724 Amazon CloudFront Developer Guide • Service-linked roles for Lambda@Edge – The service-linked roles allow specific AWS services to replicate Lambda functions to AWS Regions and to enable CloudWatch to use CloudFront log files. IAM permissions required to associate Lambda@Edge functions with CloudFront distributions In addition to the IAM permissions that you need for Lambda, you need the following permissions to associate Lambda functions with CloudFront distributions: • lambda:GetFunction – Grants permission to get configuration information for your Lambda function and a presigned URL to download a .zip file that contains the function. • lambda:EnableReplication* – Grants permission to the resource policy so that the Lambda replication service can get the function code and configuration. • lambda:DisableReplication* – Grants permission to the resource policy so that the Lambda replication service can delete the function. Important You must add the asterisk (*) at the end of the lambda:EnableReplication* and lambda:DisableReplication* actions. • For the resource, specify the ARN of the function version that you want to execute when a CloudFront event occurs, such as the following example: arn:aws:lambda:us-east-1:123456789012:function:TestFunction:2 • iam:CreateServiceLinkedRole – Grants permission to create a service-linked role that Lambda@Edge uses to replicate Lambda functions in CloudFront. After you configure Lambda@Edge for the first time, the service-linked role is automatically created for you. You don't need to add this permission to other distributions that use Lambda@Edge. • cloudfront:UpdateDistribution or cloudfront:CreateDistribution – Grants permission to update or create a distribution. For more information, see the following topics: • Identity and Access Management for Amazon CloudFront Set up IAM permissions and roles 725 Amazon CloudFront Developer Guide • Lambda resource access permissions in the AWS Lambda Developer Guide Function execution role for service principals You must create an IAM role that the lambda.amazonaws.com and edgelambda.amazonaws.com service principals can assume when they execute your function. Tip When you create your function in the Lambda console, you can choose to create a new execution role by using an AWS policy template. This step automatically adds the required Lambda@Edge permissions to execute your function. See Step 5 in the Tutorial: Creating a simple Lambda@Edge function. For more information about creating an IAM role manually, see Creating roles and attaching policies (console) in the IAM User Guide. Example Example: Role trust policy You can add this role under the Trust Relationship tab in the IAM console. Don't add this policy under the Permissions tab. { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": { "Service": [ "lambda.amazonaws.com", "edgelambda.amazonaws.com" ] }, "Action": "sts:AssumeRole" } ] } For more information about the permissions that you need to grant to the execution role, see Lambda resource access permissions in the AWS Lambda Developer Guide. Set up IAM permissions and roles 726 Amazon CloudFront Notes Developer Guide • By default, whenever a CloudFront event triggers a Lambda function, data is written to CloudWatch Logs. If you want to use these logs, the execution role needs permission to write data to CloudWatch Logs. You can use the predefined AWSLambdaBasicExecutionRole to grant permission to the execution role. For more information about CloudWatch Logs, see the section called “Edge function logs”. • If your Lambda function code accesses other AWS resources,
AmazonCloudFront_DevGuide-260
AmazonCloudFront_DevGuide.pdf
260
to grant to the execution role, see Lambda resource access permissions in the AWS Lambda Developer Guide. Set up IAM permissions and roles 726 Amazon CloudFront Notes Developer Guide • By default, whenever a CloudFront event triggers a Lambda function, data is written to CloudWatch Logs. If you want to use these logs, the execution role needs permission to write data to CloudWatch Logs. You can use the predefined AWSLambdaBasicExecutionRole to grant permission to the execution role. For more information about CloudWatch Logs, see the section called “Edge function logs”. • If your Lambda function code accesses other AWS resources, such as reading an object from an S3 bucket, the execution role needs permission to perform that action. Service-linked roles for Lambda@Edge Lambda@Edge uses IAM service-linked roles. A service-linked role is a unique type of IAM role that is linked directly to a service. Service-linked roles are predefined by the service and include all of the permissions that the service requires to call other AWS services on your behalf. Lambda@Edge uses the following IAM service-linked roles: • AWSServiceRoleForLambdaReplicator – Lambda@Edge uses this role to allow Lambda@Edge to replicate functions to AWS Regions. When you first add a Lambda@Edge trigger in CloudFront, a role named AWSServiceRoleForLambdaReplicator is created automatically to allow Lambda@Edge to replicate functions to AWS Regions. This role is required to use Lambda@Edge functions. The ARN for the AWSServiceRoleForLambdaReplicator role looks like the following example: arn:aws:iam::123456789012:role/aws-service-role/ replicator.lambda.amazonaws.com/AWSServiceRoleForLambdaReplicator • AWSServiceRoleForCloudFrontLogger – CloudFront uses this role to push log files into CloudWatch. You can use log files to debug Lambda@Edge validation errors. The AWSServiceRoleForCloudFrontLogger role is created automatically when you add Lambda@Edge function association to allow CloudFront to push Lambda@Edge error log files to CloudWatch. The ARN for the AWSServiceRoleForCloudFrontLogger role looks like this: Set up IAM permissions and roles 727 Amazon CloudFront Developer Guide arn:aws:iam::account_number:role/aws-service-role/ logger.cloudfront.amazonaws.com/AWSServiceRoleForCloudFrontLogger A service-linked role makes setting up and using Lambda@Edge easier because you don’t have to manually add the necessary permissions. Lambda@Edge defines the permissions of its service- linked roles, and only Lambda@Edge can assume the roles. The defined permissions include the trust policy and the permissions policy. You can't attach the permissions policy to any other IAM entity. You must remove any associated CloudFront or Lambda@Edge resources before you can delete a service-linked role. This helps protect your Lambda@Edge resources so that you don't remove a service-linked role that is still required to access active resources. For more information about service-linked roles, see Service-linked roles for CloudFront. Service-linked role permissions for Lambda@Edge Lambda@Edge uses two service-linked roles, named AWSServiceRoleForLambdaReplicator and AWSServiceRoleForCloudFrontLogger. The following sections describe the permissions for each of these roles. Contents • Service-linked role permissions for Lambda replicator • Service-linked role permissions for CloudFront logger Service-linked role permissions for Lambda replicator This service-linked role allows Lambda to replicate Lambda@Edge functions to AWS Regions. The AWSServiceRoleForLambdaReplicator service-linked role trusts the replicator.lambda.amazonaws.com service to assume the role. The role permissions policy allows Lambda@Edge to complete the following actions on the specified resources: • lambda:CreateFunction on arn:aws:lambda:*:*:function:* • lambda:DeleteFunction on arn:aws:lambda:*:*:function:* Set up IAM permissions and roles 728 Amazon CloudFront Developer Guide • lambda:DisableReplication on arn:aws:lambda:*:*:function:* • iam:PassRole on all AWS resources • cloudfront:ListDistributionsByLambdaFunction on all AWS resources Service-linked role permissions for CloudFront logger This service-linked role allows CloudFront to push log files into CloudWatch so that you can debug Lambda@Edge validation errors. The AWSServiceRoleForCloudFrontLogger service-linked role trusts the logger.cloudfront.amazonaws.com service to assume the role. The role permissions policy allows Lambda@Edge to complete the following actions on the specified arn:aws:logs:*:*:log-group:/aws/cloudfront/* resource: • logs:CreateLogGroup • logs:CreateLogStream • logs:PutLogEvents You must configure permissions to allow an IAM entity (such as a user, group, or role) to delete the Lambda@Edge service-linked roles. For more information, see Service-linked role permissions in the IAM User Guide. Creating service-linked roles for Lambda@Edge You don’t typically manually create the service-linked roles for Lambda@Edge. The service creates the roles for you automatically in the following scenarios: • When you first create a trigger, the service creates the AWSServiceRoleForLambdaReplicator role (if it doesn’t already exist). This role allows Lambda to replicate Lambda@Edge functions to AWS Regions. If you delete the service-linked role, the role will be created again when you add a new trigger for Lambda@Edge in a distribution. • When you update or create a CloudFront distribution that has a Lambda@Edge association, the service creates the AWSServiceRoleForCloudFrontLogger role (if the role doesn’t already exist). This role allows CloudFront to push your log files to CloudWatch. Set up IAM permissions and roles 729 Amazon CloudFront Developer Guide If you delete the service-linked role, the role will be created again when you update or create a CloudFront distribution that has a Lambda@Edge association. To manually create these service-linked roles, you can run the following AWS Command Line Interface (AWS CLI) commands: To create the AWSServiceRoleForLambdaReplicator
AmazonCloudFront_DevGuide-261
AmazonCloudFront_DevGuide.pdf
261
for Lambda@Edge in a distribution. • When you update or create a CloudFront distribution that has a Lambda@Edge association, the service creates the AWSServiceRoleForCloudFrontLogger role (if the role doesn’t already exist). This role allows CloudFront to push your log files to CloudWatch. Set up IAM permissions and roles 729 Amazon CloudFront Developer Guide If you delete the service-linked role, the role will be created again when you update or create a CloudFront distribution that has a Lambda@Edge association. To manually create these service-linked roles, you can run the following AWS Command Line Interface (AWS CLI) commands: To create the AWSServiceRoleForLambdaReplicator role • Run the following command. aws iam create-service-linked-role --aws-service-name replicator.lambda.amazonaws.com To create the AWSServiceRoleForCloudFrontLogger role • Run the following command. aws iam create-service-linked-role --aws-service-name logger.cloudfront.amazonaws.com Editing Lambda@Edge service-linked roles Lambda@Edge doesn't allow you to edit the AWSServiceRoleForLambdaReplicator or AWSServiceRoleForCloudFrontLogger service-linked roles. After the service has created a service- linked role, you can't change the name of the role because various entities might reference the role. However, you can use IAM to edit the role description. For more information, see Editing a service- linked role in the IAM User Guide. Supported AWS Regions for Lambda@Edge service-linked roles CloudFront supports using service-linked roles for Lambda@Edge in the following AWS Regions: • US East (N. Virginia) – us-east-1 • US East (Ohio) – us-east-2 • US West (N. California) – us-west-1 • US West (Oregon) – us-west-2 Set up IAM permissions and roles 730 Amazon CloudFront Developer Guide • Asia Pacific (Mumbai) – ap-south-1 • Asia Pacific (Seoul) – ap-northeast-2 • Asia Pacific (Singapore) – ap-southeast-1 • Asia Pacific (Sydney) – ap-southeast-2 • Asia Pacific (Tokyo) – ap-northeast-1 • Europe (Frankfurt) – eu-central-1 • Europe (Ireland) – eu-west-1 • Europe (London) – eu-west-2 • South America (São Paulo) – sa-east-1 Write and create a Lambda@Edge function To use Lambda@Edge, you write the code for your AWS Lambda function. To help you write Lambda@Edge functions, see the following resources: • Lambda@Edge event structure – Understand the event structure to use with Lambda@Edge. • Lambda@Edge example functions – Example functions, such as A/B testing and generating an HTTP redirect. The programming model for using Node.js or Python with Lambda@Edge is the same as using Lambda in an AWS Region. For more information, see Building Lambda functions with Node.js or Building Lambda functions with Python in the AWS Lambda Developer Guide. In your Lambda@Edge function, include the callback parameter and return the applicable object for request or response events: • Request events – Include the cf.request object in the response. If you're generating a response, include the cf.response object in the response. For more information, see Generate HTTP responses in request triggers. • Response events – Include the cf.response object in the response. After you write your own code or use one of the examples, you then create the function in Lambda. To create a function or edit an existing one, see the following topics: Write and create a Lambda@Edge function 731 Amazon CloudFront Topics • Create a Lambda@Edge function • Edit a Lambda function Developer Guide After you create the function in Lambda, you set up Lambda to run the function based on specific CloudFront events, which are called triggers. For more information, see Add triggers for a Lambda@Edge function. Create a Lambda@Edge function To set up AWS Lambda to run Lambda functions that are based on CloudFront events, follow this procedure. To create a Lambda@Edge function 1. Sign in to the AWS Management Console and open the AWS Lambda console at https:// console.aws.amazon.com/lambda/. 2. If you already have one or more Lambda functions, choose Create function. If you've don't have any functions, choose Get Started Now. 3. In the Region list at the top of the page, choose US East (N. Virginia). 4. Create a function using your own code or create a function starting with a CloudFront blueprint. • To create a function using your own code, choose Author from scratch. • To display a list of blueprints for CloudFront, enter cloudfront in the filter field, and then choose Enter. If you find a blueprint that you want to use, choose the name of the blueprint. 5. In the Basic information section, specify the following values: a. Name – Enter a name for your function. b. Role – To get started quickly, choose Create new role from template(s). You can also choose Choose an existing role or Create a custom role, and then follow the prompts to complete the information for this section. c. Role name – Enter a name for the role. d. Policy templates – Choose Basic Edge Lambda permissions. Write and create a Lambda@Edge function 732 Amazon CloudFront Developer Guide 6. If you chose Author from scratch in step 4, skip to step 7. If you chose a blueprint
AmazonCloudFront_DevGuide-262
AmazonCloudFront_DevGuide.pdf
262
specify the following values: a. Name – Enter a name for your function. b. Role – To get started quickly, choose Create new role from template(s). You can also choose Choose an existing role or Create a custom role, and then follow the prompts to complete the information for this section. c. Role name – Enter a name for the role. d. Policy templates – Choose Basic Edge Lambda permissions. Write and create a Lambda@Edge function 732 Amazon CloudFront Developer Guide 6. If you chose Author from scratch in step 4, skip to step 7. If you chose a blueprint in step 4, the cloudfront section lets you create one trigger, which associates this function with a cache in a CloudFront distribution and a CloudFront event. We recommend that you choose Remove at this point, so there isn't a trigger for the function when it's created. Then you can add triggers later. Tip We recommend that you test and debug the function before adding triggers. If you add a trigger now, the function will run as soon as you create the function and it finishes replicating to AWS locations around the world, and the corresponding distribution is deployed. 7. Choose Create function. Lambda creates two versions of your function: $LATEST and Version 1. You can edit only the $LATEST version, but the console initially displays Version 1. 8. To edit the function, choose Version 1 near the top of the page, under the ARN for the function. Then, on the Versions tab, choose $LATEST. (If you left the function and then returned to it, the button label is Qualifiers.) 9. On the Configuration tab, choose the applicable Code entry type. Then follow the prompts to edit or upload your code. 10. For Runtime, choose the value based on your function's code. 11. In the Tags section, add any applicable tags. 12. Choose Actions, and then choose Publish new version. 13. Enter a description for the new version of the function. 14. Choose Publish. 15. Test and debug the function. For more information about testing in the Lambda console, see Invoke a Lambda function using the console in the AWS Lambda Developer Guide. 16. When you're ready to have the function execute for CloudFront events, publish another version and edit the function to add triggers. For more information, see Add triggers for a Lambda@Edge function. Write and create a Lambda@Edge function 733 Amazon CloudFront Edit a Lambda function Developer Guide After you create a Lambda@Edge function, you can use the Lambda console to edit it. Notes • The original version is labeled $LATEST. • You can edit only the $LATEST version. • Each time you edit the $LATEST version, you must publish a new numbered version. • You can't create triggers for $LATEST. • When you publish a new version of a function, Lambda doesn't automatically copy triggers from the previous version to the new version. You must reproduce the triggers for the new version. • When you add a trigger for a CloudFront event to a function, if there's already a trigger for the same distribution, cache behavior, and event for an earlier version of the same function, Lambda deletes the trigger from the earlier version. • After you make updates to a CloudFront distribution, like adding triggers, you must wait for the changes to propagate to edge locations before the functions you've specified in the triggers will work. To edit a Lambda function 1. Sign in to the AWS Management Console and open the AWS Lambda console at https:// console.aws.amazon.com/lambda/. 2. 3. In the Region list at the top of the page, choose US East (N. Virginia). In the list of functions, choose the name of the function. By default, the console displays the $LATEST version. You can view earlier versions (choose Qualifiers), but you can only edit $LATEST. 4. On the Code tab, for Code entry type, choose to edit the code in the browser, upload a .zip file, or upload a file from Amazon S3. 5. Choose either Save or Save and test. 6. Choose Actions, and choose Publish new version. Write and create a Lambda@Edge function 734 Amazon CloudFront Developer Guide 7. In the Publish new version from $LATEST dialog box, enter a description of the new version. This description appears in the list of versions, along with an automatically generated version number. 8. Choose Publish. The new version automatically becomes the latest version. The version number appears on the Version in the upper-left corner of the page. Note If you haven't added triggers for your function yet, see Add triggers for a Lambda@Edge function. 9. Choose the Triggers tab. 10. Choose Add trigger. 11. In the Add trigger dialog box, choose the dotted box, and then choose CloudFront. Note If you've already created one or
AmazonCloudFront_DevGuide-263
AmazonCloudFront_DevGuide.pdf
263
version from $LATEST dialog box, enter a description of the new version. This description appears in the list of versions, along with an automatically generated version number. 8. Choose Publish. The new version automatically becomes the latest version. The version number appears on the Version in the upper-left corner of the page. Note If you haven't added triggers for your function yet, see Add triggers for a Lambda@Edge function. 9. Choose the Triggers tab. 10. Choose Add trigger. 11. In the Add trigger dialog box, choose the dotted box, and then choose CloudFront. Note If you've already created one or more triggers for a function, CloudFront is the default service. 12. Specify the following values to indicate when you want the Lambda function to execute. a. Distribution ID – Choose the ID of the distribution that you want to add the trigger to. b. Cache behavior – Choose the cache behavior that specifies the objects that you want to execute the function on. c. d. CloudFront event – Choose the CloudFront event that causes the function to execute. Enable trigger and replicate – Select this check box so Lambda replicates the function to AWS Regions globally. 13. Choose Submit. 14. To add more triggers for this function, repeat steps 10 through 13. For more information about testing and debugging the function in the Lambda console, see Invoke a Lambda function using the console in the AWS Lambda Developer Guide. Write and create a Lambda@Edge function 735 Amazon CloudFront Developer Guide When you're ready to have the function execute for CloudFront events, publish another version and edit the function to add triggers. For more information, see Add triggers for a Lambda@Edge function. Add triggers for a Lambda@Edge function A Lambda@Edge trigger is one combination of a CloudFront distribution, cache behavior, and event that causes a function to execute. For example, you can create a trigger that causes the function to execute when CloudFront receives a request from a viewer for a specific cache behavior you set up for your distribution. You can specify one or more CloudFront triggers. Tip When you create a CloudFront distribution, you specify settings that tell CloudFront how to respond when it receives different requests. The default settings are called the default cache behavior for the distribution. You can set up additional cache behaviors that define how CloudFront responds under specific circumstances, for example, when it receives a request for a specific file type. For more information, see Cache behavior settings. When you first create a Lambda function, you can specify only one trigger. You can add more triggers to the same function later by using the Lambda console or by editing the distribution in the CloudFront console. • The Lambda console works well if you want to add more triggers to a function for the same CloudFront distribution. • The CloudFront console can be better if you want to add triggers for multiple distributions because it's easier to find the distribution that you want to update. You can also update other CloudFront settings at the same time. Topics • CloudFront events that can trigger a Lambda@Edge function • Choose the event to trigger the function • Add triggers to a Lambda@Edge function Add triggers for a Lambda@Edge function 736 Amazon CloudFront Developer Guide CloudFront events that can trigger a Lambda@Edge function For each cache behavior in a Amazon CloudFront distribution, you can add up to four triggers (associations) that cause a Lambda function to execute when specific CloudFront events occur. CloudFront triggers can be based on one of four CloudFront events, as shown in the following diagram. The CloudFront events that can be used to trigger Lambda@Edge functions are the following: Viewer request The function executes when CloudFront receives a request from a viewer, before it checks to see whether the requested object is in the CloudFront cache. The function doesn't execute in the following cases: • When fetching a custom error page. • When CloudFront automatically redirects an HTTP request to HTTPS (when the value of the Viewer protocol policy is Redirect HTTP to HTTPS). Origin request The function executes only when CloudFront forwards a request to your origin. When the requested object is in the CloudFront cache, the function doesn't execute. Origin response The function executes after CloudFront receives a response from the origin and before it caches the object in the response. Note that the function executes even if an error is returned from the origin. The function doesn't execute in the following cases: Add triggers for a Lambda@Edge function 737 Amazon CloudFront Developer Guide • When the requested file is in the CloudFront cache and is not expired. • When the response is generated from a function that was triggered by an origin request event. Viewer response The function executes before returning
AmazonCloudFront_DevGuide-264
AmazonCloudFront_DevGuide.pdf
264
the CloudFront cache, the function doesn't execute. Origin response The function executes after CloudFront receives a response from the origin and before it caches the object in the response. Note that the function executes even if an error is returned from the origin. The function doesn't execute in the following cases: Add triggers for a Lambda@Edge function 737 Amazon CloudFront Developer Guide • When the requested file is in the CloudFront cache and is not expired. • When the response is generated from a function that was triggered by an origin request event. Viewer response The function executes before returning the requested file to the viewer. Note that the function executes regardless of whether the file is already in the CloudFront cache. The function doesn't execute in the following cases: • When the origin returns an HTTP status code of 400 or higher. • When a custom error page is returned. • When the response is generated from a function that was triggered by a viewer request event. • When CloudFront automatically redirects an HTTP request to HTTPS (when the value of the Viewer protocol policy is Redirect HTTP to HTTPS). When you add multiple triggers to the same cache behavior, you can use them to run the same function or run different functions for each trigger. You can also associate the same function with more than one distribution. Note When a CloudFront event triggers the execution of a Lambda function, the function must finish before CloudFront can continue. For example, if a Lambda function is triggered by a CloudFront viewer request event, CloudFront won't return a response to the viewer or forward the request to the origin until the Lambda function finishes running. This means that each request that triggers a Lambda function increases latency for the request, so you want the function to execute as fast as possible. Choose the event to trigger the function When you're deciding which CloudFront event you want to use to trigger a Lambda function, consider the following: Add triggers for a Lambda@Edge function 738 Amazon CloudFront Developer Guide I want CloudFront to cache objects that are changed by a Lambda function To cache an object that was modified by a Lambda function so that CloudFront can serve the object from the edge location the next time it's requested, use the origin request or origin response event. This reduces the load on the origin, reduces latency for subsequent requests, and reduces the cost of invoking Lambda@Edge on subsequent requests. For example, if you want to add, remove, or change headers for objects that are returned by the origin and you want CloudFront to cache the result, use the origin response event. I want the function to execute for every request To execute the function for every request that CloudFront receives for the distribution, use the viewer request or viewer response events. Origin request and origin response events occur only when a requested object isn't cached in an edge location and CloudFront forwards a request to the origin. I want the function to change the cache key To change a value that you're using as a basis for caching, use the viewer request event. For example, if a function changes the URL to include a language abbreviation in the path (for example, because the user chose their language from a dropdown list), use the viewer request event: • URL in the viewer request – https://example.com/en/index.html • URL when the request comes from an IP address in Germany – https://example.com/de/ index.html You also use the viewer request event if you're caching based on cookies or request headers. Note If the function changes cookies or headers, configure CloudFront to forward the applicable part of the request to the origin. For more information, see the following topics: • Cache content based on cookies • Cache content based on request headers Add triggers for a Lambda@Edge function 739 Amazon CloudFront Developer Guide The function affects the response from the origin To change the request in a way that affects the response from the origin, use the origin request event. Typically, most viewer request events aren't forwarded to the origin. CloudFront responds to a request with an object that's already in the edge cache. If the function changes the request based on an origin request event, CloudFront caches the response to the changed origin request. Add triggers to a Lambda@Edge function You can use the AWS Lambda console or Amazon CloudFront console to add a trigger to your Lambda@Edge function. Important You can create triggers only for numbered versions of your function (not the $LATEST). Lambda console To add triggers for CloudFront events to a Lambda@Edge function 1. Sign in to the AWS Management Console and open the AWS Lambda console at https:// console.aws.amazon.com/lambda/. 2. In the Region list
AmazonCloudFront_DevGuide-265
AmazonCloudFront_DevGuide.pdf
265
already in the edge cache. If the function changes the request based on an origin request event, CloudFront caches the response to the changed origin request. Add triggers to a Lambda@Edge function You can use the AWS Lambda console or Amazon CloudFront console to add a trigger to your Lambda@Edge function. Important You can create triggers only for numbered versions of your function (not the $LATEST). Lambda console To add triggers for CloudFront events to a Lambda@Edge function 1. Sign in to the AWS Management Console and open the AWS Lambda console at https:// console.aws.amazon.com/lambda/. 2. In the Region list at the top of the page, choose US East (N. Virginia). 3. On the Functions page, choose the name of the function that you want to add triggers for. 4. On the Function overview page, choose the Versions tab. 5. Choose the version that you want to add triggers to. After you choose a version, the name of the button changes to Version: $LATEST or Version: version number. 6. Choose the Triggers tab. 7. Choose Add trigger. 8. For Trigger configuration, choose Select a source, enter cloudfront, and then choose CloudFront. Add triggers for a Lambda@Edge function 740 Amazon CloudFront Developer Guide Note If you've already created one or more triggers, CloudFront is the default service. 9. Specify the following values to indicate when you want the Lambda function to execute. a. Distribution – Choose the distribution that you want to add the trigger to. b. Cache behavior – Choose the cache behavior that specifies the objects that you want to execute the function on. Note If you specify * for the cache behavior, the Lambda function deploys to the default cache behavior. c. d. CloudFront event – Choose the CloudFront event that causes the function to execute. Include body – Select this check box if you want to access the request body in your function. e. Confirm deploy to Lambda@Edge – Select this check box so that AWS Lambda replicates the function to AWS Regions globally. 10. Choose Add. The function starts to process requests for the specified CloudFront events when the updated CloudFront distribution is deployed. To determine whether a distribution is deployed, choose Distributions in the navigation pane. When a distribution is deployed, the value of the Status column for the distribution changes from Deploying to the date and time of deployment. CloudFront console To add triggers for CloudFront events to a Lambda@Edge function 1. Get the ARN of the Lambda function that you want to add triggers for: a. Sign in to the AWS Management Console and open the AWS Lambda console at https://console.aws.amazon.com/lambda/. b. In the list of Regions at the top of the page, choose US East (N. Virginia). Add triggers for a Lambda@Edge function 741 Amazon CloudFront Developer Guide c. In the list of functions, choose name of the function that you want to add triggers to. d. On the Function overview page, choose the Versions tab, and choose the numbered version that you want to add triggers to. e. Choose the Copy ARN button to copy the ARN to your clipboard. The ARN for the Lambda function looks something like this: arn:aws:lambda:us-east-1:123456789012:function:TestFunction:2 The number at the end (2 in this example) is the version number of the function. 2. Open the CloudFront console at https://console.aws.amazon.com/cloudfront/v4/home. 3. In the list of distributions, choose the ID of the distribution that you want to add triggers to. 4. Choose the Behaviors tab. 5. 6. Select the cache behavior that you want to add triggers to, and then choose Edit. For Function associations, in the Function type list, choose Lambda@Edge for when you want the function to execute: for viewer requests, viewer responses, origin requests, or origin responses. For more information, see Choose the event to trigger the function. 7. In the Function ARN / Name text box, paste the ARN of the Lambda function that you want to execute when the chosen event occurs. This is the value that you copied from the Lambda console. 8. Select Include body if you want to access the request body in your function. If you just want to replace the request body, you don't need to select this option. 9. To execute the same function for more event types, repeat steps 6 and 7. 10. Choose Save changes. 11. To add triggers to more cache behaviors for this distribution, repeat steps 5 through 10. The function starts to process requests for the specified CloudFront events when the updated CloudFront distribution is deployed. To determine whether a distribution is deployed, choose Distributions in the navigation pane. When a distribution is deployed, the value of the Status column for the distribution changes from Deploying to the time and date of deployment. Add triggers for a Lambda@Edge function 742 Amazon CloudFront
AmazonCloudFront_DevGuide-266
AmazonCloudFront_DevGuide.pdf
266
option. 9. To execute the same function for more event types, repeat steps 6 and 7. 10. Choose Save changes. 11. To add triggers to more cache behaviors for this distribution, repeat steps 5 through 10. The function starts to process requests for the specified CloudFront events when the updated CloudFront distribution is deployed. To determine whether a distribution is deployed, choose Distributions in the navigation pane. When a distribution is deployed, the value of the Status column for the distribution changes from Deploying to the time and date of deployment. Add triggers for a Lambda@Edge function 742 Amazon CloudFront Developer Guide Test and debug Lambda@Edge functions It's important to test your Lambda@Edge function code standalone, to make sure that it completes the intended task, and to do integration testing, to make sure that the function works correctly with CloudFront. During integration testing or after your function has been deployed, you might need to debug CloudFront errors, such as HTTP 5xx errors. Errors can be an invalid response returned from the Lambda function, execution errors when the function is triggered, or errors due to execution throttling by the Lambda service. Sections in this topic share strategies for determining which type of failure is the issue, and then steps you can take to correct the problem. Note When you review CloudWatch log files or metrics when you're troubleshooting errors, be aware that they are displayed or stored in the AWS Region closest to the location where the function executed. So, if you have a website or web application with users in the United Kingdom, and you have a Lambda function associated with your distribution, for example, you must change the Region to view the CloudWatch metrics or log files for the London AWS Region. For more information, see the section called “ Determine the Lambda@Edge Region”. Topics • Test your Lambda@Edge functions • Identify Lambda@Edge function errors in CloudFront • Troubleshoot invalid Lambda@Edge function responses (validation errors) • Troubleshoot Lambda@Edge function execution errors • Determine the Lambda@Edge Region • Determine if your account pushes logs to CloudWatch Test your Lambda@Edge functions There are two steps to testing your Lambda function: standalone testing and integration testing. Test and debug 743 Amazon CloudFront Test standalone functionality Developer Guide Before you add your Lambda function to CloudFront, make sure to test the functionality first by using the testing capabilities in the Lambda console or by using other methods. For more information about testing in the Lambda console, see Invoke a Lambda function using the console in the AWS Lambda Developer Guide. Test your function's operation in CloudFront It's important to complete integration testing, where your function is associated with a distribution and runs based on a CloudFront event. Make sure that the function is triggered for the right event, and returns a response that is valid and correct for CloudFront. For example, make sure that the event structure is correct, that only valid headers are included, and so on. As you iterate on integration testing with your function in the Lambda console, refer to the steps in the Lambda@Edge tutorial as you modify your code or change the CloudFront trigger that calls your function. For example, make sure that you're working in a numbered version of your function, as described in this step of the tutorial: Step 4: Add a CloudFront trigger to run the function. As you make changes and deploy them, be aware that it will take several minutes for your updated function and CloudFront triggers to replicate across all Regions. This typically takes a few minutes but can take up to 15 minutes. You can check to see if replication is finished by going to the CloudFront console and viewing your distribution. To check if your replication has finished deploying 1. Open the CloudFront console at https://console.aws.amazon.com/cloudfront/v4/home. 2. Choose the distribution name. 3. Check for the distribution status to change from In Progress back to Deployed, which means that your function has been replicated. Then follow the steps in the next section to verify that the function works. Be aware that testing in the console only validates your function's logic, and does not apply any service quotas (formerly known as limits) that are specific to Lambda@Edge. Test and debug 744 Amazon CloudFront Developer Guide Identify Lambda@Edge function errors in CloudFront After you've verified that your function logic works correctly, you might still see HTTP 5xx errors when your function runs in CloudFront. HTTP 5xx errors can be returned for a variety of reasons, which can include Lambda function errors or other issues in CloudFront. • If you use Lambda@Edge functions, you can use graphs in the CloudFront console to help track down what's causing the error, and then work to fix it. For example, you can see if HTTP 5xx errors
AmazonCloudFront_DevGuide-267
AmazonCloudFront_DevGuide.pdf
267
that are specific to Lambda@Edge. Test and debug 744 Amazon CloudFront Developer Guide Identify Lambda@Edge function errors in CloudFront After you've verified that your function logic works correctly, you might still see HTTP 5xx errors when your function runs in CloudFront. HTTP 5xx errors can be returned for a variety of reasons, which can include Lambda function errors or other issues in CloudFront. • If you use Lambda@Edge functions, you can use graphs in the CloudFront console to help track down what's causing the error, and then work to fix it. For example, you can see if HTTP 5xx errors are caused by CloudFront or by Lambda functions, and then, for specific functions, you can view related log files to investigate the issue. • To troubleshoot HTTP errors in general in CloudFront, see the troubleshooting steps in the following topic: Troubleshooting error response status codes in CloudFront. What causes Lambda@Edge function errors in CloudFront There are several reasons why a Lambda function might cause an HTTP 5xx error, and the troubleshooting steps you should take depend on the type of error. Errors can be categorized as the following: A Lambda function execution error An execution error results when CloudFront doesn't get a response from Lambda because there are unhandled exceptions in the function or there's an error in the code. For example, if the code includes callback(Error). An invalid Lambda function response is returned to CloudFront After the function runs, CloudFront receives a response from Lambda. An error is returned if the object structure of the response doesn't conform to the Lambda@Edge event structure, or the response contains invalid headers or other invalid fields. The execution in CloudFront is throttled due to Lambda service quotas (formerly known as limits) The Lambda service throttles executions in each Region, and returns an error if you exceed the quota. For more information, see Quotas on Lambda@Edge. How to determine the type of failure To help you decide where to focus as you debug and work to resolve errors returned by CloudFront, it's helpful to identify why CloudFront is returning an HTTP error. To get started, you can use the Test and debug 745 Amazon CloudFront Developer Guide graphs provided in the Monitoring section of the CloudFront console on the AWS Management Console. For more information about viewing graphs in the Monitoring section of the CloudFront console, see Monitor CloudFront metrics with Amazon CloudWatch. The following graphs can be especially helpful when you want to track down whether errors are being returned by origins or by a Lambda function, and to narrow down the type of issue when it's an error from a Lambda function. Error rates graph One of the graphs that you can view on the Overview tab for each of your distributions is an Error rates graph. This graph displays the rate of errors as a percentage of total requests coming to your distribution. The graph shows the total error rate, total 4xx errors, total 5xx errors, and total 5xx errors from Lambda functions. Based on the error type and volume, you can take steps to investigate and troubleshoot the cause. • If you see Lambda errors, you can investigate further by looking at the specific types of errors that the function returns. The Lambda@Edge errors tab includes graphs that categorize function errors by type to help you pinpoint the issue for a specific function. • If you see CloudFront errors, you can troubleshoot and work to fix origin errors or change your CloudFront configuration. For more information, see Troubleshooting error response status codes in CloudFront. Execution errors and invalid function responses graphs The Lambda@Edge errors tab includes graphs that categorize the Lambda@Edge errors for a specific distribution, by type. For example, one graph shows all execution errors by AWS Region. To make it easier to troubleshoot issues, you can look for specific problems by opening and examining the log files for specific functions by Region. Test and debug 746 Amazon CloudFront Developer Guide To view log files for a specific function by Region 1. On the Lambda@Edge errors tab, under Associated Lambda@Edge functions, choose the function name, and then choose View metrics. 2. Next, on the page with your function name, in the upper-right corner, choose View function logs, and then choose a Region. For example, if you see issues in the Errors graph for the US West (Oregon) Region, choose that Region from the dropdown list. This opens the Amazon CloudWatch console. 3. In the CloudWatch console for that Region, under Log streams, choose a log stream to view the events for the function. In addition, read the following sections in this chapter for more recommendations about troubleshooting and fixing errors. Throttles graph The Lambda@Edge errors tab also includes a Throttles graph. On occasion, the Lambda service throttles your
AmazonCloudFront_DevGuide-268
AmazonCloudFront_DevGuide.pdf
268
name, in the upper-right corner, choose View function logs, and then choose a Region. For example, if you see issues in the Errors graph for the US West (Oregon) Region, choose that Region from the dropdown list. This opens the Amazon CloudWatch console. 3. In the CloudWatch console for that Region, under Log streams, choose a log stream to view the events for the function. In addition, read the following sections in this chapter for more recommendations about troubleshooting and fixing errors. Throttles graph The Lambda@Edge errors tab also includes a Throttles graph. On occasion, the Lambda service throttles your function invocations on per Region basis, if you reach the regional concurrency quota (formerly known as limit). If you see a limit exceeded error, your function has reached a quota that the Lambda service imposes on executions in a Region. For more information, including how to request an increase in the quota, see Quotas on Lambda@Edge. For an example about how to use this information in troubleshooting HTTP errors, see Four steps for debugging your content delivery on AWS. Test and debug 747 Amazon CloudFront Developer Guide Troubleshoot invalid Lambda@Edge function responses (validation errors) If you identify that your problem is a Lambda validation error, it means that your Lambda function is returning an invalid response to CloudFront. Follow the guidance in this section to take steps to review your function and make sure that your response conforms to CloudFront requirements. CloudFront validates the response from a Lambda function in two ways: • The Lambda response must conform to the required object structure. Examples of bad object structure include the following: unparsable JSON, missing required fields, and an invalid object in the response. For more information, see the Lambda@Edge event structure. • The response must include only valid object values. An error will occur if the response includes a valid object but has values that are not supported. Examples include the following: adding or updating disallowed or read-only headers (see Restrictions on edge functions), exceeding the maximum body size (see Restrictions on the Size of the Generated Response in the Lambda@Edge Errors topic), and invalid characters or values (see the Lambda@Edge event structure). When Lambda returns an invalid response to CloudFront, error messages are written to log files which CloudFront pushes to CloudWatch in the Region of where the Lambda function executed. It's the default behavior to send the log files to CloudWatch when there's an invalid response. However, if you associated a Lambda function with CloudFront before the functionality was released, it might not be enabled for your function. For more information, see Determine if Your Account Pushes Logs to CloudWatch later in the topic. CloudFront pushes log files to the Region corresponding to where your function executed, in the log group that's associated with your distribution. Log groups have the following format: /aws/ cloudfront/LambdaEdge/DistributionId, where DistributionId is your distribution's ID. To determine the Region where you can find the CloudWatch log files, see Determining the Lambda@Edge Region later in this topic. If the error is reproducible, you can create a new request that results in the error and then find the request id in a failed CloudFront response (X-Amz-Cf-Id header) to locate a single failure in log files. The log file entry includes information that can help you identify why the error is being returned, and also lists the corresponding Lambda request id so you can analyze the root cause in the context of a single request. Test and debug 748 Amazon CloudFront Developer Guide If an error is intermittent, you can use CloudFront access logs to find the request id for a request that has failed, and then search CloudWatch logs for the corresponding error messages. For more information, see the previous section, Determining the Type of Failure. Troubleshoot Lambda@Edge function execution errors If the problem is a Lambda execution error, it can be helpful to create logging statements for Lambda functions, to write messages to CloudWatch log files that monitor the execution of your function in CloudFront and determine if it's working as expected. Then you can search for those statements in the CloudWatch log files to verify that your function is working. Note Even if you haven't changed your Lambda@Edge function, updates to the Lambda function execution environment might affect it and could return an execution error. For information about testing and migrating to a later version, see Upcoming updates to the AWS Lambda and AWS Lambda@Edge execution environment. Determine the Lambda@Edge Region To see the Regions where your Lambda@Edge function is receiving traffic, view metrics for the function on the CloudFront console on the AWS Management Console. Metrics are displayed for each AWS Region. On the same page, you can choose a Region and view log files for that Region so you can investigate
AmazonCloudFront_DevGuide-269
AmazonCloudFront_DevGuide.pdf
269
you haven't changed your Lambda@Edge function, updates to the Lambda function execution environment might affect it and could return an execution error. For information about testing and migrating to a later version, see Upcoming updates to the AWS Lambda and AWS Lambda@Edge execution environment. Determine the Lambda@Edge Region To see the Regions where your Lambda@Edge function is receiving traffic, view metrics for the function on the CloudFront console on the AWS Management Console. Metrics are displayed for each AWS Region. On the same page, you can choose a Region and view log files for that Region so you can investigate issues. You must review CloudWatch log files in the correct AWS Region to see the log files created when CloudFront executed your Lambda function. For more information about viewing graphs in the Monitoring section of the CloudFront console, see Monitor CloudFront metrics with Amazon CloudWatch. Determine if your account pushes logs to CloudWatch By default, CloudFront enables logging invalid Lambda function responses, and pushes the log files to CloudWatch by using one of the Service-linked roles for Lambda@Edge. If you have Lambda@Edge functions that you added to CloudFront before the invalid Lambda function response log feature was released, logging is enabled when you next update your Lambda@Edge configuration, for example, by adding a CloudFront trigger. You can verify that pushing the log files to CloudWatch is enabled for your account by doing the following: Test and debug 749 Amazon CloudFront Developer Guide • Check to see if the logs appear in CloudWatch – Make sure that you look in the Region where the Lambda@Edge function executed. For more information, see Determine the Lambda@Edge Region. • Determine if the related service-linked role exists in your account in IAM – You must have the IAM role AWSServiceRoleForCloudFrontLogger in your account. For more information about this role, see Service-linked roles for Lambda@Edge. Delete Lambda@Edge functions and replicas You can delete a Lambda@Edge function only when the replicas of the function have been deleted by CloudFront. Replicas of a Lambda function are automatically deleted in the following situations: • After you remove the last association for the function from all of your CloudFront distributions. If more than one distribution uses a function, the replicas are deleted only after you remove the function association from the last distribution. • After you delete the last distribution that a function was associated with. Replicas are typically deleted within a few hours. You cannot manually delete Lambda@Edge function replicas. This helps prevent a situation where a replica is deleted that is still in use, which would result in an error. Warning Don't build applications that use Lambda@Edge function replicas outside of CloudFront. These replicas are deleted when their associations with distributions are removed, or when distributions themselves are deleted. The replica that an outside application depends on might be removed without warning, causing it to fail. To delete a Lambda@Edge function association from a CloudFront distribution 1. Sign in to the AWS Management Console and open the CloudFront console at https:// console.aws.amazon.com/cloudfront/v4/home. 2. Choose the ID of the distribution with the Lambda@Edge function association that you want to delete. 3. Choose the Behaviors tab. Delete functions and replicas 750 Amazon CloudFront Developer Guide 4. Select the cache behavior that has the Lambda@Edge function association that you want to delete, and then choose Edit. 5. Under Function associations, Function type, choose No association to delete the Lambda@Edge function association. 6. Choose Save changes. After you delete a Lambda@Edge function association from a CloudFront distribution, you can optionally delete the Lambda function or function version from AWS Lambda. Wait a few hours after deleting the function association so that the Lambda@Edge function replicas can be cleaned up. After that, you can delete the function by using the Lambda console, AWS CLI, Lambda API, or an AWS SDK. You can also delete a specific version of a Lambda function if the version doesn't have any CloudFront distributions associated with it. After removing all the associations for a Lambda function version, wait a few hours. Then you can delete the function version. Lambda@Edge event structure The following topics describe the request and response event objects that CloudFront passes to a Lambda@Edge function when it's triggered. Topics • Dynamic origin selection • Request events • Response events Dynamic origin selection You can use the path pattern in a cache behavior to route requests to an origin based on the path and name of the requested object, such as images/*.jpg. Using Lambda@Edge, you can also route requests to an origin based on other characteristics, such as the values in request headers. There are a number of ways that this dynamic origin selection can be useful. For example, you can distribute requests across origins in different geographic areas to help with global load balancing. Or
AmazonCloudFront_DevGuide-270
AmazonCloudFront_DevGuide.pdf
270
when it's triggered. Topics • Dynamic origin selection • Request events • Response events Dynamic origin selection You can use the path pattern in a cache behavior to route requests to an origin based on the path and name of the requested object, such as images/*.jpg. Using Lambda@Edge, you can also route requests to an origin based on other characteristics, such as the values in request headers. There are a number of ways that this dynamic origin selection can be useful. For example, you can distribute requests across origins in different geographic areas to help with global load balancing. Or you can selectively route requests to different origins that each serve a particular function: bot handling, SEO optimization, authentication, and so on. For code examples that demonstrate how to use this feature, see Content-based dynamic origin selection - examples. Event structure 751 Amazon CloudFront Developer Guide In the CloudFront origin request event, the origin object in the event structure contains information about the origin that the request would be routed to, based on the path pattern. You can update the values in the origin object to route a request to a different origin. When you update the origin object, you don't need to define the origin in the distribution. You can also replace an Amazon S3 origin object with a custom origin object, and vice versa. You can only specify a single origin per request, though; either a custom origin or an Amazon S3 origin, but not both. Request events The following topics show the structure of the object that CloudFront passes to a Lambda function for viewer and origin request events. These examples show a GET request with no body. Following the examples is a list of all the possible fields in viewer and origin request events. Topics • Example viewer request • Example origin request • Request event fields Example viewer request The following example shows a viewer request event object. { "Records": [ { "cf": { "config": { "distributionDomainName": "d111111abcdef8.cloudfront.net", "distributionId": "EDFDVBD6EXAMPLE", "eventType": "viewer-request", "requestId": "4TyzHTaYWb1GX1qTfsHhEqV6HUDd_BzoBZnwfnvQc_1oF26ClkoUSEQ==" }, "request": { "clientIp": "203.0.113.178", "headers": { "host": [ { "key": "Host", "value": "d111111abcdef8.cloudfront.net" Event structure 752 Amazon CloudFront Developer Guide } ], "user-agent": [ { "key": "User-Agent", "value": "curl/7.66.0" } ], "accept": [ { "key": "accept", "value": "*/*" } ] }, "method": "GET", "querystring": "", "uri": "/" } } } ] } Example origin request The following example shows an origin request event object. { "Records": [ { "cf": { "config": { "distributionDomainName": "d111111abcdef8.cloudfront.net", "distributionId": "EDFDVBD6EXAMPLE", "eventType": "origin-request", "requestId": "4TyzHTaYWb1GX1qTfsHhEqV6HUDd_BzoBZnwfnvQc_1oF26ClkoUSEQ==" }, "request": { "clientIp": "203.0.113.178", "headers": { "x-forwarded-for": [ { "key": "X-Forwarded-For", Event structure 753 Amazon CloudFront Developer Guide "value": "203.0.113.178" } ], "user-agent": [ { "key": "User-Agent", "value": "Amazon CloudFront" } ], "via": [ { "key": "Via", "value": "2.0 2afae0d44e2540f472c0635ab62c232b.cloudfront.net (CloudFront)" } ], "host": [ { "key": "Host", "value": "example.org" } ], "cache-control": [ { "key": "Cache-Control", "value": "no-cache" } ] }, "method": "GET", "origin": { "custom": { "customHeaders": {}, "domainName": "example.org", "keepaliveTimeout": 5, "path": "", "port": 443, "protocol": "https", "readTimeout": 30, "sslProtocols": [ "TLSv1", "TLSv1.1", "TLSv1.2" ] Event structure 754 Developer Guide Amazon CloudFront } }, "querystring": "", "uri": "/" } } } ] } Request event fields Request event object data is contained in two subobjects: config (Records.cf.config) and request (Records.cf.request). The following lists describe each subobject's fields. Fields in the config object The following list describes the fields in the config object (Records.cf.config). distributionDomainName (read-only) The domain name of the distribution that's associated with the request. distributionID (read-only) The ID of the distribution that's associated with the request. eventType (read-only) The type of trigger that's associated with the request: viewer-request or origin-request. requestId (read-only) An encrypted string that uniquely identifies a viewer-to-CloudFront request. The requestId value also appears in CloudFront access logs as x-edge-request-id. For more information, see Standard logging (access logs) and Log file fields. Fields in the request object The following list describes the fields in the request object (Records.cf.request). clientIp (read-only) The IP address of the viewer that made the request. If the viewer used an HTTP proxy or a load balancer to send the request, the value is the IP address of the proxy or load balancer. Event structure 755 Amazon CloudFront headers (read/write) Developer Guide The headers in the request. Note the following: • The keys in the headers object are lowercase versions of standard HTTP header names. Using lowercase keys gives you case-insensitive access to the header values. • Each header object (for example, headers["accept"] or headers["host"]) is an array of key–value pairs. For a given header, the array contains one key–value pair for each value in the request. • key contains the case-sensitive name of the header as it appeared in the HTTP request; for example, Host, User-Agent, X-Forwarded-For, Cookie, and so on. • value contains the header value
AmazonCloudFront_DevGuide-271
AmazonCloudFront_DevGuide.pdf
271
headers (read/write) Developer Guide The headers in the request. Note the following: • The keys in the headers object are lowercase versions of standard HTTP header names. Using lowercase keys gives you case-insensitive access to the header values. • Each header object (for example, headers["accept"] or headers["host"]) is an array of key–value pairs. For a given header, the array contains one key–value pair for each value in the request. • key contains the case-sensitive name of the header as it appeared in the HTTP request; for example, Host, User-Agent, X-Forwarded-For, Cookie, and so on. • value contains the header value as it appeared in the HTTP request. • When your Lambda function adds or modifies request headers and you don't include the header key field, Lambda@Edge automatically inserts a header key using the header name that you provide. Regardless of how you've formatted the header name, the header key that's inserted automatically is formatted with initial capitalization for each part, separated by hyphens (-). For example, you can add a header like the following, without a header key: "user-agent": [ { "value": "ExampleCustomUserAgent/1.X.0" } ] In this example, Lambda@Edge automatically inserts "key": "User-Agent". For information about restrictions on header usage, see Restrictions on edge functions. method (read-only) The HTTP method of the request. querystring (read/write) The query string, if any, in the request. If the request doesn't include a query string, the event object still includes querystring with an empty value. For more information about query strings, see Cache content based on query string parameters. Event structure 756 Amazon CloudFront uri (read/write) Developer Guide The relative path of the requested object. If your Lambda function modifies the uri value, note the following: • The new uri value must begin with a forward slash (/). • When a function changes the uri value, that changes the object that the viewer is requesting. • When a function changes the uri value, that doesn't change the cache behavior for the request or the origin that the request is sent to. body (read/write) The body of the HTTP request. The body structure can contain the following fields: inputTruncated (read-only) A Boolean flag that indicates whether the body was truncated by Lambda@Edge. For more information, see Restrictions on the request body with the include body option. action (read/write) The action that you intend to take with the body. The options for action are the following: • read-only: This is the default. When returning the response from the Lambda function, if action is read-only, Lambda@Edge ignores any changes to encoding or data. • replace: Specify this when you want to replace the body sent to the origin. encoding (read/write) The encoding for the body. When Lambda@Edge exposes the body to the Lambda function, it first converts the body to base64-encoding. If you choose replace for the action to replace the body, you can opt to use base64 (the default) or text encoding. If you specify encoding as base64 but the body is not valid base64, CloudFront returns an error. data (read/write) The request body content. origin (read/write) (origin events only) The origin to send the request to. The origin structure must contain exactly one origin, which can be a custom origin or an Amazon S3 origin. Depending on your origin type that you specify (custom or Amazon S3 origins), you must specify the following fields in your request: Event structure 757 Amazon CloudFront Developer Guide customHeaders (read/write) (custom and Amazon S3 origins) (Optional) You can include custom headers with the request by specifying a header name and value pair for each custom header. You can't add headers that are disallowed, and a header with the same name can't be present in Records.cf.request.headers. The notes about request headers also apply to custom headers. For more information, see Custom headers that CloudFront can’t add to origin requests and Restrictions on edge functions. domainName (read/write) (custom and Amazon S3 origins) The domain name of the origin. The domain name can't be empty. • For custom origins – Specify a DNS domain name, such as www.example.com. The domain name can't include a colon (:), and can't be an IP address. The domain name can be up to 253 characters. • For Amazon S3 origins – Specify the DNS domain name of the Amazon S3 bucket, such as amzn-s3-demo-bucket.s3.eu-west-1.amazonaws.com. The name can be up to 128 characters, and must be all lowercase. path (read/write) (custom and Amazon S3 origins) The directory path at the origin where the request should locate content. The path should start with a forward slash (/) but shouldn't end with one (for example, it shouldn't end with example-path/). For custom origins only, the path should be URL encoded and have a maximum length of 255 characters. keepaliveTimeout (read/write) (custom origins only) How long, in seconds, that CloudFront
AmazonCloudFront_DevGuide-272
AmazonCloudFront_DevGuide.pdf
272
For Amazon S3 origins – Specify the DNS domain name of the Amazon S3 bucket, such as amzn-s3-demo-bucket.s3.eu-west-1.amazonaws.com. The name can be up to 128 characters, and must be all lowercase. path (read/write) (custom and Amazon S3 origins) The directory path at the origin where the request should locate content. The path should start with a forward slash (/) but shouldn't end with one (for example, it shouldn't end with example-path/). For custom origins only, the path should be URL encoded and have a maximum length of 255 characters. keepaliveTimeout (read/write) (custom origins only) How long, in seconds, that CloudFront should try to maintain the connection to the origin after receiving the last packet of the response. The value must be a number from 1–60, inclusive. port (read/write) (custom origins only) The port that CloudFront should connect to at your custom origin. The port must be 80, 443, or a number in the range of 1024–65535, inclusive. protocol (read/write) (custom origins only) The connection protocol that CloudFront should use when connecting to your origin. The value can be http or https. Event structure 758 Amazon CloudFront Developer Guide readTimeout (read/write) (custom origins only) How long, in seconds, CloudFront should wait for a response after sending a request to your origin. This also specifies how long CloudFront should wait after receiving a packet of a response before receiving the next packet. The value must be a number from 4–60, inclusive. If your use case requires more than 60 seconds, you can request a higher quota for Response timeout per origin. For more information, see General quotas on distributions. sslProtocols (read/write) (custom origins only) The minimum SSL/TLS protocol that CloudFront can use when establishing an HTTPS connection with your origin. Values can be any of the following: TLSv1.2, TLSv1.1, TLSv1, or SSLv3. authMethod (read/write) (Amazon S3 origins only) If you're using an origin access identity (OAI), set this field to origin-access-identity. If you aren't using an OAI, set it to none. If you set authMethod to origin-access- identity, there are several requirements: • You must specify the region (see the following field). • You must use the same OAI when you change the request from one Amazon S3 origin to another. • You can't use an OAI when you change the request from a custom origin to an Amazon S3 origin. Note This field does not support origin access control (OAC). region (read/write) (Amazon S3 origins only) The AWS Region of your Amazon S3 bucket. This is required only when you set authMethod to origin-access-identity. Event structure 759 Amazon CloudFront Response events Developer Guide The following topics show the structure of the object that CloudFront passes to a Lambda function for viewer and origin response events. Following the examples is a list of all the possible fields in viewer and origin response events. Topics • Example origin response • Example viewer response • Response event fields Example origin response The following example shows an origin response event object. { "Records": [ { "cf": { "config": { "distributionDomainName": "d111111abcdef8.cloudfront.net", "distributionId": "EDFDVBD6EXAMPLE", "eventType": "origin-response", "requestId": "4TyzHTaYWb1GX1qTfsHhEqV6HUDd_BzoBZnwfnvQc_1oF26ClkoUSEQ==" }, "request": { "clientIp": "203.0.113.178", "headers": { "x-forwarded-for": [ { "key": "X-Forwarded-For", "value": "203.0.113.178" } ], "user-agent": [ { "key": "User-Agent", "value": "Amazon CloudFront" } ], "via": [ Event structure 760 Amazon CloudFront { Developer Guide "key": "Via", "value": "2.0 8f22423015641505b8c857a37450d6c0.cloudfront.net (CloudFront)" } ], "host": [ { "key": "Host", "value": "example.org" } ], "cache-control": [ { "key": "Cache-Control", "value": "no-cache" } ] }, "method": "GET", "origin": { "custom": { "customHeaders": {}, "domainName": "example.org", "keepaliveTimeout": 5, "path": "", "port": 443, "protocol": "https", "readTimeout": 30, "sslProtocols": [ "TLSv1", "TLSv1.1", "TLSv1.2" ] } }, "querystring": "", "uri": "/" }, "response": { "headers": { "access-control-allow-credentials": [ { "key": "Access-Control-Allow-Credentials", Event structure 761 Amazon CloudFront Developer Guide "value": "true" } ], "access-control-allow-origin": [ { "key": "Access-Control-Allow-Origin", "value": "*" } ], "date": [ { "key": "Date", "value": "Mon, 13 Jan 2020 20:12:38 GMT" } ], "referrer-policy": [ { "key": "Referrer-Policy", "value": "no-referrer-when-downgrade" } ], "server": [ { "key": "Server", "value": "ExampleCustomOriginServer" } ], "x-content-type-options": [ { "key": "X-Content-Type-Options", "value": "nosniff" } ], "x-frame-options": [ { "key": "X-Frame-Options", "value": "DENY" } ], "x-xss-protection": [ { "key": "X-XSS-Protection", "value": "1; mode=block" } Event structure 762 Developer Guide Amazon CloudFront ], "content-type": [ { "key": "Content-Type", "value": "text/html; charset=utf-8" } ], "content-length": [ { "key": "Content-Length", "value": "9593" } ] }, "status": "200", "statusDescription": "OK" } } } ] } Example viewer response The following example shows a viewer response event object. { "Records": [ { "cf": { "config": { "distributionDomainName": "d111111abcdef8.cloudfront.net", "distributionId": "EDFDVBD6EXAMPLE", "eventType": "viewer-response", "requestId": "4TyzHTaYWb1GX1qTfsHhEqV6HUDd_BzoBZnwfnvQc_1oF26ClkoUSEQ==" }, "request": { "clientIp": "203.0.113.178", "headers": { "host": [ { "key": "Host", "value": "d111111abcdef8.cloudfront.net" } Event structure 763 Amazon CloudFront ], "user-agent": [ { "key": "User-Agent", "value": "curl/7.66.0" } ], "accept": [ { "key": "accept", "value": "*/*" } ]
AmazonCloudFront_DevGuide-273
AmazonCloudFront_DevGuide.pdf
273
Guide Amazon CloudFront ], "content-type": [ { "key": "Content-Type", "value": "text/html; charset=utf-8" } ], "content-length": [ { "key": "Content-Length", "value": "9593" } ] }, "status": "200", "statusDescription": "OK" } } } ] } Example viewer response The following example shows a viewer response event object. { "Records": [ { "cf": { "config": { "distributionDomainName": "d111111abcdef8.cloudfront.net", "distributionId": "EDFDVBD6EXAMPLE", "eventType": "viewer-response", "requestId": "4TyzHTaYWb1GX1qTfsHhEqV6HUDd_BzoBZnwfnvQc_1oF26ClkoUSEQ==" }, "request": { "clientIp": "203.0.113.178", "headers": { "host": [ { "key": "Host", "value": "d111111abcdef8.cloudfront.net" } Event structure 763 Amazon CloudFront ], "user-agent": [ { "key": "User-Agent", "value": "curl/7.66.0" } ], "accept": [ { "key": "accept", "value": "*/*" } ] }, "method": "GET", "querystring": "", "uri": "/" }, "response": { "headers": { "access-control-allow-credentials": [ { "key": "Access-Control-Allow-Credentials", "value": "true" } ], "access-control-allow-origin": [ { "key": "Access-Control-Allow-Origin", "value": "*" } ], "date": [ { "key": "Date", "value": "Mon, 13 Jan 2020 20:14:56 GMT" } ], "referrer-policy": [ { "key": "Referrer-Policy", "value": "no-referrer-when-downgrade" } ], Event structure Developer Guide 764 Amazon CloudFront Developer Guide "server": [ { "key": "Server", "value": "ExampleCustomOriginServer" } ], "x-content-type-options": [ { "key": "X-Content-Type-Options", "value": "nosniff" } ], "x-frame-options": [ { "key": "X-Frame-Options", "value": "DENY" } ], "x-xss-protection": [ { "key": "X-XSS-Protection", "value": "1; mode=block" } ], "age": [ { "key": "Age", "value": "2402" } ], "content-type": [ { "key": "Content-Type", "value": "text/html; charset=utf-8" } ], "content-length": [ { "key": "Content-Length", "value": "9593" } ] }, "status": "200", Event structure 765 Amazon CloudFront Developer Guide "statusDescription": "OK" } } } ] } Response event fields Response event object data is contained in three subobjects: config (Records.cf.config), request (Records.cf.request), and response (Records.cf.response). For more information about the fields in the request object, see Fields in the request object. The following lists describe the fields in the config and response subobjects. Fields in the config object The following list describes the fields in the config object (Records.cf.config). distributionDomainName (read-only) The domain name of the distribution that's associated with the response. distributionID (read-only) The ID of the distribution that's associated with the response. eventType (read-only) The type of trigger that's associated with the response: origin-response or viewer- response. requestId (read-only) An encrypted string that uniquely identifies the viewer-to-CloudFront request that this response is associated with. The requestId value also appears in CloudFront access logs as x-edge-request-id. For more information, see Standard logging (access logs) and Log file fields. Fields in the response object The following list describes the fields in the response object (Records.cf.response). For information about using a Lambda@Edge function to generate an HTTP response, see Generate HTTP responses in request triggers. Event structure 766 Amazon CloudFront headers (read/write) Developer Guide The headers in the response. Note the following: • The keys in the headers object are lowercase versions of standard HTTP header names. Using lowercase keys gives you case-insensitive access to the header values. • Each header object (for example, headers["content-type"] or headers["content- length"]) is an array of key–value pairs. For a given header, the array contains one key– value pair for each value in the response. • key contains the case-sensitive name of the header as it appears in the HTTP response; for example, Content-Type, Content-Length, Cookie, and so on. • value contains the header value as it appears in the HTTP response. • When your Lambda function adds or modifies response headers and you don't include the header key field, Lambda@Edge automatically inserts a header key using the header name that you provide. Regardless of how you've formatted the header name, the header key that's inserted automatically is formatted with initial capitalization for each part, separated by hyphens (-). For example, you can add a header like the following, without a header key: "content-type": [ { "value": "text/html;charset=UTF-8" } ] In this example, Lambda@Edge automatically inserts "key": "Content-Type". For information about restrictions on header usage, see Restrictions on edge functions. status The HTTP status code of the response. statusDescription The HTTP status description of the response. Work with requests and responses To use Lambda@Edge requests and responses, see the following topics: Work with requests and responses 767 Developer Guide Amazon CloudFront Topics • Use Lambda@Edge functions with origin failover • Generate HTTP responses in request triggers • Update HTTP responses in origin response triggers • Access the request body by choosing the include body option Use Lambda@Edge functions with origin failover You can use Lambda@Edge functions with CloudFront distributions that you've set up with origin groups, for example, for origin failover that you configure to help ensure high availability. To use a Lambda function with an origin group, specify the function in an origin request or origin response trigger for an origin group when you create the cache behavior. For more information, see the following: • Create origin groups: Create an origin group • How origin failover works with Lambda@Edge: Use origin failover with Lambda@Edge functions Generate
AmazonCloudFront_DevGuide-274
AmazonCloudFront_DevGuide.pdf
274
request body by choosing the include body option Use Lambda@Edge functions with origin failover You can use Lambda@Edge functions with CloudFront distributions that you've set up with origin groups, for example, for origin failover that you configure to help ensure high availability. To use a Lambda function with an origin group, specify the function in an origin request or origin response trigger for an origin group when you create the cache behavior. For more information, see the following: • Create origin groups: Create an origin group • How origin failover works with Lambda@Edge: Use origin failover with Lambda@Edge functions Generate HTTP responses in request triggers When CloudFront receives a request, you can use a Lambda function to generate an HTTP response that CloudFront returns directly to the viewer without forwarding the response to the origin. Generating HTTP responses reduces the load on the origin, and typically also reduces latency for the viewer. Some common scenarios for generating HTTP responses include the following: • Returning a small webpage to the viewer • Returning an HTTP 301 or 302 status code to redirect the user to another webpage • Returning an HTTP 401 status code to the viewer when the user hasn't authenticated A Lambda@Edge function can generate an HTTP response when the following CloudFront events occur: Work with requests and responses 768 Amazon CloudFront Viewer request events Developer Guide When a function is triggered by a viewer request event, CloudFront returns the response to the viewer and doesn't cache it. Origin request events When a function is triggered by an origin request event, CloudFront checks the edge cache for a response that was previously generated by the function. • If the response is in the cache, the function isn't executed and CloudFront returns the cached response to the viewer. • If the response isn't in the cache, the function is executed, CloudFront returns the response to the viewer, and also caches it. To see some sample code for generating HTTP responses, see Lambda@Edge example functions. You can also replace the HTTP responses in response triggers. For more information, see Update HTTP responses in origin response triggers. Programming model This section describes the programming model for using Lambda@Edge to generate HTTP responses. Topics • Response object • Errors • Required fields Response object The response you return as the result parameter of the callback method should have the following structure (note that only the status field is required). const response = { body: 'content', bodyEncoding: 'text' | 'base64', headers: { 'header name in lowercase': [{ key: 'header name in standard case', Work with requests and responses 769 Amazon CloudFront Developer Guide value: 'header value' }], ... }, status: 'HTTP status code (string)', statusDescription: 'status description' }; The response object can include the following values: body The body, if any, that you want CloudFront to return in the generated response. bodyEncoding The encoding for the value that you specified in the body. The only valid encodings are text and base64. If you include body in the response object but omit bodyEncoding, CloudFront treats the body as text. If you specify bodyEncoding as base64 but the body is not valid base64, CloudFront returns an error. headers Headers that you want CloudFront to return in the generated response. Note the following: • The keys in the headers object are lowercase versions of standard HTTP header names. Using lowercase keys gives you case-insensitive access to the header values. • Each header (for example, headers["accept"] or headers["host"]) is an array of key- value pairs. For a given header, the array contains one key-value pair for each value in the generated response. • key (optional) is the case-sensitive name of the header as it appears in an HTTP request; for example, accept or host. • Specify value as a header value. • If you do not include the header key portion of the key-value pair, Lambda@Edge automatically inserts a header key using the header name that you provide. Regardless of how you've formatted the header name, the header key that is inserted is automatically formatted with initial capitalization for each part, separated by hyphens (-). For example, you can add a header like the following, without a header key: 'content- type': [{ value: 'text/html;charset=UTF-8' }] Work with requests and responses 770 Amazon CloudFront Developer Guide In this example, Lambda@Edge creates the following header key: Content-Type. For information about restrictions on header usage, see Restrictions on edge functions. status The HTTP status code. Provide the status code as a string. CloudFront uses the provided status code for the following: • Return in the response • Cache in the CloudFront edge cache, when the response was generated by a function that was triggered by an origin request event • Log in CloudFront Standard logging (access logs) If the status value
AmazonCloudFront_DevGuide-275
AmazonCloudFront_DevGuide.pdf
275
key: 'content- type': [{ value: 'text/html;charset=UTF-8' }] Work with requests and responses 770 Amazon CloudFront Developer Guide In this example, Lambda@Edge creates the following header key: Content-Type. For information about restrictions on header usage, see Restrictions on edge functions. status The HTTP status code. Provide the status code as a string. CloudFront uses the provided status code for the following: • Return in the response • Cache in the CloudFront edge cache, when the response was generated by a function that was triggered by an origin request event • Log in CloudFront Standard logging (access logs) If the status value isn't between 200 and 599, CloudFront returns an error to the viewer. statusDescription The description that you want CloudFront to return in the response, to accompany the HTTP status code. You don't need to use standard descriptions, such as OK for an HTTP status code of 200. Errors The following are possible errors for generated HTTP responses. Response Contains a Body and Specifies 204 (No Content) for Status When a function is triggered by a viewer request, CloudFront returns an HTTP 502 status code (Bad Gateway) to the viewer when both of the following are true: • The value of status is 204 (No Content) • The response includes a value for body This is because Lambda@Edge imposes the optional restriction found in RFC 2616, which states that an HTTP 204 response does not need to contain a message body. Restrictions on the Size of the Generated Response The maximum size of a response that is generated by a Lambda function depends on the event that triggered the function: • Viewer request events – 40 KB Work with requests and responses 771 Amazon CloudFront Developer Guide • Origin request events – 1 MB If the response is larger than the allowed size, CloudFront returns an HTTP 502 status code (Bad Gateway) to the viewer. Required fields The status field is required. All other fields are optional. Update HTTP responses in origin response triggers When CloudFront receives an HTTP response from the origin server, if there is an origin-response trigger associated with the cache behavior, you can modify the HTTP response to override what was returned from the origin. Some common scenarios for updating HTTP responses include the following: • Changing the status to set an HTTP 200 status code and creating static body content to return to the viewer when an origin returns an error status code (4xx or 5xx). For sample code, see Example: Use an origin response trigger to update the error status code to 200. • Changing the status to set an HTTP 301 or HTTP 302 status code, to redirect the user to another website when an origin returns an error status code (4xx or 5xx). For sample code, see Example: Use an origin response trigger to update the error status code to 302. Note The function must return a status value between 200 and 599 (inclusive), otherwise CloudFront returns an error to the viewer. You can also replace the HTTP responses in viewer and origin request events. For more information, see Generate HTTP responses in request triggers. When you're working with the HTTP response, Lambda@Edge does not expose the body that is returned by the origin server to the origin-response trigger. You can generate a static content body by setting it to the desired value, or remove the body inside the function by setting the value to be Work with requests and responses 772 Amazon CloudFront Developer Guide empty. If you don't update the body field in your function, the original body returned by the origin server is returned back to viewer. Access the request body by choosing the include body option You can opt to have Lambda@Edge expose the body in a request for writable HTTP methods (POST, PUT, DELETE, and so on), so that you can access it in your Lambda function. You can choose read-only access, or you can specify that you'll replace the body. To enable this option, choose Include Body when you create a CloudFront trigger for your function that's for a viewer request or origin request event. For more information, see Add triggers for a Lambda@Edge function, or to learn about using Include Body with your function, see Lambda@Edge event structure. Scenarios when you might want to use this feature include the following: • Processing web forms, like "contact us" forms, without sending customer input data back to origin servers. • Gathering web beacon data that's sent by viewer browsers and processing it at the edge. For sample code, see Lambda@Edge example functions. Note If the request body is large, Lambda@Edge truncates it. For detailed information about the maximum size and truncation, see Restrictions on the request body with the include body option. Lambda@Edge example functions See the following
AmazonCloudFront_DevGuide-276
AmazonCloudFront_DevGuide.pdf
276
learn about using Include Body with your function, see Lambda@Edge event structure. Scenarios when you might want to use this feature include the following: • Processing web forms, like "contact us" forms, without sending customer input data back to origin servers. • Gathering web beacon data that's sent by viewer browsers and processing it at the edge. For sample code, see Lambda@Edge example functions. Note If the request body is large, Lambda@Edge truncates it. For detailed information about the maximum size and truncation, see Restrictions on the request body with the include body option. Lambda@Edge example functions See the following examples to use Lambda functions with Amazon CloudFront. Note If you choose runtime Node.js 18 or later for your Lambda@Edge function, an index.mjs file is created for you automatically. To use the following code examples, rename the index.mjs file to index.js instead. Example functions 773 Developer Guide Amazon CloudFront Topics • General examples • Generate responses - examples • Query strings - examples • Personalize content by country or device type headers - examples • Content-based dynamic origin selection - examples • Update error statuses - examples • Access the request body - examples General examples The following examples show common ways to use Lambda@Edge in CloudFront. Topics • Example: A/B testing • Example: Override a response header Example: A/B testing You can use the following example to test two different versions of an image without creating redirects or changing the URL. This example reads the cookies in the viewer request and modifies the request URL accordingly. If the viewer doesn't send a cookie with one of the expected values, the example randomly assigns the viewer to one of the URLs. Node.js 'use strict'; exports.handler = (event, context, callback) => { const request = event.Records[0].cf.request; const headers = request.headers; if (request.uri !== '/experiment-pixel.jpg') { // do not process if this is not an A-B test request callback(null, request); return; } Example functions 774 Amazon CloudFront Developer Guide const cookieExperimentA = 'X-Experiment-Name=A'; const cookieExperimentB = 'X-Experiment-Name=B'; const pathExperimentA = '/experiment-group/control-pixel.jpg'; const pathExperimentB = '/experiment-group/treatment-pixel.jpg'; /* * Lambda at the Edge headers are array objects. * * Client may send multiple Cookie headers, i.e.: * > GET /viewerRes/test HTTP/1.1 * > User-Agent: curl/7.18.1 (x86_64-unknown-linux-gnu) libcurl/7.18.1 OpenSSL/1.0.1u zlib/1.2.3 * > Cookie: First=1; Second=2 * > Cookie: ClientCode=abc * > Host: example.com * * You can access the first Cookie header at headers["cookie"][0].value * and the second at headers["cookie"][1].value. * * Header values are not parsed. In the example above, * headers["cookie"][0].value is equal to "First=1; Second=2" */ let experimentUri; if (headers.cookie) { for (let i = 0; i < headers.cookie.length; i++) { if (headers.cookie[i].value.indexOf(cookieExperimentA) >= 0) { console.log('Experiment A cookie found'); experimentUri = pathExperimentA; break; } else if (headers.cookie[i].value.indexOf(cookieExperimentB) >= 0) { console.log('Experiment B cookie found'); experimentUri = pathExperimentB; break; } } } if (!experimentUri) { console.log('Experiment cookie has not been found. Throwing dice...'); if (Math.random() < 0.75) { experimentUri = pathExperimentA; } else { experimentUri = pathExperimentB; } Example functions 775 Amazon CloudFront } Developer Guide request.uri = experimentUri; console.log(`Request uri set to "${request.uri}"`); callback(null, request); }; Python import json import random def lambda_handler(event, context): request = event['Records'][0]['cf']['request'] headers = request['headers'] if request['uri'] != '/experiment-pixel.jpg': # Not an A/B Test return request cookieExperimentA, cookieExperimentB = 'X-Experiment-Name=A', 'X-Experiment- Name=B' pathExperimentA, pathExperimentB = '/experiment-group/control-pixel.jpg', '/ experiment-group/treatment-pixel.jpg' ''' Lambda at the Edge headers are array objects. Client may send multiple cookie headers. For example: > GET /viewerRes/test HTTP/1.1 > User-Agent: curl/7.18.1 (x86_64-unknown-linux-gnu) libcurl/7.18.1 OpenSSL/1.0.1u zlib/1.2.3 > Cookie: First=1; Second=2 > Cookie: ClientCode=abc > Host: example.com You can access the first Cookie header at headers["cookie"][0].value and the second at headers["cookie"][1].value. Header values are not parsed. In the example above, headers["cookie"][0].value is equal to "First=1; Second=2" ''' Example functions 776 Amazon CloudFront experimentUri = "" Developer Guide for cookie in headers.get('cookie', []): if cookieExperimentA in cookie['value']: print("Experiment A cookie found") experimentUri = pathExperimentA break elif cookieExperimentB in cookie['value']: print("Experiment B cookie found") experimentUri = pathExperimentB break if not experimentUri: print("Experiment cookie has not been found. Throwing dice...") if random.random() < 0.75: experimentUri = pathExperimentA else: experimentUri = pathExperimentB request['uri'] = experimentUri print(f"Request uri set to {experimentUri}") return request Example: Override a response header The following example shows how to change the value of a response header based on the value of another header. Node.js 'use strict'; exports.handler = (event, context, callback) => { const response = event.Records[0].cf.response; const headers = response.headers; const headerNameSrc = 'X-Amz-Meta-Last-Modified'; const headerNameDst = 'Last-Modified'; if (headers[headerNameSrc.toLowerCase()]) { headers[headerNameDst.toLowerCase()] = [ headers[headerNameSrc.toLowerCase()][0], Example functions 777 Amazon CloudFront ]; Developer Guide console.log(`Response header "${headerNameDst}" was set to ` + `"${headers[headerNameDst.toLowerCase()][0].value}"`); } callback(null, response); }; Python import json def lambda_handler(event, context): response = event["Records"][0]["cf"]["response"] headers = response["headers"] headerNameSrc = "X-Amz-Meta-Last-Modified" headerNameDst = "Last-Modified" if headers.get(headerNameSrc.lower(), None): headers[headerNameDst.lower()] = [headers[headerNameSrc.lower()][0]] print(f"Response header {headerNameDst.lower()} was set to
AmazonCloudFront_DevGuide-277
AmazonCloudFront_DevGuide.pdf
277
how to change the value of a response header based on the value of another header. Node.js 'use strict'; exports.handler = (event, context, callback) => { const response = event.Records[0].cf.response; const headers = response.headers; const headerNameSrc = 'X-Amz-Meta-Last-Modified'; const headerNameDst = 'Last-Modified'; if (headers[headerNameSrc.toLowerCase()]) { headers[headerNameDst.toLowerCase()] = [ headers[headerNameSrc.toLowerCase()][0], Example functions 777 Amazon CloudFront ]; Developer Guide console.log(`Response header "${headerNameDst}" was set to ` + `"${headers[headerNameDst.toLowerCase()][0].value}"`); } callback(null, response); }; Python import json def lambda_handler(event, context): response = event["Records"][0]["cf"]["response"] headers = response["headers"] headerNameSrc = "X-Amz-Meta-Last-Modified" headerNameDst = "Last-Modified" if headers.get(headerNameSrc.lower(), None): headers[headerNameDst.lower()] = [headers[headerNameSrc.lower()][0]] print(f"Response header {headerNameDst.lower()} was set to {headers[headerNameSrc.lower()][0]}") return response Generate responses - examples The following examples show how you can use Lambda@Edge to generate responses. Topics • Example: Serve static content (generated response) • Example: Generate an HTTP redirect (generated response) Example: Serve static content (generated response) The following example shows how to use a Lambda function to serve static website content, which reduces the load on the origin server and reduces overall latency. Example functions 778 Amazon CloudFront Note Developer Guide You can generate HTTP responses for viewer request and origin request events. For more information, see the section called “Generate HTTP responses in request triggers”. You can also replace or remove the body of the HTTP response in origin response events. For more information, see the section called “Update HTTP responses in origin response triggers”. Node.js 'use strict'; const content = ` <\!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Simple Lambda@Edge Static Content Response</title> </head> <body> <p>Hello from Lambda@Edge!</p> </body> </html> `; exports.handler = (event, context, callback) => { /* * Generate HTTP OK response using 200 status code with HTML body. */ const response = { status: '200', statusDescription: 'OK', headers: { 'cache-control': [{ key: 'Cache-Control', value: 'max-age=100' }], 'content-type': [{ key: 'Content-Type', value: 'text/html' }] Example functions 779 Amazon CloudFront Developer Guide }, body: content, }; callback(null, response); }; Python import json CONTENT = """ <\!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Simple Lambda@Edge Static Content Response</title> </head> <body> <p>Hello from Lambda@Edge!</p> </body> </html> """ def lambda_handler(event, context): # Generate HTTP OK response using 200 status code with HTML body. response = { 'status': '200', 'statusDescription': 'OK', 'headers': { 'cache-control': [ { 'key': 'Cache-Control', 'value': 'max-age=100' } ], "content-type": [ { 'key': 'Content-Type', 'value': 'text/html' } ] }, 'body': CONTENT Example functions 780 Amazon CloudFront } return response Developer Guide Example: Generate an HTTP redirect (generated response) The following example shows how to generate an HTTP redirect. Note You can generate HTTP responses for viewer request and origin request events. For more information, see Generate HTTP responses in request triggers. Node.js 'use strict'; exports.handler = (event, context, callback) => { /* * Generate HTTP redirect response with 302 status code and Location header. */ const response = { status: '302', statusDescription: 'Found', headers: { location: [{ key: 'Location', value: 'https://docs.aws.amazon.com/lambda/latest/dg/lambda- edge.html', }], }, }; callback(null, response); }; Python def lambda_handler(event, context): # Generate HTTP redirect response with 302 status code and Location header. Example functions 781 Amazon CloudFront response = { 'status': '302', 'statusDescription': 'Found', 'headers': { 'location': [{ 'key': 'Location', Developer Guide 'value': 'https://docs.aws.amazon.com/lambda/latest/dg/lambda- edge.html' }] } } return response Query strings - examples The following examples show ways that you can use Lambda@Edge with query strings. Topics • Example: Add a header based on a query string parameter • Example: Normalize query string parameters to improve the cache hit ratio • Example: Redirect unauthenticated users to a sign-in page Example: Add a header based on a query string parameter The following example shows how to get the key-value pair of a query string parameter, and then add a header based on those values. Node.js 'use strict'; const querystring = require('querystring'); exports.handler = (event, context, callback) => { const request = event.Records[0].cf.request; /* When a request contains a query string key-value pair but the origin server * expects the value in a header, you can use this Lambda function to * convert the key-value pair to a header. Here's what the function does: * 1. Parses the query string and gets the key-value pair. Example functions 782 Amazon CloudFront Developer Guide * 2. Adds a header to the request using the key-value pair that the function got in step 1. */ /* Parse request querystring to get javascript object */ const params = querystring.parse(request.querystring); /* Move auth param from querystring to headers */ const headerName = 'Auth-Header'; request.headers[headerName.toLowerCase()] = [{ key: headerName, value: params.auth }]; delete params.auth; /* Update request querystring */ request.querystring = querystring.stringify(params); callback(null, request); }; Python from urllib.parse import parse_qs, urlencode def lambda_handler(event, context): request = event['Records'][0]['cf']['request'] ''' When a request contains a query string key-value pair but the origin server expects the value in a header, you can use this Lambda function to convert the key-value pair
AmazonCloudFront_DevGuide-278
AmazonCloudFront_DevGuide.pdf
278
key-value pair that the function got in step 1. */ /* Parse request querystring to get javascript object */ const params = querystring.parse(request.querystring); /* Move auth param from querystring to headers */ const headerName = 'Auth-Header'; request.headers[headerName.toLowerCase()] = [{ key: headerName, value: params.auth }]; delete params.auth; /* Update request querystring */ request.querystring = querystring.stringify(params); callback(null, request); }; Python from urllib.parse import parse_qs, urlencode def lambda_handler(event, context): request = event['Records'][0]['cf']['request'] ''' When a request contains a query string key-value pair but the origin server expects the value in a header, you can use this Lambda function to convert the key-value pair to a header. Here's what the function does: 1. Parses the query string and gets the key-value pair. 2. Adds a header to the request using the key-value pair that the function got in step 1. ''' # Parse request querystring to get dictionary/json params = {k : v[0] for k, v in parse_qs(request['querystring']).items()} # Move auth param from querystring to headers headerName = 'Auth-Header' request['headers'][headerName.lower()] = [{'key': headerName, 'value': params['auth']}] del params['auth'] Example functions 783 Amazon CloudFront Developer Guide # Update request querystring request['querystring'] = urlencode(params) return request Example: Normalize query string parameters to improve the cache hit ratio The following example shows how to improve your cache hit ratio by making the following changes to query strings before CloudFront forwards requests to your origin: • Alphabetize key-value pairs by the name of the parameter. • Change the case of key-value pairs to lowercase. For more information, see Cache content based on query string parameters. Node.js 'use strict'; const querystring = require('querystring'); exports.handler = (event, context, callback) => { const request = event.Records[0].cf.request; /* When you configure a distribution to forward query strings to the origin and * to cache based on an allowlist of query string parameters, we recommend * the following to improve the cache-hit ratio: * - Always list parameters in the same order. * - Use the same case for parameter names and values. * * This function normalizes query strings so that parameter names and values * are lowercase and parameter names are in alphabetical order. * * For more information, see: * https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/ QueryStringParameters.html */ console.log('Query String: ', request.querystring); /* Parse request query string to get javascript object */ Example functions 784 Amazon CloudFront Developer Guide const params = querystring.parse(request.querystring.toLowerCase()); const sortedParams = {}; /* Sort param keys */ Object.keys(params).sort().forEach(key => { sortedParams[key] = params[key]; }); /* Update request querystring with normalized */ request.querystring = querystring.stringify(sortedParams); callback(null, request); }; Python from urllib.parse import parse_qs, urlencode def lambda_handler(event, context): request = event['Records'][0]['cf']['request'] ''' When you configure a distribution to forward query strings to the origin and to cache based on an allowlist of query string parameters, we recommend the following to improve the cache-hit ratio: Always list parameters in the same order. - Use the same case for parameter names and values. This function normalizes query strings so that parameter names and values are lowercase and parameter names are in alphabetical order. For more information, see: https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/ QueryStringParameters.html ''' print("Query string: ", request["querystring"]) # Parse request query string to get js object params = {k : v[0] for k, v in parse_qs(request['querystring'].lower()).items()} # Sort param keys sortedParams = sorted(params.items(), key=lambda x: x[0]) # Update request querystring with normalized Example functions 785 Amazon CloudFront Developer Guide request['querystring'] = urlencode(sortedParams) return request Example: Redirect unauthenticated users to a sign-in page The following example shows how to redirect users to a sign-in page if they haven't entered their credentials. Node.js 'use strict'; function parseCookies(headers) { const parsedCookie = {}; if (headers.cookie) { headers.cookie[0].value.split(';').forEach((cookie) => { if (cookie) { const parts = cookie.split('='); parsedCookie[parts[0].trim()] = parts[1].trim(); } }); } return parsedCookie; } exports.handler = (event, context, callback) => { const request = event.Records[0].cf.request; const headers = request.headers; /* Check for session-id in request cookie in viewer-request event, * if session-id is absent, redirect the user to sign in page with original * request sent as redirect_url in query params. */ /* Check for session-id in cookie, if present then proceed with request */ const parsedCookies = parseCookies(headers); if (parsedCookies && parsedCookies['session-id']) { callback(null, request); return; } Example functions 786 Amazon CloudFront Developer Guide /* URI encode the original request to be sent as redirect_url in query params */ const encodedRedirectUrl = encodeURIComponent(`https:// ${headers.host[0].value}${request.uri}?${request.querystring}`); const response = { status: '302', statusDescription: 'Found', headers: { location: [{ key: 'Location', value: `https://www.example.com/signin?redirect_url= ${encodedRedirectUrl}`, }], }, }; callback(null, response); }; Python import urllib def parseCookies(headers): parsedCookie = {} if headers.get('cookie'): for cookie in headers['cookie'][0]['value'].split(';'): if cookie: parts = cookie.split('=') parsedCookie[parts[0].strip()] = parts[1].strip() return parsedCookie def lambda_handler(event, context): request = event['Records'][0]['cf']['request'] headers = request['headers'] ''' Check for session-id in request cookie in viewer-request event, if session-id is absent, redirect the user to sign in page with original request sent as redirect_url in query
AmazonCloudFront_DevGuide-279
AmazonCloudFront_DevGuide.pdf
279
request to be sent as redirect_url in query params */ const encodedRedirectUrl = encodeURIComponent(`https:// ${headers.host[0].value}${request.uri}?${request.querystring}`); const response = { status: '302', statusDescription: 'Found', headers: { location: [{ key: 'Location', value: `https://www.example.com/signin?redirect_url= ${encodedRedirectUrl}`, }], }, }; callback(null, response); }; Python import urllib def parseCookies(headers): parsedCookie = {} if headers.get('cookie'): for cookie in headers['cookie'][0]['value'].split(';'): if cookie: parts = cookie.split('=') parsedCookie[parts[0].strip()] = parts[1].strip() return parsedCookie def lambda_handler(event, context): request = event['Records'][0]['cf']['request'] headers = request['headers'] ''' Check for session-id in request cookie in viewer-request event, if session-id is absent, redirect the user to sign in page with original request sent as redirect_url in query params. ''' # Check for session-id in cookie, if present, then proceed with request parsedCookies = parseCookies(headers) Example functions 787 Amazon CloudFront Developer Guide if parsedCookies and parsedCookies['session-id']: return request # URI encode the original request to be sent as redirect_url in query params redirectUrl = "https://%s%s?%s" % (headers['host'][0]['value'], request['uri'], request['querystring']) encodedRedirectUrl = urllib.parse.quote_plus(redirectUrl.encode('utf-8')) response = { 'status': '302', 'statusDescription': 'Found', 'headers': { 'location': [{ 'key': 'Location', 'value': 'https://www.example.com/signin?redirect_url=%s' % encodedRedirectUrl }] } } return response Personalize content by country or device type headers - examples The following examples show how you can use Lambda@Edge to customize behavior based on location or the type of device used by the viewer. Topics • Example: Redirect viewer requests to a country-specific URL • Example: Serve different versions of an object based on the device Example: Redirect viewer requests to a country-specific URL The following example shows how to generate an HTTP redirect response with a country-specific URL and return the response to the viewer. This is useful when you want to provide country- specific responses. For example: • If you have country-specific subdomains, such as us.example.com and tw.example.com, you can generate a redirect response when a viewer requests example.com. • If you're streaming video but you don't have rights to stream the content in a specific country, you can redirect users in that country to a page that explains why they can't view the video. Example functions 788 Amazon CloudFront Note the following: Developer Guide • You must configure your distribution to cache based on the CloudFront-Viewer-Country header. For more information, see Cache based on selected request headers. • CloudFront adds the CloudFront-Viewer-Country header after the viewer request event. To use this example, you must create a trigger for the origin request event. Node.js 'use strict'; /* This is an origin request function */ exports.handler = (event, context, callback) => { const request = event.Records[0].cf.request; const headers = request.headers; /* * Based on the value of the CloudFront-Viewer-Country header, generate an * HTTP status code 302 (Redirect) response, and return a country-specific * URL in the Location header. * NOTE: 1. You must configure your distribution to cache based on the * CloudFront-Viewer-Country header. For more information, see * https://docs.aws.amazon.com/console/cloudfront/cache-on-selected- headers * 2. CloudFront adds the CloudFront-Viewer-Country header after the viewer * request event. To use this example, you must create a trigger for the * origin request event. */ let url = 'https://example.com/'; if (headers['cloudfront-viewer-country']) { const countryCode = headers['cloudfront-viewer-country'][0].value; if (countryCode === 'TW') { url = 'https://tw.example.com/'; } else if (countryCode === 'US') { url = 'https://us.example.com/'; } } const response = { Example functions 789 Amazon CloudFront Developer Guide status: '302', statusDescription: 'Found', headers: { location: [{ key: 'Location', value: url, }], }, }; callback(null, response); }; Python # This is an origin request function def lambda_handler(event, context): request = event['Records'][0]['cf']['request'] headers = request['headers'] ''' Based on the value of the CloudFront-Viewer-Country header, generate an HTTP status code 302 (Redirect) response, and return a country-specific URL in the Location header. NOTE: 1. You must configure your distribution to cache based on the CloudFront-Viewer-Country header. For more information, see https://docs.aws.amazon.com/console/cloudfront/cache-on-selected-headers 2. CloudFront adds the CloudFront-Viewer-Country header after the viewer request event. To use this example, you must create a trigger for the origin request event. ''' url = 'https://example.com/' viewerCountry = headers.get('cloudfront-viewer-country') if viewerCountry: countryCode = viewerCountry[0]['value'] if countryCode == 'TW': url = 'https://tw.example.com/' elif countryCode == 'US': url = 'https://us.example.com/' response = { 'status': '302', Example functions 790 Amazon CloudFront Developer Guide 'statusDescription': 'Found', 'headers': { 'location': [{ 'key': 'Location', 'value': url }] } } return response Example: Serve different versions of an object based on the device The following example shows how to serve different versions of an object based on the type of device that the user is using, for example, a mobile device or a tablet. Note the following: • You must configure your distribution to cache based on the CloudFront-Is-*-Viewer headers. For more information, see Cache based on selected request headers. • CloudFront adds the CloudFront-Is-*-Viewer headers after the viewer request event. To use this example, you must create a trigger for the origin request event. Node.js 'use strict'; /* This is an origin request
AmazonCloudFront_DevGuide-280
AmazonCloudFront_DevGuide.pdf
280
different versions of an object based on the device The following example shows how to serve different versions of an object based on the type of device that the user is using, for example, a mobile device or a tablet. Note the following: • You must configure your distribution to cache based on the CloudFront-Is-*-Viewer headers. For more information, see Cache based on selected request headers. • CloudFront adds the CloudFront-Is-*-Viewer headers after the viewer request event. To use this example, you must create a trigger for the origin request event. Node.js 'use strict'; /* This is an origin request function */ exports.handler = (event, context, callback) => { const request = event.Records[0].cf.request; const headers = request.headers; /* * Serve different versions of an object based on the device type. * NOTE: 1. You must configure your distribution to cache based on the * CloudFront-Is-*-Viewer headers. For more information, see * the following documentation: * https://docs.aws.amazon.com/console/cloudfront/cache-on-selected- headers * https://docs.aws.amazon.com/console/cloudfront/cache-on-device-type * 2. CloudFront adds the CloudFront-Is-*-Viewer headers after the viewer * request event. To use this example, you must create a trigger for the Example functions 791 Amazon CloudFront Developer Guide * origin request event. */ const desktopPath = '/desktop'; const mobilePath = '/mobile'; const tabletPath = '/tablet'; const smarttvPath = '/smarttv'; if (headers['cloudfront-is-desktop-viewer'] && headers['cloudfront-is-desktop-viewer'][0].value === 'true') { request.uri = desktopPath + request.uri; } else if (headers['cloudfront-is-mobile-viewer'] && headers['cloudfront-is-mobile-viewer'][0].value === 'true') { request.uri = mobilePath + request.uri; } else if (headers['cloudfront-is-tablet-viewer'] && headers['cloudfront-is-tablet-viewer'][0].value === 'true') { request.uri = tabletPath + request.uri; } else if (headers['cloudfront-is-smarttv-viewer'] && headers['cloudfront-is-smarttv-viewer'][0].value === 'true') { request.uri = smarttvPath + request.uri; } console.log(`Request uri set to "${request.uri}"`); callback(null, request); }; Python # This is an origin request function def lambda_handler(event, context): request = event['Records'][0]['cf']['request'] headers = request['headers'] ''' Serve different versions of an object based on the device type. NOTE: 1. You must configure your distribution to cache based on the CloudFront-Is-*-Viewer headers. For more information, see the following documentation: https://docs.aws.amazon.com/console/cloudfront/cache-on-selected-headers https://docs.aws.amazon.com/console/cloudfront/cache-on-device-type 2. CloudFront adds the CloudFront-Is-*-Viewer headers after the viewer request event. To use this example, you must create a trigger for the origin request event. Example functions 792 Amazon CloudFront ''' desktopPath = '/desktop'; mobilePath = '/mobile'; tabletPath = '/tablet'; smarttvPath = '/smarttv'; Developer Guide if 'cloudfront-is-desktop-viewer' in headers and headers['cloudfront-is-desktop- viewer'][0]['value'] == 'true': request['uri'] = desktopPath + request['uri'] elif 'cloudfront-is-mobile-viewer' in headers and headers['cloudfront-is-mobile- viewer'][0]['value'] == 'true': request['uri'] = mobilePath + request['uri'] elif 'cloudfront-is-tablet-viewer' in headers and headers['cloudfront-is-tablet- viewer'][0]['value'] == 'true': request['uri'] = tabletPath + request['uri'] elif 'cloudfront-is-smarttv-viewer' in headers and headers['cloudfront-is- smarttv-viewer'][0]['value'] == 'true': request['uri'] = smarttvPath + request['uri'] print("Request uri set to %s" % request['uri']) return request Content-based dynamic origin selection - examples The following examples show how you can use Lambda@Edge to route to different origins based on information in the request. Topics • Example: Use an origin request trigger to change from a custom origin to an Amazon S3 origin • Example: Use an origin-request trigger to change the Amazon S3 origin Region • Example: Use an origin request trigger to change from an Amazon S3 origin to a custom origin • Example: Use an origin request trigger to gradually transfer traffic from one Amazon S3 bucket to another • Example: Use an origin request trigger to change the origin domain name based on the country header Example functions 793 Amazon CloudFront Developer Guide Example: Use an origin request trigger to change from a custom origin to an Amazon S3 origin This function demonstrates how an origin-request trigger can be used to change from a custom origin to an Amazon S3 origin from which the content is fetched, based on request properties. Node.js 'use strict'; const querystring = require('querystring'); exports.handler = (event, context, callback) => { const request = event.Records[0].cf.request; /** * Reads query string to check if S3 origin should be used, and * if true, sets S3 origin properties. */ const params = querystring.parse(request.querystring); if (params['useS3Origin']) { if (params['useS3Origin'] === 'true') { const s3DomainName = 'amzn-s3-demo-bucket.s3.amazonaws.com'; /* Set S3 origin fields */ request.origin = { s3: { domainName: s3DomainName, region: '', authMethod: 'none', path: '', customHeaders: {} } }; request.headers['host'] = [{ key: 'host', value: s3DomainName}]; } } callback(null, request); }; Example functions 794 Amazon CloudFront Python from urllib.parse import parse_qs Developer Guide def lambda_handler(event, context): request = event['Records'][0]['cf']['request'] ''' Reads query string to check if S3 origin should be used, and if true, sets S3 origin properties ''' params = {k: v[0] for k, v in parse_qs(request['querystring']).items()} if params.get('useS3Origin') == 'true': s3DomainName = 'amzn-s3-demo-bucket.s3.amazonaws.com' # Set S3 origin fields request['origin'] = { 's3': { 'domainName': s3DomainName, 'region': '', 'authMethod': 'none', 'path': '', 'customHeaders': {} } } request['headers']['host'] = [{'key': 'host', 'value': s3DomainName}] return request Example: Use an origin-request trigger to change the Amazon S3 origin Region This function demonstrates how an origin-request trigger can be used
AmazonCloudFront_DevGuide-281
AmazonCloudFront_DevGuide.pdf
281
from urllib.parse import parse_qs Developer Guide def lambda_handler(event, context): request = event['Records'][0]['cf']['request'] ''' Reads query string to check if S3 origin should be used, and if true, sets S3 origin properties ''' params = {k: v[0] for k, v in parse_qs(request['querystring']).items()} if params.get('useS3Origin') == 'true': s3DomainName = 'amzn-s3-demo-bucket.s3.amazonaws.com' # Set S3 origin fields request['origin'] = { 's3': { 'domainName': s3DomainName, 'region': '', 'authMethod': 'none', 'path': '', 'customHeaders': {} } } request['headers']['host'] = [{'key': 'host', 'value': s3DomainName}] return request Example: Use an origin-request trigger to change the Amazon S3 origin Region This function demonstrates how an origin-request trigger can be used to change the Amazon S3 origin from which the content is fetched, based on request properties. In this example, we use the value of the CloudFront-Viewer-Country header to update the S3 bucket domain name to a bucket in a Region that is closer to the viewer. This can be useful in several ways: • It reduces latencies when the Region specified is nearer to the viewer's country. • It provides data sovereignty by making sure that data is served from an origin that's in the same country that the request came from. Example functions 795 Amazon CloudFront Developer Guide To use this example, you must do the following: • Configure your distribution to cache based on the CloudFront-Viewer-Country header. For more information, see Cache based on selected request headers. • Create a trigger for this function in the origin request event. CloudFront adds the CloudFront- Viewer-Country header after the viewer request event, so to use this example, you must make sure that the function executes for an origin request. Note The following example code uses the same origin access identity (OAI) for all S3 buckets that you're using for your origin. For more information, see Origin access identity. Node.js 'use strict'; exports.handler = (event, context, callback) => { const request = event.Records[0].cf.request; /** * This blueprint demonstrates how an origin-request trigger can be used to * change the origin from which the content is fetched, based on request properties. * In this example, we use the value of the CloudFront-Viewer-Country header * to update the S3 bucket domain name to a bucket in a Region that is closer to * the viewer. * * This can be useful in several ways: * 1) Reduces latencies when the Region specified is nearer to the viewer's * country. * 2) Provides data sovereignty by making sure that data is served from an * origin that's in the same country that the request came from. * * NOTE: 1. You must configure your distribution to cache based on the * CloudFront-Viewer-Country header. For more information, see * https://docs.aws.amazon.com/console/cloudfront/cache-on-selected- headers * 2. CloudFront adds the CloudFront-Viewer-Country header after the viewer Example functions 796 Amazon CloudFront Developer Guide * request event. To use this example, you must create a trigger for the * origin request event. */ const countryToRegion = { 'DE': 'eu-central-1', 'IE': 'eu-west-1', 'GB': 'eu-west-2', 'FR': 'eu-west-3', 'JP': 'ap-northeast-1', 'IN': 'ap-south-1' }; if (request.headers['cloudfront-viewer-country']) { const countryCode = request.headers['cloudfront-viewer-country'][0].value; const region = countryToRegion[countryCode]; /** * If the viewer's country is not in the list you specify, the request * goes to the default S3 bucket you've configured. */ if (region) { /** * If you've set up OAI, the bucket policy in the destination bucket * should allow the OAI GetObject operation, as configured by default * for an S3 origin with OAI. Another requirement with OAI is to provide * the Region so it can be used for the SIGV4 signature. Otherwise, the * Region is not required. */ request.origin.s3.region = region; const domainName = `amzn-s3-demo-bucket-in-${region}.s3. ${region}.amazonaws.com`; request.origin.s3.domainName = domainName; request.headers['host'] = [{ key: 'host', value: domainName }]; } } callback(null, request); }; Example functions 797 Amazon CloudFront Python Developer Guide def lambda_handler(event, context): request = event['Records'][0]['cf']['request'] ''' This blueprint demonstrates how an origin-request trigger can be used to change the origin from which the content is fetched, based on request properties. In this example, we use the value of the CloudFront-Viewer-Country header to update the S3 bucket domain name to a bucket in a Region that is closer to the viewer. This can be useful in several ways: 1) Reduces latencies when the Region specified is nearer to the viewer's country. 2) Provides data sovereignty by making sure that data is served from an origin that's in the same country that the request came from. NOTE: 1. You must configure your distribution to cache based on the CloudFront-Viewer-Country header. For more information, see https://docs.aws.amazon.com/console/cloudfront/cache-on-selected-headers 2. CloudFront adds the CloudFront-Viewer-Country header after the viewer request event. To use this example, you must create a trigger for the origin request event. ''' countryToRegion = { 'DE': 'eu-central-1', 'IE': 'eu-west-1', 'GB': 'eu-west-2', 'FR': 'eu-west-3', 'JP': 'ap-northeast-1', 'IN': 'ap-south-1' } viewerCountry = request['headers'].get('cloudfront-viewer-country') if viewerCountry:
AmazonCloudFront_DevGuide-282
AmazonCloudFront_DevGuide.pdf
282
when the Region specified is nearer to the viewer's country. 2) Provides data sovereignty by making sure that data is served from an origin that's in the same country that the request came from. NOTE: 1. You must configure your distribution to cache based on the CloudFront-Viewer-Country header. For more information, see https://docs.aws.amazon.com/console/cloudfront/cache-on-selected-headers 2. CloudFront adds the CloudFront-Viewer-Country header after the viewer request event. To use this example, you must create a trigger for the origin request event. ''' countryToRegion = { 'DE': 'eu-central-1', 'IE': 'eu-west-1', 'GB': 'eu-west-2', 'FR': 'eu-west-3', 'JP': 'ap-northeast-1', 'IN': 'ap-south-1' } viewerCountry = request['headers'].get('cloudfront-viewer-country') if viewerCountry: countryCode = viewerCountry[0]['value'] region = countryToRegion.get(countryCode) # If the viewer's country in not in the list you specify, the request # goes to the default S3 bucket you've configured if region: Example functions 798 Amazon CloudFront ''' Developer Guide If you've set up OAI, the bucket policy in the destination bucket should allow the OAI GetObject operation, as configured by default for an S3 origin with OAI. Another requirement with OAI is to provide the Region so it can be used for the SIGV4 signature. Otherwise, the Region is not required. ''' request['origin']['s3']['region'] = region domainName = 'amzn-s3-demo-bucket-in-{0}.s3. {0}.amazonaws.com'.format(region) request['origin']['s3']['domainName'] = domainName request['headers']['host'] = [{'key': 'host', 'value': domainName}] return request Example: Use an origin request trigger to change from an Amazon S3 origin to a custom origin This function demonstrates how an origin-request trigger can be used to change the custom origin from which the content is fetched, based on request properties. Node.js 'use strict'; const querystring = require('querystring'); exports.handler = (event, context, callback) => { const request = event.Records[0].cf.request; /** * Reads query string to check if custom origin should be used, and * if true, sets custom origin properties. */ const params = querystring.parse(request.querystring); if (params['useCustomOrigin']) { if (params['useCustomOrigin'] === 'true') { /* Set custom origin fields*/ request.origin = { custom: { Example functions 799 Amazon CloudFront Developer Guide domainName: 'www.example.com', port: 443, protocol: 'https', path: '', sslProtocols: ['TLSv1', 'TLSv1.1'], readTimeout: 5, keepaliveTimeout: 5, customHeaders: {} } }; request.headers['host'] = [{ key: 'host', value: 'www.example.com'}]; } } callback(null, request); }; Python from urllib.parse import parse_qs def lambda_handler(event, context): request = event['Records'][0]['cf']['request'] # Reads query string to check if custom origin should be used, and # if true, sets custom origin properties params = {k: v[0] for k, v in parse_qs(request['querystring']).items()} if params.get('useCustomOrigin') == 'true': # Set custom origin fields request['origin'] = { 'custom': { 'domainName': 'www.example.com', 'port': 443, 'protocol': 'https', 'path': '', 'sslProtocols': ['TLSv1', 'TLSv1.1'], 'readTimeout': 5, 'keepaliveTimeout': 5, 'customHeaders': {} } } Example functions 800 Amazon CloudFront Developer Guide request['headers']['host'] = [{'key': 'host', 'value': 'www.example.com'}] return request Example: Use an origin request trigger to gradually transfer traffic from one Amazon S3 bucket to another This function demonstrates how you can gradually transfer traffic from one Amazon S3 bucket to another in a controlled way. Node.js 'use strict'; function getRandomInt(min, max) { /* Random number is inclusive of min and max*/ return Math.floor(Math.random() * (max - min + 1)) + min; } exports.handler = (event, context, callback) => { const request = event.Records[0].cf.request; const BLUE_TRAFFIC_PERCENTAGE = 80; /** * This Lambda function demonstrates how to gradually transfer traffic from * one S3 bucket to another in a controlled way. * We define a variable BLUE_TRAFFIC_PERCENTAGE which can take values from * 1 to 100. If the generated randomNumber less than or equal to BLUE_TRAFFIC_PERCENTAGE, traffic * is re-directed to blue-bucket. If not, the default bucket that we've configured * is used. */ const randomNumber = getRandomInt(1, 100); if (randomNumber <= BLUE_TRAFFIC_PERCENTAGE) { const domainName = 'blue-bucket.s3.amazonaws.com'; request.origin.s3.domainName = domainName; request.headers['host'] = [{ key: 'host', value: domainName}]; } Example functions 801 Amazon CloudFront Developer Guide callback(null, request); }; Python import math import random def getRandomInt(min, max): # Random number is inclusive of min and max return math.floor(random.random() * (max - min + 1)) + min def lambda_handler(event, context): request = event['Records'][0]['cf']['request'] BLUE_TRAFFIC_PERCENTAGE = 80 ''' This Lambda function demonstrates how to gradually transfer traffic from one S3 bucket to another in a controlled way. We define a variable BLUE_TRAFFIC_PERCENTAGE which can take values from 1 to 100. If the generated randomNumber less than or equal to BLUE_TRAFFIC_PERCENTAGE, traffic is re-directed to blue-bucket. If not, the default bucket that we've configured is used. ''' randomNumber = getRandomInt(1, 100) if randomNumber <= BLUE_TRAFFIC_PERCENTAGE: domainName = 'blue-bucket.s3.amazonaws.com' request['origin']['s3']['domainName'] = domainName request['headers']['host'] = [{'key': 'host', 'value': domainName}] return request Example: Use an origin request trigger to change the origin domain name based on the country header This function demonstrates how you can change the origin domain name based on the CloudFront-Viewer-Country header, so content is served from an origin closer to the viewer's country. Example functions 802 Amazon CloudFront Developer Guide Implementing this functionality for your distribution can have advantages such as the
AmazonCloudFront_DevGuide-283
AmazonCloudFront_DevGuide.pdf
283
re-directed to blue-bucket. If not, the default bucket that we've configured is used. ''' randomNumber = getRandomInt(1, 100) if randomNumber <= BLUE_TRAFFIC_PERCENTAGE: domainName = 'blue-bucket.s3.amazonaws.com' request['origin']['s3']['domainName'] = domainName request['headers']['host'] = [{'key': 'host', 'value': domainName}] return request Example: Use an origin request trigger to change the origin domain name based on the country header This function demonstrates how you can change the origin domain name based on the CloudFront-Viewer-Country header, so content is served from an origin closer to the viewer's country. Example functions 802 Amazon CloudFront Developer Guide Implementing this functionality for your distribution can have advantages such as the following: • Reducing latencies when the Region specified is nearer to the viewer's country • Providing data sovereignty by making sure that data is served from an origin that's in the same country that the request came from Note that to enable this functionality you must configure your distribution to cache based on the CloudFront-Viewer-Country header. For more information, see the section called “Cache based on selected request headers”. Node.js 'use strict'; exports.handler = (event, context, callback) => { const request = event.Records[0].cf.request; if (request.headers['cloudfront-viewer-country']) { const countryCode = request.headers['cloudfront-viewer-country'][0].value; if (countryCode === 'GB' || countryCode === 'DE' || countryCode === 'IE' ) { const domainName = 'eu.example.com'; request.origin.custom.domainName = domainName; request.headers['host'] = [{key: 'host', value: domainName}]; } } callback(null, request); }; Python def lambda_handler(event, context): request = event['Records'][0]['cf']['request'] viewerCountry = request['headers'].get('cloudfront-viewer-country') if viewerCountry: countryCode = viewerCountry[0]['value'] if countryCode == 'GB' or countryCode == 'DE' or countryCode == 'IE': domainName = 'eu.example.com' request['origin']['custom']['domainName'] = domainName Example functions 803 Amazon CloudFront Developer Guide request['headers']['host'] = [{'key': 'host', 'value': domainName}] return request Update error statuses - examples The following examples provide guidance for how you can use Lambda@Edge to change the error status that is returned to users. Topics • Example: Use an origin response trigger to update the error status code to 200 • Example: Use an origin response trigger to update the error status code to 302 Example: Use an origin response trigger to update the error status code to 200 This function demonstrates how you can update the response status to 200 and generate static body content to return to the viewer in the following scenario: • The function is triggered in an origin response. • The response status from the origin server is an error status code (4xx or 5xx). Node.js 'use strict'; exports.handler = (event, context, callback) => { const response = event.Records[0].cf.response; /** * This function updates the response status to 200 and generates static * body content to return to the viewer in the following scenario: * 1. The function is triggered in an origin response * 2. The response status from the origin server is an error status code (4xx or 5xx) */ if (response.status >= 400 && response.status <= 599) { response.status = 200; response.statusDescription = 'OK'; response.body = 'Body generation example'; Example functions 804 Amazon CloudFront } callback(null, response); }; Python Developer Guide def lambda_handler(event, context): response = event['Records'][0]['cf']['response'] ''' This function updates the response status to 200 and generates static body content to return to the viewer in the following scenario: 1. The function is triggered in an origin response 2. The response status from the origin server is an error status code (4xx or 5xx) ''' if int(response['status']) >= 400 and int(response['status']) <= 599: response['status'] = 200 response['statusDescription'] = 'OK' response['body'] = 'Body generation example' return response Example: Use an origin response trigger to update the error status code to 302 This function demonstrates how you can update the HTTP status code to 302 to redirect to another path (cache behavior) that has a different origin configured. Note the following: • The function is triggered in an origin response. • The response status from the origin server is an error status code (4xx or 5xx). Node.js 'use strict'; exports.handler = (event, context, callback) => { const response = event.Records[0].cf.response; const request = event.Records[0].cf.request; /** Example functions 805 Amazon CloudFront Developer Guide * This function updates the HTTP status code in the response to 302, to redirect to another * path (cache behavior) that has a different origin configured. Note the following: * 1. The function is triggered in an origin response * 2. The response status from the origin server is an error status code (4xx or 5xx) */ if (response.status >= 400 && response.status <= 599) { const redirect_path = `/plan-b/path?${request.querystring}`; response.status = 302; response.statusDescription = 'Found'; /* Drop the body, as it is not required for redirects */ response.body = ''; response.headers['location'] = [{ key: 'Location', value: redirect_path }]; } callback(null, response); }; Python def lambda_handler(event, context): response = event['Records'][0]['cf']['response'] request = event['Records'][0]['cf']['request'] ''' This function updates the HTTP status code in the response to 302, to redirect to another path (cache behavior) that has a different origin
AmazonCloudFront_DevGuide-284
AmazonCloudFront_DevGuide.pdf
284
response * 2. The response status from the origin server is an error status code (4xx or 5xx) */ if (response.status >= 400 && response.status <= 599) { const redirect_path = `/plan-b/path?${request.querystring}`; response.status = 302; response.statusDescription = 'Found'; /* Drop the body, as it is not required for redirects */ response.body = ''; response.headers['location'] = [{ key: 'Location', value: redirect_path }]; } callback(null, response); }; Python def lambda_handler(event, context): response = event['Records'][0]['cf']['response'] request = event['Records'][0]['cf']['request'] ''' This function updates the HTTP status code in the response to 302, to redirect to another path (cache behavior) that has a different origin configured. Note the following: 1. The function is triggered in an origin response 2. The response status from the origin server is an error status code (4xx or 5xx) ''' if int(response['status']) >= 400 and int(response['status']) <= 599: redirect_path = '/plan-b/path?%s' % request['querystring'] response['status'] = 302 Example functions 806 Amazon CloudFront Developer Guide response['statusDescription'] = 'Found' # Drop the body as it is not required for redirects response['body'] = '' response['headers']['location'] = [{'key': 'Location', 'value': redirect_path}] return response Access the request body - examples The following examples show how you can use Lambda@Edge to work with POST requests. Note To use these examples, you must enable the include body option in the distribution's Lambda function association. It is not enabled by default. • To enable this setting in the CloudFront console, select the check box for Include Body in the Lambda Function Association. • To enable this setting in the CloudFront API or with AWS CloudFormation, set the IncludeBody field to true in LambdaFunctionAssociation. Topics • Example: Use a request trigger to read an HTML form • Example: Use a request trigger to modify an HTML form Example: Use a request trigger to read an HTML form This function demonstrates how you can process the body of a POST request generated by an HTML form (web form), such as a "contact us" form. For example, you might have an HTML form like the following: <html> <form action="https://example.com" method="post"> Param 1: <input type="text" name="name1"><br> Param 2: <input type="text" name="name2"><br> input type="submit" value="Submit"> Example functions 807 Amazon CloudFront </form> </html> Developer Guide For the example function that follows, the function must be triggered in a CloudFront viewer request or origin request. Node.js 'use strict'; const querystring = require('querystring'); /** * This function demonstrates how you can read the body of a POST request * generated by an HTML form (web form). The function is triggered in a * CloudFront viewer request or origin request event type. */ exports.handler = (event, context, callback) => { const request = event.Records[0].cf.request; if (request.method === 'POST') { /* HTTP body is always passed as base64-encoded string. Decode it. */ const body = Buffer.from(request.body.data, 'base64').toString(); /* HTML forms send the data in query string format. Parse it. */ const params = querystring.parse(body); /* For demonstration purposes, we only log the form fields here. * You can put your custom logic here. For example, you can store the * fields in a database, such as Amazon DynamoDB, and generate a response * right from your Lambda@Edge function. */ for (let param in params) { console.log(`For "${param}" user submitted "${params[param]}".\n`); } } return callback(null, request); }; Python import base64 Example functions 808 Amazon CloudFront Developer Guide from urllib.parse import parse_qs ''' Say there is a POST request body generated by an HTML such as: <html> <form action="https://example.com" method="post"> Param 1: <input type="text" name="name1"><br> Param 2: <input type="text" name="name2"><br> input type="submit" value="Submit"> </form> </html> ''' ''' This function demonstrates how you can read the body of a POST request generated by an HTML form (web form). The function is triggered in a CloudFront viewer request or origin request event type. ''' def lambda_handler(event, context): request = event['Records'][0]['cf']['request'] if request['method'] == 'POST': # HTTP body is always passed as base64-encoded string. Decode it body = base64.b64decode(request['body']['data']) # HTML forms send the data in query string format. Parse it params = {k: v[0] for k, v in parse_qs(body).items()} ''' For demonstration purposes, we only log the form fields here. You can put your custom logic here. For example, you can store the fields in a database, such as Amazon DynamoDB, and generate a response right from your Lambda@Edge function. ''' for key, value in params.items(): print("For %s use submitted %s" % (key, value)) return request Example functions 809 Amazon CloudFront Developer Guide Example: Use a request trigger to modify an HTML form This function demonstrates how you can modify the body of a POST request generated by an HTML form (web form). The function is triggered in a CloudFront viewer request or origin request. Node.js 'use strict'; const querystring = require('querystring'); exports.handler = (event, context, callback) => { var request = event.Records[0].cf.request; if (request.method === 'POST') { /* Request body is being
AmazonCloudFront_DevGuide-285
AmazonCloudFront_DevGuide.pdf
285
a response right from your Lambda@Edge function. ''' for key, value in params.items(): print("For %s use submitted %s" % (key, value)) return request Example functions 809 Amazon CloudFront Developer Guide Example: Use a request trigger to modify an HTML form This function demonstrates how you can modify the body of a POST request generated by an HTML form (web form). The function is triggered in a CloudFront viewer request or origin request. Node.js 'use strict'; const querystring = require('querystring'); exports.handler = (event, context, callback) => { var request = event.Records[0].cf.request; if (request.method === 'POST') { /* Request body is being replaced. To do this, update the following /* three fields: * 1) body.action to 'replace' * 2) body.encoding to the encoding of the new data. * * Set to one of the following values: * * text - denotes that the generated body is in text format. * Lambda@Edge will propagate this as is. * base64 - denotes that the generated body is base64 encoded. * Lambda@Edge will base64 decode the data before sending * it to the origin. * 3) body.data to the new body. */ request.body.action = 'replace'; request.body.encoding = 'text'; request.body.data = getUpdatedBody(request); } callback(null, request); }; function getUpdatedBody(request) { /* HTTP body is always passed as base64-encoded string. Decode it. */ const body = Buffer.from(request.body.data, 'base64').toString(); /* HTML forms send data in query string format. Parse it. */ const params = querystring.parse(body); /* For demonstration purposes, we're adding one more param. * Example functions 810 Amazon CloudFront Developer Guide * You can put your custom logic here. For example, you can truncate long * bodies from malicious requests. */ params['new-param-name'] = 'new-param-value'; return querystring.stringify(params); } Python import base64 from urllib.parse import parse_qs, urlencode def lambda_handler(event, context): request = event['Records'][0]['cf']['request'] if request['method'] == 'POST': ''' Request body is being replaced. To do this, update the following three fields: 1) body.action to 'replace' 2) body.encoding to the encoding of the new data. Set to one of the following values: text - denotes that the generated body is in text format. Lambda@Edge will propagate this as is. base64 - denotes that the generated body is base64 encoded. Lambda@Edge will base64 decode the data before sending it to the origin. 3) body.data to the new body. ''' request['body']['action'] = 'replace' request['body']['encoding'] = 'text' request['body']['data'] = getUpdatedBody(request) return request def getUpdatedBody(request): # HTTP body is always passed as base64-encoded string. Decode it body = base64.b64decode(request['body']['data']) # HTML forms send data in query string format. Parse it params = {k: v[0] for k, v in parse_qs(body).items()} # For demonstration purposes, we're adding one more param Example functions 811 Amazon CloudFront Developer Guide # You can put your custom logic here. For example, you can truncate long # bodies from malicious requests params['new-param-name'] = 'new-param-value' return urlencode(params) Restrictions on edge functions The following topics describe the restrictions that apply to CloudFront Functions and Lambda@Edge. Some restrictions apply to all edge functions, while others apply only to CloudFront Functions or Lambda@Edge. Each topic provides detailed information about the limitations and constraints you should consider when you develop and deploy edge functions with CloudFront. Understanding these restrictions helps you ensure that your edge functions operate as expected and comply with the supported features. Topics • Restrictions on all edge functions • Restrictions on CloudFront Functions • Restrictions on Lambda@Edge For information about quotas (formerly referred to as limits), see Quotas on CloudFront Functions and Quotas on Lambda@Edge. Restrictions on all edge functions The following restrictions apply to all edge functions, both CloudFront Functions and Lambda@Edge. Topics • AWS account ownership • Combining CloudFront Functions with Lambda@Edge • HTTP status codes • HTTP headers Restrictions on edge functions 812 Developer Guide Amazon CloudFront • Query strings • URI • URI, query string, and headers encoding • Microsoft Smooth Streaming • Tagging AWS account ownership To associate an edge function with a CloudFront distribution, the function and distribution must be owned by the same AWS account. Combining CloudFront Functions with Lambda@Edge For a given cache behavior, the following restrictions apply: • Each event type (viewer request, origin request, origin response, and viewer response) can have only one edge function association. • You can’t combine CloudFront Functions and Lambda@Edge in viewer events (viewer request and viewer response). All other combinations of edge functions are allowed. The following table explains the allowed combinations. CloudFront Functions Viewer request Viewer response Viewer request Not allowed Not allowed Lambda@Edge Origin request Allowed Origin response Allowed Allowed Allowed Viewer response Not allowed Not allowed Restrictions on all edge functions 813 Amazon CloudFront HTTP status codes Developer Guide CloudFront doesn't invoke edge functions for viewer response events when the origin returns HTTP status code 400 or higher. Lambda@Edge functions for origin response events are invoked for all origin responses, including when the origin returns
AmazonCloudFront_DevGuide-286
AmazonCloudFront_DevGuide.pdf
286
Lambda@Edge in viewer events (viewer request and viewer response). All other combinations of edge functions are allowed. The following table explains the allowed combinations. CloudFront Functions Viewer request Viewer response Viewer request Not allowed Not allowed Lambda@Edge Origin request Allowed Origin response Allowed Allowed Allowed Viewer response Not allowed Not allowed Restrictions on all edge functions 813 Amazon CloudFront HTTP status codes Developer Guide CloudFront doesn't invoke edge functions for viewer response events when the origin returns HTTP status code 400 or higher. Lambda@Edge functions for origin response events are invoked for all origin responses, including when the origin returns HTTP status code 400 or higher. For more information, see Update HTTP responses in origin response triggers. HTTP headers Certain HTTP headers are disallowed, which means they're not exposed to edge functions and functions can't add them. Other headers are read-only, which means functions can read them but can't add, modify, or delete them. Topics • Disallowed headers • Read-only headers Disallowed headers The following HTTP headers are not exposed to edge functions, and functions can't add them. If your function adds one of these headers, it fails CloudFront validation and CloudFront returns HTTP status code 502 (Bad Gateway) to the viewer. • Connection • Expect • Keep-Alive • Proxy-Authenticate • Proxy-Authorization • Proxy-Connection • Trailer • Upgrade • X-Accel-Buffering • X-Accel-Charset Restrictions on all edge functions 814 Developer Guide Amazon CloudFront • X-Accel-Limit-Rate • X-Accel-Redirect • X-Amz-Cf-* • X-Amzn-Auth • X-Amzn-Cf-Billing • X-Amzn-Cf-Id • X-Amzn-Cf-Xff • X-Amzn-Errortype • X-Amzn-Fle-Profile • X-Amzn-Header-Count • X-Amzn-Header-Order • X-Amzn-Lambda-Integration-Tag • X-Amzn-RequestId • X-Cache • X-Edge-* • X-Forwarded-Proto • X-Real-IP Read-only headers The following headers are read-only. Your function can read them and use them as input to the function logic, but it can't change the values. If your function adds or edits a read-only header, the request fails CloudFront validation and CloudFront returns HTTP status code 502 (Bad Gateway) to the viewer. Read-only headers in viewer request events The following headers are read-only in viewer request events. • Content-Length • Host • Transfer-Encoding Restrictions on all edge functions 815 Amazon CloudFront • Via Developer Guide Read-only headers in origin request events (Lambda@Edge only) The following headers are read-only in origin request events, which exist only in Lambda@Edge. • Accept-Encoding • Content-Length • If-Modified-Since • If-None-Match • If-Range • If-Unmodified-Since • Transfer-Encoding • Via Read-only headers in origin response events (Lambda@Edge only) The following headers are read-only in origin response events, which exist only in Lambda@Edge. • Transfer-Encoding • Via Read-only headers in viewer response events The following headers are read-only in viewer response events for both CloudFront Functions and Lambda@Edge. • Warning • Via The following headers are read-only in viewer response events for Lambda@Edge. • Content-Length • Content-Encoding • Transfer-Encoding Restrictions on all edge functions 816 Amazon CloudFront Query strings Developer Guide The following restrictions apply to functions that read, update, or create a query string in a request URI. • (Lambda@Edge only) To access the query string in an origin request or origin response function, your cache policy or origin request policy must be set to All for Query strings. • A function can create or update a query string for viewer request and origin request events (origin request events exist only in Lambda@Edge). • A function can read a query string, but cannot create or update one, for origin response and viewer response events (origin response events exist only in Lambda@Edge). • If a function creates or updates a query string, the following restrictions apply: • The query string can't include spaces, control characters, or the fragment identifier (#). • The total size of the URI, including the query string, must be less than 8,192 characters. • We recommend that you use percent encoding for the URI and query string. For more information, see URI, query string, and headers encoding. URI If a function changes the URI for a request, that doesn't change the cache behavior for the request or the origin that the request is forwarded to. The total size of the URI, including the query string, must be less than 8,192 characters. URI, query string, and headers encoding The values for the URI, query string, and headers that are passed to edge functions are UTF-8 encoded. Your function should use UTF-8 encoding for the URI, query string, and header values that it returns. Percent encoding is compatible with UTF-8 encoding. The following list explains how CloudFront handles encoding for the URI, query string, and headers: • When values in the request are UTF-8 encoded, CloudFront forwards the values to your function without changing them. • When values in the request are ISO-8859-1 encoded, CloudFront converts the values to UTF-8 encoding before forwarding them to your function. Restrictions on all edge functions 817 Amazon CloudFront Developer Guide • When
AmazonCloudFront_DevGuide-287
AmazonCloudFront_DevGuide.pdf
287
are passed to edge functions are UTF-8 encoded. Your function should use UTF-8 encoding for the URI, query string, and header values that it returns. Percent encoding is compatible with UTF-8 encoding. The following list explains how CloudFront handles encoding for the URI, query string, and headers: • When values in the request are UTF-8 encoded, CloudFront forwards the values to your function without changing them. • When values in the request are ISO-8859-1 encoded, CloudFront converts the values to UTF-8 encoding before forwarding them to your function. Restrictions on all edge functions 817 Amazon CloudFront Developer Guide • When values in the request are encoded using some other character encoding, CloudFront assumes that they're ISO-8859-1 encoded and tries to convert from ISO-8859-1 to UTF-8. Important The converted characters might be an inaccurate interpretation of the values in the original request. This might cause your function or your origin to produce an unintended result. The values for the URI, query string, and headers that CloudFront forwards to your origin depend on whether a function changes the values: • If a function doesn't change the URI, query string, or header, CloudFront forwards the values that it received in the request to your origin. • If a function changes the URI, query string, or header, CloudFront forwards the UTF-8 encoded values. Microsoft Smooth Streaming You can't use edge functions with a CloudFront distribution that you're using for streaming media files that you've transcoded into the Microsoft Smooth Streaming format. Tagging You can't add tags to edge functions. For more information about tagging in CloudFront, see Tag a distribution. Restrictions on CloudFront Functions The following restrictions apply only to CloudFront Functions. Contents • Logs • Request body • Using temporary credentials with the CloudFront KeyValueStore API • Runtime Restrictions on CloudFront Functions 818 Amazon CloudFront • Compute utilization Developer Guide For information about quotas (formerly referred to as limits), see Quotas on CloudFront Functions. Logs Function logs in CloudFront Functions are truncated at 10 KB. Request body CloudFront Functions can't access the body of the HTTP request. Using temporary credentials with the CloudFront KeyValueStore API You can use AWS Security Token Service (AWS STS) to generate temporary security credentials (also known as session tokens). Session tokens allow you to temporarily assume an AWS Identity and Access Management (IAM) role so that you can access AWS services. To call the CloudFront KeyValueStore API, use a Regional endpoint in AWS STS to return a version 2 session token. If you use the global endpoint for AWS STS (sts.amazonaws.com), AWS STS will generate a version 1 session token, which isn't supported by Signature Version 4A (SigV4A). As a result, you will receive an authentication error. To call the CloudFront KeyValueStore API, you can use the following options: AWS CLI and AWS SDKs You can configure the AWS CLI or an AWS SDK to use Regional AWS STS endpoints. For more information, see AWS STS Regionalized endpoints in the AWS SDK and Tools Reference Guide. For more information about available AWS STS endpoints, see Regions and endpoints in the IAM User Guide. SAML You can configure SAML to use Regional AWS STS endpoints. For more information, see the How to use regional SAML endpoints for failover blog post. SetSecurityTokenServicePreferences API Instead of using a Regional AWS STS endpoint, you can configure the global endpoint for AWS STS to return version 2 session tokens. To do so, use the SetSecurityTokenServicePreferences API operation to configure your AWS account. Restrictions on CloudFront Functions 819 Amazon CloudFront Developer Guide Example Example: IAM CLI command aws iam set-security-token-service-preferences --global-endpoint-token-version v2Token Tip We recommend that you use the AWS STS Regional endpoints instead of this option. Regional endpoints provide higher availability and failover scenarios. Custom identity provider If you're using a custom identity provider that does the federation and assumes the role, use one of the previous options for the parent identity provider system that is responsible for generating the session token. Runtime The CloudFront Functions runtime environment doesn't support dynamic code evaluation, and it restricts access to the network, file system, environment variables, and timers. For more information, see Restricted features. Note To use CloudFront KeyValueStore, your CloudFront function must use JavaScript runtime 2.0. Compute utilization CloudFront Functions have a limit on the time they can take to run, measured as compute utilization. Compute utilization is a number between 0 and 100 that indicates the amount of time that the function took to run as a percentage of the maximum allowed time. For example, a compute utilization of 35 means that the function completed in 35% of the maximum allowed time. Restrictions on CloudFront Functions 820 Amazon CloudFront Developer Guide When you test a function, you can see the compute utilization value in the output of the test event. For production functions,
AmazonCloudFront_DevGuide-288
AmazonCloudFront_DevGuide.pdf
288
runtime 2.0. Compute utilization CloudFront Functions have a limit on the time they can take to run, measured as compute utilization. Compute utilization is a number between 0 and 100 that indicates the amount of time that the function took to run as a percentage of the maximum allowed time. For example, a compute utilization of 35 means that the function completed in 35% of the maximum allowed time. Restrictions on CloudFront Functions 820 Amazon CloudFront Developer Guide When you test a function, you can see the compute utilization value in the output of the test event. For production functions, you can view the compute utilization metric on the Monitoring page in the CloudFront console, or in CloudWatch. Restrictions on Lambda@Edge The following restrictions apply only to Lambda@Edge. Contents • DNS resolution • HTTP status codes • Lambda function version • Lambda Region • Lambda role permissions • Lambda features • Supported runtimes • CloudFront headers • Restrictions on the request body with the include body option • Response timeout and keep-alive timeout (custom origins only) For information about quotas, see Quotas on Lambda@Edge. DNS resolution CloudFront performs a DNS resolution on the origin domain name before it executes your origin request Lambda@Edge function. If the DNS service for your domain is experiencing issues and CloudFront can't resolve the domain name to get the IP address, your Lambda@Edge function will not invoke. CloudFront will return an HTTP 502 status code (Bad Gateway) to the client. For more information, see DNS error (NonS3OriginDnsError). For more information about managing DNS failover, see Configuring DNS failover in the Amazon Route 53 Developer Guide. HTTP status codes Lambda@Edge functions for viewer response events cannot modify the HTTP status code of the response, regardless of whether the response came from the origin or the CloudFront cache. Restrictions on Lambda@Edge 821 Amazon CloudFront Lambda function version Developer Guide You must use a numbered version of the Lambda function, not $LATEST or aliases. Lambda Region The Lambda function must be in the US East (N. Virginia) Region. Lambda role permissions The IAM execution role associated with the Lambda function must allow the service principals lambda.amazonaws.com and edgelambda.amazonaws.com to assume the role. For more information, see Set up IAM permissions and roles for Lambda@Edge. Lambda features The following Lambda features are not supported by Lambda@Edge: • Lambda runtime management configurations other than Auto (default) • Configuration of your Lambda function to access resources inside your VPC • Lambda function dead letter queues • Lambda environment variables (except for reserved environment variables, which are automatically supported) • Lambda functions with Managing AWS Lambda dependencies with layers • Using AWS X-Ray • Lambda provisioned concurrency Note Lambda@Edge functions share the same Regional concurrency capabilities as all Lambda functions. For more information, see Quotas on Lambda@Edge. • Create a Lambda function using a container image • Lambda functions that use the arm64 architecture • Lambda functions with more than 512 MB of ephemeral storage • Using a customer managed key to encrypt your .zip deployment packages Restrictions on Lambda@Edge 822 Amazon CloudFront Supported runtimes Developer Guide Lambda@Edge supports Lambda functions with the following runtimes: Node.js • Node.js 22 • Node.js 20 • Node.js 18 • Node.js 16¹ • Node.js 14² • Node.js 12² • Node.js 10² • Node.js 8² • Node.js 6² Python • Python 3.13 • Python 3.12 • Python 3.11 • Python 3.10 • Python 3.9 • Python 3.8 • Python 3.7 ¹This version of Node.js has reached end of life, and will soon be deprecated by AWS Lambda. ²This version of Node.js has reached end of life, and is fully deprecated by AWS Lambda. You can’t create or update functions with deprecated versions of Node.js. You can only associate existing functions with these versions with CloudFront distributions. Functions with these versions that are associated with distributions will continue to run. However, we recommend that you move your function to newer versions of Node.js. For more information, see Runtime deprecation policy in the AWS Lambda Developer Guide and the Node.js release schedule on GitHub. Tip As a best practice, use the latest versions of the provided runtimes for performance improvements and new features. CloudFront headers Lambda@Edge functions can read, edit, remove, or add any of the CloudFront headers listed in Add CloudFront request headers. Restrictions on Lambda@Edge 823 Amazon CloudFront Notes Developer Guide • If you want CloudFront to add these headers, you must configure CloudFront to add them by using a cache policy or origin request policy. • CloudFront adds the headers after the viewer request event, which means the headers aren't available to Lambda@Edge functions in a viewer request. The headers are only available to Lambda@Edge functions in an origin request and origin response. • If the viewer request includes headers that have these names, and you
AmazonCloudFront_DevGuide-289
AmazonCloudFront_DevGuide.pdf
289
edit, remove, or add any of the CloudFront headers listed in Add CloudFront request headers. Restrictions on Lambda@Edge 823 Amazon CloudFront Notes Developer Guide • If you want CloudFront to add these headers, you must configure CloudFront to add them by using a cache policy or origin request policy. • CloudFront adds the headers after the viewer request event, which means the headers aren't available to Lambda@Edge functions in a viewer request. The headers are only available to Lambda@Edge functions in an origin request and origin response. • If the viewer request includes headers that have these names, and you configured CloudFront to add these headers using a cache policy or origin request policy, then CloudFront overwrites the header values that were in the viewer request. Viewer-facing functions see the header value from the viewer request, while origin-facing functions see the header value that CloudFront added. • If a viewer request function adds the CloudFront-Viewer-Country header, it fails validation and CloudFront returns HTTP status code 502 (Bad Gateway) to the viewer. Restrictions on the request body with the include body option When you choose the Include Body option to expose the request body to your Lambda@Edge function, the following information and size limits apply to the portions of the body that are exposed or replaced. • CloudFront always base64 encodes the request body before exposing it to Lambda@Edge. • If the request body is large, CloudFront truncates it before exposing it to Lambda@Edge, as follows: • For viewer request events, the body is truncated at 40 KB. • For origin request events, the body is truncated at 1 MB. • If you access the request body as read-only, CloudFront sends the full original request body to the origin. • If your Lambda@Edge function replaces the request body, the following size limits apply to the body that the function returns: • If the Lambda@Edge function returns the body as plain text: • For viewer request events, the body limit is 40 KB. • For origin request events, the body limit is 1 MB. Restrictions on Lambda@Edge 824 Amazon CloudFront Developer Guide • If the Lambda@Edge function returns the body as base64 encoded text: • For viewer request events, the body limit is 53.2 KB. • For origin request events, the body limit is 1.33 MB. Note If your Lambda@Edge function returns a body that exceeds these limits, your request will fail with an HTTP 502 status code (Lambda validation error). We recommend that you update your Lambda@Edge function so that the body doesn't exceed these limits. Response timeout and keep-alive timeout (custom origins only) If you're using Lambda@Edge functions to set the response timeout or keep-alive timeout for your distribution origins, verify that you're specifying a value that your origin can support. For more information, see Response and keep-alive timeout quotas. Restrictions on Lambda@Edge 825 Amazon CloudFront Developer Guide Reports, metrics, and logs CloudFront provides several options for reporting, monitoring, and logging your CloudFront resources. You can complete the following tasks: • View and download reports to see usage and activity for your CloudFront distributions, including billing reports, cache statistics, popular content, and top referrers. • Monitor and track CloudFront, including your edge computing functions, directly in the CloudFront console or by using Amazon CloudWatch. CloudFront sends metrics to CloudWatch for distributions and edge functions, both Lambda@Edge and CloudFront Functions. • View logs for the viewer requests that your CloudFront distributions receive with standard logs or real-time logs. In addition to viewer request logs, you can use CloudWatch Logs to get logs for your edge functions, both Lambda@Edge and CloudFront Functions. You can also use AWS CloudTrail to get logs of the CloudFront API activity in your AWS account. • Track configuration changes to your CloudFront resources using AWS Config. For more information about these options, see the following topics. Topics • AWS billing and usage reports for CloudFront • View CloudFront reports in the console • Monitor CloudFront metrics with Amazon CloudWatch • CloudFront and edge function logging • Track configuration changes with AWS Config AWS billing and usage reports for CloudFront AWS provides two usage reports for CloudFront: • The AWS billing report is a high-level view of all activity for AWS services that you're using, including CloudFront. • The AWS usage report is a summary of activity for a specific service, aggregated by hour, day, or month. It also includes usage charts that provide a graphical representation of your CloudFront usage. AWS billing and usage reports for CloudFront 826 Amazon CloudFront Note Developer Guide Like other AWS services, CloudFront charges you for only what you use. For more information, see CloudFront pricing. Topics • View the AWS billing report for CloudFront • View the AWS usage report for CloudFront • Interpret your AWS bill and usage reports for
AmazonCloudFront_DevGuide-290
AmazonCloudFront_DevGuide.pdf
290
activity for AWS services that you're using, including CloudFront. • The AWS usage report is a summary of activity for a specific service, aggregated by hour, day, or month. It also includes usage charts that provide a graphical representation of your CloudFront usage. AWS billing and usage reports for CloudFront 826 Amazon CloudFront Note Developer Guide Like other AWS services, CloudFront charges you for only what you use. For more information, see CloudFront pricing. Topics • View the AWS billing report for CloudFront • View the AWS usage report for CloudFront • Interpret your AWS bill and usage reports for CloudFront View the AWS billing report for CloudFront You can view a summary of your AWS usage and charges, listed by service, on the Bills page in the AWS Billing and Cost Management console. To view the AWS billing report 1. Sign in to the AWS Management Console and open the AWS Billing and Cost Management console at https://console.aws.amazon.com/costmanagement/. 2. In the navigation pane, choose Bills. 3. Choose a Billing period (for example, August 2023). 4. On the Charges by service tab, choose CloudFront, and then expand Global or the AWS Region name. 5. To download a detailed billing report in CSV format, choose Download all to CSV. For more information about your AWS bill, see Viewing your bill in the AWS Billing User Guide. The billing report includes the following values that apply to CloudFront: • ProductCode – AmazonCloudFront • UsageType – One of the following values: • A code that identifies the type of data transfer • Invalidations • Executions-CloudFrontFunctions View the AWS billing report for CloudFront 827 Amazon CloudFront Developer Guide • KeyValueStore-APIOperations • KeyValueStore-EdgeReads • RealTimeLog-KinesisDataStream • SSL-Cert-Custom • ItemDescription – A description of the billing rate for the UsageType. • UsageStart Date and UsageEndDate – The day that the usage applies to, in Coordinated Universal Time (UTC). • UsageQuantity – One of the following values: • The number of requests during the specified time period • The amount of data transferred in gigabytes • The number of objects invalidated • The sum of the prorated months that you had SSL certificates associated with enabled CloudFront distributions. For example, if you have one certificate associated with an enabled distribution for an entire month and another certificate associated with an enabled distribution for half of the month, this value will be 1.5. View the AWS usage report for CloudFront AWS provides a CloudFront usage report that is more detailed than the billing report but less detailed than CloudFront access logs. The usage report provides aggregate usage data by hour, day, or month, and it lists operations by region and usage type, such as data transferred out of the Australia region. To view the AWS usage report 1. Sign in to the AWS Management Console and open the AWS Billing and Cost Management console at https://console.aws.amazon.com/costmanagement/. 2. In the navigation pane, choose Cost & Reports. 3. Under the AWS Usage Report section, choose Create a Usage Report. 4. On the Download usage report page, under Services, choose Amazon CloudFront 5. Choose the Usage type. 6. Choose the Operation. View the AWS usage report for CloudFront 828 Amazon CloudFront Developer Guide 7. Choose the Time period for the report. If you choose Custom date range, you need to specify the Date range for the report manually. 8. Under Report granularity, choose Hourly, Daily, or Monthly. 9. Choose Download, and then choose XML Report or CSV Report. For more information about the AWS usage report, see AWS Usage Report in the AWS Data Exports User Guide. The CloudFront usage report includes the following values: • Service – AmazonCloudFront • Operation – HTTP method. Values include DELETE, GET, HEAD, OPTIONS, PATCH, POST, and PUT. • UsageType – One of the following values: • A code that identifies the type of data transfer • Invalidations • Executions-CloudFrontFunctions • KeyValueStore-APIOperations • KeyValueStore-EdgeReads • RealTimeLog-KinesisDataStream • SSL-Cert-Custom • Resource – Either the ID of the CloudFront distribution associated with the usage or the certificate ID of an SSL certificate that you have associated with a CloudFront distribution. • StartTime/EndTime – The day that the usage applies to, in Coordinated Universal Time (UTC). • UsageValue – 1) The number of requests during the specified time period or 2)the amount of data transferred in bytes. If you’re using Amazon S3 as the origin for CloudFront, consider running the usage report for Amazon S3, too. However, if you use Amazon S3 for purposes other than as an origin for your CloudFront distributions, it might not be clear what portion applies to your CloudFront usage. View the AWS usage report for CloudFront 829 Amazon CloudFront Tip Developer Guide For detailed information about every request that CloudFront receives for your objects, turn on CloudFront access logs for your distribution.
AmazonCloudFront_DevGuide-291
AmazonCloudFront_DevGuide.pdf
291
– 1) The number of requests during the specified time period or 2)the amount of data transferred in bytes. If you’re using Amazon S3 as the origin for CloudFront, consider running the usage report for Amazon S3, too. However, if you use Amazon S3 for purposes other than as an origin for your CloudFront distributions, it might not be clear what portion applies to your CloudFront usage. View the AWS usage report for CloudFront 829 Amazon CloudFront Tip Developer Guide For detailed information about every request that CloudFront receives for your objects, turn on CloudFront access logs for your distribution. For more information, see the section called “Standard logging (access logs)”. For more information about understanding the CloudFront charges and usage types on your reports, see the section called “Interpret your AWS bill and usage reports for CloudFront”. Interpret your AWS bill and usage reports for CloudFront Once you have the billing report and the usage report, you can use this topic to understand how to interpret each CloudFront charge that appears on your bill and the corresponding usage type for each charge. This topic includes the codes and AWS Region abbreviations that can appear on both reports. Most codes in both columns include a two-letter abbreviation that indicates the location of the activity. In the following table, region in a code is replaced in your AWS bill and in the usage report by one of the following two-letter abbreviations: • AP: Hong Kong, Philippines, South Korea, Taiwan, and Singapore (Asia Pacific) • AU: Australia • CA: Canada • EU: Europe and Israel • IN: India • JP: Japan • ME: Middle East • SA: South America • US: United States • ZA: South Africa For more information about pricing by AWS Region, see Amazon CloudFront pricing. Interpret your AWS bill and usage reports for CloudFront 830 Amazon CloudFront Notes Developer Guide • This table doesn't include charges for transferring your objects from an Amazon S3 bucket to CloudFront edge locations. These charges, if any, appear in the AWS Data Transfer portion of your AWS bill. • The first column lists charges that appear in your AWS bill report and explains what each means. • The second column lists items that appear in the AWS usage report and shows the correlation between bill charges and usage report items. CloudFront charges in your AWS bill Values in the UsageType column in the AWS usage report region-DataTransfer-Out-Bytes region-Out-Bytes-HTTP-Static: Total bytes served from CloudFront edge Bytes served via HTTP for objects with TTL ≥ locations in region in response to user GET and HEAD requests. 3,600 seconds. region-Out-Bytes-HTTPS-Static: Bytes served via HTTPS for objects with TTL ≥ 3,600 seconds. region-Out-Bytes-HTTP-Dynamic: Bytes served via HTTP for objects with TTL < 3,600 seconds. region-Out-Bytes-HTTPS-Dynamic: Bytes served via HTTPS for objects with TTL < 3,600 seconds. region-Out-Bytes-HTTP-Proxy: Interpret your AWS bill and usage reports for CloudFront 831 Amazon CloudFront Developer Guide CloudFront charges in your AWS bill Values in the UsageType column in the AWS usage report Bytes returned from CloudFront to viewers via HTTP in response to DELETE, OPTIONS, PATCH, POST, and PUT requests. region-Out-Bytes-HTTPS-Proxy: Bytes returned from CloudFront to viewers via HTTPS in response to DELETE, OPTIONS, PATCH, POST, and PUT requests. This includes bytes returned from CloudFront to viewers via gRPC. region-DataTransfer-Out-OBytes region-Out-OBytes-HTTP-Proxy Total bytes transferred from CloudFront edge Total bytes transferred via HTTP from locations to your origin or edge function in CloudFront edge locations to your origin response to DELETE, OPTIONS, PATCH, POST, and PUT requests. The charges include data transfer for WebSocket data from client to server. or edge function in response to DELETE, OPTIONS, PATCH, POST, and PUT requests. region-Out-OBytes-HTTPS-Proxy Total bytes transferred via HTTPS from CloudFront edge locations to your origin or edge function in response to DELETE, OPTIONS, PATCH, POST, and PUT requests. This includes bytes transferred via gRPC from CloudFront edge locations to your origin or CloudFront Functions. Interpret your AWS bill and usage reports for CloudFront 832 Amazon CloudFront Developer Guide CloudFront charges in your AWS bill Values in the UsageType column in the AWS usage report region-Requests-Tier1 region-Requests-HTTP-Static Number of HTTP GET and HEAD requests. Number of HTTP GET and HEAD requests s erved for objects with TTL ≥ 3,600 seconds. region-Requests-HTTP-Dynamic Number of HTTP GET and HEAD requests s erved for objects with TTL < 3,600 seconds. region-Requests-Tier2-HTTPS region-Requests-HTTPS-Static Number of HTTPS GET and HEAD requests. Number of HTTPS GET and HEAD requests s erved for objects with TTL ≥ 3,600 seconds. region-Requests-HTTPS-Dynamic Number of HTTPS GET and HEAD requests s erved for objects with TTL < 3,600 seconds. region-Requests-HTTP-Proxy region-Requests-HTTP-Proxy Same as the corresponding item in your CloudFront bill. Number of HTTP DELETE, OPTIONS, PATCH, POST, and PUT requests that CloudFront forwards to your origin or edge function. Also includes the number
AmazonCloudFront_DevGuide-292
AmazonCloudFront_DevGuide.pdf
292
for objects with TTL ≥ 3,600 seconds. region-Requests-HTTP-Dynamic Number of HTTP GET and HEAD requests s erved for objects with TTL < 3,600 seconds. region-Requests-Tier2-HTTPS region-Requests-HTTPS-Static Number of HTTPS GET and HEAD requests. Number of HTTPS GET and HEAD requests s erved for objects with TTL ≥ 3,600 seconds. region-Requests-HTTPS-Dynamic Number of HTTPS GET and HEAD requests s erved for objects with TTL < 3,600 seconds. region-Requests-HTTP-Proxy region-Requests-HTTP-Proxy Same as the corresponding item in your CloudFront bill. Number of HTTP DELETE, OPTIONS, PATCH, POST, and PUT requests that CloudFront forwards to your origin or edge function. Also includes the number of HTTP WebSocket requests (GET requests with the Upgrade: header) that CloudFront websocket forwards to your origin or edge function. Interpret your AWS bill and usage reports for CloudFront 833 Amazon CloudFront Developer Guide CloudFront charges in your AWS bill Values in the UsageType column in the AWS usage report region-Requests-HTTPS-Proxy region-Requests-HTTPS-Proxy Same as the corresponding item in your CloudFront bill. Number of HTTPS DELETE, OPTIONS, PATCH, POST, and PUT requests that CloudFront forwards to your origin or edge function. Also includes the following request types: • • The number of HTTPS WebSocket requests (GET requests with the Upgrade: websocket header) that CloudFront forwards to your origin or edge function. The number of HTTPS gRPC requests. region-Requests-HTTPS-Proxy-FLE region-Requests-HTTPS-Proxy-FLE Number of HTTPS DELETE, OPTIONS, PATCH, and POST requests processed with field-level encryption that CloudFront forwards to your origin or edge function. Same as the corresponding item in your CloudFront bill. region-Bytes-OriginShield region-Bytes-OriginShield Total bytes transferred from the origin to any Same as the corresponding item in your regional edge cache, including the regional CloudFront bill. edge cache that is enabled as Origin Shield. region-OBytes-OriginShield region-OBytes-OriginShield Total bytes transferred to the origin from any Same as the corresponding item in your regional edge cache, including the regional CloudFront bill. edge cache that is enabled as Origin Shield. Interpret your AWS bill and usage reports for CloudFront 834 Amazon CloudFront Developer Guide CloudFront charges in your AWS bill Values in the UsageType column in the AWS usage report region-Requests-OriginShield region-Requests-OriginShield Number of requests that go to Origin Shield Same as the corresponding item in your as an incremental layer. For dynamic (non- CloudFront bill. cacheable) requests that are proxied to the origin, Origin Shield is always an incremental layer. For cacheable requests, Origin Shield is sometimes an incremental layer. For more information, see the section called “Estimating Origin Shield costs”. Invalidations Invalidations The charge for invalidating objects (removing Same as the corresponding item in your the objects from CloudFront edge locations). CloudFront bill. For more information, see Pay for file invalidat ion. SSL-Cert-Custom SSL-Cert-Custom The charge for using an SSL certificate with Same as the corresponding item in your a CloudFront alternate domain name such CloudFront bill. as example.com instead of using the default CloudFront SSL certificate and the domain name that CloudFront assigned to your distr ibution. RealTimeLog-KinesisDataStream RealTimeLog-KinesisDataStream The charge for the number of lines generated for real-time logs. Same as the corresponding item in your CloudFront bill. Interpret your AWS bill and usage reports for CloudFront 835 Amazon CloudFront Developer Guide CloudFront charges in your AWS bill Values in the UsageType column in the AWS usage report Executions-CloudFrontFunctions Executions-CloudFrontFunctions The charge for the number of CloudFront Same as the corresponding item in your Functions invocations. CloudFront bill. region-Lambda-Edge-Request region-Lambda-Edge-Request The charge for the number of Lambda@Edge Same as the corresponding item in your function invocations. CloudFront bill. region-Lambda-Edge-GB-Second region-Lambda-Edge-GB-Second The charge for the duration from when your Same as the corresponding item in your Lambda@Edge function is invoked to when it CloudFront bill. returns or terminates. KeyValueStore-EdgeReads KeyValueStore-EdgeReads The charge for the number of read calls to the Same as the corresponding item in your CloudFront KeyValueStore methods, get(), exists(), and meta(). For more informati on, see Helper methods for key value stores. CloudFront bill. KeyValueStore-APIOperations KeyValueStore-APIOperations The charge for the number of calls to the Same as the corresponding item in your CloudFront KeyValueStore API. CloudFront bill. View CloudFront reports in the console Each report provides detailed information and visualizations, so that you can optimize content delivery, identify performance bottlenecks, and make data-driven decisions. Whether you need to monitor cache efficiency, analyze traffic patterns, or understand your viewers better, you can use these reports to effectively monitor and analyze your CloudFront distributions. You can view the following reports of your CloudFront activity in the console: View CloudFront console reports 836 Amazon CloudFront Topics • View CloudFront cache statistics reports • View CloudFront popular objects reports • View CloudFront top referrers reports • View CloudFront usage reports • View CloudFront viewers reports Developer Guide Most of these reports are based on the data in CloudFront access logs, which contain detailed information about every user request that CloudFront receives. You don't
AmazonCloudFront_DevGuide-293
AmazonCloudFront_DevGuide.pdf
293
cache efficiency, analyze traffic patterns, or understand your viewers better, you can use these reports to effectively monitor and analyze your CloudFront distributions. You can view the following reports of your CloudFront activity in the console: View CloudFront console reports 836 Amazon CloudFront Topics • View CloudFront cache statistics reports • View CloudFront popular objects reports • View CloudFront top referrers reports • View CloudFront usage reports • View CloudFront viewers reports Developer Guide Most of these reports are based on the data in CloudFront access logs, which contain detailed information about every user request that CloudFront receives. You don't need to enable access logs to view the reports. For more information, see Standard logging (access logs). View CloudFront cache statistics reports The Amazon CloudFront cache statistics report shows the following information: • Total requests – The total number of requests for all HTTP status codes (for example, 200 or 404) and all methods (for example, GET, HEAD, or POST) • Percentage of viewer requests by result type – Hits, misses, and errors as a percentage of total viewer requests for the selected CloudFront distribution • Bytes transferred to viewers – Total bytes and bytes from misses • HTTP status codes – Viewer requests by HTTP status code • Percentage of GET requests that didn't finish downloading – Viewer GET requests that didn't finish downloading the requested object as a percentage of total requests Data for these statistics is drawn from the same source as CloudFront access logs. However, you don't need to enable access logging to view cache statistics. You can display charts for a specified date range in the last 60 days, with data points every hour or every day. You can usually view data about requests that CloudFront received as recently as an hour ago, but data can occasionally be delayed by as much as 24 hours. Topics • View CloudFront cache statistics reports in the console • Download data in CSV format View CloudFront cache statistics reports 837 Amazon CloudFront Developer Guide • How cache statistics charts are related to data in the CloudFront standard logs (access logs) View CloudFront cache statistics reports in the console You can view the CloudFront cache statistics report in the console. To view the CloudFront cache statistics report 1. Sign in to the AWS Management Console and open the CloudFront console at https:// 2. 3. 4. 5. 6. console.aws.amazon.com/cloudfront/v4/home. In the navigation pane, choose Cache Statistics. In the CloudFront Cache Statistics Reports pane, for Start Date and End Date, select the date range for which you want to display cache statistics charts. Available ranges depend on the value that you select for Granularity: • Daily – To display charts with one data point per day, select any date range in the previous 60 days. • Hourly – To display charts with one data point every hour, select any date range of up to 14 days within the previous 60 days. Dates and times are in Coordinated Universal Time (UTC). For Granularity, specify whether to display one data point per day or one data point per hour in the charts. If you specify a date range greater than 14 days, the option to specify one data point per hour is not available. For Viewer Location, choose the continent from which viewer requests originated, or choose All Locations. Cache statistics charts include data for requests that CloudFront received from the specified location. In the Distribution list, select the distributions for which you want to display data in the usage charts: • An individual distribution – The charts display data for the selected CloudFront distribution. The Distribution list displays the distribution ID and alternate domain names (CNAMEs) for the distribution, if any. If a distribution doesn't have alternate domain names, the list includes origin domain names for the distribution. • All distributions – The charts display summed data for all distributions that are associated with the current AWS account, excluding distributions that you have deleted. View CloudFront cache statistics reports 838 Amazon CloudFront 7. Choose Update. Tip Developer Guide • To view data for a daily or hourly data point within a chart, hover over the data point. • For charts that show data transferred, you can change the vertical scale to gigabytes, megabytes, or kilobytes. Download data in CSV format You can download the cache statistics report in CSV format. This section explains how to download the report and describes the values in the report. To download the cache statistics report in CSV format 1. While viewing the cache statistics report, choose CSV. 2. In the Opening file name dialog box, choose whether to open or save the file. Information about the report The first few rows of the report include the following information: Version The version of the format for this
AmazonCloudFront_DevGuide-294
AmazonCloudFront_DevGuide.pdf
294
data transferred, you can change the vertical scale to gigabytes, megabytes, or kilobytes. Download data in CSV format You can download the cache statistics report in CSV format. This section explains how to download the report and describes the values in the report. To download the cache statistics report in CSV format 1. While viewing the cache statistics report, choose CSV. 2. In the Opening file name dialog box, choose whether to open or save the file. Information about the report The first few rows of the report include the following information: Version The version of the format for this CSV file. Report The name of the report. DistributionID The ID of the distribution that you ran the report for, or ALL if you ran the report for all distributions. StartDateUTC The beginning of the date range for which you ran the report, in Coordinated Universal Time (UTC). View CloudFront cache statistics reports 839 Amazon CloudFront EndDateUTC Developer Guide The end of the date range for which you ran the report, in Coordinated Universal Time (UTC). GeneratedTimeUTC The date and time on which you ran the report, in Coordinated Universal Time (UTC). Granularity Whether each row in the report represents one hour or one day. ViewerLocation The continent that viewer requests originated from, or ALL, if you chose to download the report for all locations. Data in the cache statistics report The report includes the following values: DistributionID The ID of the distribution that you ran the report for, or ALL if you ran the report for all distributions. FriendlyName An alternate domain name (CNAME) for the distribution, if any. If a distribution has no alternate domain names, the list includes an origin domain name for the distribution. ViewerLocation The continent that viewer requests originated from, or ALL, if you chose to download the report for all locations. TimeBucket The hour or the day that data applies to, in Coordinated Universal Time (UTC). RequestCount The total number of requests for all HTTP status codes (for example, 200 or 404) and all methods (for example, GET, HEAD, or POST). View CloudFront cache statistics reports 840 Amazon CloudFront HitCount Developer Guide The number of viewer requests for which the object is served from a CloudFront edge cache. MissCount The number of viewer requests for which the object isn't currently in an edge cache, so CloudFront must get the object from your origin. ErrorCount The number of viewer requests that resulted in an error, so CloudFront didn't serve the object. IncompleteDownloadCount The number of viewer requests for which the viewer started but didn't finish downloading the object. HTTP2xx The number of viewer requests for which the HTTP status code was a 2xx value (succeeded). HTTP3xx The number of viewer requests for which the HTTP status code was a 3xx value (additional action is required). HTTP4xx The number of viewer requests for which the HTTP status code was a 4xx value (client error). HTTP5xx The number of viewer requests for which the HTTP status code was a 5xx value (server error). TotalBytes The total number of bytes served to viewers by CloudFront in response to all requests for all HTTP methods. BytesFromMisses The number of bytes served to viewers for objects that were not in the edge cache at the time of the request. This value is a good approximation of bytes transferred from your origin to CloudFront edge caches. However, it excludes requests for objects that are already in the edge cache but that have expired. View CloudFront cache statistics reports 841 Amazon CloudFront Developer Guide How cache statistics charts are related to data in the CloudFront standard logs (access logs) The following table shows how cache statistics charts in the CloudFront console correspond with values in CloudFront access logs. For more information about CloudFront access logs, see Standard logging (access logs). Total requests This chart shows the total number of requests for all HTTP status codes (for example, 200 or 404) and all methods (for example, GET, HEAD, or POST). Total requests shown in this chart equal the total number of requests in the access log files for the same time period. Percentage of viewer requests by result type This chart shows hits, misses, and errors as a percentage of total viewer requests for the selected CloudFront distribution: • Hit – A viewer request for which the object is served from a CloudFront edge cache. In access logs, these are requests for which the value of x-edge-response-result-type is Hit. • Miss – A viewer request for which the object isn't currently in an edge cache, so CloudFront must get the object from your origin. In access logs, these are requests for which the value of x-edge-response-result-type is Miss. • Error – A viewer request that resulted in an error, so CloudFront didn't
AmazonCloudFront_DevGuide-295
AmazonCloudFront_DevGuide.pdf
295
hits, misses, and errors as a percentage of total viewer requests for the selected CloudFront distribution: • Hit – A viewer request for which the object is served from a CloudFront edge cache. In access logs, these are requests for which the value of x-edge-response-result-type is Hit. • Miss – A viewer request for which the object isn't currently in an edge cache, so CloudFront must get the object from your origin. In access logs, these are requests for which the value of x-edge-response-result-type is Miss. • Error – A viewer request that resulted in an error, so CloudFront didn't serve the object. In access logs, these are requests for which the value of x-edge-response-result-type is Error, LimitExceeded, or CapacityExceeded. The chart does not include refresh hits—requests for objects that are in the edge cache but that have expired. In access logs, refresh hits are requests for which the value of x-edge- response-result-type is RefreshHit. Bytes transferred to viewers This chart shows two values: • Total bytes – The total number of bytes served to viewers by CloudFront in response to all requests for all HTTP methods. In CloudFront access logs, Total Bytes is the sum of the values in the sc-bytes column for all of the requests during the same time period. • Bytes from misses – The number of bytes served to viewers for objects that were not in the edge cache at the time of the request. In CloudFront access logs, bytes from misses is the sum of the values in the sc-bytes column for requests for which the value of x-edge- View CloudFront cache statistics reports 842 Amazon CloudFront Developer Guide result-type is Miss. This value is a good approximation of bytes transferred from your origin to CloudFront edge caches. However, it excludes requests for objects that are already in the edge cache but that have expired. HTTP status codes This chart shows viewer requests by HTTP status code. In CloudFront access logs, status codes appear in the sc-status column: • 2xx – The request succeeded. • 3xx – Additional action is required. For example, 301 (Moved Permanently) means that the requested object has moved to a different location. • 4xx – The client apparently made an error. For example, 404 (Not Found) means that the client requested an object that could not be found. • 5xx – The origin server didn't fill the request. For example, 503 (Service Unavailable) means that the origin server is currently unavailable. Percentage of GET requests that didn't finish downloading This chart shows viewer GET requests that didn't finish downloading the requested object as a percentage of total requests. Typically, downloading an object doesn't complete because the viewer canceled the download, for example, by clicking a different link or by closing the browser. In CloudFront access logs, these requests have a value of 200 in the sc-status column and a value of Error in the x-edge-result-type column. View CloudFront popular objects reports View the Amazon CloudFront popular objects report to see the 50 most popular objects for a distribution during a specified date range in the previous 60 days. You can also view statistics about those objects, including the following: • Number of requests for the object • Number of hits and misses • Hit ratio • Number of bytes served for misses • Total bytes served • Number of incomplete downloads • Number of requests by HTTP status code (2xx, 3xx, 4xx, and 5xx) View CloudFront popular objects reports 843 Amazon CloudFront Developer Guide Data for these statistics is drawn from the same source as CloudFront access logs. However, you don't need to enable access logging to view popular objects. Topics • View CloudFront popular objects reports in the console • How CloudFront calculates popular objects statistics • Download data in CSV format • How data in the popular objects report is related to data in the CloudFront standard logs (access logs) View CloudFront popular objects reports in the console You can view the CloudFront popular objects report in the console. To view popular objects for a CloudFront distribution 1. Sign in to the AWS Management Console and open the CloudFront console at https:// 2. 3. console.aws.amazon.com/cloudfront/v4/home. In the navigation pane, choose Popular Objects. In the CloudFront Popular Objects Report pane, for Start Date and End Date, select the date range for which you want to display a list of popular objects. You can choose any date range in the previous 60 days. Dates and times are in Coordinated Universal Time (UTC). 4. In the Distribution list, select the distribution for which you want to display a list of popular objects. 5. Choose Update. How CloudFront calculates popular objects statistics To get an accurate count of the top 50 objects in your distribution, CloudFront counts the requests for all
AmazonCloudFront_DevGuide-296
AmazonCloudFront_DevGuide.pdf
296
navigation pane, choose Popular Objects. In the CloudFront Popular Objects Report pane, for Start Date and End Date, select the date range for which you want to display a list of popular objects. You can choose any date range in the previous 60 days. Dates and times are in Coordinated Universal Time (UTC). 4. In the Distribution list, select the distribution for which you want to display a list of popular objects. 5. Choose Update. How CloudFront calculates popular objects statistics To get an accurate count of the top 50 objects in your distribution, CloudFront counts the requests for all of your objects in 10-minute intervals beginning at midnight and keeps a running total of the top 150 objects for the next 24 hours. (CloudFront also retains daily totals for the top 150 objects for 60 days.) Near the bottom of the list, objects constantly rise onto or drop off the list, so the totals for those objects are approximations. The 50 objects at the top of the list of 150 objects might rise and fall View CloudFront popular objects reports 844 Amazon CloudFront Developer Guide within the list, but they rarely drop off the list altogether, so the totals for those objects are more reliable. When an object drops off the list of the top 150 objects and then rises onto the list again over the course of a day, CloudFront adds an estimated number of requests for the period that the object was missing from the list. The estimate is based on the number of requests received by whichever object was at the bottom of the list during that time period. If the object rises into the top 50 objects later in the day, the estimates of the number of requests that CloudFront received while the object was out of the top 150 objects usually causes the number of requests in the popular objects report to exceed the number of requests that appear in the access logs for that object. Download data in CSV format You can download the popular objects report in CSV format. This section explains how to download the report and describes the values in the report. To download the popular objects report in CSV format 1. While viewing the popular objects report, choose CSV. 2. In the Opening file name dialog box, choose whether to open or save the file. Information about the report The first few rows of the report include the following information: Version The version of the format for this CSV file. Report The name of the report. DistributionID The ID of the distribution that you ran the report for. StartDateUTC The beginning of the date range for which you ran the report, in Coordinated Universal Time (UTC). View CloudFront popular objects reports 845 Amazon CloudFront EndDateUTC Developer Guide The end of the date range for which you ran the report, in Coordinated Universal Time (UTC). GeneratedTimeUTC The date and time on which you ran the report, in Coordinated Universal Time (UTC). Data in the popular objects report The report includes the following values: DistributionID The ID of the distribution that you ran the report for. FriendlyName An alternate domain name (CNAME) for the distribution, if any. If a distribution has no alternate domain names, the list includes an origin domain name for the distribution. Object The last 500 characters of the URL for the object. RequestCount The total number of requests for this object. HitCount The number of viewer requests for which the object is served from a CloudFront edge cache. MissCount The number of viewer requests for which the object isn't currently in an edge cache, so CloudFront must get the object from your origin. HitCountPct The value of HitCount as a percentage of the value of RequestCount. BytesFromMisses The number of bytes served to viewers for this object when the object was not in the edge cache at the time of the request. View CloudFront popular objects reports 846 Amazon CloudFront TotalBytes Developer Guide The total number of bytes served to viewers by CloudFront for this object in response to all requests for all HTTP methods. IncompleteDownloadCount The number of viewer requests for this object for which the viewer started but didn't finish downloading the object. HTTP2xx The number of viewer requests for which the HTTP status code was a 2xx value (succeeded). HTTP3xx The number of viewer requests for which the HTTP status code was a 3xx value (additional action is required). HTTP4xx The number of viewer requests for which the HTTP status code was a 4xx value (client error). HTTP5xx The number of viewer requests for which the HTTP status code was a 5xx value (server error). How data in the popular objects report is related to data in the CloudFront standard logs (access logs) The
AmazonCloudFront_DevGuide-297
AmazonCloudFront_DevGuide.pdf
297
viewer started but didn't finish downloading the object. HTTP2xx The number of viewer requests for which the HTTP status code was a 2xx value (succeeded). HTTP3xx The number of viewer requests for which the HTTP status code was a 3xx value (additional action is required). HTTP4xx The number of viewer requests for which the HTTP status code was a 4xx value (client error). HTTP5xx The number of viewer requests for which the HTTP status code was a 5xx value (server error). How data in the popular objects report is related to data in the CloudFront standard logs (access logs) The following list shows how values in the popular objects report in the CloudFront console correspond with values in CloudFront access logs. For more information about CloudFront access logs, see Standard logging (access logs). URL The last 500 characters of the URL that viewers use to access the object. Requests The total number of requests for the object. This value generally corresponds closely with the number of GET requests for the object in CloudFront access logs. View CloudFront popular objects reports 847 Amazon CloudFront Hits Developer Guide The number of viewer requests for which the object was served from a CloudFront edge cache. In access logs, these are requests for which the value of x-edge-response-result-type is Hit. Misses The number of viewer requests for which the object wasn't in an edge cache, so CloudFront retrieved the object from your origin. In access logs, these are requests for which the value of x-edge-response-result-type is Miss. Hit ratio The value of the Hits column as a percentage of the value of the Requests column. Bytes from misses The number of bytes served to viewers for objects that were not in the edge cache at the time of the request. In CloudFront access logs, bytes from misses is the sum of the values in the sc- bytes column for requests for which the value of x-edge-result-type is Miss. Total bytes The total number of bytes that CloudFront served to viewers in response to all requests for the object for all HTTP methods. In CloudFront access logs, total bytes is the sum of the values in the sc-bytes column for all of the requests during the same time period. Incomplete downloads The number of viewer requests that did not finish downloading the requested object. Typically, the reason that a download doesn't complete is that the viewer canceled it, for example, by clicking a different link or by closing the browser. In CloudFront access logs, these requests have a value of 200 in the sc-status column and a value of Error in the x-edge-result-type column. 2xx The number of requests for which the HTTP status code is 2xx, Successful. In CloudFront access logs, status codes appear in the sc-status column. 3xx The number of requests for which the HTTP status code is 3xx, Redirection. 3xx status codes indicate that additional action is required. For example, 301 (Moved Permanently) means that the requested object has moved to a different location. View CloudFront popular objects reports 848 Amazon CloudFront 4xx Developer Guide The number of requests for which the HTTP status code is 4xx, Client Error. 4xx status codes indicate that the client apparently made an error. For example, 404 (Not Found) means that the client requested an object that could not be found. 5xx The number of requests for which the HTTP status code is 5xx, Server Error. 5xx status codes indicate that the origin server didn't fill the request. For example, 503 (Service Unavailable) means that the origin server is currently unavailable. View CloudFront top referrers reports The CloudFront top referrers report includes the following for any date range in the previous 60 days: • Top 25 referrers (domains of websites that originated the most HTTP and HTTPS requests for objects that CloudFront is distributing for your distribution) • Number of requests from a referrer • Number of requests from a referrer as a percentage of the total number of requests during the specified period Data for the top referrers report is drawn from the same source as CloudFront access logs. However, you don't need to enable access logging to view the top referrers. Top referrers can be search engines, other websites that link directly to your objects, or your own website. For example, if https://example.com/index.html links to 10 graphics, example.com is the referrer for all 10 graphics. Note If a user enters a URL directly into the address line of a browser, there is no referrer for the requested object. Topics • View CloudFront top referrers reports in the console View CloudFront top referrers reports 849 Amazon CloudFront Developer Guide • How CloudFront calculates top referrers statistics • Download data in CSV format • How data in the top referrers report is related to data
AmazonCloudFront_DevGuide-298
AmazonCloudFront_DevGuide.pdf
298
can be search engines, other websites that link directly to your objects, or your own website. For example, if https://example.com/index.html links to 10 graphics, example.com is the referrer for all 10 graphics. Note If a user enters a URL directly into the address line of a browser, there is no referrer for the requested object. Topics • View CloudFront top referrers reports in the console View CloudFront top referrers reports 849 Amazon CloudFront Developer Guide • How CloudFront calculates top referrers statistics • Download data in CSV format • How data in the top referrers report is related to data in the CloudFront standard logs (access logs) View CloudFront top referrers reports in the console You can view the CloudFront top referrers report in the console. To view top referrers for a CloudFront distribution 1. Sign in to the AWS Management Console and open the CloudFront console at https:// 2. 3. console.aws.amazon.com/cloudfront/v4/home. In the navigation pane, choose Top Referrers. In the CloudFront Top Referrers Report pane, for Start Date and End Date, select the date range for which you want to display a list of top referrers. Dates and times are in Coordinated Universal Time (UTC). 4. In the Distribution list, select the distribution for which you want to display a list of top referrers. 5. Choose Update. How CloudFront calculates top referrers statistics To get an accurate count of the top 25 referrers, CloudFront counts the requests for all of your objects in 10-minute intervals and keeps a running total of the top 75 referrers. Near the bottom of the list, referrers constantly rise onto or drop off the list, so the totals for those referrers are approximations. The 25 referrers at the top of the list of 75 referrers might rise and fall within the list, but they rarely drop off of the list altogether, so the totals for those referrers typically are more reliable. Download data in CSV format You can download the top referrers report in CSV format. This section explains how to download the report and describes the values in the report. View CloudFront top referrers reports 850 Amazon CloudFront Developer Guide To download the top referrers report in CSV format 1. While viewing the Top Referrers report, choose CSV. 2. In the Opening file name dialog box, choose whether to open or save the file. Information about the report The first few rows of the report include the following information: Version The version of the format for this CSV file. Report The name of the report. DistributionID The ID of the distribution that you ran the report for, or ALL if you ran the report for all distributions. StartDateUTC The beginning of the date range for which you ran the report, in Coordinated Universal Time (UTC). EndDateUTC The end of the date range for which you ran the report, in Coordinated Universal Time (UTC). GeneratedTimeUTC The date and time on which you ran the report, in Coordinated Universal Time (UTC). Data in the top referrers report The report includes the following values: DistributionID The ID of the distribution that you ran the report for, or ALL if you ran the report for all distributions. View CloudFront top referrers reports 851 Amazon CloudFront FriendlyName Developer Guide An alternate domain name (CNAME) for the distribution, if any. If a distribution has no alternate domain names, the list includes an origin domain name for the distribution. Referrer The domain name of the referrer. RequestCount The total number of requests from the domain name in the Referrer column. RequestsPct The number of requests submitted by the referrer as a percentage of the total number of requests during the specified period. How data in the top referrers report is related to data in the CloudFront standard logs (access logs) The following list shows how values in the Top Referrers report in the CloudFront console correspond with values in CloudFront access logs. For more information about CloudFront access logs, see Standard logging (access logs). Referrer The domain name of the referrer. In access logs, referrers are listed in the cs(Referer) column. Request count The total number of requests from the domain name in the Referrer column. This value generally corresponds closely with the number of GET requests from the referrer in CloudFront access logs. Request % The number of requests submitted by the referrer as a percentage of the total number of requests during the specified period. If you have more than 25 referrers, then you can't calculate Request % based on the data in this table because the request count column doesn't include all of the requests during the specified period. View CloudFront top referrers reports 852 Amazon CloudFront Developer Guide View CloudFront usage reports The CloudFront usage reports include the following information: • Number of requests – Shows
AmazonCloudFront_DevGuide-299
AmazonCloudFront_DevGuide.pdf
299
closely with the number of GET requests from the referrer in CloudFront access logs. Request % The number of requests submitted by the referrer as a percentage of the total number of requests during the specified period. If you have more than 25 referrers, then you can't calculate Request % based on the data in this table because the request count column doesn't include all of the requests during the specified period. View CloudFront top referrers reports 852 Amazon CloudFront Developer Guide View CloudFront usage reports The CloudFront usage reports include the following information: • Number of requests – Shows the total number of requests that CloudFront responds to from edge locations in the selected region during each time interval for the specified CloudFront distribution. • Data transferred by protocol and data transferred by destination – Both show the total amount of data transferred from CloudFront edge locations in the selected region during each time interval for the specified CloudFront distribution. They separate the data differently, as follows: • By protocol – Separates the data by protocol: HTTP or HTTPS. • By destination – Separates the data by destination: to your viewers or to your origin. The CloudFront usage report is based on the AWS usage report for CloudFront. This report doesn't require any additional configuration. For more information, see View the AWS usage report for CloudFront. You can view reports for a specified date range in the last 60 days, with data points every hour or every day. You can usually view data about requests that CloudFront received as recently as four hours ago, but data can occasionally be delayed by as much as 24 hours. For more information, see How the usage charts are related to data in the CloudFront usage report. Topics • View CloudFront usage reports in the console • Download data in CSV format • How the usage charts are related to data in the CloudFront usage report View CloudFront usage reports in the console You can view the CloudFront usage report in the console. To view CloudFront usage reports 1. Sign in to the AWS Management Console and open the CloudFront console at https:// console.aws.amazon.com/cloudfront/v4/home. View CloudFront usage reports 853 Amazon CloudFront Developer Guide 2. 3. 4. 5. In the navigation pane, choose Usage Reports. In the CloudFront Usage Reports pane, for Start Date and End Date, select the date range for which you want to display usage charts. Available ranges depend on the value that you select for Granularity: • Daily — To display charts with one data point per day, select any date range in the previous 60 days. • Hourly — To display charts with one data point every hour, select any date range of up to 14 days within the previous 60 days. Dates and times are in Coordinated Universal Time (UTC). For Granularity, specify whether to display one data point per day or one data point per hour in the charts. If you specify a date range greater than 14 days, the option to specify one data point per hour is not available. For Billing Region, choose the CloudFront billing region that has the data you want to view, or choose All Regions. Usage charts include data for requests that CloudFront processes in edge locations in the specified region. The region where CloudFront processes requests might or might not correspond with the location of your viewers. Select only Regions that are included in the price class for your distribution. Otherwise, the usage charts probably won't contain any data. For example, if you chose Price Class 200 for your distribution, the South America and Australia billing regions are not included, so CloudFront generally won't process your requests from those regions. For more information about price classes, see CloudFront pricing. 6. In the Distribution list, select the distributions for which you want to display data in the usage charts: • An individual distribution — The charts display data for the selected CloudFront distribution. The Distribution list displays the distribution ID and alternate domain names (CNAMEs) for the distribution, if any. If a distribution has no alternate domain names, the list includes origin domain names for the distribution. • All distributions (excludes deleted) — The charts display summed data for all distributions that are associated with the current AWS account, excluding distributions that you have deleted. • All Deleted Distributions — The charts display summed data for all distributions that are associated with the current AWS account and that were deleted in the last 60 days. View CloudFront usage reports 854 Amazon CloudFront 7. Choose Update Graphs. Tip Developer Guide • To view data for a daily or hourly data point within a chart, hover over the data point. • For charts that show data transferred, note that you can change the
AmazonCloudFront_DevGuide-300
AmazonCloudFront_DevGuide.pdf
300
deleted) — The charts display summed data for all distributions that are associated with the current AWS account, excluding distributions that you have deleted. • All Deleted Distributions — The charts display summed data for all distributions that are associated with the current AWS account and that were deleted in the last 60 days. View CloudFront usage reports 854 Amazon CloudFront 7. Choose Update Graphs. Tip Developer Guide • To view data for a daily or hourly data point within a chart, hover over the data point. • For charts that show data transferred, note that you can change the vertical scale to gigabytes, megabytes, or kilobytes. Download data in CSV format You can download the usage report in CSV format. This section explains how to download the report and describes the values in the report. To download the usage report in CSV format 1. While viewing the Usage report, choose CSV. 2. In the Opening file name dialog box, choose whether to open or save the file. Information about the report The first few rows of the report include the following information: Version The version of the format for this CSV file. Report The name of the report. DistributionID The ID of the distribution that you ran the report for, ALL if you ran the report for all distributions, or ALL_DELETED if you ran the report for all deleted distributions. StartDateUTC The beginning of the date range for which you ran the report, in Coordinated Universal Time (UTC). View CloudFront usage reports 855 Amazon CloudFront EndDateUTC Developer Guide The end of the date range for which you ran the report, in Coordinated Universal Time (UTC). GeneratedTimeUTC The date and time on which you ran the report, in Coordinated Universal Time (UTC). Granularity Whether each row in the report represents one hour or one day. BillingRegion The continent that viewer requests originated from, or ALL, if you chose to download the report for all billing regions. Data in the usage report The report includes the following values: DistributionID The ID of the distribution that you ran the report for, ALL if you ran the report for all distributions, or ALL_DELETED if you ran the report for all deleted distributions. FriendlyName An alternate domain name (CNAME) for the distribution, if any. If a distribution has no alternate domain names, the list includes an origin domain name for the distribution. BillingRegion The CloudFront billing region that you ran the report for, or ALL. TimeBucket The hour or the day that data applies to, in Coordinated Universal Time (UTC). HTTP The number of HTTP requests that CloudFront responded to from edge locations in the selected region during each time interval for the specified CloudFront distribution. Values include: • The number of GET and HEAD requests, which cause CloudFront to transfer data to your viewers View CloudFront usage reports 856 Amazon CloudFront Developer Guide • The number of DELETE, OPTIONS, PATCH, POST, and PUT requests, which cause CloudFront to transfer data to your origin HTTPS The number of HTTPS requests that CloudFront responded to from edge locations in the selected region during each time interval for the specified CloudFront distribution. Values include: • The number of GET and HEAD requests, which cause CloudFront to transfer data to your viewers • The number of DELETE, OPTIONS, PATCH, POST, and PUT requests, which cause CloudFront to transfer data to your origin HTTPBytes The total amount of data transferred over HTTP from CloudFront edge locations in the selected billing region during the time period for the specified CloudFront distribution. Values include: • Data transferred from CloudFront to your viewers in response to GET and HEAD requests • Data transferred from your viewers to CloudFront for DELETE, OPTIONS, PATCH, POST, and PUT requests • Data transferred from CloudFront to your viewers in response to DELETE, OPTIONS, PATCH, POST, and PUT requests HTTPSBytes The total amount of data transferred over HTTPS from CloudFront edge locations in the selected billing region during the time period for the specified CloudFront distribution. Values include: • Data transferred from CloudFront to your viewers in response to GET and HEAD requests • Data transferred from your viewers to CloudFront for DELETE, OPTIONS, PATCH, POST, and PUT requests • Data transferred from CloudFront to your viewers in response to DELETE, OPTIONS, PATCH, POST, and PUT requests BytesIn The total amount of data transferred from CloudFront to your origin for DELETE, OPTIONS, PATCH, POST, and PUT requests in the selected region during each time interval for the specified CloudFront distribution. View CloudFront usage reports 857 Amazon CloudFront BytesOut Developer Guide The total amount of data transferred over HTTP and HTTPS from CloudFront to your viewers in the selected region during each time interval for the specified CloudFront distribution. Values include: • Data transferred from CloudFront to
AmazonCloudFront_DevGuide-301
AmazonCloudFront_DevGuide.pdf
301
and PUT requests • Data transferred from CloudFront to your viewers in response to DELETE, OPTIONS, PATCH, POST, and PUT requests BytesIn The total amount of data transferred from CloudFront to your origin for DELETE, OPTIONS, PATCH, POST, and PUT requests in the selected region during each time interval for the specified CloudFront distribution. View CloudFront usage reports 857 Amazon CloudFront BytesOut Developer Guide The total amount of data transferred over HTTP and HTTPS from CloudFront to your viewers in the selected region during each time interval for the specified CloudFront distribution. Values include: • Data transferred from CloudFront to your viewers in response to GET and HEAD requests • Data transferred from CloudFront to your viewers in response to DELETE, OPTIONS, PATCH, POST, and PUT requests How the usage charts are related to data in the CloudFront usage report The following list shows how the usage charts in the CloudFront console correspond with values in the Usage Type column in the CloudFront usage report. Topics • Number of requests • Data transferred by protocol • Data transferred by destination Number of requests This chart shows the total number of requests that CloudFront responds to from edge locations in the selected region during each time interval for the specified CloudFront distribution, separated by protocol (HTTP or HTTPS) and type (static, dynamic, or proxy). Number of HTTP requests • region-Requests-HTTP-Static: Number of HTTP GET and HEAD requests served for objects with TTL ≥ 3600 seconds • region-Requests-HTTP-Dynamic: Number of HTTP GET and HEAD requests served for objects with TTL < 3600 seconds • region-Requests-HTTP-Proxy: Number of HTTP DELETE, OPTIONS, PATCH, POST, and PUT requests that CloudFront forwards to your origin Number of HTTPS requests • region-Requests-HTTPS-Static: Number of HTTPS GET and HEAD requests served for objects with TTL ≥ 3600 seconds View CloudFront usage reports 858 Amazon CloudFront Developer Guide • region-Requests-HTTPS-Dynamic: Number of HTTPS GET and HEAD requests served for objects with TTL < 3600 seconds • region-Requests-HTTPS-Proxy: Number of HTTPS DELETE, OPTIONS, PATCH, POST, and PUT requests that CloudFront forwards to your origin Data transferred by protocol This chart shows the total amount of data transferred from CloudFront edge locations in the selected region during each time interval for the specified CloudFront distribution, separated by protocol (HTTP or HTTPS), type (static, dynamic, or proxy), and destination (viewers or origin). Data transferred over HTTP • region-Out-Bytes-HTTP-Static: Bytes served via HTTP for objects with TTL ≥ 3600 seconds • region-Out-Bytes-HTTP-Dynamic: Bytes served via HTTP for objects with TTL < 3600 seconds • region-Out-Bytes-HTTP-Proxy: Bytes returned from CloudFront to viewers via HTTP in response to DELETE, OPTIONS, PATCH, POST, and PUT requests • region-Out-OBytes-HTTP-Proxy: Total bytes transferred via HTTP from CloudFront edge locations to your origin in response to DELETE, OPTIONS, PATCH, POST, and PUT requests Data transferred over HTTPS • region-Out-Bytes-HTTPS-Static: Bytes served via HTTPS for objects with TTL ≥ 3600 seconds • region-Out-Bytes-HTTPS-Dynamic: Bytes served via HTTPS for objects with TTL < 3600 seconds • region-Out-Bytes-HTTPS-Proxy: Bytes returned from CloudFront to viewers via HTTPS in response to DELETE, OPTIONS, PATCH, POST, and PUT requests • region-Out-OBytes-HTTPS-Proxy: Total bytes transferred via HTTPS from CloudFront edge locations to your origin in response to DELETE, OPTIONS, PATCH, POST, and PUT requests Data transferred by destination This chart shows the total amount of data transferred from CloudFront edge locations in the selected region during each time interval for the specified CloudFront distribution, separated by destination (viewers or origin), protocol (HTTP or HTTPS), and type (static, dynamic, or proxy). View CloudFront usage reports 859 Amazon CloudFront Developer Guide Data transferred from CloudFront to your viewers • region-Out-Bytes-HTTP-Static: Bytes served via HTTP for objects with TTL ≥ 3600 seconds • region-Out-Bytes-HTTPS-Static: Bytes served via HTTPS for objects with TTL ≥ 3600 seconds • region-Out-Bytes-HTTP-Dynamic: Bytes served via HTTP for objects with TTL < 3600 seconds • region-Out-Bytes-HTTPS-Dynamic: Bytes served via HTTPS for objects with TTL < 3600 seconds • region-Out-Bytes-HTTP-Proxy: Bytes returned from CloudFront to viewers via HTTP in response to DELETE, OPTIONS, PATCH, POST, and PUT requests • region-Out-Bytes-HTTPS-Proxy: Bytes returned from CloudFront to viewers via HTTPS in response to DELETE, OPTIONS, PATCH, POST, and PUT requests Data transferred from CloudFront to your origin • region-Out-OBytes-HTTP-Proxy: Total bytes transferred via HTTP from CloudFront edge locations to your origin in response to DELETE, OPTIONS, PATCH, POST, and PUT requests • region-Out-OBytes-HTTPS-Proxy: Total bytes transferred via HTTPS from CloudFront edge locations to your origin in response to DELETE, OPTIONS, PATCH, POST, and PUT requests View CloudFront viewers reports The CloudFront viewers reports include the following information for any date range in the previous 60 days: • Devices – The types of devices most frequently used to access your content (such as Desktop or Mobile) • Browsers – The top 10 browsers most frequently used to access your
AmazonCloudFront_DevGuide-302
AmazonCloudFront_DevGuide.pdf
302
region-Out-OBytes-HTTP-Proxy: Total bytes transferred via HTTP from CloudFront edge locations to your origin in response to DELETE, OPTIONS, PATCH, POST, and PUT requests • region-Out-OBytes-HTTPS-Proxy: Total bytes transferred via HTTPS from CloudFront edge locations to your origin in response to DELETE, OPTIONS, PATCH, POST, and PUT requests View CloudFront viewers reports The CloudFront viewers reports include the following information for any date range in the previous 60 days: • Devices – The types of devices most frequently used to access your content (such as Desktop or Mobile) • Browsers – The top 10 browsers most frequently used to access your content (such as Chrome or Firefox) • Operating systems – The top 10 operating systems most frequently used when accessing your content (such as Linux, macOS, or Windows) • Locations – The top 50 locations (countries or U.S. states/territories) of the viewers that most frequently access your content • You can also view locations with hourly data points for any date range of up to 14 days in the previous 60 days View CloudFront viewers reports 860 Amazon CloudFront Note Developer Guide You don't need to enable access logging to see viewers charts and reports. Topics • View viewers charts and reports in the console • Download data in CSV format • Data included in the viewers reports • How data in the locations report is related to data in the CloudFront standard logs (access logs) View viewers charts and reports in the console You can view CloudFront viewers charts and reports in the console. To view CloudFront viewers charts and reports 1. Sign in to the AWS Management Console and open the CloudFront console at https:// 2. 3. console.aws.amazon.com/cloudfront/v4/home. In the navigation pane, choose Viewers. In the CloudFront Viewers pane, for Start Date and End Date, select the date range for which you want to display viewer charts and reports. For the Locations chart, available ranges depend on the value that you select for Granularity: • Daily – To display charts with one data point per day, select any date range in the previous 60 days. • Hourly – To display charts with one data point every hour, select any date range of up to 14 days within the previous 60 days. Dates and times are in Coordinated Universal Time (UTC). 4. (Browsers and Operating Systems charts only) For Grouping, specify whether you want to group browsers and operating systems by name (Chrome, Firefox) or by name and version (Chrome 40.0, Firefox 35.0). View CloudFront viewers reports 861 Amazon CloudFront Developer Guide 5. 6. 7. (Locations chart only) For Granularity, specify whether to display one data point per day or one data point per hour in the charts. If you specify a date range greater than 14 days, the option to specify one data point per hour is not available. (Locations chart only) For Details, specify whether to display the top locations by countries or by U.S. states. In the Distribution list, select the distribution for which you want to display data in the usage charts: • An individual distribution – The charts display data for the selected CloudFront distribution. The Distribution list displays the distribution ID and an alternate domain name (CNAME) for the distribution, if any. If a distribution has no alternate domain names, the list includes an origin domain name for the distribution. • All distributions (excludes deleted) – The charts display summed data for all distributions that are associated with the current AWS account, excluding distributions that you have deleted. 8. Choose Update. To view data for a daily or hourly data point within a chart, hover over the data point. Download data in CSV format You can download each of the viewer reports in CSV format. This section explains how to download the reports and describes the values in the report. To download the viewer reports in CSV format 1. While viewing the Viewer report, choose CSV. 2. Choose the data that you want to download, for example, Devices or Devices Trends. 3. In the Opening file name dialog box, choose whether to open or save the file. Data included in the viewers reports The first few rows of each report include the following information: Version The version of the format for this CSV file. View CloudFront viewers reports 862 Amazon CloudFront Report The name of the report. DistributionID Developer Guide The ID of the distribution that you ran the report for, or ALL if you ran the report for all distributions. StartDateUTC The beginning of the date range for which you ran the report, in Coordinated Universal Time (UTC). EndDateUTC The end of the date range for which you ran the report, in Coordinated Universal Time (UTC). GeneratedTimeUTC The date and time on which you ran the report, in Coordinated Universal Time (UTC).
AmazonCloudFront_DevGuide-303
AmazonCloudFront_DevGuide.pdf
303
information: Version The version of the format for this CSV file. View CloudFront viewers reports 862 Amazon CloudFront Report The name of the report. DistributionID Developer Guide The ID of the distribution that you ran the report for, or ALL if you ran the report for all distributions. StartDateUTC The beginning of the date range for which you ran the report, in Coordinated Universal Time (UTC). EndDateUTC The end of the date range for which you ran the report, in Coordinated Universal Time (UTC). GeneratedTimeUTC The date and time on which you ran the report, in Coordinated Universal Time (UTC). Grouping (browsers and operating systems reports only) Whether the data is grouped by the name or by the name and version of the browser or operating system. Granularity Whether each row in the report represents one hour or one day. Details (locations report only) Whether requests are listed by country or by U.S. state. The following topics describe the information in the different viewers reports. Topics • Devices report • Device trends report • Browsers report • Browser trends report View CloudFront viewers reports 863 Amazon CloudFront Developer Guide • Operating systems report • Operating system trends report • Locations report • Location trends report Devices report The report includes the following values: DistributionID The ID of the distribution that you ran the report for, or ALL if you ran the report for all distributions. FriendlyName An alternate domain name (CNAME) for the distribution, if any. If a distribution has no alternate domain names, the list includes an origin domain name for the distribution. Requests The number of requests that CloudFront received from each type of device. RequestsPct The number of requests that CloudFront received from each type of device as a percentage of the total number of requests that CloudFront received from all devices. Custom Requests for which the value of the User-Agent HTTP header was not associated with one of the standard device types, for example, Desktop or Mobile. Device trends report The report includes the following values: DistributionID The ID of the distribution that you ran the report for, or ALL if you ran the report for all distributions. View CloudFront viewers reports 864 Amazon CloudFront FriendlyName Developer Guide An alternate domain name (CNAME) for the distribution, if any. If a distribution has no alternate domain names, the list includes an origin domain name for the distribution. TimeBucket The hour or the day that the data applies to, in Coordinated Universal Time (UTC). Desktop The number of requests that CloudFront received from desktop computers during the period. Mobile The number of requests that CloudFront received from mobile devices during the period. Mobile devices can include both tablets and mobile phones. If CloudFront can't determine whether a request originated from a mobile device or a tablet, it's counted in the Mobile column. Smart-TV The number of requests that CloudFront received from smart TVs during the period. Tablet The number of requests that CloudFront received from tablets during the period. If CloudFront can't determine whether a request originated from a mobile device or a tablet, it's counted in the Mobile column. Unknown Requests for which the value of the User-Agent HTTP header was not associated with one of the standard device types, for example, Desktop or Mobile. Empty The number of requests that CloudFront received that didn't include a value in the HTTP User- Agent header during the period. Browsers report The report includes the following values: DistributionID The ID of the distribution that you ran the report for, or ALL if you ran the report for all distributions. View CloudFront viewers reports 865 Amazon CloudFront FriendlyName Developer Guide An alternate domain name (CNAME) for the distribution, if any. If a distribution has no alternate domain names, the list includes an origin domain name for the distribution. Group The browser or the browser and version that CloudFront received requests from, depending on the value of Grouping. In addition to browser names, possible values include the following: • Bot/Crawler – primarily requests from search engines that are indexing your content. • Empty – requests for which the value of the User-Agent HTTP header was empty. • Other – browsers that CloudFront identified but that aren't among the most popular. If Bot/ Crawler, Empty, and/or Unknown don't appear among the first nine values, then they're also included in Other. • Unknown – requests for which the value of the User-Agent HTTP header was not associated with a standard browser. Most requests in this category come from custom applications or scripts. Requests The number of requests that CloudFront received from each type of browser. RequestsPct The number of requests that CloudFront received from each type of browser as a percentage of the total number of requests that CloudFront received during the time
AmazonCloudFront_DevGuide-304
AmazonCloudFront_DevGuide.pdf
304
CloudFront identified but that aren't among the most popular. If Bot/ Crawler, Empty, and/or Unknown don't appear among the first nine values, then they're also included in Other. • Unknown – requests for which the value of the User-Agent HTTP header was not associated with a standard browser. Most requests in this category come from custom applications or scripts. Requests The number of requests that CloudFront received from each type of browser. RequestsPct The number of requests that CloudFront received from each type of browser as a percentage of the total number of requests that CloudFront received during the time period. Browser trends report The report includes the following values: DistributionID The ID of the distribution that you ran the report for, or ALL if you ran the report for all distributions. FriendlyName An alternate domain name (CNAME) for the distribution, if any. If a distribution has no alternate domain names, the list includes an origin domain name for the distribution. View CloudFront viewers reports 866 Amazon CloudFront TimeBucket Developer Guide The hour or the day that the data applies to, in Coordinated Universal Time (UTC). (Browsers) The remaining columns in the report list the browsers or the browsers and their versions, depending on the value of Grouping. In addition to browser names, possible values include the following: • Bot/Crawler – primarily requests from search engines that are indexing your content. • Empty – requests for which the value of the User-Agent HTTP header was empty. • Other – browsers that CloudFront identified but that aren't among the most popular. If Bot/ Crawler, Empty, and/or Unknown don't appear among the first nine values, then they're also included in Other. • Unknown – requests for which the value of the User-Agent HTTP header was not associated with a standard browser. Most requests in this category come from custom applications or scripts. Operating systems report The report includes the following values: DistributionID The ID of the distribution that you ran the report for, or ALL if you ran the report for all distributions. FriendlyName An alternate domain name (CNAME) for the distribution, if any. If a distribution has no alternate domain names, the list includes an origin domain name for the distribution. Group The operating system or the operating system and version that CloudFront received requests from, depending on the value of Grouping. In addition to operating system names, possible values include the following: • Bot/Crawler – primarily requests from search engines that are indexing your content. • Empty – requests for which the value of the User-Agent HTTP header was empty. View CloudFront viewers reports 867 Amazon CloudFront Developer Guide • Other – operating systems that CloudFront identified but that aren't among the most popular. If Bot/Crawler, Empty, and/or Unknown don't appear among the first nine values, then they're also included in Other. • Unknown – requests for which the value of the User-Agent HTTP header was not associated with a standard browser. Most requests in this category come from custom applications or scripts. Requests The number of requests that CloudFront received from each type of operating system. RequestsPct The number of requests that CloudFront received from each type of operating system as a percentage of the total number of requests that CloudFront received during the time period. Operating system trends report The report includes the following values: DistributionID The ID of the distribution that you ran the report for, or ALL if you ran the report for all distributions. FriendlyName An alternate domain name (CNAME) for the distribution, if any. If a distribution has no alternate domain names, the list includes an origin domain name for the distribution. TimeBucket The hour or the day that the data applies to, in Coordinated Universal Time (UTC). (Operating systems) The remaining columns in the report list the operating systems or the operating systems and their versions, depending on the value of Grouping. In addition to operating system names, possible values include the following: • Bot/Crawler – primarily requests from search engines that are indexing your content. • Empty – requests for which the value of the User-Agent HTTP header was empty. View CloudFront viewers reports 868 Amazon CloudFront Developer Guide • Other – operating systems that CloudFront identified but that aren't among the most popular. If Bot/Crawler, Empty, and/or Unknown don't appear among the first nine values, then they're also included in Other. • Unknown – requests for which the operating system isn't specified in the User-Agent HTTP header. Locations report The report includes the following values: DistributionID The ID of the distribution that you ran the report for, or ALL if you ran the report for all distributions. FriendlyName An alternate domain name (CNAME) for the distribution, if any. If a distribution has no alternate domain names, the list includes an origin
AmazonCloudFront_DevGuide-305
AmazonCloudFront_DevGuide.pdf
305
operating systems that CloudFront identified but that aren't among the most popular. If Bot/Crawler, Empty, and/or Unknown don't appear among the first nine values, then they're also included in Other. • Unknown – requests for which the operating system isn't specified in the User-Agent HTTP header. Locations report The report includes the following values: DistributionID The ID of the distribution that you ran the report for, or ALL if you ran the report for all distributions. FriendlyName An alternate domain name (CNAME) for the distribution, if any. If a distribution has no alternate domain names, the list includes an origin domain name for the distribution. LocationCode The abbreviation for the location that CloudFront received requests from. For more information about possible values, see the description of Location in How data in the locations report is related to data in the CloudFront standard logs (access logs). LocationName The name of the location that CloudFront received requests from. Requests The number of requests that CloudFront received from each location. RequestsPct The number of requests that CloudFront received from each location as a percentage of the total number of requests that CloudFront received from all locations during the time period. TotalBytes The number of bytes that CloudFront served to viewers in this country or state, for the specified distribution and period. View CloudFront viewers reports 869 Amazon CloudFront Location trends report The report includes the following values: DistributionID Developer Guide The ID of the distribution that you ran the report for, or ALL if you ran the report for all distributions. FriendlyName An alternate domain name (CNAME) for the distribution, if any. If a distribution has no alternate domain names, the list includes an origin domain name for the distribution. TimeBucket The hour or the day that the data applies to, in Coordinated Universal Time (UTC). (Locations) The remaining columns in the report list the locations that CloudFront received requests from. For more information about possible values, see the description of Location in How data in the locations report is related to data in the CloudFront standard logs (access logs). How data in the locations report is related to data in the CloudFront standard logs (access logs) The following list shows how data in the Locations report in the CloudFront console corresponds with values in CloudFront access logs. For more information about CloudFront access logs, see Standard logging (access logs). Location The country or U.S. state that the viewer is in. In access logs, the c-ip column contains the IP address of the device that the viewer is running on. We use geolocation data to identify the geographic location of the device based on the IP address. If you're displaying the Locations report by country, the country list is based on ISO 3166-2, Codes for the representation of names of countries and their subdivisions – Part 2: Country subdivision code. The country list includes the following additional values: • Anonymous Proxy – The request originated from an anonymous proxy. View CloudFront viewers reports 870 Amazon CloudFront Developer Guide • Satellite Provider – The request originated from a satellite provider that provides internet service to multiple countries. Viewers might be in countries with a high risk of fraud. • Europe (Unknown) – The request originated from an IP in a block that is used by multiple European countries. The country that the request originated from can't be determined. CloudFront uses Europe (Unknown) as the default. • Asia/Pacific (Unknown) – The request originated from an IP in a block that is used by multiple countries in the Asia/Pacific region. The country that the request originated from can't be determined. CloudFront uses Asia/Pacific (Unknown) as the default. If you display the Locations report by U.S. state, note that the report can include U.S. territories and U.S. Armed Forces regions. Note If CloudFront can't determine a user's location, the location will appear as Unknown in viewer reports. Request Count The total number of requests from the country or U.S. state that the viewer is in, for the specified distribution and period. This value generally corresponds closely with the number of GET requests from IP addresses in that country or state in CloudFront access logs. Request % One of the following, depending on the value that you selected for Details: • Countries – The requests from this country as a percentage of the total number of requests. • U.S. States – The requests from this state as a percentage of the total number of requests from the United States. If requests came from more than 50 countries, then you can't calculate Request % based on the data in this table because the Request Count column doesn't include all of the requests during the specified period. Bytes The number of bytes that CloudFront served to viewers in this country
AmazonCloudFront_DevGuide-306
AmazonCloudFront_DevGuide.pdf
306
of the following, depending on the value that you selected for Details: • Countries – The requests from this country as a percentage of the total number of requests. • U.S. States – The requests from this state as a percentage of the total number of requests from the United States. If requests came from more than 50 countries, then you can't calculate Request % based on the data in this table because the Request Count column doesn't include all of the requests during the specified period. Bytes The number of bytes that CloudFront served to viewers in this country or state, for the specified distribution and period. To change the display of data in this column to KB, MB, or GB, choose the link in the column heading. View CloudFront viewers reports 871 Amazon CloudFront Developer Guide Monitor CloudFront metrics with Amazon CloudWatch Amazon CloudFront is integrated with Amazon CloudWatch and automatically publishes operational metrics for distributions and edge functions (both Lambda@Edge and CloudFront Functions). You can use these metrics to troubleshoot, track, and debug issues. Many of these metrics are displayed in a set of graphs in the CloudFront console, and are also accessible by using the CloudFront API or CLI. All of these metrics are available in the CloudWatch console or through the CloudWatch API or CLI. CloudFront metrics don't count against CloudWatch quotas (formerly known as limits) and don't incur any additional cost. In addition to the default metrics for CloudFront distributions, you can turn on additional metrics for an additional cost. The additional metrics apply to CloudFront distributions, and must be turned on for each distribution separately. For more information about the cost, see the section called “Estimate the cost for the additional CloudFront metrics”. You can also set alarms based on these metrics in the CloudFront console, or in the CloudWatch console, API, or CLI. For example, you can set an alarm based on the 5xxErrorRate metric, which represents the percentage of all viewer requests for which the response's HTTP status code is in the range of 500 to 599, inclusive. When the error rate reaches a certain value for a certain amount of time, for example, 5% of requests for 5 continuous minutes, the alarm is triggered. You specify the alarm's value and its time unit when you create the alarm. Notes • When you create a CloudWatch alarm in the CloudFront console, it creates one for you in the US East (N. Virginia) Region (us-east-1). If you create an alarm from the CloudWatch console, you must use the same Region. Because CloudFront is a global service, metrics for the service are sent to US East (N. Virginia). • When creating alarms, standard CloudWatch pricing applies. Topics • View CloudFront and edge function metrics • Create alarms for metrics • Download metrics data in CSV format Monitor CloudFront metrics with Amazon CloudWatch 872 Amazon CloudFront Developer Guide • Get metrics by using the Amazon CloudWatch API View CloudFront and edge function metrics You can view operational metrics about your CloudFront distributions and edge functions in the CloudFront console. To view CloudFront and edge function metrics in CloudFront 1. Sign in to the AWS Management Console and open the CloudFront console at https:// 2. 3. console.aws.amazon.com/cloudfront/v4/home. In the navigation pane, choose Monitoring. To view graphs about the activity for a specific CloudFront distribution or edge function, choose one, and then choose View distribution metrics or View metrics. 4. You can customize the graphs by doing the following: a. To change the time range for the information displayed in the graphs, choose 1h (1 hour), 3h (3 hours), or another range, or specify a custom range. b. To change how often CloudFront updates the information in the graph, choose the down arrow next to the refresh icon, and then choose a refresh rate. The default refresh rate is 1 minute, but you can choose other options. 5. To view CloudFront graphs in the CloudWatch console, choose Add to dashboard. You must use the US East (N. Virginia) Region to view the graphs in the CloudWatch console. Topics • Default CloudFront distribution metrics • Turn on additional CloudFront distribution metrics • Default Lambda@Edge function metrics • Default CloudFront Functions metrics Default CloudFront distribution metrics The following default metrics are included for all CloudFront distributions, at no additional cost: View CloudFront and edge function metrics 873 Amazon CloudFront Requests Developer Guide The total number of viewer requests received by CloudFront, for all HTTP methods and for both HTTP and HTTPS requests. Bytes downloaded The total number of bytes downloaded by viewers for GET and HEAD requests. Bytes uploaded The total number of bytes that viewers uploaded to CloudFront, using OPTIONS, POST and PUT requests. 4xx error rate The percentage of all viewer requests for which the response's
AmazonCloudFront_DevGuide-307
AmazonCloudFront_DevGuide.pdf
307
Default CloudFront Functions metrics Default CloudFront distribution metrics The following default metrics are included for all CloudFront distributions, at no additional cost: View CloudFront and edge function metrics 873 Amazon CloudFront Requests Developer Guide The total number of viewer requests received by CloudFront, for all HTTP methods and for both HTTP and HTTPS requests. Bytes downloaded The total number of bytes downloaded by viewers for GET and HEAD requests. Bytes uploaded The total number of bytes that viewers uploaded to CloudFront, using OPTIONS, POST and PUT requests. 4xx error rate The percentage of all viewer requests for which the response's HTTP status code is 4xx. 5xx error rate The percentage of all viewer requests for which the response's HTTP status code is 5xx. Total error rate The percentage of all viewer requests for which the response's HTTP status code is 4xx or 5xx. These metrics are shown in graphs for each CloudFront distribution on the Monitoring page of the CloudFront console.. On each graph, the totals are displayed at 1-minute granularity. In addition to viewing the graphs, you can also download metrics reports as CSV files. Turn on additional CloudFront distribution metrics In addition to the default metrics, you can turn on additional metrics for an additional cost. For more information about the cost, see the section called “Estimate the cost for the additional CloudFront metrics”. These additional metrics must be turned on for each distribution separately: Cache hit rate The percentage of all cacheable requests for which CloudFront served the content from its cache. HTTP POST and PUT requests, and errors, are not considered cacheable requests. View CloudFront and edge function metrics 874 Amazon CloudFront Origin latency Developer Guide The total time spent from when CloudFront receives a request to when it starts providing a response to the network (not the viewer), for requests that are served from the origin, not the CloudFront cache. This is also known as first byte latency, or time-to-first-byte. Error rate by status code The percentage of all viewer requests for which the response's HTTP status code is a particular code in the 4xx or 5xx range. This metric is available for all of the following error codes: 401, 403, 404, 502, 503, and 504. You can turn on additional metrics in the CloudFront console, with AWS CloudFormation, with the AWS Command Line Interface (AWS CLI), or with the CloudFront API. Console To turn on additional metrics 1. Sign in to the AWS Management Console and open the CloudFront console at https:// console.aws.amazon.com/cloudfront/v4/home. 2. In the navigation pane, choose Monitoring. 3. Choose the distribution to turn on additional metrics for, and then choose View distribution metrics. 4. Choose Manage additional metrics. 5. In the Manage additional metrics window, turn on Enabled. After you turn on the additional metrics, you can close the Manage additional metrics window. After you turn on the additional metrics, they are shown in graphs. On each graph, the totals are displayed at 1-minute granularity. In addition to viewing the graphs, you can also download metrics reports as CSV files. CloudFormation To turn on additional metrics with CloudFormation, use the AWS::CloudFront::MonitoringSubscription resource type. The following example shows the AWS CloudFormation template syntax, in YAML format, for enabling additional metrics. View CloudFront and edge function metrics 875 Amazon CloudFront Developer Guide Type: AWS::CloudFront::MonitoringSubscription Properties: DistributionId: EDFDVBD6EXAMPLE MonitoringSubscription: RealtimeMetricsSubscriptionConfig: RealtimeMetricsSubscriptionStatus: Enabled CLI To manage additional metrics with the AWS Command Line Interface (AWS CLI), use one of the following commands: To turn on additional metrics for a distribution • Use the create-monitoring-subscription command, as in the following example. Replace EDFDVBD6EXAMPLE with the ID of the distribution that you're enabling additional metrics for. aws cloudfront create-monitoring-subscription -- distribution-id EDFDVBD6EXAMPLE --monitoring-subscription RealtimeMetricsSubscriptionConfig={RealtimeMetricsSubscriptionStatus=Enabled} To see whether additional metrics are turned on for a distribution • Use the get-monitoring-subscription command, as in the following example. Replace EDFDVBD6EXAMPLE with the ID of the distribution that you're checking. aws cloudfront get-monitoring-subscription --distribution-id EDFDVBD6EXAMPLE To turn off additional metrics for a distribution • Use the delete-monitoring-subscription command, as in the following example. Replace EDFDVBD6EXAMPLE with the ID of the distribution that you're turning off additional metrics for. View CloudFront and edge function metrics 876 Amazon CloudFront Developer Guide aws cloudfront delete-monitoring-subscription --distribution-id EDFDVBD6EXAMPLE API To manage additional metrics with the CloudFront API, use one of the following API operations. • To turn on additional metrics for a distribution, use CreateMonitoringSubscription. • To see whether additional metrics are turned on for a distribution, use GetMonitoringSubscription. • To turn off additional metrics for a distribution, use DeleteMonitoringSubscription. For more information about these API operations, see the API reference documentation for your AWS SDK or other API client. Estimate the cost for the additional CloudFront metrics When you turn on additional metrics for a distribution, CloudFront sends up to 8 metrics to CloudWatch
AmazonCloudFront_DevGuide-308
AmazonCloudFront_DevGuide.pdf
308
delete-monitoring-subscription --distribution-id EDFDVBD6EXAMPLE API To manage additional metrics with the CloudFront API, use one of the following API operations. • To turn on additional metrics for a distribution, use CreateMonitoringSubscription. • To see whether additional metrics are turned on for a distribution, use GetMonitoringSubscription. • To turn off additional metrics for a distribution, use DeleteMonitoringSubscription. For more information about these API operations, see the API reference documentation for your AWS SDK or other API client. Estimate the cost for the additional CloudFront metrics When you turn on additional metrics for a distribution, CloudFront sends up to 8 metrics to CloudWatch in the US East (N. Virginia) Region. CloudWatch charges a low, fixed rate for each metric. This rate is charged only once per month, per metric (up to 8 metrics per distribution). This is a fixed rate, so your cost remains the same regardless of the number of requests or responses that the CloudFront distribution receives or sends. For the per-metric rate, see the Amazon CloudWatch pricing page and the CloudWatch pricing calculator. Additional API charges apply when you retrieve the metrics with the CloudWatch API. Default Lambda@Edge function metrics You can use CloudWatch metrics to monitor, in real time, problems with your Lambda@Edge functions. There's no additional charge for these metrics. When you attach a Lambda@Edge function to a cache behavior in a CloudFront distribution, Lambda begins sending metrics to CloudWatch automatically. Metrics are available for all Lambda Regions, but to view metrics in the CloudWatch console or get the metric data from the CloudWatch API, you must use the US East (N. Virginia) Region (us-east-1). The metric group name is formatted as: AWS/CloudFront/distribution-ID, where distribution-ID is the ID of the CloudFront distribution that the Lambda@Edge function is associated with. For more information about CloudWatch metrics, see the Amazon CloudWatch User Guide. View CloudFront and edge function metrics 877 Amazon CloudFront Developer Guide The following default metrics are shown in graphs for each Lambda@Edge function on the Monitoring page of the CloudFront console: • 5xx error rate for Lambda@Edge • Lambda execution errors • Lambda invalid responses • Lambda throttles The graphs include the number of invocations, errors, throttles, and so on. On each graph, the totals are displayed at 1-minute granularity, grouped by AWS Region. If you see a spike in errors that you want to investigate, you can choose a function and then view log files by AWS Region, until you determine which function is causing the problems and in which AWS Region. For more information about troubleshooting Lambda@Edge errors, see: • the section called “How to determine the type of failure” • Four Steps for Debugging your Content Delivery on AWS Default CloudFront Functions metrics CloudFront Functions sends operational metrics to Amazon CloudWatch so that you can monitor your functions. Viewing these metrics can help you troubleshoot, track, and debug issues. CloudFront Functions publishes the following metrics to CloudWatch: • Invocations (FunctionInvocations) – The number of times the function was started (invoked) in a given time period. • Validation errors (FunctionValidationErrors) – The number of validation errors produced by the function in a given time period. Validation errors occur when the function runs successfully but returns invalid data (an invalid event object). • Execution errors (FunctionExecutionErrors) – The number of execution errors that occurred in a given time period. Execution errors occur when the function fails to complete successfully. • Compute utilization (FunctionComputeUtilization) – The amount of time that the function took to run as a percentage of the maximum allowed time. For example, a value of 35 means that the function completed in 35% of the maximum allowed time. This metric is a number between 0 and 100. View CloudFront and edge function metrics 878 Amazon CloudFront Developer Guide If this value reaches or is near 100, the function has used or is close to using the allowed execution time and subsequent requests might be throttled. If your function is running at 80% or more utilization, we recommend that you review your function to reduce the execution time and improve utilization. For example, you might want to only log errors, simplify any complex regex expressions, or remove unnecessary parsing of complex JSON objects. • Throttles (FunctionThrottles) – The number of times that the function was throttled in a given time period. Functions can be throttled for the following reasons: • The function continuously exceeds the maximum time allowed for execution • The function results in compilation errors • There is an unusually high number of requests per second CloudFront KeyValueStore also sends the following operational metrics to Amazon CloudWatch: • Read requests (KvsReadRequests) – The number of times the function successfully read from the key value store within a given time period. • Read errors (KvsReadErrors) – The number of times the function failed to
AmazonCloudFront_DevGuide-309
AmazonCloudFront_DevGuide.pdf
309
(FunctionThrottles) – The number of times that the function was throttled in a given time period. Functions can be throttled for the following reasons: • The function continuously exceeds the maximum time allowed for execution • The function results in compilation errors • There is an unusually high number of requests per second CloudFront KeyValueStore also sends the following operational metrics to Amazon CloudWatch: • Read requests (KvsReadRequests) – The number of times the function successfully read from the key value store within a given time period. • Read errors (KvsReadErrors) – The number of times the function failed to read from the key value store within a given time period. All of these metrics are published to CloudWatch in the US East (N. Virginia) Region (us-east-1), in the CloudFront namespace. You can also view these metrics in the CloudWatch console. In the CloudWatch console, you can view the metrics per function or per function per distribution. You can also use CloudWatch to set alarms based on these metrics. For example, you can set an alarm based on the execution time (FunctionComputeUilization) metric, which represents the percentage of available time that your function took to run. When the execution time reaches a certain value for a certain amount of time. For example, if you choose greater than 70% of available time for 15 continuous minutes, the alarm is triggered. You specify the alarms value and its time unit when you create the alarm. Note CloudFront Functions sends metrics to CloudWatch only for functions in the LIVE stage that run in response to production requests and responses. When you test a function, CloudFront doesn't send any metrics to CloudWatch. The test output contains information View CloudFront and edge function metrics 879 Amazon CloudFront Developer Guide about errors, compute utilization, and function logs (console.log() statements), but this information isn't sent to CloudWatch. For information about how to get these metrics with the CloudWatch API, see the section called “Get metrics by using the CloudWatch API”. Create alarms for metrics In the CloudFront console, you can set alarms to notify you by Amazon Simple Notification Service (Amazon SNS) based on specific CloudFront metrics. To create alarms for metrics 1. Sign in to the AWS Management Console and open the CloudFront console at https:// console.aws.amazon.com/cloudfront/v4/home. 2. In the navigation pane, choose Alarms. 3. Choose Create alarm. 4. For Details, specify the following: a. Alarm name – A name for the alarm. b. Distribution – The CloudFront distribution that you're creating the alarm for. 5. For Condition, specify the following: a. Metric – The metric that you're creating the alarm for. b. "IF" <condition> – The threshold when CloudWatch should trigger an alarm and send a notification to the Amazon SNS topic. For example, to receive a notification when the 5xx error rate exceeds 1%, specify the following: 5xx error rate > 1 c. "FOR" consecutive periods – The period of time that the condition must be met before triggering an alarm. When you choose a value, aim for an appropriate balance between a value that doesn't alarm for temporary problems, but will alarm for sustained or real problems. d. (Optional) Notify – The Amazon SNS topic to send notification to if this metric triggers an alarm. 6. Choose Create alarm. Create alarms 880 Amazon CloudFront Notes Developer Guide • When you enter the values for the condition, use whole numbers without punctuation. For example, to specify one thousand, enter 1000. • For 4xx, 5xx, and total error rates, the value that you specify is a percentage. • For requests, bytes downloaded, and bytes uploaded, the value that you specify is units. For example, 1073742000 bytes. For more information about creating Amazon SNS topics, see Creating an Amazon SNS topic in the Amazon Simple Notification Service Developer Guide. Download metrics data in CSV format You can download the CloudWatch metrics data for a CloudFront distribution in CSV format. To download metrics data in CSV format 1. Sign in to the AWS Management Console and open the CloudFront console at https:// console.aws.amazon.com/cloudfront/v4/home. 2. In the navigation pane, choose Monitoring. 3. Choose the distribution and then choose View distribution metrics. 4. Choose Download CSV and then choose the time period (for example, For last 1 day (1 hour period). 5. After your file downloads, open it to view the following information. Topics • Information about the report • Data in the metrics report Information about the report The first few rows of the report include the following information: Download metrics data 881 Amazon CloudFront Version The CloudFront reporting version. Report The name of the report. DistributionID Developer Guide The ID of the distribution for which you ran the report. StartDateUTC The beginning of the date range for which you ran the report, in Coordinated Universal Time (UTC).
AmazonCloudFront_DevGuide-310
AmazonCloudFront_DevGuide.pdf
310
the time period (for example, For last 1 day (1 hour period). 5. After your file downloads, open it to view the following information. Topics • Information about the report • Data in the metrics report Information about the report The first few rows of the report include the following information: Download metrics data 881 Amazon CloudFront Version The CloudFront reporting version. Report The name of the report. DistributionID Developer Guide The ID of the distribution for which you ran the report. StartDateUTC The beginning of the date range for which you ran the report, in Coordinated Universal Time (UTC). EndDateUTC The end of the date range for which you ran the report, in Coordinated Universal Time (UTC). GeneratedTimeUTC The date and time on which you ran the report, in Coordinated Universal Time (UTC). Granularity The time period for each row in the report, for example, ONE_MINUTE. Data in the metrics report The report includes the following values: DistributionID The ID of the distribution for which you ran the report. FriendlyName An alternate domain name (CNAME) for the distribution, if any. If a distribution has no alternate domain names, the list includes an origin domain name for the distribution. TimeBucket The hour or the day that the data applies to, in Coordinated Universal Time (UTC). Download metrics data 882 Amazon CloudFront Requests Developer Guide The total number of requests for all HTTP status codes (for example, 200, 404, and so on) and all methods (for example, GET, HEAD, POST, and so on) during the time period. BytesDownloaded The number of bytes that viewers downloaded for the specified distribution during the time period. BytesUploaded The number of bytes that viewers uploaded for the specified distribution during the time period. TotalErrorRatePct The percentage of requests for which the HTTP status code was a 4xx or 5xx error for the specified distribution during the time period. 4xxErrorRatePct The percentage of requests for which the HTTP status code was a 4xx error for the specified distribution during the time period. 5xxErrorRatePct The percentage of requests for which the HTTP status code was a 5xx error for the specified distribution during the time period. If you have turned on additional metrics for your distribution, then the report also includes the following additional values: 401ErrorRatePct The percentage of requests for which the HTTP status code was a 401 error for the specified distribution during the time period. 403ErrorRatePct The percentage of requests for which the HTTP status code was a 403 error for the specified distribution during the time period. Download metrics data 883 Amazon CloudFront 404ErrorRatePct Developer Guide The percentage of requests for which the HTTP status code was a 404 error for the specified distribution during the time period. 502ErrorRatePct The percentage of requests for which the HTTP status code was a 502 error for the specified distribution during the time period. 503ErrorRatePct The percentage of requests for which the HTTP status code was a 503 error for the specified distribution during the time period. 504ErrorRatePct The percentage of requests for which the HTTP status code was a 504 error for the specified distribution during the time period. OriginLatency The total time spent, in milliseconds, from when CloudFront received a request to when it started providing a response to the network (not the viewer), for requests that were served from the origin, not the CloudFront cache. This is also known as first byte latency, or time-to- first-byte. CacheHitRate The percentage of all cacheable requests for which CloudFront served the content from its cache. HTTP POST and PUT requests, and errors, are not considered cacheable requests. Get metrics by using the Amazon CloudWatch API You can use the CloudWatch API or AWS Command Line Interface (AWS CLI) to get the CloudFront metrics in programs or applications that you build. You can use the raw data to build your own custom dashboards, your own alarming tools, and so on. For more information, see get-metric-data in the AWS CLI Command Reference or the GetMetricData API operation in the Amazon CloudWatch API Reference. Topics • Values for all CloudFront metrics Get metrics by using the CloudWatch API 884 Amazon CloudFront Developer Guide • Values for CloudFront distribution metrics • Values for CloudFront function metrics Note To get the CloudFront metrics from the CloudWatch API, you must use the US East (N. Virginia) Region (us-east-1). You also need to know certain values and types for each metric. Values for all CloudFront metrics The following values apply to all CloudFront metrics: Namespace The value for Namespace is always AWS/CloudFront. Dimensions Each CloudFront metric has the following dimensions: DistributionId The ID of the CloudFront distribution for which you want to get metrics. FunctionName The name of the function (in CloudFront Functions) for which you want to get metrics. This dimension applies
AmazonCloudFront_DevGuide-311
AmazonCloudFront_DevGuide.pdf
311
• Values for CloudFront function metrics Note To get the CloudFront metrics from the CloudWatch API, you must use the US East (N. Virginia) Region (us-east-1). You also need to know certain values and types for each metric. Values for all CloudFront metrics The following values apply to all CloudFront metrics: Namespace The value for Namespace is always AWS/CloudFront. Dimensions Each CloudFront metric has the following dimensions: DistributionId The ID of the CloudFront distribution for which you want to get metrics. FunctionName The name of the function (in CloudFront Functions) for which you want to get metrics. This dimension applies only to functions. Region The value for Region is always Global, because CloudFront is a global service. Values for CloudFront distribution metrics Use information from the following list to get details about specific CloudFront distribution metrics from the CloudWatch API. Some of these metrics are available only when you have turned on additional metrics for the distribution. Get metrics by using the CloudWatch API 885 Amazon CloudFront Note Developer Guide Only one statistic, Average or Sum, is applicable for each metric. The following list specifies which statistic is applicable to that metric. 4xx error rate The percentage of all viewer requests for which the response's HTTP status code is 4xx. • Metric name: 4xxErrorRate • Valid statistic: Average • Unit: Percent 401 error rate The percentage of all viewer requests for which the response's HTTP status code is 401. To get this metric, you must first turn on additional metrics. • Metric name: 401ErrorRate • Valid statistic: Average • Unit: Percent 403 error rate The percentage of all viewer requests for which the response's HTTP status code is 403. To get this metric, you must first turn on additional metrics. • Metric name: 403ErrorRate • Valid statistic: Average • Unit: Percent 404 error rate The percentage of all viewer requests for which the response's HTTP status code is 404. To get this metric, you must first turn on additional metrics. • Metric name: 404ErrorRate • Valid statistic: Average • Unit: Percent Get metrics by using the CloudWatch API 886 Amazon CloudFront 5xx error rate Developer Guide The percentage of all viewer requests for which the response's HTTP status code is 5xx. • Metric name: 5xxErrorRate • Valid statistic: Average • Unit: Percent 502 error rate The percentage of all viewer requests for which the response's HTTP status code is 502. To get this metric, you must first turn on additional metrics. • Metric name: 502ErrorRate • Valid statistic: Average • Unit: Percent 503 error rate The percentage of all viewer requests for which the response's HTTP status code is 503. To get this metric, you must first turn on additional metrics. • Metric name: 503ErrorRate • Valid statistic: Average • Unit: Percent 504 error rate The percentage of all viewer requests for which the response's HTTP status code is 504. To get this metric, you must first turn on additional metrics. • Metric name: 504ErrorRate • Valid statistic: Average • Unit: Percent Bytes downloaded The total number of bytes downloaded by viewers for GET, HEAD, and OPTIONS requests. • Metric name: BytesDownloaded • Valid statistic: Sum • Unit: None Get metrics by using the CloudWatch API 887 Amazon CloudFront Bytes uploaded Developer Guide The total number of bytes that viewers uploaded to your origin with CloudFront, using POST and PUT requests. • Metric name: BytesUploaded • Valid statistic: Sum • Unit: None Cache hit rate The percentage of all cacheable requests for which CloudFront served the content from its cache. HTTP POST and PUT requests, and errors, are not considered cacheable requests. To get this metric, you must first turn on additional metrics. • Metric name: CacheHitRate • Valid statistic: Average • Unit: Percent Origin latency The total time spent, in milliseconds, from when CloudFront receives a request to when it starts providing a response to the network (not the viewer), for requests that are served from the origin, not the CloudFront cache. This is also known as first byte latency, or time-to-first-byte. To get this metric, you must first turn on additional metrics. • Metric name: OriginLatency • Valid statistic: Percentile • Unit: Milliseconds Note To get a Percentile statistic from the CloudWatch API, use the ExtendedStatistics parameter, not Statistics. For more information, see GetMetricStatistics in the Amazon CloudWatch API Reference, or the reference documentation for the AWS SDKs. Requests The total number of viewer requests received by CloudFront, for all HTTP methods and for both HTTP and HTTPS requests. Get metrics by using the CloudWatch API 888 Amazon CloudFront Developer Guide • Metric name: Requests • Valid statistic: Sum • Unit: None Total error rate The percentage of all viewer requests for which the response's HTTP status code is 4xx or 5xx. • Metric name: TotalErrorRate • Valid
AmazonCloudFront_DevGuide-312
AmazonCloudFront_DevGuide.pdf
312
statistic from the CloudWatch API, use the ExtendedStatistics parameter, not Statistics. For more information, see GetMetricStatistics in the Amazon CloudWatch API Reference, or the reference documentation for the AWS SDKs. Requests The total number of viewer requests received by CloudFront, for all HTTP methods and for both HTTP and HTTPS requests. Get metrics by using the CloudWatch API 888 Amazon CloudFront Developer Guide • Metric name: Requests • Valid statistic: Sum • Unit: None Total error rate The percentage of all viewer requests for which the response's HTTP status code is 4xx or 5xx. • Metric name: TotalErrorRate • Valid statistic: Average • Unit: Percent Values for CloudFront function metrics Use information from the following list to get details about specific CloudFront function metrics from the CloudWatch API. Note Only one statistic, Average or Sum, is applicable for each metric. The following list specifies which statistic is applicable to that metric. Invocations The number of times the function was started (invoked) in a given time period. • Metric name: FunctionInvocations • Valid statistic: Sum • Unit: None Validation errors The number of validation errors produced by the function in a given time period. Validation errors occur when the function runs successfully but returns invalid data (an invalid event object). • Metric name: FunctionValidationErrors • Valid statistic: Sum • Unit: None Get metrics by using the CloudWatch API 889 Amazon CloudFront Execution errors Developer Guide The number of execution errors that occurred in a given time period. Execution errors occur when the function fails to complete successfully. • Metric name: FunctionExecutionErrors • Valid statistic: Sum • Unit: None Compute utilization The amount of time (0-100) that the function took to run as a percentage of the maximum allowed time. For example, a value of 35 means that the function completed in 35% of the maximum allowed time. • Metric name: FunctionComputeUtilization • Valid statistic: Average • Unit: Percent Throttles The number of times that the function was throttled in a given time period. • Metric name: FunctionThrottles • Valid statistic: Sum • Unit: None CloudFront and edge function logging Amazon CloudFront provides different kinds of logging. You can log the viewer requests that come to your CloudFront distributions, or you can log the CloudFront service activity (API activity) in your AWS account. You can also get logs from your CloudFront Functions and Lambda@Edge functions. Logging requests CloudFront provides the following ways to log the requests that come to your distributions. Standard logs (access logs) CloudFront standard logs provide detailed records about every request that's made to a distribution. You can use the logs for scenarios, such as security and access audits. CloudFront and edge function logging 890 Amazon CloudFront Developer Guide CloudFront standard logs are delivered to the delivery destination that you specify. For more information, see Standard logging (access logs). Real-time logs CloudFront real-time logs provide information about requests made to a distribution, in real time (log records are delivered within seconds of receiving the requests). You can choose the sampling rate for your real-time logs—that is, the percentage of requests for which you want to receive real-time log records. You can also choose the specific fields that you want to receive in the log records. CloudFront real-time logs are delivered to the data stream of your choice in Amazon Kinesis Data Streams. CloudFront charges for real-time logs, in addition to the charges you incur for using Kinesis Data Streams. For more information, see Use real-time logs. Logging edge functions You can use Amazon CloudWatch Logs to get logs for your edge functions, both Lambda@Edge and CloudFront Functions. You can access the logs using the CloudWatch console or the CloudWatch Logs API. For more information, see the section called “Edge function logs”. Logging service activity You can use AWS CloudTrail to log the CloudFront service activity (API activity) in your AWS account. CloudTrail provides a record of API actions taken by a user, role, or AWS service in CloudFront. Using the information collected by CloudTrail, you can determine the API request that was made to CloudFront, the IP address from which the request was made, who made the request, when it was made, and additional details. For more information, see Logging Amazon CloudFront API calls using AWS CloudTrail. For more information about logging, see the following topics: Topics • Standard logging (access logs) • Use real-time logs Logging edge functions 891 Amazon CloudFront • Edge function logs • Logging Amazon CloudFront API calls using AWS CloudTrail Developer Guide Standard logging (access logs) You can configure CloudFront to create log files that contain detailed information about every user (viewer) request that CloudFront receives. These are called standard logs, also known as access logs. Each log contains information such as the time the request was received, the processing time, request paths, and
AmazonCloudFront_DevGuide-313
AmazonCloudFront_DevGuide.pdf
313
Logging Amazon CloudFront API calls using AWS CloudTrail. For more information about logging, see the following topics: Topics • Standard logging (access logs) • Use real-time logs Logging edge functions 891 Amazon CloudFront • Edge function logs • Logging Amazon CloudFront API calls using AWS CloudTrail Developer Guide Standard logging (access logs) You can configure CloudFront to create log files that contain detailed information about every user (viewer) request that CloudFront receives. These are called standard logs, also known as access logs. Each log contains information such as the time the request was received, the processing time, request paths, and server responses. You can use these access logs to analyze response times and to troubleshoot issues. The following diagram shows how CloudFront logs information about requests for your objects. In this example, the distributions are configured to send access logs to an Amazon S3 bucket. 1. In this example, you have two websites, A and B, and two corresponding CloudFront distributions. Users request your objects using URLs that are associated with your distributions. 2. CloudFront routes each request to the appropriate edge location. 3. CloudFront writes data about each request to a log file specific to that distribution. In this example, information about requests related to Distribution A goes into a log file for Standard logging (access logs) 892 Amazon CloudFront Developer Guide Distribution A. Information about requests related to Distribution B goes into a log file for Distribution B. 4. CloudFront periodically saves the log file for a distribution in the Amazon S3 bucket that you specified when you enabled logging. CloudFront then starts saving information about subsequent requests in a new log file for the distribution. If viewers don't access your content during a given hour, you don't receive any log files for that hour. Note We recommend that you use the logs to understand the nature of the requests for your content, not as a complete accounting of all requests. CloudFront delivers access logs on a best-effort basis. The log entry for a particular request might be delivered long after the request was actually processed and, in rare cases, a log entry might not be delivered at all. When a log entry is omitted from access logs, the number of entries in the access logs won't match the usage that appears in the AWS billing and usage reports. CloudFront supports two versions of standard logging. Standard logging (legacy) supports sending your access logs to Amazon S3 only. Standard logging (v2) supports additional delivery destinations. You can configure both or either logging option for your distribution. For more information, see the following topics: Topics • Configure standard logging (v2) • Configure standard logging (legacy) • Standard logging reference Tip CloudFront also offers real-time logs, which give you information about requests made to a distribution in real time (logs are delivered within seconds of receiving the requests). You can use real-time logs to monitor, analyze, and take action based on content delivery performance. For more information, see Use real-time logs. Standard logging (access logs) 893 Amazon CloudFront Developer Guide Configure standard logging (v2) You can enable standard logging when you create or update a distribution. Standard logging (v2) includes the following features: • Send access logs to Amazon CloudWatch Logs, Amazon Data Firehose, and Amazon Simple Storage Service (Amazon S3). • Select the log fields that you want. You can also select a subset of real-time log fields. • Select additional output log file formats. If you’re using Amazon S3, you have the following optional features: • Send logs to opt-in AWS Regions. • Organize your logs with partitioning. • Enable Hive-compatible file names. For more information, see Send logs to Amazon S3. To get started with standard logging, complete the following steps: 1. Set up your required permissions for the specified AWS service that will receive your logs. 2. Configure standard logging from the CloudFront console or the CloudWatch API. 3. View your access logs. Note • If you enable standard logging (v2), this doesn’t affect or change standard logging (legacy). You can continue to use standard logging (legacy) for your distribution, in addition to using standard logging (v2). For more information, see Configure standard logging (legacy). • If you already enabled standard logging (legacy) and you want to enable standard logging (v2) to Amazon S3, we recommend that you specify a different Amazon S3 bucket or use a separate path in the same bucket (for example, use a log prefix or partitioning). This helps you keep track of which log files are associated with which distribution and prevents log files from overwriting each other. Standard logging (access logs) 894 Amazon CloudFront Permissions Developer Guide CloudFront uses CloudWatch vended logs to deliver access logs. To do so, you need permissions to the specified AWS service so that you
AmazonCloudFront_DevGuide-314
AmazonCloudFront_DevGuide.pdf
314
If you already enabled standard logging (legacy) and you want to enable standard logging (v2) to Amazon S3, we recommend that you specify a different Amazon S3 bucket or use a separate path in the same bucket (for example, use a log prefix or partitioning). This helps you keep track of which log files are associated with which distribution and prevents log files from overwriting each other. Standard logging (access logs) 894 Amazon CloudFront Permissions Developer Guide CloudFront uses CloudWatch vended logs to deliver access logs. To do so, you need permissions to the specified AWS service so that you can enable logging delivery. To see the required permissions for each logging destination, choose from the following topics in the Amazon CloudWatch Logs User Guide. • CloudWatch Logs • Firehose • Amazon S3 After you have set up permissions to your logging destination, you can enable standard logging for your distribution. Note CloudFront supports sending access logs to different AWS accounts (cross accounts). To enable cross-account delivery, both accounts (your account and the receiving account) must have the required permissions. For more information, see the Enable standard logging for cross-account delivery section or the Cross-account delivery example in the Amazon CloudWatch Logs User Guide. Enable standard logging To enable standard logging, you can use the CloudFront console or the CloudWatch API. Contents • Enable standard logging (CloudFront console) • Enable standard logging (CloudWatch API) Enable standard logging (CloudFront console) To enable standard logging for a CloudFront distribution (console) 1. Use the CloudFront console to update an existing distribution. Standard logging (access logs) 895 Amazon CloudFront 2. Choose the Logging tab. 3. Choose Add, then select the service to receive your logs: Developer Guide • CloudWatch Logs • Firehose • Amazon S3 4. For the Destination, select the resource for your service. If you haven’t already created your resource, you can choose Create or see the following documentation. • For CloudWatch Logs, enter the Log group name. • For Firehose, enter the Firehose delivery stream. • For Amazon S3, enter the Bucket name. Tip To specify a prefix, enter the prefix after the bucket name, such as amzn-s3- demo-bucket.s3.amazonaws.com/MyLogPrefix. If you don't specify a prefix, CloudFront will automatically add one for you. For more information, see Send logs to Amazon S3. 5. For Additional settings – optional, you can specify the following options: a. b. c. For Field selection, select the log field names that you want to deliver to your destination. You can select access log fields and a subset of real-time log fields. (Amazon S3 only) For Partitioning, specify the path to partition your log file data. (Amazon S3 only) For Hive-compatible file format, you can select the checkbox to use Hive-compatible S3 paths. This helps simplify loading new data into your Hive-compatible tools. d. For Output format, specify your preferred format. Note If you choose Parquet, this option incurs CloudWatch charges for converting your access logs to Apache Parquet. For more information, see the Vended Logs section for CloudWatch pricing. e. For Field delimiter, specify how to separate log fields. Standard logging (access logs) 896 Amazon CloudFront Developer Guide 6. Complete the steps to update or create your distribution. 7. 8. 9. To add another destination, repeat steps 3–6. From the Logs page, verify that the standard logs status is Enabled next to the distribution. (Optional) To enable cookie logging, choose Manage, Settings and turn on Cookie logging, then choose Save changes. Tip Cookie logging is a global setting that applies to all standard logging for your distribution. You can’t override this setting for separate delivery destinations. For more information about the standard logging delivery and log fields, see the Standard logging reference. Enable standard logging (CloudWatch API) You can also use the CloudWatch API to enable standard logging for your distributions. Notes • When calling the CloudWatch API to enable standard logging, you must specify the US East (N. Virginia) Region (us-east-1), even if you want to enable cross Region delivery to another destination. For example, if you want to send your access logs to an S3 bucket in the Europe (Ireland) Region (eu-west-1), use the CloudWatch API in the us-east-1 Region. • There is an additional option to include cookies in standard logging. In the CloudFront API, this is the IncludeCookies parameter. If you configure access logging by using the CloudWatch API and you specify that you want to include cookies, you must use the CloudFront console or CloudFront API to update your distribution to include cookies. Otherwise, CloudFront can’t send cookies to your log destination. For more information, see Cookie logging. To enable standard logging for a distribution (CloudWatch API) 1. After you a create a distribution, get the Amazon Resource Name (ARN). Standard logging (access logs) 897 Amazon CloudFront Developer Guide You can find
AmazonCloudFront_DevGuide-315
AmazonCloudFront_DevGuide.pdf
315
option to include cookies in standard logging. In the CloudFront API, this is the IncludeCookies parameter. If you configure access logging by using the CloudWatch API and you specify that you want to include cookies, you must use the CloudFront console or CloudFront API to update your distribution to include cookies. Otherwise, CloudFront can’t send cookies to your log destination. For more information, see Cookie logging. To enable standard logging for a distribution (CloudWatch API) 1. After you a create a distribution, get the Amazon Resource Name (ARN). Standard logging (access logs) 897 Amazon CloudFront Developer Guide You can find the ARN from the Distribution page in the CloudFront console or you can use the GetDistribution API operation. A distribution ARN follows the format: arn:aws:cloudfront::123456789012:distribution/d111111abcdef8 2. Next, use the CloudWatch PutDeliverySource API operation to create a delivery source for the distribution. a. Enter a name for the delivery source. b. Pass the resourceArn of the distribution. c. d. For logType, specify ACCESS_LOGS as the type of logs that are collected. Example Example AWS CLI put-delivery-source command The following is an example of configuring a delivery source for a distribution. aws logs put-delivery-source --name S3-delivery --resource-arn arn:aws:cloudfront::123456789012:distribution/d111111abcdef8 --log-type ACCESS_LOGS Output { "deliverySource": { "name": "S3-delivery", "arn": "arn:aws:logs:us-east-1:123456789012:delivery-source:S3-delivery", "resourceArns": [ "arn:aws:cloudfront::123456789012:distribution/d111111abcdef8" ], "service": "cloudfront", "logType": "ACCESS_LOGS" } } 3. Use the PutDeliveryDestination API operation to configure where to store your logs. a. For destinationResourceArn, specify the ARN of the destination. This can be a CloudWatch Logs log group, a Firehose delivery stream, or an Amazon S3 bucket. b. For outputFormat, specify the output format for your logs. Standard logging (access logs) 898 Amazon CloudFront Developer Guide c. Example Example AWS CLI put-delivery-destination command The following is an example of configuring a delivery destination to an Amazon S3 bucket. aws logs put-delivery-destination --name S3-destination --delivery-destination- configuration destinationResourceArn=arn:aws:s3:::amzn-s3-demo-bucket Output { "name": "S3-destination", "arn": "arn:aws:logs:us-east-1:123456789012:delivery-destination:S3- destination", "deliveryDestinationType": "S3", "deliveryDestinationConfiguration": { "destinationResourceArn": "arn:aws:s3:::amzn-s3-demo-bucket" } } Note If you're delivering logs cross-account, you must use the PutDeliveryDestinationPolicy API operation to assign an AWS Identity and Access Management (IAM) policy to the destination account. The IAM policy allows delivery from one account to another account. 4. Use the CreateDelivery API operation to link the delivery source to the destination that you created in the previous steps. This API operation associates the delivery source with the end destination. a. b. c. d. e. For deliverySourceName, specify the source name. For deliveryDestinationArn, specify the ARN for the delivery destination. For fieldDelimiter, specify the string to separate each log field. For recordFields, specify the log fields that you want. If you’re using S3, specify whether to use enableHiveCompatiblePath and suffixPath. Standard logging (access logs) 899 Amazon CloudFront Developer Guide Example Example AWS CLI create-delivery command The following is an example of creating a delivery. aws logs create-delivery --delivery-source-name cf-delivery --delivery-destination- arn arn:aws:logs:us-east-1:123456789012:delivery-destination:S3-destination Output { "id": "abcNegnBoTR123", "arn": "arn:aws:logs:us-east-1:123456789012:delivery:abcNegnBoTR123", "deliverySourceName": "cf-delivery", "deliveryDestinationArn": "arn:aws:logs:us-east-1:123456789012:delivery- destination:S3-destination", "deliveryDestinationType": "S3", "recordFields": [ "date", "time", "x-edge-location", "sc-bytes", "c-ip", "cs-method", "cs(Host)", "cs-uri-stem", "sc-status", "cs(Referer)", "cs(User-Agent)", "cs-uri-query", "cs(Cookie)", "x-edge-result-type", "x-edge-request-id", "x-host-header", "cs-protocol", "cs-bytes", "time-taken", "x-forwarded-for", "ssl-protocol", "ssl-cipher", "x-edge-response-result-type", "cs-protocol-version", Standard logging (access logs) 900 Amazon CloudFront Developer Guide "fle-status", "fle-encrypted-fields", "c-port", "time-to-first-byte", "x-edge-detailed-result-type", "sc-content-type", "sc-content-len", "sc-range-start", "sc-range-end", "c-country", "cache-behavior-path-pattern" ], "fieldDelimiter": "" } 5. From the CloudFront console, on the Logs page, verify that the standard logs status is Enabled next to the distribution. For more information about the standard logging delivery and log fields, see the Standard logging reference. Note To enable standard logging (v2) for CloudFront by using AWS CloudFormation, you can use the following CloudWatch Logs properties: • Delivery • DeliveryDestination • DeliverySource The ResourceArn is the CloudFront distribution and LogType must be ACCESS_LOGS as the supported log type. Enable standard logging for cross-account delivery If you enable standard logging for your AWS account and you want to deliver your access logs to another account, make sure that you configure the source account and the destination account Standard logging (access logs) 901 Amazon CloudFront Developer Guide correctly. The source account with the CloudFront distribution sends its access logs to the destination account. In this example procedure, the source account 111111111111) sends its access logs to an Amazon S3 bucket in the destination account (222222222222). To send access logs to an Amazon S3 bucket in the destination account, use the AWS CLI. Configure the destination account For destination account, complete the following procedure. To configure the destination account 1. To create the log delivery destination, you can enter the following AWS CLI command. This example uses the MyLogPrefix string to create a prefix for your access logs. aws logs put-delivery-destination --name cloudfront-delivery-destination -- delivery-destination-configuration "destinationResourceArn=arn:aws:s3:::amzn-s3- demo-bucket-cloudfront-logs/MyLogPrefix" Output { "deliveryDestination": { "name": "cloudfront-delivery-destination", "arn": "arn:aws:logs:us-east-1:222222222222:delivery- destination:cloudfront-delivery-destination", "deliveryDestinationType": "S3", "deliveryDestinationConfiguration": {"destinationResourceArn": "arn:aws:s3:::amzn-s3-demo-bucket-cloudfront-logs/MyLogPrefix"} } } Note If you specify an S3 bucket without a prefix, CloudFront will automatically append the
AmazonCloudFront_DevGuide-316
AmazonCloudFront_DevGuide.pdf
316
access logs to an Amazon S3 bucket in the destination account, use the AWS CLI. Configure the destination account For destination account, complete the following procedure. To configure the destination account 1. To create the log delivery destination, you can enter the following AWS CLI command. This example uses the MyLogPrefix string to create a prefix for your access logs. aws logs put-delivery-destination --name cloudfront-delivery-destination -- delivery-destination-configuration "destinationResourceArn=arn:aws:s3:::amzn-s3- demo-bucket-cloudfront-logs/MyLogPrefix" Output { "deliveryDestination": { "name": "cloudfront-delivery-destination", "arn": "arn:aws:logs:us-east-1:222222222222:delivery- destination:cloudfront-delivery-destination", "deliveryDestinationType": "S3", "deliveryDestinationConfiguration": {"destinationResourceArn": "arn:aws:s3:::amzn-s3-demo-bucket-cloudfront-logs/MyLogPrefix"} } } Note If you specify an S3 bucket without a prefix, CloudFront will automatically append the AWSLogs/<account-ID>/CloudFront as a prefix that appears in the suffixPath of the S3 delivery destination. For more information, see S3DeliveryConfiguration. 2. Add the resource policy for the log delivery destination to allow the source account to create a log delivery. Standard logging (access logs) 902 Amazon CloudFront Developer Guide In the following policy, replace 111111111111 with the source account ID and specify the delivery destination ARN from the output in step 1. { "Version": "2012-10-17", "Statement": [ { "Sid": "AllowCreateDelivery", "Effect": "Allow", "Principal": {"AWS": "111111111111"}, "Action": ["logs:CreateDelivery"], "Resource": "arn:aws:logs:us-east-1:222222222222:delivery- destination:cloudfront-delivery-destination" } ] } 3. 4. Save the file, such as deliverypolicy.json. To attach the previous policy to the delivery destination, enter the following AWS CLI command. aws logs put-delivery-destination-policy --delivery-destination-name cloudfront- delivery-destination --delivery-destination-policy file://deliverypolicy.json 5. Add the below statement to the destination Amazon S3 bucket policy, replacing the resource ARN and the source account ID. This policy allows the delivery.logs.amazonaws.com service principal to perform the s3:PutObject action. { "Sid": "AWSLogsDeliveryWrite", "Effect": "Allow", "Principal": {"Service": "delivery.logs.amazonaws.com"}, "Action": "s3:PutObject", "Resource": "arn:aws:s3:::amzn-s3-demo-bucket-cloudfront-logs/*", "Condition": { "StringEquals": { "s3:x-amz-acl": "bucket-owner-full-control", "aws:SourceAccount": "111111111111" }, "ArnLike": {"aws:SourceArn": "arn:aws:logs:us-east-1:111111111111:delivery- source:*"} Standard logging (access logs) 903 Amazon CloudFront } } Developer Guide 6. If you're using AWS KMS for your bucket, add the following statement to the KMS key policy to grant permissions to the delivery.logs.amazonaws.com service principal. { "Sid": "Allow Logs Delivery to use the key", "Effect": "Allow", "Principal": {"Service": "delivery.logs.amazonaws.com"}, "Action": [ "kms:Encrypt", "kms:Decrypt", "kms:ReEncrypt*", "kms:GenerateDataKey*", "kms:DescribeKey" ], "Resource": "*", "Condition": { "StringEquals": {"aws:SourceAccount": "111111111111"}, "ArnLike": {"aws:SourceArn": "arn:aws:logs:us-east-1:111111111111:delivery- source:*"} } } Configure the source account After you configure the destination account, follow this procedure to create the delivery source and enable logging for the distribution in the source account. To configure the source account 1. Create a delivery source for CloudFront standard logging so that you can send log files to CloudWatch Logs. You can enter the following AWS CLI command, replacing the name and your distribution ARN. aws logs put-delivery-source --name s3-cf-delivery --resource-arn arn:aws:cloudfront::111111111111:distribution/E1TR1RHV123ABC --log-type ACCESS_LOGS Standard logging (access logs) 904 Amazon CloudFront Output { Developer Guide "deliverySource": { "name": "s3-cf-delivery", "arn": "arn:aws:logs:us-east-1:111111111111:delivery-source:s3-cf- delivery", "resourceArns": ["arn:aws:cloudfront::111111111111:distribution/E1TR1RHV123ABC"], "service": "cloudfront", "logType": "ACCESS_LOGS" } } 2. Create a delivery to map the source account's log delivery source and the destination account's log delivery destination. In the following AWS CLI command, specify the delivery destination ARN from the output in Step 1: Configure the destination account. aws logs create-delivery --delivery-source-name s3-cf-delivery -- delivery-destination-arn arn:aws:logs:us-east-1:222222222222:delivery- destination:cloudfront-delivery-destination Output { "delivery": { "id": "OPmOpLahVzhx1234", "arn": "arn:aws:logs:us-east-1:111111111111:delivery:OPmOpLahVzhx1234", "deliverySourceName": "s3-cf-delivery", "deliveryDestinationArn": "arn:aws:logs:us-east-1:222222222222:delivery- destination:cloudfront-delivery-destination", "deliveryDestinationType": "S3", "recordFields": [ "date", "time", "x-edge-location", "sc-bytes", "c-ip", "cs-method", Standard logging (access logs) 905 Amazon CloudFront Developer Guide "cs(Host)", "cs-uri-stem", "sc-status", "cs(Referer)", "cs(User-Agent)", "cs-uri-query", "cs(Cookie)", "x-edge-result-type", "x-edge-request-id", "x-host-header", "cs-protocol", "cs-bytes", "time-taken", "x-forwarded-for", "ssl-protocol", "ssl-cipher", "x-edge-response-result-type", "cs-protocol-version", "fle-status", "fle-encrypted-fields", "c-port", "time-to-first-byte", "x-edge-detailed-result-type", "sc-content-type", "sc-content-len", "sc-range-start", "sc-range-end", "c-country", "cache-behavior-path-pattern" ], "fieldDelimiter": "\t" } } 3. Verify your cross-account delivery is successful. a. b. From the source account, sign in to the CloudFront console and choose your distribution. On the Logging tab, under Type, you will see an entry created for the S3 cross-account log delivery. From the destination account, sign in to the Amazon S3 console and choose your Amazon S3 bucket. You will see the prefix MyLogPrefix in the bucket name and any access logs delivered to that folder. Standard logging (access logs) 906 Amazon CloudFront Output file format Developer Guide Depending on the delivery destination that you choose, you can specify one of the following formats for log files: • JSON • Plain • w3c • Raw • Parquet (Amazon S3 only) Note You can only set the output format when you first create the delivery destination. This can't be updated later. To change the output format, delete the delivery and create another one. For more information, see PutDeliveryDestination in the Amazon CloudWatch Logs API Reference. Edit standard logging settings You can enable or disable logging and update other log settings by using the CloudFront console or the CloudWatch API. Your changes to logging settings take effect within 12 hours. For more information, see the following topics: • To update a distribution by using the CloudFront console, see Update a distribution. • To update a distribution by using the CloudFront API, see
AmazonCloudFront_DevGuide-317
AmazonCloudFront_DevGuide.pdf
317
first create the delivery destination. This can't be updated later. To change the output format, delete the delivery and create another one. For more information, see PutDeliveryDestination in the Amazon CloudWatch Logs API Reference. Edit standard logging settings You can enable or disable logging and update other log settings by using the CloudFront console or the CloudWatch API. Your changes to logging settings take effect within 12 hours. For more information, see the following topics: • To update a distribution by using the CloudFront console, see Update a distribution. • To update a distribution by using the CloudFront API, see UpdateDistribution in the Amazon CloudFront API Reference. • For more information about CloudWatch Logs API operations, see the Amazon CloudWatch Logs API Reference. Access log fields You can select the same log fields that standard logging (legacy) supports. For more information, see log file fields. In addition, you can select the following real-time log fields. Standard logging (access logs) 907 Amazon CloudFront Developer Guide 1. timestamp(ms) – Timestamp in milliseconds. 2. origin-fbl – The number of seconds of first-byte latency between CloudFront and your origin. 3. origin-lbl – The number of seconds of last-byte latency between CloudFront and your origin. 4. asn – The autonomous system number (ASN) of the viewer. 5. c-country – A country code that represents the viewer's geographic location, as determined by the viewer's IP address. For a list of country codes, see ISO 3166-1 alpha-2. 6. cache-behavior-path-pattern – The path pattern that identifies the cache behavior that matched the viewer request. Send logs to CloudWatch Logs To send logs to CloudWatch Logs, create or use an existing CloudWatch Logs log group. For more information about configuring a CloudWatch Logs log group, see Working with Log Groups and Log Streams. After you create your log group, you must have the required permissions to allow standard logging. For more information about the required permissions, see Logs sent to CloudWatch Logs in the Amazon CloudWatch Logs User Guide. Notes • When you specify the name of the CloudWatch Logs log group, only use the regex pattern [\w-]. For more information, see the PutDeliveryDestination API operation in the Amazon CloudWatch Logs API Reference. • Verify that your log group resource policy doesn't exceed the size limit. See the Log group resource policy size limit considerations section in the CloudWatch Logs topic. Example access log sent to CloudWatch Logs { "date": "2024-11-14", "time": "21:34:06", "x-edge-location": "SOF50-P2", "asn": "16509", "timestamp(ms)": "1731620046814", "origin-fbl": "0.251", Standard logging (access logs) 908 Amazon CloudFront "origin-lbl": "0.251", "x-host-header": "d111111abcdef8.cloudfront.net", "cs(Cookie)": "examplecookie=value" } Send logs to Firehose Developer Guide To send logs to Firehose, create or use an existing Firehose delivery stream. For information about creating your delivery stream, see Creating an Amazon Data Firehose delivery stream. After you create your delivery stream, you must have the required permissions to allow standard logging. For more information, see Logs sent to Firehose in the Amazon CloudWatch Logs User Guide. Note When you specify the name of the Firehose stream, only use the regex pattern [\w-]. For more information, see the PutDeliveryDestination API operation in the Amazon CloudWatch Logs API Reference. Example access log sent to Firehose {"date":"2024-11-15","time":"19:45:51","x-edge-location":"SOF50- P2","asn":"16509","timestamp(ms)":"1731699951183","origin-fbl":"0.254","origin- lbl":"0.254","x-host- header":"d111111abcdef8.cloudfront.net","cs(Cookie)":"examplecookie=value"} {"date":"2024-11-15","time":"19:45:52","x-edge-location":"SOF50- P2","asn":"16509","timestamp(ms)":"1731699952950","origin-fbl":"0.125","origin- lbl":"0.125","x-host- header":"d111111abcdef8.cloudfront.net","cs(Cookie)":"examplecookie=value"} Send logs to Amazon S3 To send your access logs to Amazon S3, create or use an existing S3 bucket. When you enable logging in CloudFront, specify the bucket name. For information about creating a bucket, see Create a bucket in the Amazon Simple Storage Service User Guide. After you create your bucket, you must have the required permissions to allow standard logging. For more information, see Logs sent to Amazon S3 in the Amazon CloudWatch Logs User Guide. Standard logging (access logs) 909 Amazon CloudFront Developer Guide • After you enable logging, AWS automatically adds the required bucket policies for you. • You can also use S3 buckets in the opt-in AWS Regions. Note If you already enabled standard logging (legacy) and you want to enable standard logging (v2) to Amazon S3, we recommend that you specify a different Amazon S3 bucket or use a separate path in the same bucket (for example, use a log prefix or partitioning). This helps you keep track of which log files are associated with which distribution and prevents log files from overwriting each other. Topics • Specify an S3 bucket • Partitioning • Hive-compatible file name format • Example paths to access logs • Example access log sent to Amazon S3 Specify an S3 bucket When you specify an S3 bucket as the delivery destination, note the following. The S3 bucket name can only use the regex pattern [\w-]. For more information, see the PutDeliveryDestination API operation in the Amazon CloudWatch Logs API Reference. If you specified a prefix for your S3 bucket, your logs appear
AmazonCloudFront_DevGuide-318
AmazonCloudFront_DevGuide.pdf
318
track of which log files are associated with which distribution and prevents log files from overwriting each other. Topics • Specify an S3 bucket • Partitioning • Hive-compatible file name format • Example paths to access logs • Example access log sent to Amazon S3 Specify an S3 bucket When you specify an S3 bucket as the delivery destination, note the following. The S3 bucket name can only use the regex pattern [\w-]. For more information, see the PutDeliveryDestination API operation in the Amazon CloudWatch Logs API Reference. If you specified a prefix for your S3 bucket, your logs appear under that path. If you don't specify a prefix, CloudFront will automatically append the AWSLogs/{account-id}/CloudFront prefix for you. For more information, see Example paths to access logs. Partitioning You can use partitioning to organize your access logs when CloudFront sends them to your S3 bucket. This helps you organize and locate your access logs based on the path that you want. You can use the following variables to create a folder path. Standard logging (access logs) 910 Amazon CloudFront Developer Guide • {DistributionId} or {distributionid} • {yyyy} • {MM} • {dd} • {HH} • {accountid} You can use any number of variables and specify folder names in your path. CloudFront then uses this path to create a folder structure for you in the S3 bucket. Examples • my_distribution_log_data/{DistributionId}/logs • /cloudfront/{DistributionId}/my_distribution_log_data/{yyyy}/{MM}/{dd}/ {HH}/logs Note You can use either variable for distribution ID in the suffix path. However, if you're sending access logs to AWS Glue, you must use the {distributionid} variable because AWS Glue expects partition names to be in lowercase. Update your existing log configuration in CloudFront to replace {DistributionId} with {distributionid}. Hive-compatible file name format You can use this option so that S3 objects that contain delivered access logs use a prefix structure that allows for integration with Apache Hive. For more information, see the CreateDelivery API operation. Example Example /cloudfront/DistributionId={DistributionId}/my_distribution_log_data/year={yyyy}/ month={MM}/day={dd}/hour={HH}/logs For more information about partitioning and the Hive-compatible options, see the S3DeliveryConfiguration element in the Amazon CloudWatch Logs API Reference. Standard logging (access logs) 911 Amazon CloudFront Example paths to access logs Developer Guide When you specify an S3 bucket as the destination, you can use the following options to create the path to your access logs: • An Amazon S3 bucket, with or without a prefix • Partitioning, by using a CloudFront provided variable or entering your own • Enabling the Hive-compatible option The following tables show how your access logs appear in your bucket, depending on the options that you choose. Amazon S3 bucket with a prefix Partition that you specify in the suffix path Updated suffix path Hive-comp atible enabled? Access logs are sent to None None No Amazon S3 bucket name amzn-s3-d emo-bucke t/MyLogPr efix amzn-s3-d myFolderA/ myFolderA/ No emo-bucke t/MyLogPr efix amzn-s3-d myFolderA/ myFolderA/ Yes emo-bucke {yyyy} {yyyy} t/MyLogPr efix amzn-s3-d emo-bucke t/MyLogPr efix/ amzn-s3-d emo-bucke t/MyLogPr efix/myFo lderA/ amzn-s3-d emo-bucke t/MyLogPr efix/myFo lderA/yea r=2025 Standard logging (access logs) 912 Amazon CloudFront Developer Guide Amazon S3 bucket without a prefix Amazon S3 bucket name Partition that you specify in the suffix path amzn-s3-d emo-bucket None Updated suffix path Hive-comp atible enabled? Access logs are sent to No AWSLogs/{ account-i d}/CloudF ront/ amzn-s3-d myFolderA/ AWSLogs/{ No emo-bucket account-i d}/CloudF ront/myFo lderA/ amzn-s3-d myFolderA/ AWSLogs/{ Yes emo-bucket account-i d}/CloudF ront/myFo lderA/ amzn-s3-d myFolderA/ AWSLogs/{ Yes emo-bucket {yyyy} account-i d}/CloudF ront/myFo lderA/{yy yy} amzn-s3-d emo-bucke t/AWSLogs / <your-acc ount-ID> / CloudFront/ amzn-s3-d emo-bucke t/AWSLogs / <your-acc ount-ID> / CloudFront/ myFolderA/ amzn-s3-d emo-bucke t/AWSLogs /aws- account- id=<your-acc ount-ID> / CloudFront/ myFolderA/ amzn-s3-d emo-bucke t/AWSLogs /aws- account- id=<your-acc Standard logging (access logs) 913 Amazon CloudFront Amazon S3 bucket name Partition that you specify in the suffix path Updated suffix path Hive-comp atible enabled? Access logs are sent to Developer Guide ount-ID> / CloudFront/ myFolderA/ year=2025 AWS account ID as a partition Amazon S3 bucket name Partition that you specify in the suffix path amzn-s3-d emo-bucket None Updated suffix path Hive-comp atible enabled? Access logs are sent to Yes AWSLogs/{ account-i d}/CloudF ront/ amzn-s3-d myFolderA/ AWSLogs/{ Yes emo-bucket {accountid} account-i d}/CloudF ront/myFo lderA/{ac countid} amzn-s3-d emo-bucke t/AWSLogs /aws- account- id=<your-acc ount-ID> / CloudFront/ amzn-s3-d emo-bucke t/AWSLogs /aws- account- id=<your- account- ID>/CloudFro nt/myFold erA/accou ntid= <your- account-ID> Standard logging (access logs) 914 Amazon CloudFront Notes Developer Guide • The {account-id} variable is reserved for CloudFront. CloudFront automatically adds this variable to your suffix path if you specify an Amazon S3 bucket without a prefix. If your logs are Hive-compatible, this variable appears as aws-account-id. • You can use the {accountid} variable so that CloudFront adds your account ID to the suffix path. If your logs are Hive-compatible, this variable appears as accountid. • For more information about the suffix path, see S3DeliveryConfiguration. Example access log sent to Amazon S3 #Fields:
AmazonCloudFront_DevGuide-319
AmazonCloudFront_DevGuide.pdf
319
account- ID>/CloudFro nt/myFold erA/accou ntid= <your- account-ID> Standard logging (access logs) 914 Amazon CloudFront Notes Developer Guide • The {account-id} variable is reserved for CloudFront. CloudFront automatically adds this variable to your suffix path if you specify an Amazon S3 bucket without a prefix. If your logs are Hive-compatible, this variable appears as aws-account-id. • You can use the {accountid} variable so that CloudFront adds your account ID to the suffix path. If your logs are Hive-compatible, this variable appears as accountid. • For more information about the suffix path, see S3DeliveryConfiguration. Example access log sent to Amazon S3 #Fields: date time x-edge-location asn timestamp(ms) x-host-header cs(Cookie) 2024-11-14 22:30:25 SOF50-P2 16509 1731623425421 d111111abcdef8.cloudfront.net examplecookie=value2 Disable standard logging You can disable standard logging for your distribution if you no longer need it. To disable standard logging 1. Sign in to the CloudFront console. 2. Choose Distribution and then choose your distribution ID. 3. Choose Logging and then under Standard log destinations, select the destination. 4. Choose Manage and then choose Delete. 5. Repeat the previous step if you have more than one standard logging. Note When you delete standard logging from the CloudFront console, this action only deletes the delivery and the delivery destination. It doesn't delete the delivery source from your AWS account. To delete a delivery source, specify the delivery source name in the aws logs delete-delivery-source --name DeliverySourceName command. For more information, see DeleteDeliverySource in the Amazon CloudWatch Logs API Reference. Standard logging (access logs) 915 Amazon CloudFront Troubleshoot Developer Guide Use the following information to fix common issues when you work with CloudFront standard logging (v2). Delivery source already exists When you enable standard logging for a distribution, you create a delivery source. You then use that delivery source to create deliveries to destination type that you want: CloudWatch Logs, Firehose, Amazon S3. Currently, you can only have one delivery source per distribution. If you try to create another delivery source for the same distribution, the following error message appears. This ResourceId has already been used in another Delivery Source in this account To create another delivery source, delete the existing one first. For more information, see DeleteDeliverySource in the Amazon CloudWatch Logs API Reference. I changed the suffix path and the Amazon S3 bucket can't receive my logs If you enabled standard logging (v2) and specify a bucket ARN without a prefix, CloudFront will append the following default to the suffix path: AWSLogs/{account-id}/CloudFront. If you use the CloudFront console or the UpdateDeliveryConfiguration API operation to specify a different suffix path, you must update the Amazon S3 bucket policy to use the same path. Example Example: Updating the suffix path 1. Your default suffix path is AWSLogs/{account-id}/CloudFront and you replace it with myFolderA. 2. Because your new suffix path is different than the path specified in the Amazon S3 bucket policy, your access logs won't be delivered. 3. You can do one of the following steps: • Update the Amazon S3 bucket permission from amzn-s3-demo-bucket/AWSLogs/<your- account-ID>/CloudFront/* to amzn-s3-demo-bucket/myFolderA/*. • Update your logging configuration to use the default suffix again: AWSLogs/{account-id}/ CloudFront For more information, see Permissions. Standard logging (access logs) 916 Amazon CloudFront Delete log files Developer Guide CloudFront doesn't automatically delete log files from your destination. For information about deleting log files, see the following topics: Amazon S3 • Deleting objects in the Amazon Simple Storage Service Console User Guide CloudWatch Logs • Working with log groups and log streams in the Amazon CloudWatch Logs User Guide • DeleteLogGroup in the Amazon CloudWatch Logs API Reference Firehose • DeleteDeliveryStream in the Amazon Data Firehose API Reference Pricing CloudFront doesn’t charge for enabling standard logs. However, you can incur charges for the delivery, ingestion, storage or access, depending on the log delivery destination that you select. For more information, see Amazon CloudWatch Logs Pricing. Under Paid Tier, choose the Logs tab, and then under Vended Logs, see the information for each delivery destination. For more information about pricing for each AWS service, see the following topics: • Amazon CloudWatch Logs Pricing • Amazon Data Firehose Pricing • Amazon S3 Pricing Note There are no additional charges for log delivery to Amazon S3, though you incur Amazon S3 charges for storing and accessing the log files. If you enable the Parquet option to convert your access logs to Apache Parquet, this option incurs CloudWatch charges. For more information, see the Vended Logs section for CloudWatch pricing. Standard logging (access logs) 917 Amazon CloudFront Developer Guide Configure standard logging (legacy) Notes • This topic is for the previous version of standard logging. For the latest version, see Configure standard logging (v2). • If you already enabled standard logging (legacy) and you want to enable standard logging (v2) to Amazon S3, we recommend that you specify a different Amazon S3
AmazonCloudFront_DevGuide-320
AmazonCloudFront_DevGuide.pdf
320
charges for storing and accessing the log files. If you enable the Parquet option to convert your access logs to Apache Parquet, this option incurs CloudWatch charges. For more information, see the Vended Logs section for CloudWatch pricing. Standard logging (access logs) 917 Amazon CloudFront Developer Guide Configure standard logging (legacy) Notes • This topic is for the previous version of standard logging. For the latest version, see Configure standard logging (v2). • If you already enabled standard logging (legacy) and you want to enable standard logging (v2) to Amazon S3, we recommend that you specify a different Amazon S3 bucket or use a separate path in the same bucket (for example, use a log prefix or partitioning). This helps you keep track of which log files are associated with which distribution and prevents log files from overwriting each other. To get started with standard logging (legacy), complete the following steps: 1. Choose an Amazon S3 bucket that will receive your logs and add the required permissions. 2. Configure standard logging (legacy) from the CloudFront console or the CloudFront API. You can only choose an Amazon S3 bucket to receive your logs. 3. View your access logs. Choose an Amazon S3 bucket for standard logs When you enable logging for a distribution, you specify the Amazon S3 bucket that you want CloudFront to store log files in. If you're using Amazon S3 as your origin, we recommend that you use a separate bucket for your log files. Specify the Amazon S3 bucket that you want CloudFront to store access logs in, for example, amzn-s3-demo-bucket.s3.amazonaws.com. You can store the log files for multiple distributions in the same bucket. When you enable logging, you can specify an optional prefix for the file names, so you can keep track of which log files are associated with which distributions. About choosing an S3 bucket • Your bucket must have access control list (ACL) enabled. If you choose a bucket without ACL enabled from the CloudFront console, an error message will appear. See Permissions. Standard logging (access logs) 918 Amazon CloudFront Developer Guide • Don't choose an Amazon S3 bucket with S3 Object Ownership set to bucket owner enforced. That setting disables ACLs for the bucket and the objects in it, which prevents CloudFront from delivering log files to the bucket. • Don't choose an Amazon S3 bucket in the following AWS Regions. CloudFront doesn't deliver standard logs to buckets in these Regions: • Africa (Cape Town) • Asia Pacific (Hong Kong) • Asia Pacific (Hyderabad) • Asia Pacific (Jakarta) • Asia Pacific (Melbourne) • Canada West (Calgary) • Europe (Milan) • Europe (Spain) • Europe (Zurich) • Israel (Tel Aviv) • Middle East (Bahrain) • Middle East (UAE) Permissions Important Starting in April 2023, you must enable S3 ACLs for new S3 buckets used for CloudFront standard logs. You can enable ACLs when you create a bucket, or enable ACLs for an existing bucket. For more information about the changes, see Default settings for new S3 buckets FAQ in the Amazon Simple Storage Service User Guide and Heads-Up: Amazon S3 Security Changes Are Coming in April of 2023 in the AWS News Blog. Your AWS account must have the following permissions for the bucket that you specify for log files: Standard logging (access logs) 919 Amazon CloudFront Developer Guide • The ACL for the bucket must grant you FULL_CONTROL. If you're the bucket owner, your account has this permission by default. If you're not, the bucket owner must update the ACL for the bucket. • s3:GetBucketAcl • s3:PutBucketAcl ACL for the bucket When you create or update a distribution and enable logging, CloudFront uses these permissions to update the ACL for the bucket to give the awslogsdelivery account FULL_CONTROL permission. The awslogsdelivery account writes log files to the bucket. If your account doesn't have the required permissions to update the ACL, creating or updating the distribution will fail. In some circumstances, if you programmatically submit a request to create a bucket but a bucket with the specified name already exists, S3 resets permissions on the bucket to the default value. If you configured CloudFront to save access logs in an S3 bucket and you stop getting logs in that bucket, check permissions on the bucket to ensure that CloudFront has the necessary permissions. Restoring the ACL for the bucket If you remove permissions for the awslogsdelivery account, CloudFront won't be able to save logs to the S3 bucket. To enable CloudFront to start saving logs for your distribution again, restore the ACL permission by doing one of the following: • Disable logging for your distribution in CloudFront, and then enable it again. For more information, see Standard logging. • Add the ACL permission for awslogsdelivery manually by navigating to the S3 bucket in the
AmazonCloudFront_DevGuide-321
AmazonCloudFront_DevGuide.pdf
321
stop getting logs in that bucket, check permissions on the bucket to ensure that CloudFront has the necessary permissions. Restoring the ACL for the bucket If you remove permissions for the awslogsdelivery account, CloudFront won't be able to save logs to the S3 bucket. To enable CloudFront to start saving logs for your distribution again, restore the ACL permission by doing one of the following: • Disable logging for your distribution in CloudFront, and then enable it again. For more information, see Standard logging. • Add the ACL permission for awslogsdelivery manually by navigating to the S3 bucket in the Amazon S3 console and adding permission. To add the ACL for awslogsdelivery, you must provide the canonical ID for the account, which is the following: c4c1ede66af53448b93c283ce9448c4ba468c9432aa01d700d3878632f77d2d0 For more information about adding ACLs to S3 buckets, see Configuring ACLs in the Amazon Simple Storage Service User Guide. Standard logging (access logs) 920 Amazon CloudFront ACL for each log file Developer Guide In addition to the ACL on the bucket, there's an ACL on each log file. The bucket owner has FULL_CONTROL permission on each log file, the distribution owner (if different from the bucket owner) has no permission, and the awslogsdelivery account has read and write permissions. Disabling logging If you disable logging, CloudFront doesn't delete the ACLs for either the bucket or the log files. You can delete the ACLs if needed. Required key policy for SSE-KMS buckets If the S3 bucket for your standard logs uses server-side encryption with AWS KMS keys (SSE-KMS) by using a customer managed key, you must add the following statement to the key policy for your customer managed key. This allows CloudFront to write log files to the bucket. You can't use SSE- KMS with the AWS managed key because CloudFront won't be able to write log files to the bucket. { "Sid": "Allow CloudFront to use the key to deliver logs", "Effect": "Allow", "Principal": { "Service": "delivery.logs.amazonaws.com" }, "Action": "kms:GenerateDataKey*", "Resource": "*" } If the S3 bucket for your standard logs uses SSE-KMS with an S3 Bucket Key, you also need to add the kms:Decrypt permission to the policy statement. In that case, the full policy statement looks like the following. { "Sid": "Allow CloudFront to use the key to deliver logs", "Effect": "Allow", "Principal": { "Service": "delivery.logs.amazonaws.com" }, "Action": [ "kms:GenerateDataKey*", "kms:Decrypt" ], Standard logging (access logs) 921 Amazon CloudFront "Resource": "*" } Note Developer Guide When you enable SSE-KMS for your S3 bucket, specify the complete ARN for the customer managed key. For more information, see Specifying server-side encryption with AWS KMS keys (SSE-KMS) in the Amazon Simple Storage Service User Guide. Enable standard logging (legacy) To enable standard logs, use the CloudFront console or the CloudFront API. Contents • Enable standard logging (legacy) (CloudFront console) • Enable standard logging (legacy) (CloudFront API) Enable standard logging (legacy) (CloudFront console) To enable standard logs for a CloudFront distribution (console) 1. Use the CloudFront console to create a new distribution or update an existing one. 2. 3. 4. 5. For the Standard logging section, for Log delivery, choose On. (Optional) For Cookie logging, choose On if you want to include cookies in your logs. For more information, see Cookie logging. Tip Cookie logging is a global setting that applies to all standard logs for your distribution. You can’t override this setting for separate delivery destinations. For the Deliver to section, specify Amazon S3 (Legacy). Specify your Amazon S3 bucket. If you don't have one already, you can choose Create or see the documentation to create a bucket. 6. (Optional) For Log prefix, specify the string, if any, that you want CloudFront to prefix to the access log file names for this distribution, for example, exampleprefix/. The trailing slash Standard logging (access logs) 922 Amazon CloudFront Developer Guide ( / ) is optional but recommended to simplify browsing your log files. For more information, see Log prefix. 7. Complete the steps to update or create your distribution. 8. From the Logs page, verify that the standard logs status is Enabled next to the distribution. For more information about the standard logging delivery and log fields, see the Standard logging reference. Enable standard logging (legacy) (CloudFront API) You can also use the CloudFront API to enable standard logs for your distributions. To enable standard logs for a distribution (CloudFront API) • Use the CreateDistribution or UpdateDistribution API operation and configure the LoggingConfig object. Edit standard logging settings You can enable or disable logging, change the Amazon S3 bucket where your logs are stored, and change the prefix for log files by using the CloudFront console or the CloudFront API. Your changes to logging settings take effect within 12 hours. For more information, see the following topics: • To update a distribution using the CloudFront console,
AmazonCloudFront_DevGuide-322
AmazonCloudFront_DevGuide.pdf
322
(CloudFront API) You can also use the CloudFront API to enable standard logs for your distributions. To enable standard logs for a distribution (CloudFront API) • Use the CreateDistribution or UpdateDistribution API operation and configure the LoggingConfig object. Edit standard logging settings You can enable or disable logging, change the Amazon S3 bucket where your logs are stored, and change the prefix for log files by using the CloudFront console or the CloudFront API. Your changes to logging settings take effect within 12 hours. For more information, see the following topics: • To update a distribution using the CloudFront console, see Update a distribution. • To update a distribution using the CloudFront API, see UpdateDistribution in the Amazon CloudFront API Reference. Send logs to Amazon S3 When you send your logs to Amazon S3, your logs appear in the following format. File name format The name of each log file that CloudFront saves in your Amazon S3 bucket uses the following file name format: <optional prefix>/<distribution ID>.YYYY-MM-DD-HH.unique-ID.gz Standard logging (access logs) 923 Amazon CloudFront Developer Guide The date and time are in Coordinated Universal Time (UTC). For example, if you use example-prefix as the prefix, and your distribution ID is EMLARXS9EXAMPLE, your file names look similar to this: example-prefix/EMLARXS9EXAMPLE.2019-11-14-20.RT4KCN4SGK9.gz When you enable logging for a distribution, you can specify an optional prefix for the file names, so you can keep track of which log files are associated with which distributions. If you include a value for the log file prefix and your prefix doesn't end with a forward slash (/), CloudFront appends one automatically. If your prefix does end with a forward slash, CloudFront doesn't add another one. The .gz at the end of the file name indicates that CloudFront has compressed the log file using gzip. Standard log file format Each entry in a log file gives details about a single viewer request. The log files have the following characteristics: • Use the W3C extended log file format. • Contain tab-separated values. • Contain records that are not necessarily in chronological order. • Contain two header lines: one with the file format version, and another that lists the W3C fields included in each record. • Contain URL-encoded equivalents for spaces and certain other characters in field values. URL-encoded equivalents are used for the following characters: • ASCII character codes 0 through 32, inclusive • ASCII character codes 127 and higher • All characters in the following table The URL encoding standard is defined in RFC 1738. URL-Encoded value Character %3C < Standard logging (access logs) 924 Amazon CloudFront Developer Guide URL-Encoded value Character %3E %22 %23 %25 %7B %7D %7C %5C %5E %7E %5B %5D %60 %27 %20 > " # % { } | \ ^ ~ [ ] ` ' space Delete log files CloudFront doesn't automatically delete log files from your Amazon S3 bucket. For information about deleting log files from an Amazon S3 bucket, see Deleting objects in the Amazon Simple Storage Service Console User Guide. Standard logging (access logs) 925 Amazon CloudFront Pricing Developer Guide Standard logging is an optional feature of CloudFront. CloudFront doesn’t charge for enabling standard logs. However, you accrue the usual Amazon S3 charges for storing and accessing the files on Amazon S3. You can delete them at any time. For more information about Amazon S3 pricing, see Amazon S3 Pricing. For more information about CloudFront pricing, see CloudFront Pricing. Standard logging reference The following sections apply to both standard logging (v2) and standard logging (legacy). Topics • Timing of log file delivery • How requests are logged when the request URL or headers exceed the maximum size • Log file fields • Analyze logs Timing of log file delivery CloudFront delivers logs for a distribution up to several times an hour. In general, a log file contains information about the requests that CloudFront received during a given time period. CloudFront usually delivers the log file for that time period to your destination within an hour of the events that appear in the log. Note, however, that some or all log file entries for a time period can sometimes be delayed by up to 24 hours. When log entries are delayed, CloudFront saves them in a log file for which the file name includes the date and time of the period in which the requests occurred, not the date and time when the file was delivered. When creating a log file, CloudFront consolidates information for your distribution from all of the edge locations that received requests for your objects during the time period that the log file covers. CloudFront can save more than one file for a time period depending on how many requests CloudFront receives for the objects associated with a distribution. CloudFront begins to reliably deliver access logs
AmazonCloudFront_DevGuide-323
AmazonCloudFront_DevGuide.pdf
323
delayed, CloudFront saves them in a log file for which the file name includes the date and time of the period in which the requests occurred, not the date and time when the file was delivered. When creating a log file, CloudFront consolidates information for your distribution from all of the edge locations that received requests for your objects during the time period that the log file covers. CloudFront can save more than one file for a time period depending on how many requests CloudFront receives for the objects associated with a distribution. CloudFront begins to reliably deliver access logs about four hours after you enable logging. You might get a few access logs before that time. Standard logging (access logs) 926 Amazon CloudFront Note Developer Guide If no users request your objects during the time period, you don't receive any log files for that period. How requests are logged when the request URL or headers exceed the maximum size If the total size of all request headers, including cookies, exceeds 20 KB, or if the URL exceeds 8192 bytes, CloudFront can't parse the request completely and can't log the request. Because the request isn't logged, you won't see in the log files the HTTP error status code returned. If the request body exceeds the maximum size, the request is logged, including the HTTP error status code. Log file fields The log file for a distribution contains 33 fields. The following list contains each field name, in order, along with a description of the information in that field. 1. date The date on which the event occurred in the format YYYY-MM-DD. For example, 2019-06-30. The date and time are in Coordinated Universal Time (UTC). For WebSocket connections, this is the date when the connection closed. 2. time The time when the CloudFront server finished responding to the request (in UTC), for example, 01:42:39. For WebSocket connections, this is the time when the connection is closed. 3. x-edge-location The edge location that served the request. Each edge location is identified by a three-letter code and an arbitrarily assigned number (for example, DFW3). The three-letter code typically corresponds with the International Air Transport Association (IATA) airport code for an airport near the edge location's geographic location. (These abbreviations might change in the future.) 4. sc-bytes Standard logging (access logs) 927 Amazon CloudFront Developer Guide The total number of bytes that the server sent to the viewer in response to the request, including headers. For WebSocket and gRPC connections, this is the total number of bytes sent from the server to the client through the connection. 5. c-ip The IP address of the viewer that made the request, for example, 192.0.2.183 or 2001:0db8:85a3::8a2e:0370:7334. If the viewer used an HTTP proxy or a load balancer to send the request, the value of this field is the IP address of the proxy or load balancer. See also the x-forwarded-for field. 6. cs-method The HTTP request method received from the viewer. 7. cs(Host) The domain name of the CloudFront distribution (for example, d111111abcdef8.cloudfront.net). 8. cs-uri-stem The portion of the request URL that identifies the path and object (for example, /images/ cat.jpg). Question marks (?) in URLs and query strings are not included in the log. 9. sc-status Contains one of the following values: • The HTTP status code of the server's response (for example, 200). • 000, which indicates that the viewer closed the connection before the server could respond to the request. If the viewer closes the connection after the server starts to send the response, this field contains the HTTP status code of the response that the server started to send. 10.cs(Referer) The value of the Referer header in the request. This is the name of the domain that originated the request. Common referrers include search engines, other websites that link directly to your objects, and your own website. 11.cs(User-Agent) The value of the User-Agent header in the request. The User-Agent header identifies the source of the request, such as the type of device and browser that submitted the request or, if the request came from a search engine, which search engine. Standard logging (access logs) 928 Amazon CloudFront 12.cs-uri-query Developer Guide The query string portion of the request URL, if any. When a URL doesn't contain a query string, this field's value is a hyphen (-). For more information, see Cache content based on query string parameters. 13.cs(Cookie) The Cookie header in the request, including name—value pairs and the associated attributes. If you enable cookie logging, CloudFront logs the cookies in all requests regardless of which cookies you choose to forward to the origin. When a request doesn't include a cookie header, this field's value is a hyphen (-). For more information about cookies, see Cache content based on cookies. 14.x-edge-result-type How the
AmazonCloudFront_DevGuide-324
AmazonCloudFront_DevGuide.pdf
324
string portion of the request URL, if any. When a URL doesn't contain a query string, this field's value is a hyphen (-). For more information, see Cache content based on query string parameters. 13.cs(Cookie) The Cookie header in the request, including name—value pairs and the associated attributes. If you enable cookie logging, CloudFront logs the cookies in all requests regardless of which cookies you choose to forward to the origin. When a request doesn't include a cookie header, this field's value is a hyphen (-). For more information about cookies, see Cache content based on cookies. 14.x-edge-result-type How the server classified the response after the last byte left the server. In some cases, the result type can change between the time that the server is ready to send the response and the time that it finishes sending the response. See also the x-edge-response-result-type field. For example, in HTTP streaming, suppose the server finds a segment of the stream in the cache. In that scenario, the value of this field would ordinarily be Hit. However, if the viewer closes the connection before the server has delivered the entire segment, the final result type (and the value of this field) is Error. WebSocket and gRPC connections will have a value of Miss for this field because the content is not cacheable and is proxied directly to the origin. Possible values include: • Hit – The server served the object to the viewer from the cache. • RefreshHit – The server found the object in the cache but the object had expired, so the server contacted the origin to verify that the cache had the latest version of the object. • Miss – The request could not be satisfied by an object in the cache, so the server forwarded the request to the origin and returned the result to the viewer. • LimitExceeded – The request was denied because a CloudFront quota (formerly referred to as a limit) was exceeded. • CapacityExceeded – The server returned an HTTP 503 status code because it didn't have enough capacity at the time of the request to serve the object. Standard logging (access logs) 929 Amazon CloudFront Developer Guide • Error – Typically, this means the request resulted in a client error (the value of the sc- status field is in the 4xx range) or a server error (the value of the sc-status field is in the 5xx range). If the value of the sc-status field is 200, or if the value of this field is Error and the value of the x-edge-response-result-type field is not Error, it means the HTTP request was successful but the client disconnected before receiving all of the bytes. • Redirect – The server redirected the viewer from HTTP to HTTPS according to the distribution settings. 15.x-edge-request-id An opaque string that uniquely identifies a request. CloudFront also sends this string in the x- amz-cf-id response header. 16.x-host-header The value that the viewer included in the Host header of the request. If you're using the CloudFront domain name in your object URLs (such as d111111abcdef8.cloudfront.net), this field contains that domain name. If you're using alternate domain names (CNAMEs) in your object URLs (such as www.example.com), this field contains the alternate domain name. If you're using alternate domain names, see cs(Host) in field 7 for the domain name that is associated with your distribution. 17.cs-protocol The protocol of the viewer request (http, https, grpcs, ws, or wss). 18.cs-bytes The total number of bytes of data that the viewer included in the request, including headers. For WebSocket and gRPC connections, this is the total number of bytes sent from the client to the server on the connection. 19.time-taken The number of seconds (to the thousandth of a second, for example, 0.082) from when the server receives the viewer's request to when the server writes the last byte of the response to the output queue, as measured on the server. From the perspective of the viewer, the total time to get the full response will be longer than this value because of network latency and TCP buffering. 20.x-forwarded-for Standard logging (access logs) 930 Amazon CloudFront Developer Guide If the viewer used an HTTP proxy or a load balancer to send the request, the value of the c- ip field is the IP address of the proxy or load balancer. In that case, this field is the IP address of the viewer that originated the request. This field can contain multiple comma-separated IP addresses. Each IP address can be an IPv4 address (for example, 192.0.2.183) or an IPv6 address (for example, 2001:0db8:85a3::8a2e:0370:7334). If the viewer did not use an HTTP proxy or a load balancer, the value of this field is a hyphen (-). 21.ssl-protocol When the request used HTTPS, this field contains the SSL/TLS
AmazonCloudFront_DevGuide-325
AmazonCloudFront_DevGuide.pdf
325
or a load balancer to send the request, the value of the c- ip field is the IP address of the proxy or load balancer. In that case, this field is the IP address of the viewer that originated the request. This field can contain multiple comma-separated IP addresses. Each IP address can be an IPv4 address (for example, 192.0.2.183) or an IPv6 address (for example, 2001:0db8:85a3::8a2e:0370:7334). If the viewer did not use an HTTP proxy or a load balancer, the value of this field is a hyphen (-). 21.ssl-protocol When the request used HTTPS, this field contains the SSL/TLS protocol that the viewer and server negotiated for transmitting the request and response. For a list of possible values, see the supported SSL/TLS protocols in Supported protocols and ciphers between viewers and CloudFront. When cs-protocol in field 17 is http, the value for this field is a hyphen (-). 22.ssl-cipher When the request used HTTPS, this field contains the SSL/TLS cipher that the viewer and server negotiated for encrypting the request and response. For a list of possible values, see the supported SSL/TLS ciphers in Supported protocols and ciphers between viewers and CloudFront. When cs-protocol in field 17 is http, the value for this field is a hyphen (-). 23.x-edge-response-result-type How the server classified the response just before returning the response to the viewer. See also the x-edge-result-type field. Possible values include: • Hit – The server served the object to the viewer from the cache. • RefreshHit – The server found the object in the cache but the object had expired, so the server contacted the origin to verify that the cache had the latest version of the object. • Miss – The request could not be satisfied by an object in the cache, so the server forwarded the request to the origin server and returned the result to the viewer. • LimitExceeded – The request was denied because a CloudFront quota (formerly referred to as a limit) was exceeded. • CapacityExceeded – The server returned a 503 error because it didn't have enough capacity at the time of the request to serve the object. Standard logging (access logs) 931 Amazon CloudFront Developer Guide • Error – Typically, this means the request resulted in a client error (the value of the sc- status field is in the 4xx range) or a server error (the value of the sc-status field is in the 5xx range). If the value of the x-edge-result-type field is Error and the value of this field is not Error, the client disconnected before finishing the download. • Redirect – The server redirected the viewer from HTTP to HTTPS according to the distribution settings. 24.cs-protocol-version The HTTP version that the viewer specified in the request. Possible values include HTTP/0.9, HTTP/1.0, HTTP/1.1, HTTP/2.0, and HTTP/3.0. 25.fle-status When field-level encryption is configured for a distribution, this field contains a code that indicates whether the request body was successfully processed. When the server successfully processes the request body, encrypts values in the specified fields, and forwards the request to the origin, the value of this field is Processed. The value of x-edge-result-type can still indicate a client-side or server-side error in this case. Possible values for this field include: • ForwardedByContentType – The server forwarded the request to the origin without parsing or encryption because no content type was configured. • ForwardedByQueryArgs – The server forwarded the request to the origin without parsing or encryption because the request contains a query argument that wasn't in the configuration for field-level encryption. • ForwardedDueToNoProfile – The server forwarded the request to the origin without parsing or encryption because no profile was specified in the configuration for field-level encryption. • MalformedContentTypeClientError – The server rejected the request and returned an HTTP 400 status code to the viewer because the value of the Content-Type header was in an invalid format. • MalformedInputClientError – The server rejected the request and returned an HTTP 400 status code to the viewer because the request body was in an invalid format. • MalformedQueryArgsClientError – The server rejected the request and returned an HTTP 400 status code to the viewer because a query argument was empty or in an invalid format. Standard logging (access logs) 932 Amazon CloudFront Developer Guide • RejectedByContentType – The server rejected the request and returned an HTTP 400 status code to the viewer because no content type was specified in the configuration for field- level encryption. • RejectedByQueryArgs – The server rejected the request and returned an HTTP 400 status code to the viewer because no query argument was specified in the configuration for field- level encryption. • ServerError – The origin server returned an error. If the request exceeds a field-level encryption quota (formerly referred to as a limit), this field contains one
AmazonCloudFront_DevGuide-326
AmazonCloudFront_DevGuide.pdf
326
invalid format. Standard logging (access logs) 932 Amazon CloudFront Developer Guide • RejectedByContentType – The server rejected the request and returned an HTTP 400 status code to the viewer because no content type was specified in the configuration for field- level encryption. • RejectedByQueryArgs – The server rejected the request and returned an HTTP 400 status code to the viewer because no query argument was specified in the configuration for field- level encryption. • ServerError – The origin server returned an error. If the request exceeds a field-level encryption quota (formerly referred to as a limit), this field contains one of the following error codes, and the server returns HTTP status code 400 to the viewer. For a list of the current quotas on field-level encryption, see Quotas on field-level encryption. • FieldLengthLimitClientError – A field that is configured to be encrypted exceeded the maximum length allowed. • FieldNumberLimitClientError – A request that the distribution is configured to encrypt contains more than the number of fields allowed. • RequestLengthLimitClientError – The length of the request body exceeded the maximum length allowed when field-level encryption is configured. If field-level encryption is not configured for the distribution, the value of this field is a hyphen (-). 26.fle-encrypted-fields The number of field-level encryption fields that the server encrypted and forwarded to the origin. CloudFront servers stream the processed request to the origin as they encrypt data, so this field can have a value even if the value of fle-status is an error. If field-level encryption is not configured for the distribution, the value of this field is a hyphen (-). 27.c-port The port number of the request from the viewer. 28.time-to-first-byte The number of seconds between receiving the request and writing the first byte of the response, as measured on the server. Standard logging (access logs) 933 Amazon CloudFront Developer Guide 29.x-edge-detailed-result-type This field contains the same value as the x-edge-result-type field, except in the following cases: • When the object was served to the viewer from the Origin Shield layer, this field contains OriginShieldHit. • When the object was not in the CloudFront cache and the response was generated by an origin request Lambda@Edge function, this field contains MissGeneratedResponse. • When the value of the x-edge-result-type field is Error, this field contains one of the following values with more information about the error: • AbortedOrigin – The server encountered an issue with the origin. • ClientCommError – The response to the viewer was interrupted due to a communication problem between the server and the viewer. • ClientGeoBlocked – The distribution is configured to refuse requests from the viewer's geographic location. • ClientHungUpRequest – The viewer stopped prematurely while sending the request. • Error – An error occurred for which the error type doesn't fit any of the other categories. This error type can occur when the server serves an error response from the cache. • InvalidRequest – The server received an invalid request from the viewer. • InvalidRequestBlocked – Access to the requested resource is blocked. • InvalidRequestCertificate – The distribution doesn't match the SSL/TLS certificate for which the HTTPS connection was established. • InvalidRequestHeader – The request contained an invalid header. • InvalidRequestMethod – The distribution is not configured to handle the HTTP request method that was used. This can happen when the distribution supports only cacheable requests. • OriginCommError – The request timed out while connecting to the origin, or reading data from the origin. • OriginConnectError – The server couldn't connect to the origin. • OriginContentRangeLengthError – The Content-Length header in the origin's response doesn't match the length in the Content-Range header. • OriginDnsError – The server couldn't resolve the origin's domain name. Standard logging (access logs) • OriginError – The origin returned an incorrect response. 934 Amazon CloudFront Developer Guide • OriginHeaderTooBigError – A header returned by the origin is too big for the edge server to process. • OriginInvalidResponseError – The origin returned an invalid response. • OriginReadError – The server couldn't read from the origin. • OriginWriteError – The server couldn't write to the origin. • OriginZeroSizeObjectError – A zero size object sent from the origin resulted in an error. • SlowReaderOriginError – The viewer was slow to read the message that caused the origin error. 30.sc-content-type The value of the HTTP Content-Type header of the response. 31.sc-content-len The value of the HTTP Content-Length header of the response. 32.sc-range-start When the response contains the HTTP Content-Range header, this field contains the range start value. 33.sc-range-end When the response contains the HTTP Content-Range header, this field contains the range end value. 34.distribution-tenant-id The ID of the distribution tenant. The following is an example log file for a distribution. #Version: 1.0 #Fields: date time x-edge-location sc-bytes c-ip cs-method cs(Host) cs-uri-stem sc- status cs(Referer) cs(User-Agent) cs-uri-query cs(Cookie) x-edge-result-type x-edge-
AmazonCloudFront_DevGuide-327
AmazonCloudFront_DevGuide.pdf
327
slow to read the message that caused the origin error. 30.sc-content-type The value of the HTTP Content-Type header of the response. 31.sc-content-len The value of the HTTP Content-Length header of the response. 32.sc-range-start When the response contains the HTTP Content-Range header, this field contains the range start value. 33.sc-range-end When the response contains the HTTP Content-Range header, this field contains the range end value. 34.distribution-tenant-id The ID of the distribution tenant. The following is an example log file for a distribution. #Version: 1.0 #Fields: date time x-edge-location sc-bytes c-ip cs-method cs(Host) cs-uri-stem sc- status cs(Referer) cs(User-Agent) cs-uri-query cs(Cookie) x-edge-result-type x-edge- request-id x-host-header cs-protocol cs-bytes time-taken x-forwarded-for ssl-protocol ssl-cipher x-edge-response-result-type cs-protocol-version fle-status fle-encrypted- fields c-port time-to-first-byte x-edge-detailed-result-type sc-content-type sc- content-len sc-range-start sc-range-end Standard logging (access logs) 935 Amazon CloudFront Developer Guide 2019-12-04 21:02:31 LAX1 392 192.0.2.100 GET d111111abcdef8.cloudfront.net / index.html 200 - Mozilla/5.0%20(Windows%20NT%2010.0;%20Win64; %20x64)%20AppleWebKit/537.36%20(KHTML,%20like %20Gecko)%20Chrome/78.0.3904.108%20Safari/537.36 - - Hit SOX4xwn4XV6Q4rgb7XiVGOHms_BGlTAC4KyHmureZmBNrjGdRLiNIQ== d111111abcdef8.cloudfront.net https 23 0.001 - TLSv1.2 ECDHE-RSA-AES128-GCM-SHA256 Hit HTTP/2.0 - - 11040 0.001 Hit text/html 78 - - 2019-12-04 21:02:31 LAX1 392 192.0.2.100 GET d111111abcdef8.cloudfront.net / index.html 200 - Mozilla/5.0%20(Windows%20NT%2010.0;%20Win64; %20x64)%20AppleWebKit/537.36%20(KHTML,%20like %20Gecko)%20Chrome/78.0.3904.108%20Safari/537.36 - - Hit k6WGMNkEzR5BEM_SaF47gjtX9zBDO2m349OY2an0QPEaUum1ZOLrow== d111111abcdef8.cloudfront.net https 23 0.000 - TLSv1.2 ECDHE-RSA-AES128-GCM-SHA256 Hit HTTP/2.0 - - 11040 0.000 Hit text/html 78 - - 2019-12-04 21:02:31 LAX1 392 192.0.2.100 GET d111111abcdef8.cloudfront.net / index.html 200 - Mozilla/5.0%20(Windows%20NT%2010.0;%20Win64; %20x64)%20AppleWebKit/537.36%20(KHTML,%20like %20Gecko)%20Chrome/78.0.3904.108%20Safari/537.36 - - Hit f37nTMVvnKvV2ZSvEsivup_c2kZ7VXzYdjC-GUQZ5qNs-89BlWazbw== d111111abcdef8.cloudfront.net https 23 0.001 - TLSv1.2 ECDHE-RSA-AES128-GCM-SHA256 Hit HTTP/2.0 - - 11040 0.001 Hit text/html 78 - - 2019-12-13 22:36:27 SEA19-C1 900 192.0.2.200 GET d111111abcdef8.cloudfront.net / favicon.ico 502 http://www.example.com/ Mozilla/5.0%20(Windows %20NT%2010.0;%20Win64;%20x64)%20AppleWebKit/537.36%20(KHTML, %20like%20Gecko)%20Chrome/78.0.3904.108%20Safari/537.36 - - Error 1pkpNfBQ39sYMnjjUQjmH2w1wdJnbHYTbag21o_3OfcQgPzdL2RSSQ== www.example.com http 675 0.102 - - - Error HTTP/1.1 - - 25260 0.102 OriginDnsError text/html 507 - - 2019-12-13 22:36:26 SEA19-C1 900 192.0.2.200 GET d111111abcdef8.cloudfront.net / 502 - Mozilla/5.0%20(Windows%20NT%2010.0;%20Win64;%20x64)%20AppleWebKit/537.36%20(KHTML, %20like%20Gecko)%20Chrome/78.0.3904.108%20Safari/537.36 - - Error 3AqrZGCnF_g0-5KOvfA7c9XLcf4YGvMFSeFdIetR1N_2y8jSis8Zxg== www.example.com http 735 0.107 - - - Error HTTP/1.1 - - 3802 0.107 OriginDnsError text/html 507 - - 2019-12-13 22:37:02 SEA19-C2 900 192.0.2.200 GET d111111abcdef8.cloudfront.net / 502 - curl/7.55.1 - - Error kBkDzGnceVtWHqSCqBUqtA_cEs2T3tFUBbnBNkB9El_uVRhHgcZfcw== www.example.com http 387 0.103 - - - Error HTTP/1.1 - - 12644 0.103 OriginDnsError text/html 507 - - Analyze logs Because you can receive multiple access logs per hour, we recommend that you combine all the log files you receive for a given time period into one file. You can then analyze the data for that period more accurately and completely. Standard logging (access logs) 936 Amazon CloudFront Developer Guide One way to analyze your access logs is to use Amazon Athena. Athena is an interactive query service that can help you analyze data for AWS services, including CloudFront. To learn more, see Querying Amazon CloudFront Logs in the Amazon Athena User Guide. In addition, the following AWS blog posts discuss some ways to analyze access logs. • Amazon CloudFront Request Logging (for content delivered via HTTP) • Enhanced CloudFront Logs, Now With Query Strings Use real-time logs With CloudFront real-time logs, you can get information about requests made to a distribution in real time (logs are delivered within seconds of receiving the requests). You can use real-time logs to monitor, analyze, and take action based on content delivery performance. CloudFront real-time logs are configurable. You can choose: • The sampling rate for your real-time logs—that is, the percentage of requests for which you want to receive real-time log records. • The specific fields that you want to receive in the log records. • The specific cache behaviors (path patterns) that you want to receive real-time logs for. CloudFront real-time logs are delivered to the data stream of your choice in Amazon Kinesis Data Streams. You can build your own Kinesis data stream consumer, or use Amazon Data Firehose to send the log data to Amazon Simple Storage Service (Amazon S3), Amazon Redshift, Amazon OpenSearch Service (OpenSearch Service), or a third-party log processing service. CloudFront charges for real-time logs, in addition to the charges you incur for using Kinesis Data Streams. For more information about pricing, see Amazon CloudFront Pricing and Amazon Kinesis Data Streams pricing. Important We recommend that you use the logs to understand the nature of the requests for your content, not as a complete accounting of all requests. CloudFront delivers real-time logs on a best-effort basis. The log entry for a particular request might be delivered long after the request was actually processed and, in rare cases, a log entry might not be delivered at all. Use real-time logs 937 Amazon CloudFront Developer Guide When a log entry is omitted from real-time logs, the number of entries in the real-time logs won't match the usage that appears in the AWS billing and usage reports. Topics • Create and use real-time log configurations • Understand real-time log configurations • Create a Kinesis Data Streams consumer • Troubleshoot real-time logs Create and use real-time log configurations To get information about requests made to a distribution
AmazonCloudFront_DevGuide-328
AmazonCloudFront_DevGuide.pdf
328
might be delivered long after the request was actually processed and, in rare cases, a log entry might not be delivered at all. Use real-time logs 937 Amazon CloudFront Developer Guide When a log entry is omitted from real-time logs, the number of entries in the real-time logs won't match the usage that appears in the AWS billing and usage reports. Topics • Create and use real-time log configurations • Understand real-time log configurations • Create a Kinesis Data Streams consumer • Troubleshoot real-time logs Create and use real-time log configurations To get information about requests made to a distribution in real time. you can use a real-time log configurations. Logs are delivered within seconds of receiving the requests. You can create a real- time log configuration in the CloudFront console, with the AWS Command Line Interface (AWS CLI), or with the CloudFront API. To use a real-time log configuration, you attach it to one or more cache behaviors in a CloudFront distribution. Console To create a real-time log configuration 1. Sign in to the AWS Management Console and open the Logs page in the CloudFront console at https://console.aws.amazon.com/cloudfront/v4/home?#/logs. 2. Choose the Real-time configurations tab. 3. Choose Create configuration. 4. 5. For Name, enter a name for the configuration. For Sampling rate, enter the percentage of requests for which you want to receive log records. 6. For Fields, choose the fields to receive in the real-time logs. • To include all CMCD fields for your logs, choose CMCD all keys. 7. For Endpoint, choose one or more Kinesis data streams to receive real-time logs. Use real-time logs 938 Amazon CloudFront Developer Guide Note CloudFront real-time logs are delivered to the data stream that you specify in Kinesis Data Streams. To read and analyze your real-time logs, you can build your own Kinesis data stream consumer. You can also use Firehose to send the log data to Amazon S3, Amazon Redshift, Amazon OpenSearch Service, or a third-party log processing service. 8. 9. For IAM role, choose Create new service role or choose an existing role. You must have permission to create IAM roles. (Optional) For Distribution, choose a CloudFront distribution and cache behavior to attach to the real-time log configuration. 10. Choose Create configuration. If successful, the console shows the details of the real-time log configuration that you just created. For more information, see Understand real-time log configurations. AWS CLI To create a real-time log configuration with the AWS CLI, use the aws cloudfront create- realtime-log-config command. You can use an input file to provide the command's input parameters, rather than specifying each individual parameter as command line input. To create a real-time log configuration (CLI with input file) 1. Use the following command to create a file named rtl-config.yaml that contains all of the input parameters for the create-realtime-log-config command. aws cloudfront create-realtime-log-config --generate-cli-skeleton yaml-input > rtl-config.yaml 2. Open the file named rtl-config.yaml that you just created. Edit the file to specify the real-time log configuration settings that you want, then save the file. Note the following: • For StreamType, the only valid value is Kinesis. Use real-time logs 939 Amazon CloudFront Developer Guide For more information about the real-time long configuration settings, see Understand real- time log configurations. 3. Use the following command to create the real-time log configuration using input parameters from the rtl-config.yaml file. aws cloudfront create-realtime-log-config --cli-input-yaml file://rtl- config.yaml If successful, the command's output shows the details of the real-time log configuration that you just created. To attach a real-time log configuration to an existing distribution (CLI with input file) 1. Use the following command to save the distribution configuration for the CloudFront distribution that you want to update. Replace distribution_ID with the distribution's ID. aws cloudfront get-distribution-config --id distribution_ID --output yaml > dist-config.yaml 2. Open the file named dist-config.yaml that you just created. Edit the file, making the following changes to each cache behavior that you are updating to use a real-time log configuration. • In the cache behavior, add a field named RealtimeLogConfigArn. For the field's value, use the ARN of the real-time log configuration that you want to attach to this cache behavior. • Rename the ETag field to IfMatch, but don't change the field's value. Save the file when finished. 3. Use the following command to update the distribution to use the real-time log configuration. Replace distribution_ID with the distribution's ID. Use real-time logs 940 Amazon CloudFront Developer Guide aws cloudfront update-distribution --id distribution_ID --cli-input-yaml file:// dist-config.yaml If successful, the command's output shows the details of the distribution that you just updated. API To create a real-time log configuration with the CloudFront API, use the CreateRealtimeLogConfig API operation. For more information about the parameters that you specify in this API call, see Understand real-time log configurations and the API reference documentation for
AmazonCloudFront_DevGuide-329
AmazonCloudFront_DevGuide.pdf
329
the field's value. Save the file when finished. 3. Use the following command to update the distribution to use the real-time log configuration. Replace distribution_ID with the distribution's ID. Use real-time logs 940 Amazon CloudFront Developer Guide aws cloudfront update-distribution --id distribution_ID --cli-input-yaml file:// dist-config.yaml If successful, the command's output shows the details of the distribution that you just updated. API To create a real-time log configuration with the CloudFront API, use the CreateRealtimeLogConfig API operation. For more information about the parameters that you specify in this API call, see Understand real-time log configurations and the API reference documentation for your AWS SDK or other API client. After you create a real-time log configuration, you can attach it to a cache behavior, by using one of the following API operations: • To attach it to a cache behavior in an existing distribution, use UpdateDistribution. • To attach it to a cache behavior in a new distribution, use CreateDistribution. For both of these API operations, provide the ARN of the real-time log configuration in the RealtimeLogConfigArn field, inside a cache behavior. For more information about the other fields that you specify in these API calls, see Distribution settings reference and the API reference documentation for your AWS SDK or other API client. Understand real-time log configurations To use CloudFront real-time logs, you start by creating a real-time log configuration. The real-time log configuration contains information about which log fields you want to receive, the sampling rate for log records, and the Kinesis data stream where you want to deliver the logs. Specifically, a real-time log configuration contains the following settings: Contents • Name • Sampling rate • Fields • Endpoint (Kinesis Data Streams) • IAM role Use real-time logs 941 Amazon CloudFront Name A name to identify the real-time log configuration. Sampling rate Developer Guide The sampling rate is a whole number between 1 and 100 (inclusive) that determines the percentage of viewer requests that are sent to Kinesis Data Streams as real-time log records. To include every viewer request in your real-time logs, specify 100 for the sampling rate. You might choose a lower sampling rate to reduce costs while still receiving a representative sample of request data in your real-time logs. Fields A list of the fields that are included in each real-time log record. Each log record can contain up to 40 fields, and you can choose to receive all of the available fields, or only the fields that you need for monitoring and analyzing performance. The following list contains each field name and a description of the information in that field. The fields are listed in the order in which they appear in the log records that are delivered to Kinesis Data Streams. Fields 46-63 are common media client data (CMCD) that media player clients can send to CDNs with each request. You can use this data to understand each request, such as the media type (audio, video), playback rate, and streaming length. These fields will only appear in your real-time logs if they're sent to CloudFront. 1. timestamp The date and time at which the edge server finished responding to the request. 2. c-ip The IP address of the viewer that made the request, for example, 192.0.2.183 or 2001:0db8:85a3::8a2e:0370:7334. If the viewer used an HTTP proxy or a load balancer to send the request, the value of this field is the IP address of the proxy or load balancer. See also the x-forwarded-for field. 3. s-ip The IP address of the CloudFront server that served the request, for example, 192.0.2.183 or 2001:0db8:85a3::8a2e:0370:7334. Use real-time logs 942 Amazon CloudFront 4. time-to-first-byte Developer Guide The number of seconds between receiving the request and writing the first byte of the response, as measured on the server. 5. sc-status The HTTP status code of the server's response (for example, 200). 6. sc-bytes The total number of bytes that the server sent to the viewer in response to the request, including headers. For WebSocket and gRPC connections, this is the total number of bytes sent from the server to the client through the connection. 7. cs-method The HTTP request method received from the viewer. 8. cs-protocol The protocol of the viewer request (http, https, grpcs, ws, or wss). 9. cs-host The value that the viewer included in the Host header of the request. If you're using the CloudFront domain name in your object URLs (such as d111111abcdef8.cloudfront.net), this field contains that domain name. If you're using alternate domain names (CNAMEs) in your object URLs (such as www.example.com), this field contains the alternate domain name. 10.cs-uri-stem The entire request URL, including the query string (if one exists), but without the domain name. For example, /images/cat.jpg?mobile=true. Note In standard logs, the cs-uri-stem value doesn't include the query string. 11.cs-bytes The total number of
AmazonCloudFront_DevGuide-330
AmazonCloudFront_DevGuide.pdf
330
request (http, https, grpcs, ws, or wss). 9. cs-host The value that the viewer included in the Host header of the request. If you're using the CloudFront domain name in your object URLs (such as d111111abcdef8.cloudfront.net), this field contains that domain name. If you're using alternate domain names (CNAMEs) in your object URLs (such as www.example.com), this field contains the alternate domain name. 10.cs-uri-stem The entire request URL, including the query string (if one exists), but without the domain name. For example, /images/cat.jpg?mobile=true. Note In standard logs, the cs-uri-stem value doesn't include the query string. 11.cs-bytes The total number of bytes of data that the viewer included in the request, including headers. For WebSocket and gRPC connections, this is the total number of bytes sent from the client to the server on the connection. Use real-time logs 943 Amazon CloudFront 12.x-edge-location Developer Guide The edge location that served the request. Each edge location is identified by a three-letter code and an arbitrarily assigned number (for example, DFW3). The three-letter code typically corresponds with the International Air Transport Association (IATA) airport code for an airport near the edge location's geographic location. (These abbreviations might change in the future.) 13.x-edge-request-id An opaque string that uniquely identifies a request. CloudFront also sends this string in the x- amz-cf-id response header. 14.x-host-header The domain name of the CloudFront distribution (for example, d111111abcdef8.cloudfront.net). 15.time-taken The number of seconds (to the thousandth of a second, for example, 0.082) from when the server receives the viewer's request to when the server writes the last byte of the response to the output queue, as measured on the server. From the perspective of the viewer, the total time to get the full response will be longer than this value because of network latency and TCP buffering. 16.cs-protocol-version The HTTP version that the viewer specified in the request. Possible values include HTTP/0.9, HTTP/1.0, HTTP/1.1, HTTP/2.0, and HTTP/3.0. 17.c-ip-version The IP version of the request (IPv4 or IPv6). 18.cs-user-agent The value of the User-Agent header in the request. The User-Agent header identifies the source of the request, such as the type of device and browser that submitted the request or, if the request came from a search engine, which search engine. 19.cs-referer The value of the Referer header in the request. This is the name of the domain that originated the request. Common referrers include search engines, other websites that link directly to your objects, and your own website. Use real-time logs 944 Amazon CloudFront 20.cs-cookie Developer Guide The Cookie header in the request, including name—value pairs and the associated attributes. Note This field is truncated to 800 bytes. 21.cs-uri-query The query string portion of the request URL, if any. 22.x-edge-response-result-type How the server classified the response just before returning the response to the viewer. See also the x-edge-result-type field. Possible values include: • Hit – The server served the object to the viewer from the cache. • RefreshHit – The server found the object in the cache but the object had expired, so the server contacted the origin to verify that the cache had the latest version of the object. • Miss – The request could not be satisfied by an object in the cache, so the server forwarded the request to the origin server and returned the result to the viewer. • LimitExceeded – The request was denied because a CloudFront quota (formerly referred to as a limit) was exceeded. • CapacityExceeded – The server returned a 503 error because it didn't have enough capacity at the time of the request to serve the object. • Error – Typically, this means the request resulted in a client error (the value of the sc- status field is in the 4xx range) or a server error (the value of the sc-status field is in the 5xx range). If the value of the x-edge-result-type field is Error and the value of this field is not Error, the client disconnected before finishing the download. • Redirect – The server redirected the viewer from HTTP to HTTPS according to the distribution settings. 23.x-forwarded-for If the viewer used an HTTP proxy or a load balancer to send the request, the value of the c- ip field is the IP address of the proxy or load balancer. In that case, this field is the IP address of the viewer that originated the request. This field can contain multiple comma-separated Use real-time logs 945 Amazon CloudFront Developer Guide IP addresses. Each IP address can be an IPv4 address (for example, 192.0.2.183) or an IPv6 address (for example, 2001:0db8:85a3::8a2e:0370:7334). 24.ssl-protocol When the request used HTTPS, this field contains the SSL/TLS protocol that the viewer and server negotiated for transmitting the request and response. For a list of possible values, see the supported SSL/TLS protocols in Supported protocols and
AmazonCloudFront_DevGuide-331
AmazonCloudFront_DevGuide.pdf
331
field is the IP address of the proxy or load balancer. In that case, this field is the IP address of the viewer that originated the request. This field can contain multiple comma-separated Use real-time logs 945 Amazon CloudFront Developer Guide IP addresses. Each IP address can be an IPv4 address (for example, 192.0.2.183) or an IPv6 address (for example, 2001:0db8:85a3::8a2e:0370:7334). 24.ssl-protocol When the request used HTTPS, this field contains the SSL/TLS protocol that the viewer and server negotiated for transmitting the request and response. For a list of possible values, see the supported SSL/TLS protocols in Supported protocols and ciphers between viewers and CloudFront. 25.ssl-cipher When the request used HTTPS, this field contains the SSL/TLS cipher that the viewer and server negotiated for encrypting the request and response. For a list of possible values, see the supported SSL/TLS ciphers in Supported protocols and ciphers between viewers and CloudFront. 26.x-edge-result-type How the server classified the response after the last byte left the server. In some cases, the result type can change between the time that the server is ready to send the response and the time that it finishes sending the response. See also the x-edge-response-result-type field. For example, in HTTP streaming, suppose the server finds a segment of the stream in the cache. In that scenario, the value of this field would ordinarily be Hit. However, if the viewer closes the connection before the server has delivered the entire segment, the final result type (and the value of this field) is Error. WebSocket and gRPC connections will have a value of Miss for this field because the content is not cacheable and is proxied directly to the origin. Possible values include: • Hit – The server served the object to the viewer from the cache. • RefreshHit – The server found the object in the cache but the object had expired, so the server contacted the origin to verify that the cache had the latest version of the object. • Miss – The request could not be satisfied by an object in the cache, so the server forwarded the request to the origin and returned the result to the viewer. • LimitExceeded – The request was denied because a CloudFront quota (formerly referred to as a limit) was exceeded. • CapacityExceeded – The server returned an HTTP 503 status code because it didn't have enough capacity at the time of the request to serve the object. Use real-time logs 946 Amazon CloudFront Developer Guide • Error – Typically, this means the request resulted in a client error (the value of the sc- status field is in the 4xx range) or a server error (the value of the sc-status field is in the 5xx range). If the value of the sc-status field is 200, or if the value of this field is Error and the value of the x-edge-response-result-type field is not Error, it means the HTTP request was successful but the client disconnected before receiving all of the bytes. • Redirect – The server redirected the viewer from HTTP to HTTPS according to the distribution settings. 27.fle-encrypted-fields The number of field-level encryption fields that the server encrypted and forwarded to the origin. CloudFront servers stream the processed request to the origin as they encrypt data, so this field can have a value even if the value of fle-status is an error. 28.fle-status When field-level encryption is configured for a distribution, this field contains a code that indicates whether the request body was successfully processed. When the server successfully processes the request body, encrypts values in the specified fields, and forwards the request to the origin, the value of this field is Processed. The value of x-edge-result-type can still indicate a client-side or server-side error in this case. Possible values for this field include: • ForwardedByContentType – The server forwarded the request to the origin without parsing or encryption because no content type was configured. • ForwardedByQueryArgs – The server forwarded the request to the origin without parsing or encryption because the request contains a query argument that wasn't in the configuration for field-level encryption. • ForwardedDueToNoProfile – The server forwarded the request to the origin without parsing or encryption because no profile was specified in the configuration for field-level encryption. • MalformedContentTypeClientError – The server rejected the request and returned an HTTP 400 status code to the viewer because the value of the Content-Type header was in an invalid format. • MalformedInputClientError – The server rejected the request and returned an HTTP 400 status code to the viewer because the request body was in an invalid format. Use real-time logs 947 Amazon CloudFront Developer Guide • MalformedQueryArgsClientError – The server rejected the request and returned an HTTP 400 status code to the viewer because a query argument was empty
AmazonCloudFront_DevGuide-332
AmazonCloudFront_DevGuide.pdf
332
because no profile was specified in the configuration for field-level encryption. • MalformedContentTypeClientError – The server rejected the request and returned an HTTP 400 status code to the viewer because the value of the Content-Type header was in an invalid format. • MalformedInputClientError – The server rejected the request and returned an HTTP 400 status code to the viewer because the request body was in an invalid format. Use real-time logs 947 Amazon CloudFront Developer Guide • MalformedQueryArgsClientError – The server rejected the request and returned an HTTP 400 status code to the viewer because a query argument was empty or in an invalid format. • RejectedByContentType – The server rejected the request and returned an HTTP 400 status code to the viewer because no content type was specified in the configuration for field- level encryption. • RejectedByQueryArgs – The server rejected the request and returned an HTTP 400 status code to the viewer because no query argument was specified in the configuration for field- level encryption. • ServerError – The origin server returned an error. If the request exceeds a field-level encryption quota (formerly referred to as a limit), this field contains one of the following error codes, and the server returns HTTP status code 400 to the viewer. For a list of the current quotas on field-level encryption, see Quotas on field-level encryption. • FieldLengthLimitClientError – A field that is configured to be encrypted exceeded the maximum length allowed. • FieldNumberLimitClientError – A request that the distribution is configured to encrypt contains more than the number of fields allowed. • RequestLengthLimitClientError – The length of the request body exceeded the maximum length allowed when field-level encryption is configured. 29.sc-content-type The value of the HTTP Content-Type header of the response. 30.sc-content-len The value of the HTTP Content-Length header of the response. 31.sc-range-start When the response contains the HTTP Content-Range header, this field contains the range start value. 32.sc-range-end When the response contains the HTTP Content-Range header, this field contains the range end value. 33.c-port Use real-time logs 948 Amazon CloudFront Developer Guide The port number of the request from the viewer. 34.x-edge-detailed-result-type This field contains the same value as the x-edge-result-type field, except in the following cases: • When the object was served to the viewer from the Origin Shield layer, this field contains OriginShieldHit. • When the object was not in the CloudFront cache and the response was generated by an origin request Lambda@Edge function, this field contains MissGeneratedResponse. • When the value of the x-edge-result-type field is Error, this field contains one of the following values with more information about the error: • AbortedOrigin – The server encountered an issue with the origin. • ClientCommError – The response to the viewer was interrupted due to a communication problem between the server and the viewer. • ClientGeoBlocked – The distribution is configured to refuse requests from the viewer's geographic location. • ClientHungUpRequest – The viewer stopped prematurely while sending the request. • Error – An error occurred for which the error type doesn't fit any of the other categories. This error type can occur when the server serves an error response from the cache. • InvalidRequest – The server received an invalid request from the viewer. • InvalidRequestBlocked – Access to the requested resource is blocked. • InvalidRequestCertificate – The distribution doesn't match the SSL/TLS certificate for which the HTTPS connection was established. • InvalidRequestHeader – The request contained an invalid header. • InvalidRequestMethod – The distribution is not configured to handle the HTTP request method that was used. This can happen when the distribution supports only cacheable requests. • OriginCommError – The request timed out while connecting to the origin, or reading data from the origin. • OriginConnectError – The server couldn't connect to the origin. • OriginContentRangeLengthError – The Content-Length header in the origin's response doesn't match the length in the Content-Range header. Use real-time logs 949 Amazon CloudFront Developer Guide • OriginDnsError – The server couldn't resolve the origin's domain name. • OriginError – The origin returned an incorrect response. • OriginHeaderTooBigError – A header returned by the origin is too big for the edge server to process. • OriginInvalidResponseError – The origin returned an invalid response. • OriginReadError – The server couldn't read from the origin. • OriginWriteError – The server couldn't write to the origin. • OriginZeroSizeObjectError – A zero size object sent from the origin resulted in an error. • SlowReaderOriginError – The viewer was slow to read the message that caused the origin error. 35.c-country A country code that represents the viewer's geographic location, as determined by the viewer's IP address. For a list of country codes, see ISO 3166-1 alpha-2. 36.cs-accept-encoding The value of the Accept-Encoding header in the viewer request. 37.cs-accept The value of the Accept header in the
AmazonCloudFront_DevGuide-333
AmazonCloudFront_DevGuide.pdf
333
invalid response. • OriginReadError – The server couldn't read from the origin. • OriginWriteError – The server couldn't write to the origin. • OriginZeroSizeObjectError – A zero size object sent from the origin resulted in an error. • SlowReaderOriginError – The viewer was slow to read the message that caused the origin error. 35.c-country A country code that represents the viewer's geographic location, as determined by the viewer's IP address. For a list of country codes, see ISO 3166-1 alpha-2. 36.cs-accept-encoding The value of the Accept-Encoding header in the viewer request. 37.cs-accept The value of the Accept header in the viewer request. 38.cache-behavior-path-pattern The path pattern that identifies the cache behavior that matched the viewer request. 39.cs-headers The HTTP headers (names and values) in the viewer request. Note This field is truncated to 800 bytes. 40.cs-header-names The names of the HTTP headers (not values) in the viewer request. Use real-time logs 950 Amazon CloudFront Note This field is truncated to 800 bytes. 41.cs-headers-count The number of HTTP headers in the viewer request. 42.primary-distribution-id Developer Guide When continuous deployment is enabled, this ID identifies which distribution is the primary in the current distribution. 43.primary-distribution-dns-name When continuous deployment is enabled, this value shows the primary domain name that is related to the current CloudFront distribution (for example, d111111abcdef8.cloudfront.net). 44.origin-fbl The number of seconds of first-byte latency between CloudFront and your origin. 45.origin-lbl The number of seconds of last-byte latency between CloudFront and your origin. 46.asn The autonomous system number (ASN) of the viewer. 47. CMCD fields in real-time logs For more information about these fields, see the CTA Specification Web Application Video Ecosystem - Common Media Client Data CTA-5004 document. 48.cmcd-encoded-bitrate The encoded bitrate of the requested audio or video object. 49.cmcd-buffer-length The buffer length of the requested media object. 50.cmcd-buffer-starvation Use real-time logs 951 Amazon CloudFront Developer Guide Whether the buffer was starved at some point between the prior request and the object request. This can cause the player to be in a rebuffering stat, which can stall the video or audio playback. 51.cmcd-content-id A unique string that identifies the current content. 52.cmcd-object-duration The playback duration of the requested object (in milliseconds). 53.cmcd-deadline The deadline from the request time that the first sample of this object must be available, so that a buffer underrun state or other playback problems are avoided. 54.cmcd-measured-throughput The throughput between the client and server, as measured by the client. 55.cmcd-next-object-request The relative path of the next requested object. 56.cmcd-next-range-request If the next request is a partial object request, this string denotes the byte range to be requested. 57.cmcd-object-type The media type of the current object being requested. 58.cmcd-playback-rate 1 if real-time, 2 if double-speed, 0 if not playing. 59.cmcd-requested-maximum-throughput The requested maximum throughput that the client considers sufficient for asset delivery. 60.cmcd-streaming-format The streaming format that defines the current request. 61.cmcd-session-id A GUID identifying the current playback session. 62.cmcd-stream-type Use real-time logs 952 Amazon CloudFront Developer Guide Token identifying segment availability. v = all segments are available. l = segments become available over time. 63.cmcd-startup Key is included without a value if the object is needed urgently during startup, seeking, or recovery after a buffer-empty event. 64.cmcd-top-bitrate The highest bitrate rendition that the client can play. 65.cmcd-version The version of this specification used for interpreting the defined key names and values. If this key is omitted, the client and server must interpret the values as being defined by version 1. 66.r-host This field is sent for origin requests and it indicates the domain of the origin server used to serve the object. In case of errors, you can use this field to find the last origin attempted, for example: cd8jhdejh6a.mediapackagev2.us-east-1.amazonaws.com. 67.sr-reason This field provides a reason why the origin was selected. It's empty when a request to the primary origin succeeds. If origin failover occurs, the field will contain the HTTP error code that led to the failover, such as Failover:403 or Failover:502. In case of origin failover, if the retried request also fails and you have not configured custom error pages, then r-status indicates the response of the second origin. However, if you have configured custom error pages along with origin failover, then this will contain the response of the second origin if the request failed and a custom error page was returned instead. If no origin failover occurs but media quality-aware resilience (MQAR) origin selection occurs, then this will be logged as MediaQuality. For more information, see Media quality-aware resiliency. 68.x-edge-mqcs This field indicates the Media Quality Confidence Score (MQCS) (range: 0 – 100) for media segments that CloudFront retrieved in the CMSD response headers from MediaPackage v2. Use real-time logs 953 Amazon CloudFront Developer Guide This field is available for requests matching a cache behavior that has an MQAR-enabled origin group. CloudFront logs
AmazonCloudFront_DevGuide-334
AmazonCloudFront_DevGuide.pdf
334
contain the response of the second origin if the request failed and a custom error page was returned instead. If no origin failover occurs but media quality-aware resilience (MQAR) origin selection occurs, then this will be logged as MediaQuality. For more information, see Media quality-aware resiliency. 68.x-edge-mqcs This field indicates the Media Quality Confidence Score (MQCS) (range: 0 – 100) for media segments that CloudFront retrieved in the CMSD response headers from MediaPackage v2. Use real-time logs 953 Amazon CloudFront Developer Guide This field is available for requests matching a cache behavior that has an MQAR-enabled origin group. CloudFront logs this field for media segments that are also served from its cache in addition to origin requests. For more information, see Media quality-aware resiliency. 69.distribution-tenant-id The ID of the distribution tenant. Endpoint (Kinesis Data Streams) The endpoint contains information about the Kinesis Data Streams where you want to send real- time logs. You provide the Amazon Resource Name (ARN) of the data stream. For more information about creating a Kinesis Data Streams, see the following topics in the Amazon Kinesis Data Streams Developer Guide. • Creating and managing streams • Perform basic Kinesis Data Streams operations using the AWS CLI • Creating a stream (uses the AWS SDK for Java) When you create a data stream, you need to specify the number of shards. Use the following information to help you estimate the number of shards you need. To estimate the number of shards for your Kinesis data stream 1. Calculate (or estimate) the number of requests per second that your CloudFront distribution receives. You can use the CloudFront usage reports (in the CloudFront console) and the CloudFront metrics (in the CloudFront and Amazon CloudWatch consoles) to help you calculate your requests per second. 2. Determine the typical size of a single real-time log record. In general, a single log record is around 500 bytes. A large record that includes all available fields is generally around 1 KB. If you're not sure what your log record size is, you can enable real-time logs with a low sampling rate (for example, 1%), and then calculate the average record size using monitoring data in Kinesis Data Streams (total incoming bytes divided by total number of records). Use real-time logs 954 Amazon CloudFront Developer Guide 3. On the Amazon Kinesis Data Streams pricing page, under AWS Pricing Calculator, choose Create your custom estimate now. • In the calculator, enter the number of requests (records) per second. • Enter the average record size of a single log record. • Choose Show calculations. The pricing calculator shows you the number of shards you need and the estimated cost. IAM role The AWS Identity and Access Management (IAM) role that gives CloudFront permission to deliver real-time logs to your Kinesis data stream. When you create a real-time log configuration with the CloudFront console, you can choose Create new service role to let the console create the IAM role for you. When you create a real-time log configuration with AWS CloudFormation or the CloudFront API (AWS CLI or SDK), you must create the IAM role yourself and provide the role ARN. To create the IAM role yourself, use the following policies. IAM role trust policy To use the following IAM role trust policy, replace 111122223333 with your AWS account number. The Condition element in this policy helps to prevent the confused deputy problem because CloudFront can only assume this role on behalf of a distribution in your AWS account. { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": { "Service": "cloudfront.amazonaws.com" }, "Action": "sts:AssumeRole", "Condition": { "StringEquals": { "aws:SourceAccount": "111122223333" } Use real-time logs 955 Amazon CloudFront } } ] } Developer Guide IAM role permissions policy for an unencrypted data stream To use the following policy, replace arn:aws:kinesis:us-east-2:123456789012:stream/ StreamName with the ARN of your Kinesis data stream. { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "kinesis:DescribeStreamSummary", "kinesis:DescribeStream", "kinesis:PutRecord", "kinesis:PutRecords" ], "Resource": [ "arn:aws:kinesis:us-east-2:123456789012:stream/StreamName" ] } ] } IAM role permissions policy for an encrypted data stream To use the following policy, replace arn:aws:kinesis:us-east-2:123456789012:stream/ StreamName with the ARN of your Kinesis data stream and arn:aws:kms:us- east-2:123456789012:key/e58a3d0b-fe4f-4047-a495-ae03cc73d486 with the ARN of your AWS KMS key. { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "kinesis:DescribeStreamSummary", Use real-time logs 956 Amazon CloudFront Developer Guide "kinesis:DescribeStream", "kinesis:PutRecord", "kinesis:PutRecords" ], "Resource": [ "arn:aws:kinesis:us-east-2:123456789012:stream/StreamName" ] }, { "Effect": "Allow", "Action": [ "kms:GenerateDataKey" ], "Resource": [ "arn:aws:kms:us-east-2:123456789012:key/e58a3d0b-fe4f-4047-a495- ae03cc73d486" ] } ] } Create a Kinesis Data Streams consumer To read and analyze your real-time logs, you build or use a Kinesis Data Streams consumer. When you build a consumer for CloudFront real-time logs, it's important to know that the fields in every real-time log record are always delivered in the same order, as listed in the Fields section. Make sure
AmazonCloudFront_DevGuide-335
AmazonCloudFront_DevGuide.pdf
335
"Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "kinesis:DescribeStreamSummary", Use real-time logs 956 Amazon CloudFront Developer Guide "kinesis:DescribeStream", "kinesis:PutRecord", "kinesis:PutRecords" ], "Resource": [ "arn:aws:kinesis:us-east-2:123456789012:stream/StreamName" ] }, { "Effect": "Allow", "Action": [ "kms:GenerateDataKey" ], "Resource": [ "arn:aws:kms:us-east-2:123456789012:key/e58a3d0b-fe4f-4047-a495- ae03cc73d486" ] } ] } Create a Kinesis Data Streams consumer To read and analyze your real-time logs, you build or use a Kinesis Data Streams consumer. When you build a consumer for CloudFront real-time logs, it's important to know that the fields in every real-time log record are always delivered in the same order, as listed in the Fields section. Make sure that you build your consumer to accommodate this fixed order. For example, consider a real-time log configuration that includes only these three fields: time- to-first-byte, sc-status, and c-country. In this scenario, the last field, c-country, is always field number 3 in every log record. However, if you later add fields to the real-time log configuration, the placement of each field in a record can change. For example, if you add the fields sc-bytes and time-taken to the real-time log configuration, these fields are inserted into each log record according to the order shown in the Fields section. The resulting order of all five fields is time-to-first-byte, sc-status, sc-bytes, time- taken, and c-country. The c-country field was originally field number 3, but is now field number 5. Make sure that your consumer application can handle fields that change position in a log record, in case you add fields to your real-time log configuration. Use real-time logs 957 Amazon CloudFront Developer Guide Troubleshoot real-time logs After you create a real-time log configuration, you might find that no records (or not all records) are delivered to Kinesis Data Streams. In this case, you should first verify that your CloudFront distribution is receiving viewer requests. If it is, you can check the following setting to continue troubleshooting. IAM role permissions To deliver real-time log records to your Kinesis data stream, CloudFront uses the IAM role in the real-time log configuration. Make sure that the role trust policy and the role permissions policy match the policies shown in IAM role. Kinesis Data Streams throttling If CloudFront writes real-time log records to your Kinesis data stream faster than the stream can handle, Kinesis Data Streams might throttle the requests from CloudFront. In this case, you can increase the number of shards in your Kinesis data stream. Each shard can support writes up to 1,000 records per second, up to a maximum data write of 1 MB per second. Edge function logs You can use Amazon CloudWatch Logs to get logs for your edge functions, both Lambda@Edge and CloudFront Functions. You can access the logs by using the CloudWatch console or the CloudWatch Logs API. Important We recommend that you use the logs to understand the nature of the requests for your content, not as a complete accounting of all requests. CloudFront delivers edge function logs on a best-effort basis. The log entry for a particular request might be delivered long after the request was actually processed and, in rare cases, a log entry might not be delivered at all. When a log entry is omitted from edge function logs, the number of entries in the edge function logs won't match the usage that appears in the AWS billing and usage reports. Topics • Lambda@Edge logs Edge function logs 958 Amazon CloudFront • CloudFront Functions logs Lambda@Edge logs Developer Guide Lambda@Edge automatically sends function logs to CloudWatch Logs, creating log streams in the AWS Regions where the functions are invoked. When you create or modify a function in AWS Lambda, you can either use the default CloudWatch log group name or customize it. • The default log group name is /aws/lambda/<FunctionName> where <FunctionName> is the name that you specified when you created the function. When sending logs to CloudWatch, Lambda@Edge will automatically add the us-east-1 prefix to the function name, so that the log group name is /aws/lambda/us-east-1.<FunctionName>. This prefix corresponds to the AWS Region where the function was created. This prefix remains part of the log group name, even in other Regions where the function is invoked. • If you specify a custom log group name, such as /MyLogGroup, Lambda@Edge won't add the Region prefix. The log group name remains the same across all other Regions where the function is invoked. Note If you create a custom log group and specify the same name as the default /aws/ lambda/<FunctionName>, Lambda@Edge adds the us-east-1 prefix to the function name. In addition to customizing the log group name, Lambda@Edge functions support JSON and plain text log formats, and log-level filtering. For more information , see Configuring advance logging controls for Lambda function in the AWS Lambda Developer Guide. Note Lambda@Edge throttles logs based on the request volume and
AmazonCloudFront_DevGuide-336
AmazonCloudFront_DevGuide.pdf
336
such as /MyLogGroup, Lambda@Edge won't add the Region prefix. The log group name remains the same across all other Regions where the function is invoked. Note If you create a custom log group and specify the same name as the default /aws/ lambda/<FunctionName>, Lambda@Edge adds the us-east-1 prefix to the function name. In addition to customizing the log group name, Lambda@Edge functions support JSON and plain text log formats, and log-level filtering. For more information , see Configuring advance logging controls for Lambda function in the AWS Lambda Developer Guide. Note Lambda@Edge throttles logs based on the request volume and the size of logs. You must review CloudWatch log files in the correct Region to see your Lambda@Edge function log files. To see the Regions where your Lambda@Edge function is running, view graphs of metrics for Edge function logs 959 Amazon CloudFront Developer Guide the function in the CloudFront console. Metrics are displayed for each Region. On the same page, you can choose a Region and then view log files for that Region to investigate issues. To learn more about how to use CloudWatch Logs with Lambda@Edge functions, see the following topics: • For more information about viewing graphs in the Monitoring section of the CloudFront console, see the section called “Monitor CloudFront metrics with Amazon CloudWatch”. • For information about the permissions required to send data to CloudWatch Logs, see the section called “Set up IAM permissions and roles”. • For information about adding logging to a Lambda@Edge function, see AWS Lambda function logging in Node.js or AWS Lambda function logging in Python in the AWS Lambda Developer Guide. • For information about CloudWatch Logs quotas (formerly known as limits), see CloudWatch Logs quotas in the Amazon CloudWatch Logs User Guide. CloudFront Functions logs If a CloudFront function's code contains console.log() statements, CloudFront Functions automatically sends these log lines to CloudWatch Logs. If there are no console.log() statements, nothing is sent to CloudWatch Logs. CloudFront Functions always creates log streams in the US East (N. Virginia) Region (us-east-1), no matter which edge location ran the function. The log group name is in the format /aws/ cloudfront/function/<FunctionName>, where <FunctionName> is the name that you gave to the function when you created it. The log stream name is in the format YYYY/M/D/UUID. The following shows an example log message sent to CloudWatch Logs. Each line begins with an ID that uniquely identifies a CloudFront request. The message begins with a START line that includes the CloudFront distribution ID, and ends with an END line. Between the START and END lines are the log lines generated by console.log() statements in the function. U7b4hR_RaxMADupvKAvr8_m9gsGXvioUggLV5Oyq-vmAtH8HADpjhw== START DistributionID: E3E5D42GADAXZZ U7b4hR_RaxMADupvKAvr8_m9gsGXvioUggLV5Oyq-vmAtH8HADpjhw== Example function log output U7b4hR_RaxMADupvKAvr8_m9gsGXvioUggLV5Oyq-vmAtH8HADpjhw== END Edge function logs 960 Amazon CloudFront Note Developer Guide CloudFront Functions sends logs to CloudWatch only for functions in the LIVE stage that run in response to production requests and responses. When you test a function, CloudFront doesn't send any logs to CloudWatch. The test output contains information about errors, compute utilization, and function logs (console.log() statements), but this information isn't sent to CloudWatch. CloudFront Functions uses an AWS Identity and Access Management (IAM) service-linked role to send logs to CloudWatch Logs in your account. A service-linked role is an IAM role that is linked directly to an AWS service. Service-linked roles are predefined by the service and include all of the permissions that the service requires to call other AWS services for you. CloudFront Functions uses the AWSServiceRoleForCloudFrontLogger service-linked role. For more information about this role, see the section called “Service-linked roles for Lambda@Edge” (Lambda@Edge uses the same service-linked role). When a function fails with a validation error or an execution error, the information is logged in standard logs and real-time logs. For specific information about the error, see the x-edge- result-type, x-edge-response-result-type, and x-edge-detailed-result-type fields. Logging Amazon CloudFront API calls using AWS CloudTrail CloudFront is integrated with AWS CloudTrail, a service that provides a record of actions taken by a user, role, or an AWS service. CloudTrail captures all API calls for CloudFront as events. The calls captured include calls from the CloudFront console and code calls to the CloudFront API operations. Using the information collected by CloudTrail, you can determine the request that was made to CloudFront, the IP address from which the request was made, when it was made, and additional details. Every event or log entry contains information about who generated the request. The identity information helps you determine the following: • Whether the request was made with root user or user credentials. • Whether the request was made on behalf of an IAM Identity Center user. • Whether the request was made with temporary security credentials for a role or federated user. • Whether the request was made by another AWS service. AWS
AmazonCloudFront_DevGuide-337
AmazonCloudFront_DevGuide.pdf
337
CloudTrail, you can determine the request that was made to CloudFront, the IP address from which the request was made, when it was made, and additional details. Every event or log entry contains information about who generated the request. The identity information helps you determine the following: • Whether the request was made with root user or user credentials. • Whether the request was made on behalf of an IAM Identity Center user. • Whether the request was made with temporary security credentials for a role or federated user. • Whether the request was made by another AWS service. AWS CloudTrail logs 961 Amazon CloudFront Developer Guide CloudTrail is active in your AWS account when you create the account and you automatically have access to the CloudTrail Event history. The CloudTrail Event history provides a viewable, searchable, downloadable, and immutable record of the past 90 days of recorded management events in an AWS Region. For more information, see Working with CloudTrail Event history in the AWS CloudTrail User Guide. There are no CloudTrail charges for viewing the Event history. For an ongoing record of events in your AWS account past 90 days, create a trail or a CloudTrail Lake event data store. CloudTrail trails A trail enables CloudTrail to deliver log files to an Amazon S3 bucket. All trails created using the AWS Management Console are multi-Region. You can create a single-Region or a multi-Region trail by using the AWS CLI. Creating a multi-Region trail is recommended because you capture activity in all AWS Regions in your account. If you create a single-Region trail, you can view only the events logged in the trail's AWS Region. For more information about trails, see Creating a trail for your AWS account and Creating a trail for an organization in the AWS CloudTrail User Guide. You can deliver one copy of your ongoing management events to your Amazon S3 bucket at no charge from CloudTrail by creating a trail, however, there are Amazon S3 storage charges. For more information about CloudTrail pricing, see AWS CloudTrail Pricing. For information about Amazon S3 pricing, see Amazon S3 Pricing. CloudTrail Lake event data stores CloudTrail Lake lets you run SQL-based queries on your events. CloudTrail Lake converts existing events in row-based JSON format to Apache ORC format. ORC is a columnar storage format that is optimized for fast retrieval of data. Events are aggregated into event data stores, which are immutable collections of events based on criteria that you select by applying advanced event selectors. The selectors that you apply to an event data store control which events persist and are available for you to query. For more information about CloudTrail Lake, see Working with AWS CloudTrail Lake in the AWS CloudTrail User Guide. CloudTrail Lake event data stores and queries incur costs. When you create an event data store, you choose the pricing option you want to use for the event data store. The pricing option determines the cost for ingesting and storing events, and the default and maximum retention period for the event data store. For more information about CloudTrail pricing, see AWS CloudTrail Pricing. AWS CloudTrail logs 962 Amazon CloudFront Note Developer Guide CloudFront is a global service. CloudTrail records events for CloudFront in the US East (N. Virginia) Region. For more information, see Global service events in the AWS CloudTrail User Guide. If you use temporary security credentials by using AWS Security Token Service, calls to regional endpoints, such as us-west-2, are logged in CloudTrail to their appropriate Region. For more information about CloudFront endpoints, see CloudFront endpoints and quotas in the AWS General Reference. CloudFront data events in CloudTrail Data events provide information about the resource operations performed on or in a resource (for example, reading or writing to a CloudFront distribution). These are also known as data plane operations. Data events are often high-volume activities. By default, CloudTrail doesn’t log data events. The CloudTrail Event history doesn't record data events. Additional charges apply for data events. For more information about CloudTrail pricing, see AWS CloudTrail Pricing. You can log data events for the CloudFront resource types by using the CloudTrail console, AWS CLI, or CloudTrail API operations. For more information about how to log data events, see Logging data events with the AWS Management Console and Logging data events with the AWS Command Line Interface in the AWS CloudTrail User Guide. The following table lists the CloudFront resource types for which you can log data events. The Data event type (console) column shows the value to choose from the Data event type list on the CloudTrail console. The resources.type value column shows the resources.type value, which you would specify when configuring advanced event selectors using the AWS CLI or CloudTrail APIs. The Data APIs logged to CloudTrail column shows the
AmazonCloudFront_DevGuide-338
AmazonCloudFront_DevGuide.pdf
338
about how to log data events, see Logging data events with the AWS Management Console and Logging data events with the AWS Command Line Interface in the AWS CloudTrail User Guide. The following table lists the CloudFront resource types for which you can log data events. The Data event type (console) column shows the value to choose from the Data event type list on the CloudTrail console. The resources.type value column shows the resources.type value, which you would specify when configuring advanced event selectors using the AWS CLI or CloudTrail APIs. The Data APIs logged to CloudTrail column shows the API calls logged to CloudTrail for the resource type. AWS CloudTrail logs 963 Amazon CloudFront Developer Guide Data event type (console) resources.type value Data APIs logged to CloudTrail CloudFront KeyValueStore AWS::CloudFront::K • DeleteKeys eyValueStore • DescribeKeyValueStore • GetKey • ListKeys • PutKeys • UpdateKeys You can configure advanced event selectors to filter on the eventName, readOnly, and resources.ARN fields to log only those events that are important to you. For more information about these fields, see AdvancedFieldSelector in the AWS CloudTrail API Reference. CloudFront management events in CloudTrail Management events provide information about management operations that are performed on resources in your AWS account. These are also known as control plane operations. By default, CloudTrail logs management events. Amazon CloudFront logs all CloudFront control plane operations as management events. For a list of the Amazon CloudFront control plane operations that CloudFront logs to CloudTrail, see the Amazon CloudFront API Reference. CloudFront event examples An event represents a single request from any source and includes information about the requested API operation, the date and time of the operation, request parameters, and so on. CloudTrail log files aren't an ordered stack trace of the public API calls, so events don't appear in any specific order. Contents • Example: UpdateDistribution • Example: UpdateKeys AWS CloudTrail logs 964 Amazon CloudFront Example: UpdateDistribution Developer Guide The following example shows a CloudTrail event that demonstrates the UpdateDistribution operation. For calls to the CloudFront API, the eventSource is cloudfront.amazonaws.com. { "eventVersion": "1.08", "userIdentity": { "type": "AssumedRole", "principalId": "AIDACKCEVSQ6C2EXAMPLE:role-session-name", "arn": "arn:aws:sts::111122223333:assumed-role/Admin/role-session-name", "accountId": "111122223333", "accessKeyId": "ASIAIOSFODNN7EXAMPLE", "sessionContext": { "sessionIssuer": { "type": "Role", "principalId": "AIDACKCEVSQ6C2EXAMPLE", "arn": "arn:aws:iam::111122223333:role/Admin", "accountId": "111122223333", "userName": "Admin" }, "webIdFederationData": {}, "attributes": { "creationDate": "2024-02-02T19:23:50Z", "mfaAuthenticated": "false" } } }, "eventTime": "2024-02-02T19:26:01Z", "eventSource": "cloudfront.amazonaws.com", "eventName": "UpdateDistribution", "awsRegion": "us-east-1", "sourceIPAddress": "52.94.133.137", "userAgent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36", "requestParameters": { "distributionConfig": { "defaultRootObject": "", "aliases": { "quantity": 3, "items": [ "alejandro_rosalez.awsps.myinstance.com", AWS CloudTrail logs 965 Amazon CloudFront Developer Guide "cross-testing.alejandro_rosalez.awsps.myinstance.com", "*.alejandro_rosalez.awsps.myinstance.com" ] }, "cacheBehaviors": { "quantity": 0, "items": [] }, "httpVersion": "http2and3", "originGroups": { "quantity": 0, "items": [] }, "viewerCertificate": { "minimumProtocolVersion": "TLSv1.2_2021", "cloudFrontDefaultCertificate": false, "aCMCertificateArn": "arn:aws:acm:us-east-1:111122223333:certificate/ a1b2c3d4-5678-90ab-cdef-EXAMPLE11111", "sSLSupportMethod": "sni-only" }, "webACLId": "arn:aws:wafv2:us-east-1:111122223333:global/webacl/testing- acl/a1b2c3d4-5678-90ab-cdef-EXAMPLE22222", "customErrorResponses": { "quantity": 0, "items": [] }, "logging": { "includeCookies": false, "prefix": "", "enabled": false, "bucket": "" }, "priceClass": "PriceClass_All", "restrictions": { "geoRestriction": { "restrictionType": "none", "quantity": 0, "items": [] } }, "isIPV6Enabled": true, "callerReference": "1578329170895", "continuousDeploymentPolicyId": "", "enabled": true, AWS CloudTrail logs 966 Amazon CloudFront Developer Guide "defaultCacheBehavior": { "targetOriginId": "d111111abcdef8", "minTTL": 0, "compress": false, "maxTTL": 31536000, "functionAssociations": { "quantity": 0, "items": [] }, "trustedKeyGroups": { "quantity": 0, "items": [], "enabled": false }, "smoothStreaming": false, "fieldLevelEncryptionId": "", "defaultTTL": 86400, "lambdaFunctionAssociations": { "quantity": 0, "items": [] }, "viewerProtocolPolicy": "redirect-to-https", "forwardedValues": { "cookies": {"forward": "none"}, "queryStringCacheKeys": { "quantity": 0, "items": [] }, "queryString": false, "headers": { "quantity": 1, "items": ["*"] } }, "trustedSigners": { "items": [], "enabled": false, "quantity": 0 }, "allowedMethods": { "quantity": 2, "items": [ "HEAD", "GET" AWS CloudTrail logs 967 Amazon CloudFront Developer Guide ], "cachedMethods": { "quantity": 2, "items": [ "HEAD", "GET" ] } } }, "staging": false, "origins": { "quantity": 1, "items": [ { "originPath": "", "connectionTimeout": 10, "customOriginConfig": { "originReadTimeout": 30, "hTTPSPort": 443, "originProtocolPolicy": "https-only", "originKeepaliveTimeout": 5, "hTTPPort": 80, "originSslProtocols": { "quantity": 3, "items": [ "TLSv1", "TLSv1.1", "TLSv1.2" ] } }, "id": "d111111abcdef8", "domainName": "d111111abcdef8.cloudfront.net", "connectionAttempts": 3, "customHeaders": { "quantity": 0, "items": [] }, "originShield": {"enabled": false}, "originAccessControlId": "" } ] }, AWS CloudTrail logs 968 Amazon CloudFront Developer Guide "comment": "HIDDEN_DUE_TO_SECURITY_REASONS" }, "id": "EDFDVBD6EXAMPLE", "ifMatch": "E1RTLUR9YES76O" }, "responseElements": { "distribution": { "activeTrustedSigners": { "quantity": 0, "enabled": false }, "id": "EDFDVBD6EXAMPLE", "domainName": "d111111abcdef8.cloudfront.net", "distributionConfig": { "defaultRootObject": "", "aliases": { "quantity": 3, "items": [ "alejandro_rosalez.awsps.myinstance.com", "cross-testing.alejandro_rosalez.awsps.myinstance.com", "*.alejandro_rosalez.awsps.myinstance.com" ] }, "cacheBehaviors": {"quantity": 0}, "httpVersion": "http2and3", "originGroups": {"quantity": 0}, "viewerCertificate": { "minimumProtocolVersion": "TLSv1.2_2021", "cloudFrontDefaultCertificate": false, "aCMCertificateArn": "arn:aws:acm:us- east-1:111122223333:certificate/a1b2c3d4-5678-90ab-cdef-EXAMPLE11111", "sSLSupportMethod": "sni-only", "certificateSource": "acm", "certificate": "arn:aws:acm:us-east-1:111122223333:certificate/ a1b2c3d4-5678-90ab-cdef-EXAMPLE11111" }, "webACLId": "arn:aws:wafv2:us-east-1:111122223333:global/webacl/ testing-acl/a1b2c3d4-5678-90ab-cdef-EXAMPLE22222", "customErrorResponses": {"quantity": 0}, "logging": { "includeCookies": false, "prefix": "", "enabled": false, "bucket": "" AWS CloudTrail logs 969 Developer Guide Amazon CloudFront }, "priceClass": "PriceClass_All", "restrictions": { "geoRestriction": { "restrictionType": "none", "quantity": 0 } }, "isIPV6Enabled": true, "callerReference": "1578329170895", "continuousDeploymentPolicyId": "", "enabled": true, "defaultCacheBehavior": { "targetOriginId": "d111111abcdef8", "minTTL": 0, "compress": false, "maxTTL": 31536000, "functionAssociations": {"quantity": 0}, "trustedKeyGroups": {
AmazonCloudFront_DevGuide-339
AmazonCloudFront_DevGuide.pdf
339
"distributionConfig": { "defaultRootObject": "", "aliases": { "quantity": 3, "items": [ "alejandro_rosalez.awsps.myinstance.com", "cross-testing.alejandro_rosalez.awsps.myinstance.com", "*.alejandro_rosalez.awsps.myinstance.com" ] }, "cacheBehaviors": {"quantity": 0}, "httpVersion": "http2and3", "originGroups": {"quantity": 0}, "viewerCertificate": { "minimumProtocolVersion": "TLSv1.2_2021", "cloudFrontDefaultCertificate": false, "aCMCertificateArn": "arn:aws:acm:us- east-1:111122223333:certificate/a1b2c3d4-5678-90ab-cdef-EXAMPLE11111", "sSLSupportMethod": "sni-only", "certificateSource": "acm", "certificate": "arn:aws:acm:us-east-1:111122223333:certificate/ a1b2c3d4-5678-90ab-cdef-EXAMPLE11111" }, "webACLId": "arn:aws:wafv2:us-east-1:111122223333:global/webacl/ testing-acl/a1b2c3d4-5678-90ab-cdef-EXAMPLE22222", "customErrorResponses": {"quantity": 0}, "logging": { "includeCookies": false, "prefix": "", "enabled": false, "bucket": "" AWS CloudTrail logs 969 Developer Guide Amazon CloudFront }, "priceClass": "PriceClass_All", "restrictions": { "geoRestriction": { "restrictionType": "none", "quantity": 0 } }, "isIPV6Enabled": true, "callerReference": "1578329170895", "continuousDeploymentPolicyId": "", "enabled": true, "defaultCacheBehavior": { "targetOriginId": "d111111abcdef8", "minTTL": 0, "compress": false, "maxTTL": 31536000, "functionAssociations": {"quantity": 0}, "trustedKeyGroups": { "quantity": 0, "enabled": false }, "smoothStreaming": false, "fieldLevelEncryptionId": "", "defaultTTL": 86400, "lambdaFunctionAssociations": {"quantity": 0}, "viewerProtocolPolicy": "redirect-to-https", "forwardedValues": { "cookies": {"forward": "none"}, "queryStringCacheKeys": {"quantity": 0}, "queryString": false, "headers": { "quantity": 1, "items": ["*"] } }, "trustedSigners": { "enabled": false, "quantity": 0 }, "allowedMethods": { "quantity": 2, "items": [ "HEAD", AWS CloudTrail logs 970 Amazon CloudFront Developer Guide "GET" ], "cachedMethods": { "quantity": 2, "items": [ "HEAD", "GET" ] } } }, "staging": false, "origins": { "quantity": 1, "items": [ { "originPath": "", "connectionTimeout": 10, "customOriginConfig": { "originReadTimeout": 30, "hTTPSPort": 443, "originProtocolPolicy": "https-only", "originKeepaliveTimeout": 5, "hTTPPort": 80, "originSslProtocols": { "quantity": 3, "items": [ "TLSv1", "TLSv1.1", "TLSv1.2" ] } }, "id": "d111111abcdef8", "domainName": "d111111abcdef8.cloudfront.net", "connectionAttempts": 3, "customHeaders": {"quantity": 0}, "originShield": {"enabled": false}, "originAccessControlId": "" } ] }, "comment": "HIDDEN_DUE_TO_SECURITY_REASONS" }, AWS CloudTrail logs 971 Amazon CloudFront Developer Guide "aliasICPRecordals": [ { "cNAME": "alejandro_rosalez.awsps.myinstance.com", "iCPRecordalStatus": "APPROVED" }, { "cNAME": "cross-testing.alejandro_rosalez.awsps.myinstance.com", "iCPRecordalStatus": "APPROVED" }, { "cNAME": "*.alejandro_rosalez.awsps.myinstance.com", "iCPRecordalStatus": "APPROVED" } ], "aRN": "arn:aws:cloudfront::111122223333:distribution/EDFDVBD6EXAMPLE", "status": "InProgress", "lastModifiedTime": "Feb 2, 2024 7:26:01 PM", "activeTrustedKeyGroups": { "enabled": false, "quantity": 0 }, "inProgressInvalidationBatches": 0 }, "eTag": "E1YHBLAB2BJY1G" }, "requestID": "4e6b66f9-d548-11e3-a8a9-73e33example", "eventID": "5ab02562-0fc5-43d0-b7b6-90293example", "readOnly": false, "eventType": "AwsApiCall", "apiVersion": "2020_05_31", "managementEvent": true, "recipientAccountId": "111122223333", "eventCategory": "Management", "tlsDetails": { "tlsVersion": "TLSv1.3", "cipherSuite": "TLS_AES_128_GCM_SHA256", "clientProvidedHostHeader": "cloudfront.amazonaws.com" }, "sessionCredentialFromConsole": "true" } Example: UpdateKeys The following example shows a CloudTrail event that demonstrates the UpdateKeys operation. AWS CloudTrail logs 972 Amazon CloudFront Developer Guide For calls to the CloudFront KeyValueStore API, the eventSource is edgekeyvaluestore.amazonaws.com instead of cloudfront.amazonaws.com. { "eventVersion": "1.09", "userIdentity": { "type": "AssumedRole", "principalId": "AIDACKCEVSQ6C2EXAMPLE:role-session-name", "arn": "arn:aws:sts::111122223333:assumed-role/Admin/role-session-name", "accountId": "111122223333", "accessKeyId": "ASIAIOSFODNN7EXAMPLE", "sessionContext": { "sessionIssuer": { "type": "Role", "principalId": "AIDACKCEVSQ6C2EXAMPLE", "arn": "arn:aws:iam::111122223333:role/Admin", "accountId": "111122223333", "userName": "Admin" }, "attributes": { "creationDate": "2023-11-01T23:41:14Z", "mfaAuthenticated": "false" } } }, "eventTime": "2023-11-01T23:41:28Z", "eventSource": "edgekeyvaluestore.amazonaws.com", "eventName": "UpdateKeys", "awsRegion": "us-east-1", "sourceIPAddress": "3.235.183.252", "userAgent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36, "requestParameters": { "kvsARN": "arn:aws:cloudfront::111122223333:key-value-store/a1b2c3d4-5678-90ab- cdef-EXAMPLE11111", "ifMatch": "KV3O6B1CX531EBP", "deletes": [ {"key": "key1"} ] }, "responseElements": { "itemCount": 0, "totalSizeInBytes": 0, AWS CloudTrail logs 973 Amazon CloudFront Developer Guide "eTag": "KVDC9VEVZ71ZGO" }, "requestID": "5ccf104c-acce-4ea1-b7fc-73e33example", "eventID": "a0b1b5c7-906c-439d-9925-90293example", "readOnly": false, "resources": [ { "accountId": "111122223333", "type": "AWS::CloudFront::KeyValueStore", "ARN": "arn:aws:cloudfront::111122223333:key-value-store/ a1b2c3d4-5678-90ab-cdef-EXAMPLE11111" } ], "eventType": "AwsApiCall", "managementEvent": false, "recipientAccountId": "111122223333", "eventCategory": "Data", "tlsDetails": { "tlsVersion": "TLSv1.3", "cipherSuite": "TLS_AES_128_GCM_SHA256", "clientProvidedHostHeader": "111122223333.cloudfront-kvs.global.api.aws" } } For information about CloudTrail record contents, see CloudTrail record contents in the AWS CloudTrail User Guide. Track configuration changes with AWS Config To record and evaluate configurations of your AWS resources, you can use AWS Config, which provides you with a detailed view of the configuration of your distributions. This includes how the resources are related to one another and how they were configured in the past, so you can review changes over time. You can also use AWS Config to record configuration changes to your CloudFront distribution settings. You can capture changes to distribution states, price classes, origins, geographic restriction settings, and Lambda@Edge configurations. Note AWS Config does not record key–value tags for CloudFront streaming distributions. Track configuration changes with AWS Config 974 Amazon CloudFront Contents • Set up AWS Config with CloudFront • View CloudFront configuration history • Evaluate CloudFront configurations with AWS Config Rules Set up AWS Config with CloudFront Developer Guide When you set up AWS Config, you can choose to record all supported AWS resources or record only some specified resources, such as recording changes for CloudFront only. For a list of supported CloudFront resources, see the Amazon CloudFront section of the Supported Resource Types topic in the AWS Config Developer Guide. Notes • To track configuration changes to your CloudFront distribution, you must sign in to the CloudFront console in the US East (N. Virginia) AWS Region. • There might be a delay in recording resources with AWS Config. AWS Config records resources only after it discovers the resources. Console To set up AWS Config with CloudFront 1. Sign in to the AWS Management Console and open the AWS Config console at https:// console.aws.amazon.com/config/. 2. Choose Get Started Now. 3. On the Settings page, for Resource types to record, specify the AWS resource types that you want AWS Config to record. If you want to record only CloudFront changes, choose Specific types, and then, under CloudFront, choose the distribution or streaming distribution that
AmazonCloudFront_DevGuide-340
AmazonCloudFront_DevGuide.pdf
340
(N. Virginia) AWS Region. • There might be a delay in recording resources with AWS Config. AWS Config records resources only after it discovers the resources. Console To set up AWS Config with CloudFront 1. Sign in to the AWS Management Console and open the AWS Config console at https:// console.aws.amazon.com/config/. 2. Choose Get Started Now. 3. On the Settings page, for Resource types to record, specify the AWS resource types that you want AWS Config to record. If you want to record only CloudFront changes, choose Specific types, and then, under CloudFront, choose the distribution or streaming distribution that you want to track changes for. To add or change which distributions to track, choose Settings on the left, after completing your initial setup. 4. Specify additional required options for AWS Config: set up a notification, specify a location for the configuration information, and add rules for evaluating resource types. Set up AWS Config with CloudFront 975 Amazon CloudFront Developer Guide For more information, see Setting up AWS Config with the Console in the AWS Config Developer Guide. AWS CLI To set up AWS Config with CloudFront using the AWS CLI, see Setting up AWS Config with the AWS CLI in the AWS Config Developer Guide. AWS Config API To set up AWS Config with CloudFront using the AWS Config API, see the StartConfigurationRecorder API operation in the AWS Config API Reference. View CloudFront configuration history After AWS Config starts recording configuration changes to your distributions, you can get the configuration history of any distribution that you have configured for CloudFront. You can view configuration histories in the following ways. Console For each recorded resource, you can view a timeline page that provides a history of configuration details. To view this page, choose the gray icon in the Config Timeline column of the Dedicated Hosts page. For more information, see Viewing Configuration Details in the AWS Config Console in the AWS Config Developer Guide. AWS CLI To get a list of all your distributions, run the list-discovered-resources command, as shown in the following example. aws configservice list-discovered-resources --resource-type AWS::CloudFront::Distribution To get the configuration details of a distribution for a specific time interval, run the get- resource-config-history command. For more information, see View Configuration Details Using the CLI in the AWS Config Developer Guide. View CloudFront configuration history 976 Amazon CloudFront AWS Config API Developer Guide To get a list of all your distributions, use the ListDiscoveredResources API operation. To get the configuration details of a distribution for a specific time interval, use the GetResourceConfigHistory API operation. For more information, see the AWS Config API Reference. Evaluate CloudFront configurations with AWS Config Rules You can evaluate configurations against desired configurations with AWS Config Rules. For example, AWS Config Rules helps you to evaluate whether your CloudFront resources comply with common security best practices. You can choose managed rules like viewer policy HTTPS, SNI enabled, OAC enabled, origin failover enabled, AWS WAF WebACL, or AWS Shield Advanced resource policies to be triggered when the configuration changes. Managed rules can run evaluations periodically, at a frequency that you choose. AWS Firewall Manager relies on AWS Config for automatic alerts and remediations. For more information, see Evaluating Resources with AWS Config Rules and List of AWS Config Managed Rules in the AWS Config Developer Guide. Evaluate CloudFront configurations with AWS Config Rules 977 Amazon CloudFront Developer Guide Security in Amazon CloudFront Cloud security at AWS is the highest priority. As an AWS customer, you benefit from a data center and network architecture that is built to meet the requirements of the most security-sensitive organizations. Security is a shared responsibility between AWS and you. The shared responsibility model describes this as security of the cloud and security in the cloud: • Security of the cloud – AWS is responsible for protecting the infrastructure that runs AWS services in the AWS Cloud. AWS also provides you with services that you can use securely. Third-party auditors regularly test and verify the effectiveness of our security as part of the AWS compliance programs. To learn about the compliance programs that apply to Amazon CloudFront, see AWS Services in Scope by Compliance Program. • Security in the cloud – Your responsibility is determined by the AWS service that you use. You are also responsible for other factors including the sensitivity of your data, your organization’s requirements, and applicable laws and regulations. This documentation helps you understand how to apply the shared responsibility model when using CloudFront. The following topics show you how to configure CloudFront to meet your security and compliance objectives. You also learn how to use other AWS services that help you to monitor and secure your CloudFront resources. Topics • Data protection in Amazon CloudFront • Identity and Access Management for Amazon CloudFront • Logging and
AmazonCloudFront_DevGuide-341
AmazonCloudFront_DevGuide.pdf
341
Your responsibility is determined by the AWS service that you use. You are also responsible for other factors including the sensitivity of your data, your organization’s requirements, and applicable laws and regulations. This documentation helps you understand how to apply the shared responsibility model when using CloudFront. The following topics show you how to configure CloudFront to meet your security and compliance objectives. You also learn how to use other AWS services that help you to monitor and secure your CloudFront resources. Topics • Data protection in Amazon CloudFront • Identity and Access Management for Amazon CloudFront • Logging and monitoring in Amazon CloudFront • Compliance validation for Amazon CloudFront • Resilience in Amazon CloudFront • Infrastructure security in Amazon CloudFront Data protection in Amazon CloudFront The AWS shared responsibility model applies to data protection in Amazon CloudFront. As described in this model, AWS is responsible for protecting the global infrastructure that runs all Data protection 978 Amazon CloudFront Developer Guide of the AWS Cloud. You are responsible for maintaining control over your content that is hosted on this infrastructure. You are also responsible for the security configuration and management tasks for the AWS services that you use. For more information about data privacy, see the Data Privacy FAQ. For information about data protection in Europe, see the AWS Shared Responsibility Model and GDPR blog post on the AWS Security Blog. For data protection purposes, we recommend that you protect AWS account credentials and set up individual users with AWS IAM Identity Center or AWS Identity and Access Management (IAM). That way, each user is given only the permissions necessary to fulfill their job duties. We also recommend that you secure your data in the following ways: • Use multi-factor authentication (MFA) with each account. • Use SSL/TLS to communicate with AWS resources. We require TLS 1.2 and recommend TLS 1.3. • Set up API and user activity logging with AWS CloudTrail. For information about using CloudTrail trails to capture AWS activities, see Working with CloudTrail trails in the AWS CloudTrail User Guide. • Use AWS encryption solutions, along with all default security controls within AWS services. • Use advanced managed security services such as Amazon Macie, which assists in discovering and securing sensitive data that is stored in Amazon S3. • If you require FIPS 140-3 validated cryptographic modules when accessing AWS through a command line interface or an API, use a FIPS endpoint. For more information about the available FIPS endpoints, see Federal Information Processing Standard (FIPS) 140-3. We strongly recommend that you never put confidential or sensitive information, such as your customers' email addresses, into tags or free-form text fields such as a Name field. This includes when you work with CloudFront or other AWS services using the console, API, AWS CLI, or AWS SDKs. Any data that you enter into tags or free-form text fields used for names may be used for billing or diagnostic logs. If you provide a URL to an external server, we strongly recommend that you do not include credentials information in the URL to validate your request to that server. Amazon CloudFront provides several options that you can use to help secure the content that it delivers: • Configure HTTPS connections. • Configure field-level encryption to provide additional security for specific data during transit. • Restrict access to content so that only specific people, or people in a specific area, can view it. Data protection 979 Amazon CloudFront Developer Guide The following topics explain the options in more detail. Topics • Encryption in transit • Encryption at rest • Restrict access to content Encryption in transit To encrypt your data during transit, you configure Amazon CloudFront to require that viewers use HTTPS to request your files, so that connections are encrypted when CloudFront communicates with viewers. You also can configure CloudFront to use HTTPS to get files from your origin, so that connections are encrypted when CloudFront communicates with your origin. For more information, see Use HTTPS with CloudFront. Field-level encryption adds an additional layer of security along with HTTPS that lets you protect specific data throughout system processing so that only certain applications can see it. By configuring field-level encryption in CloudFront, you can securely upload user-submitted sensitive information to your web servers. The sensitive information provided by your clients is encrypted at the edge closer to the user. It remains encrypted throughout your entire application stack, ensuring that only applications that need the data—and have the credentials to decrypt it—are able to do so. For more information, see Use field-level encryption to help protect sensitive data. The CloudFront API endpoints, cloudfront.amazonaws.com and cloudfront- fips.amazonaws.com, only accept HTTPS traffic. This means that when you send and receive information using the CloudFront API, your data—including distribution configurations, cache policies and origin
AmazonCloudFront_DevGuide-342
AmazonCloudFront_DevGuide.pdf
342
in CloudFront, you can securely upload user-submitted sensitive information to your web servers. The sensitive information provided by your clients is encrypted at the edge closer to the user. It remains encrypted throughout your entire application stack, ensuring that only applications that need the data—and have the credentials to decrypt it—are able to do so. For more information, see Use field-level encryption to help protect sensitive data. The CloudFront API endpoints, cloudfront.amazonaws.com and cloudfront- fips.amazonaws.com, only accept HTTPS traffic. This means that when you send and receive information using the CloudFront API, your data—including distribution configurations, cache policies and origin request policies, key groups and public keys, and function code in CloudFront Functions—is always encrypted in transit. In addition, all requests sent to the CloudFront API endpoints are signed with AWS credentials and logged in AWS CloudTrail. Function code and configuration in CloudFront Functions is always encrypted in transit when copied to the edge location points of presence (POPs), and between other storage locations used by CloudFront. Encryption in transit 980 Amazon CloudFront Encryption at rest Developer Guide Function code and configuration in CloudFront Functions is always stored in an encrypted format on the edge location POPs, and in other storage locations used by CloudFront. Restrict access to content Many companies that distribute content over the internet want to restrict access to documents, business data, media streams, or content that is intended for a subset of users. To securely serve this content by using Amazon CloudFront, you can do one or more of the following: Use signed URLs or cookies You can restrict access to content that is intended for selected users—for example, users who have paid a fee—by serving this private content through CloudFront using signed URLs or signed cookies. For more information, see Serve private content with signed URLs and signed cookies. Restrict access to content in Amazon S3 buckets If you restrict access to your content by using, for example, CloudFront signed URLs or signed cookies, you also won't want people to view files by using the direct URL for the file. Instead, you want them to access the files only by using the CloudFront URL, so that your protections work. If you use an Amazon S3 bucket as the origin for a CloudFront distribution, you can set up an origin access control (OAC) which makes it possible to restrict access to the S3 bucket. For more information, see the section called “Restrict access to an Amazon S3 origin”. Restrict access to content served by an Application Load Balancer When you use CloudFront with an Application Load Balancer in Elastic Load Balancing as the origin, you can configure CloudFront to prevent users from directly accessing the Application Load Balancer. This allows users to access the Application Load Balancer only through CloudFront, ensuring that you get the benefits of using CloudFront. For more information, see Restrict access to Application Load Balancers. Use AWS WAF web ACLs You can use AWS WAF, a web application firewall service, to create a web access control list (web ACL) to restrict access to your content. Based on conditions that you specify, such as the IP addresses that requests originate from or the values of query strings, CloudFront responds Encryption at rest 981 Amazon CloudFront Developer Guide to requests either with the requested content or with an HTTP 403 status code (Forbidden). For more information, see Use AWS WAF protections. Use geo restriction You can use geo restriction, also known as geoblocking, to prevent users in specific geographic locations from accessing content that you serve through a CloudFront distribution. There are several options to choose from when you configure geo restrictions. For more information, see Restrict the geographic distribution of your content. Identity and Access Management for Amazon CloudFront AWS Identity and Access Management (IAM) is an AWS service that helps an administrator securely control access to AWS resources. IAM administrators control who can be authenticated (signed in) and authorized (have permissions) to use CloudFront resources. IAM is an AWS service that you can use with no additional charge. Topics • Audience • Authenticating with identities • Managing access using policies • How Amazon CloudFront works with IAM • Identity-based policy examples for Amazon CloudFront • AWS managed policies for Amazon CloudFront • Use service-linked roles for CloudFront • Troubleshoot Amazon CloudFront identity and access Audience How you use AWS Identity and Access Management (IAM) differs, depending on the work that you do in CloudFront. Service user – If you use the CloudFront service to do your job, then your administrator provides you with the credentials and permissions that you need. As you use more CloudFront features to do your work, you might need additional permissions. Understanding how access is managed can Identity and Access Management 982 Amazon CloudFront Developer Guide help you
AmazonCloudFront_DevGuide-343
AmazonCloudFront_DevGuide.pdf
343
Amazon CloudFront • AWS managed policies for Amazon CloudFront • Use service-linked roles for CloudFront • Troubleshoot Amazon CloudFront identity and access Audience How you use AWS Identity and Access Management (IAM) differs, depending on the work that you do in CloudFront. Service user – If you use the CloudFront service to do your job, then your administrator provides you with the credentials and permissions that you need. As you use more CloudFront features to do your work, you might need additional permissions. Understanding how access is managed can Identity and Access Management 982 Amazon CloudFront Developer Guide help you request the right permissions from your administrator. If you cannot access a feature in CloudFront, see Troubleshoot Amazon CloudFront identity and access. Service administrator – If you're in charge of CloudFront resources at your company, you probably have full access to CloudFront. It's your job to determine which CloudFront features and resources your service users should access. You must then submit requests to your IAM administrator to change the permissions of your service users. Review the information on this page to understand the basic concepts of IAM. To learn more about how your company can use IAM with CloudFront, see How Amazon CloudFront works with IAM. IAM administrator – If you're an IAM administrator, you might want to learn details about how you can write policies to manage access to CloudFront. To view example CloudFront identity-based policies that you can use in IAM, see Identity-based policy examples for Amazon CloudFront. Authenticating with identities Authentication is how you sign in to AWS using your identity credentials. You must be authenticated (signed in to AWS) as the AWS account root user, as an IAM user, or by assuming an IAM role. You can sign in to AWS as a federated identity by using credentials provided through an identity source. AWS IAM Identity Center (IAM Identity Center) users, your company's single sign-on authentication, and your Google or Facebook credentials are examples of federated identities. When you sign in as a federated identity, your administrator previously set up identity federation using IAM roles. When you access AWS by using federation, you are indirectly assuming a role. Depending on the type of user you are, you can sign in to the AWS Management Console or the AWS access portal. For more information about signing in to AWS, see How to sign in to your AWS account in the AWS Sign-In User Guide. If you access AWS programmatically, AWS provides a software development kit (SDK) and a command line interface (CLI) to cryptographically sign your requests by using your credentials. If you don't use AWS tools, you must sign requests yourself. For more information about using the recommended method to sign requests yourself, see AWS Signature Version 4 for API requests in the IAM User Guide. Regardless of the authentication method that you use, you might be required to provide additional security information. For example, AWS recommends that you use multi-factor authentication (MFA) to increase the security of your account. To learn more, see Multi-factor authentication in Authenticating with identities 983 Amazon CloudFront Developer Guide the AWS IAM Identity Center User Guide and AWS Multi-factor authentication in IAM in the IAM User Guide. AWS account root user When you create an AWS account, you begin with one sign-in identity that has complete access to all AWS services and resources in the account. This identity is called the AWS account root user and is accessed by signing in with the email address and password that you used to create the account. We strongly recommend that you don't use the root user for your everyday tasks. Safeguard your root user credentials and use them to perform the tasks that only the root user can perform. For the complete list of tasks that require you to sign in as the root user, see Tasks that require root user credentials in the IAM User Guide. Federated identity As a best practice, require human users, including users that require administrator access, to use federation with an identity provider to access AWS services by using temporary credentials. A federated identity is a user from your enterprise user directory, a web identity provider, the AWS Directory Service, the Identity Center directory, or any user that accesses AWS services by using credentials provided through an identity source. When federated identities access AWS accounts, they assume roles, and the roles provide temporary credentials. For centralized access management, we recommend that you use AWS IAM Identity Center. You can create users and groups in IAM Identity Center, or you can connect and synchronize to a set of users and groups in your own identity source for use across all your AWS accounts and applications. For information about IAM Identity Center, see What is IAM Identity Center?
AmazonCloudFront_DevGuide-344
AmazonCloudFront_DevGuide.pdf
344
the AWS Directory Service, the Identity Center directory, or any user that accesses AWS services by using credentials provided through an identity source. When federated identities access AWS accounts, they assume roles, and the roles provide temporary credentials. For centralized access management, we recommend that you use AWS IAM Identity Center. You can create users and groups in IAM Identity Center, or you can connect and synchronize to a set of users and groups in your own identity source for use across all your AWS accounts and applications. For information about IAM Identity Center, see What is IAM Identity Center? in the AWS IAM Identity Center User Guide. IAM users and groups An IAM user is an identity within your AWS account that has specific permissions for a single person or application. Where possible, we recommend relying on temporary credentials instead of creating IAM users who have long-term credentials such as passwords and access keys. However, if you have specific use cases that require long-term credentials with IAM users, we recommend that you rotate access keys. For more information, see Rotate access keys regularly for use cases that require long- term credentials in the IAM User Guide. An IAM group is an identity that specifies a collection of IAM users. You can't sign in as a group. You can use groups to specify permissions for multiple users at a time. Groups make permissions easier Authenticating with identities 984 Amazon CloudFront Developer Guide to manage for large sets of users. For example, you could have a group named IAMAdmins and give that group permissions to administer IAM resources. Users are different from roles. A user is uniquely associated with one person or application, but a role is intended to be assumable by anyone who needs it. Users have permanent long-term credentials, but roles provide temporary credentials. To learn more, see Use cases for IAM users in the IAM User Guide. IAM roles An IAM role is an identity within your AWS account that has specific permissions. It is similar to an IAM user, but is not associated with a specific person. To temporarily assume an IAM role in the AWS Management Console, you can switch from a user to an IAM role (console). You can assume a role by calling an AWS CLI or AWS API operation or by using a custom URL. For more information about methods for using roles, see Methods to assume a role in the IAM User Guide. IAM roles with temporary credentials are useful in the following situations: • Federated user access – To assign permissions to a federated identity, you create a role and define permissions for the role. When a federated identity authenticates, the identity is associated with the role and is granted the permissions that are defined by the role. For information about roles for federation, see Create a role for a third-party identity provider (federation) in the IAM User Guide. If you use IAM Identity Center, you configure a permission set. To control what your identities can access after they authenticate, IAM Identity Center correlates the permission set to a role in IAM. For information about permissions sets, see Permission sets in the AWS IAM Identity Center User Guide. • Temporary IAM user permissions – An IAM user or role can assume an IAM role to temporarily take on different permissions for a specific task. • Cross-account access – You can use an IAM role to allow someone (a trusted principal) in a different account to access resources in your account. Roles are the primary way to grant cross- account access. However, with some AWS services, you can attach a policy directly to a resource (instead of using a role as a proxy). To learn the difference between roles and resource-based policies for cross-account access, see Cross account resource access in IAM in the IAM User Guide. • Cross-service access – Some AWS services use features in other AWS services. For example, when you make a call in a service, it's common for that service to run applications in Amazon EC2 or store objects in Amazon S3. A service might do this using the calling principal's permissions, using a service role, or using a service-linked role. Authenticating with identities 985 Amazon CloudFront Developer Guide • Forward access sessions (FAS) – When you use an IAM user or role to perform actions in AWS, you are considered a principal. When you use some services, you might perform an action that then initiates another action in a different service. FAS uses the permissions of the principal calling an AWS service, combined with the requesting AWS service to make requests to downstream services. FAS requests are only made when a service receives a request that requires interactions with other AWS services or resources to complete.
AmazonCloudFront_DevGuide-345
AmazonCloudFront_DevGuide.pdf
345
using a service-linked role. Authenticating with identities 985 Amazon CloudFront Developer Guide • Forward access sessions (FAS) – When you use an IAM user or role to perform actions in AWS, you are considered a principal. When you use some services, you might perform an action that then initiates another action in a different service. FAS uses the permissions of the principal calling an AWS service, combined with the requesting AWS service to make requests to downstream services. FAS requests are only made when a service receives a request that requires interactions with other AWS services or resources to complete. In this case, you must have permissions to perform both actions. For policy details when making FAS requests, see Forward access sessions. • Service role – A service role is an IAM role that a service assumes to perform actions on your behalf. An IAM administrator can create, modify, and delete a service role from within IAM. For more information, see Create a role to delegate permissions to an AWS service in the IAM User Guide. • Service-linked role – A service-linked role is a type of service role that is linked to an AWS service. The service can assume the role to perform an action on your behalf. Service-linked roles appear in your AWS account and are owned by the service. An IAM administrator can view, but not edit the permissions for service-linked roles. • Applications running on Amazon EC2 – You can use an IAM role to manage temporary credentials for applications that are running on an EC2 instance and making AWS CLI or AWS API requests. This is preferable to storing access keys within the EC2 instance. To assign an AWS role to an EC2 instance and make it available to all of its applications, you create an instance profile that is attached to the instance. An instance profile contains the role and enables programs that are running on the EC2 instance to get temporary credentials. For more information, see Use an IAM role to grant permissions to applications running on Amazon EC2 instances in the IAM User Guide. Managing access using policies You control access in AWS by creating policies and attaching them to AWS identities or resources. A policy is an object in AWS that, when associated with an identity or resource, defines their permissions. AWS evaluates these policies when a principal (user, root user, or role session) makes a request. Permissions in the policies determine whether the request is allowed or denied. Most policies are stored in AWS as JSON documents. For more information about the structure and contents of JSON policy documents, see Overview of JSON policies in the IAM User Guide. Administrators can use AWS JSON policies to specify who has access to what. That is, which principal can perform actions on what resources, and under what conditions. Managing access using policies 986 Amazon CloudFront Developer Guide By default, users and roles have no permissions. To grant users permission to perform actions on the resources that they need, an IAM administrator can create IAM policies. The administrator can then add the IAM policies to roles, and users can assume the roles. IAM policies define permissions for an action regardless of the method that you use to perform the operation. For example, suppose that you have a policy that allows the iam:GetRole action. A user with that policy can get role information from the AWS Management Console, the AWS CLI, or the AWS API. Identity-based policies Identity-based policies are JSON permissions policy documents that you can attach to an identity, such as an IAM user, group of users, or role. These policies control what actions users and roles can perform, on which resources, and under what conditions. To learn how to create an identity-based policy, see Define custom IAM permissions with customer managed policies in the IAM User Guide. Identity-based policies can be further categorized as inline policies or managed policies. Inline policies are embedded directly into a single user, group, or role. Managed policies are standalone policies that you can attach to multiple users, groups, and roles in your AWS account. Managed policies include AWS managed policies and customer managed policies. To learn how to choose between a managed policy or an inline policy, see Choose between managed policies and inline policies in the IAM User Guide. Resource-based policies Resource-based policies are JSON policy documents that you attach to a resource. Examples of resource-based policies are IAM role trust policies and Amazon S3 bucket policies. In services that support resource-based policies, service administrators can use them to control access to a specific resource. For the resource where the policy is attached, the policy defines what actions a specified principal can perform on that resource and under what conditions. You must specify a
AmazonCloudFront_DevGuide-346
AmazonCloudFront_DevGuide.pdf
346
learn how to choose between a managed policy or an inline policy, see Choose between managed policies and inline policies in the IAM User Guide. Resource-based policies Resource-based policies are JSON policy documents that you attach to a resource. Examples of resource-based policies are IAM role trust policies and Amazon S3 bucket policies. In services that support resource-based policies, service administrators can use them to control access to a specific resource. For the resource where the policy is attached, the policy defines what actions a specified principal can perform on that resource and under what conditions. You must specify a principal in a resource-based policy. Principals can include accounts, users, roles, federated users, or AWS services. Resource-based policies are inline policies that are located in that service. You can't use AWS managed policies from IAM in a resource-based policy. Managing access using policies 987 Amazon CloudFront Access control lists (ACLs) Developer Guide Access control lists (ACLs) control which principals (account members, users, or roles) have permissions to access a resource. ACLs are similar to resource-based policies, although they do not use the JSON policy document format. Amazon S3, AWS WAF, and Amazon VPC are examples of services that support ACLs. To learn more about ACLs, see Access control list (ACL) overview in the Amazon Simple Storage Service Developer Guide. Other policy types AWS supports additional, less-common policy types. These policy types can set the maximum permissions granted to you by the more common policy types. • Permissions boundaries – A permissions boundary is an advanced feature in which you set the maximum permissions that an identity-based policy can grant to an IAM entity (IAM user or role). You can set a permissions boundary for an entity. The resulting permissions are the intersection of an entity's identity-based policies and its permissions boundaries. Resource-based policies that specify the user or role in the Principal field are not limited by the permissions boundary. An explicit deny in any of these policies overrides the allow. For more information about permissions boundaries, see Permissions boundaries for IAM entities in the IAM User Guide. • Service control policies (SCPs) – SCPs are JSON policies that specify the maximum permissions for an organization or organizational unit (OU) in AWS Organizations. AWS Organizations is a service for grouping and centrally managing multiple AWS accounts that your business owns. If you enable all features in an organization, then you can apply service control policies (SCPs) to any or all of your accounts. The SCP limits permissions for entities in member accounts, including each AWS account root user. For more information about Organizations and SCPs, see Service control policies in the AWS Organizations User Guide. • Resource control policies (RCPs) – RCPs are JSON policies that you can use to set the maximum available permissions for resources in your accounts without updating the IAM policies attached to each resource that you own. The RCP limits permissions for resources in member accounts and can impact the effective permissions for identities, including the AWS account root user, regardless of whether they belong to your organization. For more information about Organizations and RCPs, including a list of AWS services that support RCPs, see Resource control policies (RCPs) in the AWS Organizations User Guide. • Session policies – Session policies are advanced policies that you pass as a parameter when you programmatically create a temporary session for a role or federated user. The resulting session's Managing access using policies 988 Amazon CloudFront Developer Guide permissions are the intersection of the user or role's identity-based policies and the session policies. Permissions can also come from a resource-based policy. An explicit deny in any of these policies overrides the allow. For more information, see Session policies in the IAM User Guide. Multiple policy types When multiple types of policies apply to a request, the resulting permissions are more complicated to understand. To learn how AWS determines whether to allow a request when multiple policy types are involved, see Policy evaluation logic in the IAM User Guide. How Amazon CloudFront works with IAM Before you use IAM to manage access to CloudFront, learn what IAM features are available to use with CloudFront. IAM features you can use with Amazon CloudFront IAM feature CloudFront support Identity-based policies Resource-based policies Policy actions Policy resources Policy condition keys (service-specific) ACLs Yes No Yes Yes Yes No ABAC (tags in policies) Partial Temporary credentials Forward access sessions (FAS) Service roles Service-linked roles Yes No No Yes How Amazon CloudFront works with IAM 989 Amazon CloudFront Developer Guide To get a high-level view of how CloudFront and other AWS services work with most IAM features, see AWS services that work with IAM in the IAM User Guide. Identity-based policies for CloudFront Supports identity-based policies: Yes Identity-based policies are JSON permissions policy documents
AmazonCloudFront_DevGuide-347
AmazonCloudFront_DevGuide.pdf
347
with Amazon CloudFront IAM feature CloudFront support Identity-based policies Resource-based policies Policy actions Policy resources Policy condition keys (service-specific) ACLs Yes No Yes Yes Yes No ABAC (tags in policies) Partial Temporary credentials Forward access sessions (FAS) Service roles Service-linked roles Yes No No Yes How Amazon CloudFront works with IAM 989 Amazon CloudFront Developer Guide To get a high-level view of how CloudFront and other AWS services work with most IAM features, see AWS services that work with IAM in the IAM User Guide. Identity-based policies for CloudFront Supports identity-based policies: Yes Identity-based policies are JSON permissions policy documents that you can attach to an identity, such as an IAM user, group of users, or role. These policies control what actions users and roles can perform, on which resources, and under what conditions. To learn how to create an identity-based policy, see Define custom IAM permissions with customer managed policies in the IAM User Guide. With IAM identity-based policies, you can specify allowed or denied actions and resources as well as the conditions under which actions are allowed or denied. You can't specify the principal in an identity-based policy because it applies to the user or role to which it is attached. To learn about all of the elements that you can use in a JSON policy, see IAM JSON policy elements reference in the IAM User Guide. Identity-based policy examples for CloudFront To view examples of CloudFront identity-based policies, see Identity-based policy examples for Amazon CloudFront. Resource-based policies within CloudFront Supports resource-based policies: No Resource-based policies are JSON policy documents that you attach to a resource. Examples of resource-based policies are IAM role trust policies and Amazon S3 bucket policies. In services that support resource-based policies, service administrators can use them to control access to a specific resource. For the resource where the policy is attached, the policy defines what actions a specified principal can perform on that resource and under what conditions. You must specify a principal in a resource-based policy. Principals can include accounts, users, roles, federated users, or AWS services. To enable cross-account access, you can specify an entire account or IAM entities in another account as the principal in a resource-based policy. Adding a cross-account principal to a resource- based policy is only half of establishing the trust relationship. When the principal and the resource are in different AWS accounts, an IAM administrator in the trusted account must also grant the principal entity (user or role) permission to access the resource. They grant permission by How Amazon CloudFront works with IAM 990 Amazon CloudFront Developer Guide attaching an identity-based policy to the entity. However, if a resource-based policy grants access to a principal in the same account, no additional identity-based policy is required. For more information, see Cross account resource access in IAM in the IAM User Guide. Policy actions for CloudFront Supports policy actions: Yes Administrators can use AWS JSON policies to specify who has access to what. That is, which principal can perform actions on what resources, and under what conditions. The Action element of a JSON policy describes the actions that you can use to allow or deny access in a policy. Policy actions usually have the same name as the associated AWS API operation. There are some exceptions, such as permission-only actions that don't have a matching API operation. There are also some operations that require multiple actions in a policy. These additional actions are called dependent actions. Include actions in a policy to grant permissions to perform the associated operation. To see a list of CloudFront actions, see Actions defined by Amazon CloudFront in the Service Authorization Reference. Policy actions in CloudFront use the following prefix before the action: cloudfront To specify multiple actions in a single statement, separate them with commas. "Action": [ "cloudfront:action1", "cloudfront:action2" ] To view examples of CloudFront identity-based policies, see Identity-based policy examples for Amazon CloudFront. Policy resources for CloudFront Supports policy resources: Yes How Amazon CloudFront works with IAM 991 Amazon CloudFront Developer Guide Administrators can use AWS JSON policies to specify who has access to what. That is, which principal can perform actions on what resources, and under what conditions. The Resource JSON policy element specifies the object or objects to which the action applies. Statements must include either a Resource or a NotResource element. As a best practice, specify a resource using its Amazon Resource Name (ARN). You can do this for actions that support a specific resource type, known as resource-level permissions. For actions that don't support resource-level permissions, such as listing operations, use a wildcard (*) to indicate that the statement applies to all resources. "Resource": "*" To see a list of CloudFront resource types and their ARNs, see Resources defined by Amazon CloudFront in the Service Authorization Reference.
AmazonCloudFront_DevGuide-348
AmazonCloudFront_DevGuide.pdf
348
JSON policy element specifies the object or objects to which the action applies. Statements must include either a Resource or a NotResource element. As a best practice, specify a resource using its Amazon Resource Name (ARN). You can do this for actions that support a specific resource type, known as resource-level permissions. For actions that don't support resource-level permissions, such as listing operations, use a wildcard (*) to indicate that the statement applies to all resources. "Resource": "*" To see a list of CloudFront resource types and their ARNs, see Resources defined by Amazon CloudFront in the Service Authorization Reference. To learn with which actions you can specify the ARN of each resource, see Actions defined by Amazon CloudFront. To view examples of CloudFront identity-based policies, see Identity-based policy examples for Amazon CloudFront. Policy condition keys for CloudFront Supports service-specific policy condition keys: Yes Administrators can use AWS JSON policies to specify who has access to what. That is, which principal can perform actions on what resources, and under what conditions. The Condition element (or Condition block) lets you specify conditions in which a statement is in effect. The Condition element is optional. You can create conditional expressions that use condition operators, such as equals or less than, to match the condition in the policy with values in the request. If you specify multiple Condition elements in a statement, or multiple keys in a single Condition element, AWS evaluates them using a logical AND operation. If you specify multiple values for a single condition key, AWS evaluates the condition using a logical OR operation. All of the conditions must be met before the statement's permissions are granted. You can also use placeholder variables when you specify conditions. For example, you can grant an IAM user permission to access a resource only if it is tagged with their IAM user name. For more information, see IAM policy elements: variables and tags in the IAM User Guide. How Amazon CloudFront works with IAM 992 Amazon CloudFront Developer Guide AWS supports global condition keys and service-specific condition keys. To see all AWS global condition keys, see AWS global condition context keys in the IAM User Guide. To see a list of CloudFront condition keys, see Condition keys for Amazon CloudFront in the Service Authorization Reference. To learn with which actions and resources you can use a condition key, see Actions defined by Amazon CloudFront. To view examples of CloudFront identity-based policies, see Identity-based policy examples for Amazon CloudFront. ACLs in CloudFront Supports ACLs: No Access control lists (ACLs) control which principals (account members, users, or roles) have permissions to access a resource. ACLs are similar to resource-based policies, although they do not use the JSON policy document format. ABAC with CloudFront Supports ABAC (tags in policies): Partial Attribute-based access control (ABAC) is an authorization strategy that defines permissions based on attributes. In AWS, these attributes are called tags. You can attach tags to IAM entities (users or roles) and to many AWS resources. Tagging entities and resources is the first step of ABAC. Then you design ABAC policies to allow operations when the principal's tag matches the tag on the resource that they are trying to access. ABAC is helpful in environments that are growing rapidly and helps with situations where policy management becomes cumbersome. To control access based on tags, you provide tag information in the condition element of a policy using the aws:ResourceTag/key-name, aws:RequestTag/key-name, or aws:TagKeys condition keys. If a service supports all three condition keys for every resource type, then the value is Yes for the service. If a service supports all three condition keys for only some resource types, then the value is Partial. For more information about ABAC, see Define permissions with ABAC authorization in the IAM User Guide. To view a tutorial with steps for setting up ABAC, see Use attribute-based access control (ABAC) in the IAM User Guide. How Amazon CloudFront works with IAM 993 Amazon CloudFront Developer Guide CloudFront supports ABAC for distributions only. Using temporary credentials with CloudFront Supports temporary credentials: Yes Some AWS services don't work when you sign in using temporary credentials. For additional information, including which AWS services work with temporary credentials, see AWS services that work with IAM in the IAM User Guide. You are using temporary credentials if you sign in to the AWS Management Console using any method except a user name and password. For example, when you access AWS using your company's single sign-on (SSO) link, that process automatically creates temporary credentials. You also automatically create temporary credentials when you sign in to the console as a user and then switch roles. For more information about switching roles, see Switch from a user to an IAM role (console) in the IAM User Guide. You can manually create
AmazonCloudFront_DevGuide-349
AmazonCloudFront_DevGuide.pdf
349
credentials, see AWS services that work with IAM in the IAM User Guide. You are using temporary credentials if you sign in to the AWS Management Console using any method except a user name and password. For example, when you access AWS using your company's single sign-on (SSO) link, that process automatically creates temporary credentials. You also automatically create temporary credentials when you sign in to the console as a user and then switch roles. For more information about switching roles, see Switch from a user to an IAM role (console) in the IAM User Guide. You can manually create temporary credentials using the AWS CLI or AWS API. You can then use those temporary credentials to access AWS. AWS recommends that you dynamically generate temporary credentials instead of using long-term access keys. For more information, see Temporary security credentials in IAM. Forward access sessions for CloudFront Supports forward access sessions (FAS): No When you use an IAM user or role to perform actions in AWS, you are considered a principal. When you use some services, you might perform an action that then initiates another action in a different service. FAS uses the permissions of the principal calling an AWS service, combined with the requesting AWS service to make requests to downstream services. FAS requests are only made when a service receives a request that requires interactions with other AWS services or resources to complete. In this case, you must have permissions to perform both actions. For policy details when making FAS requests, see Forward access sessions. Service roles for CloudFront Supports service roles: No A service role is an IAM role that a service assumes to perform actions on your behalf. An IAM administrator can create, modify, and delete a service role from within IAM. For more information, see Create a role to delegate permissions to an AWS service in the IAM User Guide. How Amazon CloudFront works with IAM 994 Amazon CloudFront Warning Developer Guide Changing the permissions for a service role might break CloudFront functionality. Edit service roles only when CloudFront provides guidance to do so. Service-linked roles for CloudFront Supports service-linked roles: Yes A service-linked role is a type of service role that is linked to an AWS service. The service can assume the role to perform an action on your behalf. Service-linked roles appear in your AWS account and are owned by the service. An IAM administrator can view, but not edit the permissions for service-linked roles. CloudFront uses service-linked roles to performs actions for you. For more information about creating or managing CloudFront service-linked roles, see Use service-linked roles for CloudFront. For more information about creating or managing Lambda@Edge service-linked roles, see Service- linked roles for Lambda@Edge. For details about creating or managing service-linked roles, see AWS services that work with IAM. Find a service in the table that includes a Yes in the Service-linked role column. Choose the Yes link to view the service-linked role documentation for that service. Identity-based policy examples for Amazon CloudFront By default, users and roles don't have permission to create or modify CloudFront resources. They also can't perform tasks by using the AWS Management Console, AWS Command Line Interface (AWS CLI), or AWS API. To grant users permission to perform actions on the resources that they need, an IAM administrator can create IAM policies. The administrator can then add the IAM policies to roles, and users can assume the roles. To learn how to create an IAM identity-based policy by using these example JSON policy documents, see Create IAM policies (console) in the IAM User Guide. For details about actions and resource types defined by CloudFront, including the format of the ARNs for each of the resource types, see Actions, resources, and condition keys for Amazon CloudFront in the Service Authorization Reference. Identity-based policy examples 995 Developer Guide Amazon CloudFront Topics • Policy best practices • Allow users to view their own permissions • Permissions to access CloudFront programmatically • Permissions required to use the CloudFront console • Customer managed policy examples Policy best practices Identity-based policies determine whether someone can create, access, or delete CloudFront resources in your account. These actions can incur costs for your AWS account. When you create or edit identity-based policies, follow these guidelines and recommendations: • Get started with AWS managed policies and move toward least-privilege permissions – To get started granting permissions to your users and workloads, use the AWS managed policies that grant permissions for many common use cases. They are available in your AWS account. We recommend that you reduce permissions further by defining AWS customer managed policies that are specific to your use cases. For more information, see AWS managed policies or AWS managed policies for job functions in the IAM User Guide. • Apply least-privilege permissions –