url stringlengths 11 2.25k | text stringlengths 88 50k | ts timestamp[s]date 2026-01-13 08:47:33 2026-01-13 09:30:40 |
|---|---|---|
https://young-programmers.blogspot.com/search/label/xturtle | Young Programmers Podcast: xturtle skip to main | skip to sidebar Young Programmers Podcast A video podcast for computer programmers in grades 3 and up. We learn about Scratch, Tynker, Alice, Python, Pygame, and Scala, and interview interesting programmers. From professional software developer and teacher Dave Briccetti, and many special guests. Viewing the Videos or Subscribing to the Podcast Some of the entries have a picture, which you can click to access the video. Otherwise, to see the videos, use this icon to subscribe to or view the feed: Or, subscribe in iTunes Showing posts with label xturtle . Show all posts Showing posts with label xturtle . Show all posts Wednesday, July 22, 2009 Xturtle With Loops to Make Polygons Explanation of polygons.py program, which uses xturtle to draw polygons of any number of sides. at 10:15 PM Labels: python , xturtle Older Posts Home Subscribe to: Comments (Atom) About Me Dave Briccetti View my complete profile Where to Get Software Kojo Python Alice Scratch Other Blogs Dave Briccetti’s Blog One of My Best Classes Ever 10 years ago Tags alice (3) Android (1) arduino (1) art (1) audacity (2) dictionary (2) Flickr (1) functions (2) gamedev (1) garageband (1) GIMP (2) Google (2) guest (4) hacker (1) higher-order functions (1) inkscape (1) interview (9) Java (2) JavaFX (2) Jython (3) Kojo (2) lift (1) music (2) physics (1) platform (1) programmer (4) pygame (6) python (31) PythonCard (1) random (6) Sande (2) Scala (5) scratch (10) shdh (2) shdh34 (2) sound (3) sprite (2) Swing (3) teaching (3) twitter (2) Tynker (1) Web Services (1) xturtle (1) Followers Blog Archive ▼  2015 (1) ▼  February (1) This Podcast Moves to YouTube ►  2013 (4) ►  July (1) ►  June (3) ►  2012 (2) ►  February (1) ►  January (1) ►  2011 (8) ►  November (1) ►  July (3) ►  May (1) ►  February (2) ►  January (1) ►  2010 (6) ►  October (2) ►  June (2) ►  February (2) ►  2009 (37) ►  December (4) ►  November (1) ►  September (7) ►  August (11) ►  July (14)   | 2026-01-13T09:30:35 |
https://young-programmers.blogspot.com/search/label/Swing#sidebar | Young Programmers Podcast: Swing skip to main | skip to sidebar Young Programmers Podcast A video podcast for computer programmers in grades 3 and up. We learn about Scratch, Tynker, Alice, Python, Pygame, and Scala, and interview interesting programmers. From professional software developer and teacher Dave Briccetti, and many special guests. Viewing the Videos or Subscribing to the Podcast Some of the entries have a picture, which you can click to access the video. Otherwise, to see the videos, use this icon to subscribe to or view the feed: Or, subscribe in iTunes Showing posts with label Swing . Show all posts Showing posts with label Swing . Show all posts Thursday, December 24, 2009 Jython/Swing Game of Life Version 2 A very quick look at version 2 of our Jython implementation of Conway’s Game of Life. Source code at 12:25 AM Labels: Jython , python , Swing Saturday, September 19, 2009 Jython/Swing Conway’s Game of Life A brief overview of a Jython (Python) implementation of Conway’s Game of Life using Java's Swing for the GUI. Source code : http://davebsoft.com/cfkfiles/python/Life/. at 4:33 PM Labels: Java , Jython , python , Swing Friday, September 18, 2009 A Graphical User Interface with Jython and Swing Dave Briccetti shows how to create a simple Python program with a graphical user interface using Jython (Python running on Java) and Swing. at 4:59 PM Labels: Java , Jython , python , Swing Older Posts Home Subscribe to: Comments (Atom) About Me Dave Briccetti View my complete profile Where to Get Software Kojo Python Alice Scratch Other Blogs Dave Briccetti’s Blog One of My Best Classes Ever 10 years ago Tags alice (3) Android (1) arduino (1) art (1) audacity (2) dictionary (2) Flickr (1) functions (2) gamedev (1) garageband (1) GIMP (2) Google (2) guest (4) hacker (1) higher-order functions (1) inkscape (1) interview (9) Java (2) JavaFX (2) Jython (3) Kojo (2) lift (1) music (2) physics (1) platform (1) programmer (4) pygame (6) python (31) PythonCard (1) random (6) Sande (2) Scala (5) scratch (10) shdh (2) shdh34 (2) sound (3) sprite (2) Swing (3) teaching (3) twitter (2) Tynker (1) Web Services (1) xturtle (1) Followers Blog Archive ▼  2015 (1) ▼  February (1) This Podcast Moves to YouTube ►  2013 (4) ►  July (1) ►  June (3) ►  2012 (2) ►  February (1) ►  January (1) ►  2011 (8) ►  November (1) ►  July (3) ►  May (1) ►  February (2) ►  January (1) ►  2010 (6) ►  October (2) ►  June (2) ►  February (2) ►  2009 (37) ►  December (4) ►  November (1) ►  September (7) ►  August (11) ►  July (14)   | 2026-01-13T09:30:35 |
https://young-programmers.blogspot.com/2013/07/ | Young Programmers Podcast: July 2013 skip to main | skip to sidebar Young Programmers Podcast A video podcast for computer programmers in grades 3 and up. We learn about Scratch, Tynker, Alice, Python, Pygame, and Scala, and interview interesting programmers. From professional software developer and teacher Dave Briccetti, and many special guests. Viewing the Videos or Subscribing to the Podcast Some of the entries have a picture, which you can click to access the video. Otherwise, to see the videos, use this icon to subscribe to or view the feed: Or, subscribe in iTunes Thursday, July 18, 2013 Introduction to Python Functions A look at how to, and why you should, use functions in your Python programs. at 10:06 PM Labels: functions , python , random Newer Posts Older Posts Home Subscribe to: Comments (Atom) About Me Dave Briccetti View my complete profile Where to Get Software Kojo Python Alice Scratch Other Blogs Dave Briccetti’s Blog One of My Best Classes Ever 10 years ago Tags alice (3) Android (1) arduino (1) art (1) audacity (2) dictionary (2) Flickr (1) functions (2) gamedev (1) garageband (1) GIMP (2) Google (2) guest (4) hacker (1) higher-order functions (1) inkscape (1) interview (9) Java (2) JavaFX (2) Jython (3) Kojo (2) lift (1) music (2) physics (1) platform (1) programmer (4) pygame (6) python (31) PythonCard (1) random (6) Sande (2) Scala (5) scratch (10) shdh (2) shdh34 (2) sound (3) sprite (2) Swing (3) teaching (3) twitter (2) Tynker (1) Web Services (1) xturtle (1) Followers Blog Archive ►  2015 (1) ►  February (1) ▼  2013 (4) ▼  July (1) Introduction to Python Functions ►  June (3) ►  2012 (2) ►  February (1) ►  January (1) ►  2011 (8) ►  November (1) ►  July (3) ►  May (1) ►  February (2) ►  January (1) ►  2010 (6) ►  October (2) ►  June (2) ►  February (2) ►  2009 (37) ►  December (4) ►  November (1) ►  September (7) ►  August (11) ►  July (14)   | 2026-01-13T09:30:35 |
https://young-programmers.blogspot.com/2009/12/invisible-player-escapes-maze.html | Young Programmers Podcast: Invisible Player Escapes Maze skip to main | skip to sidebar Young Programmers Podcast A video podcast for computer programmers in grades 3 and up. We learn about Scratch, Tynker, Alice, Python, Pygame, and Scala, and interview interesting programmers. From professional software developer and teacher Dave Briccetti, and many special guests. Viewing the Videos or Subscribing to the Podcast Some of the entries have a picture, which you can click to access the video. Otherwise, to see the videos, use this icon to subscribe to or view the feed: Or, subscribe in iTunes Friday, December 25, 2009 Invisible Player Escapes Maze Escape the maze. You are invisible, and so are all the obstacles unless they are close to you. Illustrates use of the ghost effect, and broadcast. http://scratch.mit.edu/projects/davebric/818925 at 1:37 PM Labels: scratch Newer Post Older Post Home About Me Dave Briccetti View my complete profile Where to Get Software Kojo Python Alice Scratch Other Blogs Dave Briccetti’s Blog One of My Best Classes Ever 10 years ago Tags alice (3) Android (1) arduino (1) art (1) audacity (2) dictionary (2) Flickr (1) functions (2) gamedev (1) garageband (1) GIMP (2) Google (2) guest (4) hacker (1) higher-order functions (1) inkscape (1) interview (9) Java (2) JavaFX (2) Jython (3) Kojo (2) lift (1) music (2) physics (1) platform (1) programmer (4) pygame (6) python (31) PythonCard (1) random (6) Sande (2) Scala (5) scratch (10) shdh (2) shdh34 (2) sound (3) sprite (2) Swing (3) teaching (3) twitter (2) Tynker (1) Web Services (1) xturtle (1) Followers Blog Archive ►  2015 (1) ►  February (1) ►  2013 (4) ►  July (1) ►  June (3) ►  2012 (2) ►  February (1) ►  January (1) ►  2011 (8) ►  November (1) ►  July (3) ►  May (1) ►  February (2) ►  January (1) ►  2010 (6) ►  October (2) ►  June (2) ►  February (2) ▼  2009 (37) ▼  December (4) Invisible Player Escapes Maze, Pygame Version 1 Invisible Player Escapes Maze Growing Player Escapes Maze Jython/Swing Game of Life Version 2 ►  November (1) ►  September (7) ►  August (11) ►  July (14)   | 2026-01-13T09:30:35 |
https://docs.aws.amazon.com/id_id/lambda/latest/dg/with-s3-tutorial.html#with-s3-tutorial-create-function-package | Tutorial: Menggunakan pemicu Amazon S3 untuk membuat gambar thumbnail - AWS Lambda Tutorial: Menggunakan pemicu Amazon S3 untuk membuat gambar thumbnail - AWS Lambda Dokumentasi AWS Lambda Panduan Developerr Prasyarat Buat dua ember Amazon S3 Unggah gambar uji ke bucket sumber Anda Membuat kebijakan izin Membuat peran eksekusi Buat paket penerapan fungsi Buat fungsi Lambda Konfigurasikan Amazon S3 untuk menjalankan fungsi Uji fungsi Lambda Anda dengan acara dummy Uji fungsi Anda menggunakan pemicu Amazon S3 Bersihkan sumber daya Anda Terjemahan disediakan oleh mesin penerjemah. Jika konten terjemahan yang diberikan bertentangan dengan versi bahasa Inggris aslinya, utamakan versi bahasa Inggris. Tutorial: Menggunakan pemicu Amazon S3 untuk membuat gambar thumbnail Dalam tutorial ini, Anda membuat dan mengonfigurasi fungsi Lambda yang mengubah ukuran gambar yang ditambahkan ke bucket Amazon Simple Storage Service (Amazon S3). Saat Anda menambahkan file gambar ke bucket, Amazon S3 akan memanggil fungsi Lambda Anda. Fungsi tersebut kemudian membuat versi thumbnail gambar dan mengeluarkannya ke bucket Amazon S3 yang berbeda. Untuk menyelesaikan tutorial ini, Anda melakukan langkah-langkah berikut: Buat bucket Amazon S3 sumber dan tujuan dan unggah gambar sampel. Buat fungsi Lambda yang mengubah ukuran gambar dan mengeluarkan thumbnail ke bucket Amazon S3. Konfigurasikan pemicu Lambda yang memanggil fungsi Anda saat objek diunggah ke bucket sumber Anda. Uji fungsi Anda, pertama dengan acara dummy, lalu dengan mengunggah gambar ke bucket sumber Anda. Dengan menyelesaikan langkah-langkah ini, Anda akan mempelajari cara menggunakan Lambda untuk menjalankan tugas pemrosesan file pada objek yang ditambahkan ke bucket Amazon S3. Anda dapat menyelesaikan tutorial ini menggunakan AWS Command Line Interface (AWS CLI) atau Konsol Manajemen AWS. Jika Anda mencari contoh sederhana untuk mempelajari cara mengonfigurasi pemicu Amazon S3 untuk Lambda, Anda dapat mencoba Tutorial: Menggunakan pemicu Amazon S3 untuk menjalankan fungsi Lambda. Topik Prasyarat Buat dua ember Amazon S3 Unggah gambar uji ke bucket sumber Anda Membuat kebijakan izin Membuat peran eksekusi Buat paket penerapan fungsi Buat fungsi Lambda Konfigurasikan Amazon S3 untuk menjalankan fungsi Uji fungsi Lambda Anda dengan acara dummy Uji fungsi Anda menggunakan pemicu Amazon S3 Bersihkan sumber daya Anda Prasyarat Jika Anda ingin menggunakan AWS CLI untuk menyelesaikan tutorial, instal versi terbaru dari AWS Command Line Interface . Untuk kode fungsi Lambda Anda, Anda dapat menggunakan Python atau Node.js. Instal alat dukungan bahasa dan manajer paket untuk bahasa yang ingin Anda gunakan. Jika Anda belum menginstal AWS Command Line Interface, ikuti langkah-langkah di Menginstal atau memperbarui versi terbaru AWS CLI untuk menginstalnya . Tutorial ini membutuhkan terminal baris perintah atau shell untuk menjalankan perintah. Di Linux dan macOS, gunakan shell dan manajer paket pilihan Anda. catatan Di Windows, beberapa perintah Bash CLI yang biasa Anda gunakan dengan Lambda ( zip seperti) tidak didukung oleh terminal bawaan sistem operasi. Untuk mendapatkan versi terintegrasi Windows dari Ubuntu dan Bash, instal Windows Subsystem untuk Linux. Buat dua ember Amazon S3 Pertama buat dua ember Amazon S3. Bucket pertama adalah bucket sumber tempat Anda akan mengunggah gambar Anda. Bucket kedua digunakan oleh Lambda untuk menyimpan thumbnail yang diubah ukurannya saat Anda menjalankan fungsi. Konsol Manajemen AWS Untuk membuat bucket Amazon S3 (konsol) Buka konsol Amazon S3 dan pilih halaman Bucket tujuan umum . Pilih yang Wilayah AWS paling dekat dengan lokasi geografis Anda. Anda dapat mengubah wilayah Anda menggunakan daftar drop-down di bagian atas layar. Kemudian dalam tutorial, Anda harus membuat fungsi Lambda Anda di Wilayah yang sama. Pilih Buat bucket . Pada Konfigurasi umum , lakukan hal berikut: Untuk jenis Bucket , pastikan Tujuan umum dipilih. Untuk nama Bucket , masukkan nama unik global yang memenuhi aturan penamaan Amazon S3 Bucket . Nama bucket hanya dapat berisi huruf kecil, angka, titik (.), dan tanda hubung (-). Biarkan semua opsi lain disetel ke nilai defaultnya dan pilih Buat bucket . Ulangi langkah 1 hingga 5 untuk membuat bucket tujuan Anda. Untuk nama Bucket amzn-s3-demo-source-bucket-resized , masukkan, di amzn-s3-demo-source-bucket mana nama bucket sumber yang baru saja Anda buat. AWS CLI Untuk membuat bucket Amazon S3 ()AWS CLI Jalankan perintah CLI berikut untuk membuat bucket sumber Anda. Nama yang Anda pilih untuk bucket Anda harus unik secara global dan ikuti aturan penamaan Amazon S3 Bucket . Nama hanya dapat berisi huruf kecil, angka, titik (.), dan tanda hubung (-). Untuk region dan LocationConstraint , pilih yang paling Wilayah AWS dekat dengan lokasi geografis Anda. aws s3api create-bucket --bucket amzn-s3-demo-source-bucket --region us-east-1 \ --create-bucket-configuration LocationConstraint= us-east-1 Kemudian dalam tutorial, Anda harus membuat fungsi Lambda Anda Wilayah AWS sama dengan bucket sumber Anda, jadi catat wilayah yang Anda pilih. Jalankan perintah berikut untuk membuat bucket tujuan Anda. Untuk nama bucket, Anda harus menggunakan amzn-s3-demo-source-bucket-resized , di amzn-s3-demo-source-bucket mana nama bucket sumber yang Anda buat di langkah 1. Untuk region dan LocationConstraint , pilih yang sama dengan yang Wilayah AWS Anda gunakan untuk membuat bucket sumber Anda. aws s3api create-bucket --bucket amzn-s3-demo-source-bucket-resized --region us-east-1 \ --create-bucket-configuration LocationConstraint= us-east-1 Unggah gambar uji ke bucket sumber Anda Kemudian dalam tutorial, Anda akan menguji fungsi Lambda Anda dengan memanggilnya menggunakan atau konsol Lambda. AWS CLI Untuk mengonfirmasi bahwa fungsi Anda beroperasi dengan benar, bucket sumber Anda harus berisi gambar uji. Gambar ini dapat berupa file JPG atau PNG yang Anda pilih. Konsol Manajemen AWS Untuk mengunggah gambar uji ke bucket sumber Anda (konsol) Buka halaman Bucket konsol Amazon S3. Pilih bucket sumber yang Anda buat di langkah sebelumnya. Pilih Unggah . Pilih Tambahkan file dan gunakan pemilih file untuk memilih objek yang ingin Anda unggah. Pilih Buka , lalu pilih Unggah . AWS CLI Untuk mengunggah gambar uji ke bucket sumber Anda (AWS CLI) Dari direktori yang berisi gambar yang ingin Anda unggah, jalankan perintah CLI berikut. Ganti --bucket parameter dengan nama bucket sumber Anda. Untuk --body parameter --key dan, gunakan nama file gambar pengujian Anda. aws s3api put-object --bucket amzn-s3-demo-source-bucket --key HappyFace.jpg --body ./HappyFace.jpg Membuat kebijakan izin Langkah pertama dalam membuat fungsi Lambda Anda adalah membuat kebijakan izin. Kebijakan ini memberi fungsi Anda izin yang diperlukan untuk mengakses AWS sumber daya lain. Untuk tutorial ini, kebijakan memberikan izin baca dan tulis Lambda untuk bucket Amazon S3 dan memungkinkannya untuk menulis ke Amazon Log. CloudWatch Konsol Manajemen AWS Untuk membuat kebijakan (konsol) Buka halaman Kebijakan konsol AWS Identity and Access Management (IAM). Pilih Buat kebijakan . Pilih tab JSON , lalu tempelkan kebijakan khusus berikut ke editor JSON. { "Version":"2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "logs:PutLogEvents", "logs:CreateLogGroup", "logs:CreateLogStream" ], "Resource": "arn:aws:logs:*:*:*" }, { "Effect": "Allow", "Action": [ "s3:GetObject" ], "Resource": "arn:aws:s3:::*/*" }, { "Effect": "Allow", "Action": [ "s3:PutObject" ], "Resource": "arn:aws:s3:::*/*" } ] } Pilih Berikutnya . Di bawah Detail kebijakan , untuk nama Kebijakan , masukkan LambdaS3Policy . Pilih Buat kebijakan . AWS CLI Untuk membuat kebijakan (AWS CLI) Simpan JSON berikut dalam file bernama policy.json . { "Version":"2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "logs:PutLogEvents", "logs:CreateLogGroup", "logs:CreateLogStream" ], "Resource": "arn:aws:logs:*:*:*" }, { "Effect": "Allow", "Action": [ "s3:GetObject" ], "Resource": "arn:aws:s3:::*/*" }, { "Effect": "Allow", "Action": [ "s3:PutObject" ], "Resource": "arn:aws:s3:::*/*" } ] } Dari direktori tempat Anda menyimpan dokumen kebijakan JSON, jalankan perintah CLI berikut. aws iam create-policy --policy-name LambdaS3Policy --policy-document file://policy.json Membuat peran eksekusi Peran eksekusi adalah peran IAM yang memberikan izin fungsi Lambda untuk mengakses dan sumber daya. Layanan AWS Untuk memberikan akses baca dan tulis fungsi ke bucket Amazon S3, Anda melampirkan kebijakan izin yang Anda buat di langkah sebelumnya. Konsol Manajemen AWS Untuk membuat peran eksekusi dan melampirkan kebijakan izin Anda (konsol) Buka halaman Peran konsol (IAM). Pilih Buat peran . Untuk jenis entitas Tepercaya , pilih Layanan AWS , dan untuk kasus Penggunaan , pilih Lambda . Pilih Berikutnya . Tambahkan kebijakan izin yang Anda buat di langkah sebelumnya dengan melakukan hal berikut: Dalam kotak pencarian kebijakan, masukkan LambdaS3Policy . Dalam hasil pencarian, pilih kotak centang untuk LambdaS3Policy . Pilih Berikutnya . Di bawah Rincian peran , untuk nama Peran masuk LambdaS3Role . Pilih Buat peran . AWS CLI Untuk membuat peran eksekusi dan melampirkan kebijakan izin Anda ()AWS CLI Simpan JSON berikut dalam file bernama trust-policy.json . Kebijakan kepercayaan ini memungkinkan Lambda untuk menggunakan izin peran dengan memberikan lambda.amazonaws.com izin utama layanan untuk memanggil tindakan AWS Security Token Service ()AWS STS. AssumeRole { "Version":"2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": { "Service": "lambda.amazonaws.com" }, "Action": "sts:AssumeRole" } ] } Dari direktori tempat Anda menyimpan dokumen kebijakan kepercayaan JSON, jalankan perintah CLI berikut untuk membuat peran eksekusi. aws iam create-role --role-name LambdaS3Role --assume-role-policy-document file://trust-policy.json Untuk melampirkan kebijakan izin yang Anda buat pada langkah sebelumnya, jalankan perintah CLI berikut. Ganti Akun AWS nomor di ARN polis dengan nomor akun Anda sendiri. aws iam attach-role-policy --role-name LambdaS3Role --policy-arn arn:aws:iam:: 123456789012 :policy/LambdaS3Policy Buat paket penerapan fungsi Untuk membuat fungsi Anda, Anda membuat paket deployment yang berisi kode fungsi dan dependensinya. Untuk CreateThumbnail fungsi ini, kode fungsi Anda menggunakan pustaka terpisah untuk mengubah ukuran gambar. Ikuti instruksi untuk bahasa yang Anda pilih untuk membuat paket penyebaran yang berisi pustaka yang diperlukan. Node.js Untuk membuat paket penyebaran (Node.js) Buat direktori bernama lambda-s3 untuk kode fungsi dan dependensi Anda dan navigasikan ke dalamnya. mkdir lambda-s3 cd lambda-s3 Buat proyek Node.js baru dengan npm . Untuk menerima opsi default yang disediakan dalam pengalaman interaktif, tekan Enter . npm init Simpan kode fungsi berikut dalam file bernama index.mjs . Pastikan untuk mengganti us-east-1 dengan Wilayah AWS di mana Anda membuat ember sumber dan tujuan Anda sendiri. // dependencies import { S3Client, GetObjectCommand, PutObjectCommand } from '@aws-sdk/client-s3'; import { Readable } from 'stream'; import sharp from 'sharp'; import util from 'util'; // create S3 client const s3 = new S3Client( { region: 'us-east-1' }); // define the handler function export const handler = async (event, context) => { // Read options from the event parameter and get the source bucket console.log("Reading options from event:\n", util.inspect(event, { depth: 5})); const srcBucket = event.Records[0].s3.bucket.name; // Object key may have spaces or unicode non-ASCII characters const srcKey = decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g, " ")); const dstBucket = srcBucket + "-resized"; const dstKey = "resized-" + srcKey; // Infer the image type from the file suffix const typeMatch = srcKey.match(/\.([^.]*)$/); if (!typeMatch) { console.log("Could not determine the image type."); return; } // Check that the image type is supported const imageType = typeMatch[1].toLowerCase(); if (imageType != "jpg" && imageType != "png") { console.log(`Unsupported image type: $ { imageType}`); return; } // Get the image from the source bucket. GetObjectCommand returns a stream. try { const params = { Bucket: srcBucket, Key: srcKey }; var response = await s3.send(new GetObjectCommand(params)); var stream = response.Body; // Convert stream to buffer to pass to sharp resize function. if (stream instanceof Readable) { var content_buffer = Buffer.concat(await stream.toArray()); } else { throw new Error('Unknown object stream type'); } } catch (error) { console.log(error); return; } // set thumbnail width. Resize will set the height automatically to maintain aspect ratio. const width = 200; // Use the sharp module to resize the image and save in a buffer. try { var output_buffer = await sharp(content_buffer).resize(width).toBuffer(); } catch (error) { console.log(error); return; } // Upload the thumbnail image to the destination bucket try { const destparams = { Bucket: dstBucket, Key: dstKey, Body: output_buffer, ContentType: "image" }; const putResult = await s3.send(new PutObjectCommand(destparams)); } catch (error) { console.log(error); return; } console.log('Successfully resized ' + srcBucket + '/' + srcKey + ' and uploaded to ' + dstBucket + '/' + dstKey); }; Di lambda-s3 direktori Anda, instal perpustakaan tajam menggunakan npm. Perhatikan bahwa versi terbaru dari sharp (0.33) tidak kompatibel dengan Lambda. Instal versi 0.32.6 untuk menyelesaikan tutorial ini. npm install sharp@0.32.6 install Perintah npm membuat node_modules direktori untuk modul Anda. Setelah langkah ini, struktur direktori Anda akan terlihat seperti berikut. lambda-s3 |- index.mjs |- node_modules | |- base64js | |- bl | |- buffer ... |- package-lock.json |- package.json Buat paket deployment .zip yang berisi kode fungsi Anda dan dependensinya. Di macOS dan Linux, jalankan perintah berikut. zip -r function.zip . Di Windows, gunakan utilitas zip pilihan Anda untuk membuat file.zip. Pastikan bahwa package-lock.json file index.mjs package.json ,, dan node_modules direktori Anda semuanya berada di root file.zip Anda. Python Untuk membuat paket penyebaran (Python) Simpan kode contoh sebagai file bernama lambda_function.py . import boto3 import os import sys import uuid from urllib.parse import unquote_plus from PIL import Image import PIL.Image s3_client = boto3.client('s3') def resize_image(image_path, resized_path): with Image.open(image_path) as image: image.thumbnail(tuple(x / 2 for x in image.size)) image.save(resized_path) def lambda_handler(event, context): for record in event['Records']: bucket = record['s3']['bucket']['name'] key = unquote_plus(record['s3']['object']['key']) tmpkey = key.replace('/', '') download_path = '/tmp/ { } { }'.format(uuid.uuid4(), tmpkey) upload_path = '/tmp/resized- { }'.format(tmpkey) s3_client.download_file(bucket, key, download_path) resize_image(download_path, upload_path) s3_client.upload_file(upload_path, ' { }-resized'.format(bucket), 'resized- { }'.format(key)) Di direktori yang sama di mana Anda membuat lambda_function.py file Anda, buat direktori baru bernama package dan instal pustaka Pillow (PIL) dan AWS SDK untuk Python (Boto3). Meskipun runtime Lambda Python menyertakan versi Boto3 SDK, kami menyarankan agar Anda menambahkan semua dependensi fungsi Anda ke paket penerapan Anda, meskipun mereka disertakan dalam runtime. Untuk informasi selengkapnya, lihat Dependensi runtime dengan Python. mkdir package pip install \ --platform manylinux2014_x86_64 \ --target=package \ --implementation cp \ --python-version 3.12 \ --only-binary=:all: --upgrade \ pillow boto3 Pustaka Pillow berisi kode C/C ++. Dengan menggunakan --only-binary=:all: opsi --platform manylinux_2014_x86_64 dan, pip akan mengunduh dan menginstal versi Pillow yang berisi binari pra-kompilasi yang kompatibel dengan sistem operasi Amazon Linux 2. Ini memastikan bahwa paket penerapan Anda akan berfungsi di lingkungan eksekusi Lambda, terlepas dari sistem operasi dan arsitektur mesin build lokal Anda. Buat file.zip yang berisi kode aplikasi Anda dan pustaka Pillow dan Boto3. Di Linux atau macOS, jalankan perintah berikut dari antarmuka baris perintah Anda. cd package zip -r ../lambda_function.zip . cd .. zip lambda_function.zip lambda_function.py Di Windows, gunakan alat zip pilihan Anda untuk membuat file lambda_function.zip . Pastikan bahwa lambda_function.py file Anda dan folder yang berisi dependensi Anda semuanya berada di root file.zip. Anda juga dapat membuat paket deployment menggunakan lingkungan virtual Python. Lihat Bekerja dengan arsip file.zip untuk fungsi Python Lambda Buat fungsi Lambda Anda dapat membuat fungsi Lambda menggunakan konsol Lambda AWS CLI atau Lambda. Ikuti instruksi untuk bahasa yang Anda pilih untuk membuat fungsi. Konsol Manajemen AWS Untuk membuat fungsi (konsol) Untuk membuat fungsi Lambda Anda menggunakan konsol, pertama-tama Anda membuat fungsi dasar yang berisi beberapa kode 'Hello world'. Anda kemudian mengganti kode ini dengan kode fungsi Anda sendiri dengan mengunggah file the.zip atau JAR yang Anda buat pada langkah sebelumnya. Buka halaman Fungsi di konsol Lambda. Pastikan Anda bekerja di tempat yang sama dengan saat Wilayah AWS Anda membuat bucket Amazon S3. Anda dapat mengubah wilayah Anda menggunakan daftar drop-down di bagian atas layar. Pilih Buat fungsi . Pilih Penulis dari scratch . Di bagian Informasi dasar , lakukan hal berikut: Untuk Nama fungsi , masukkan CreateThumbnail . Untuk Runtime , pilih Node.js 22.x atau Python 3.12 sesuai dengan bahasa yang Anda pilih untuk fungsi Anda. Untuk Arsitektur , pilih x86_64 . Di tab Ubah peran eksekusi default , lakukan hal berikut: Perluas tab, lalu pilih Gunakan peran yang ada . Pilih yang LambdaS3Role Anda buat sebelumnya. Pilih Buat fungsi . Untuk mengunggah kode fungsi (konsol) Di panel Sumber kode , pilih Unggah dari . Pilih file.zip . Pilih Unggah . Di pemilih file, pilih file.zip Anda dan pilih Buka. Pilih Simpan . AWS CLI Untuk membuat fungsi (AWS CLI) Jalankan perintah CLI untuk bahasa yang Anda pilih. Untuk role parameter, pastikan untuk mengganti 123456789012 dengan Akun AWS ID Anda sendiri. Untuk region parameternya, ganti us-east-1 dengan wilayah tempat Anda membuat bucket Amazon S3. Untuk Node.js , jalankan perintah berikut dari direktori yang berisi function.zip file Anda. aws lambda create-function --function-name CreateThumbnail \ --zip-file fileb://function.zip --handler index.handler --runtime nodejs24.x \ --timeout 10 --memory-size 1024 \ --role arn:aws:iam:: 123456789012 :role/LambdaS3Role --region us-east-1 Untuk Python , jalankan perintah berikut dari direktori yang berisi file Anda lambda_function.zip . aws lambda create-function --function-name CreateThumbnail \ --zip-file fileb://lambda_function.zip --handler lambda_function.lambda_handler \ --runtime python3.14 --timeout 10 --memory-size 1024 \ --role arn:aws:iam:: 123456789012 :role/LambdaS3Role --region us-east-1 Konfigurasikan Amazon S3 untuk menjalankan fungsi Agar fungsi Lambda dapat berjalan saat mengunggah gambar ke bucket sumber, Anda perlu mengonfigurasi pemicu untuk fungsi Anda. Anda dapat mengonfigurasi pemicu Amazon S3 menggunakan konsol atau. AWS CLI penting Prosedur ini mengonfigurasi bucket Amazon S3 untuk menjalankan fungsi Anda setiap kali objek dibuat di bucket. Pastikan untuk mengonfigurasi ini hanya di bucket sumber. Jika fungsi Lambda Anda membuat objek dalam bucket yang sama yang memanggilnya, fungsi Anda dapat dipanggil terus menerus dalam satu loop. Hal ini dapat mengakibatkan biaya yang tidak diharapkan ditagih ke Anda Akun AWS. Konsol Manajemen AWS Untuk mengonfigurasi pemicu Amazon S3 (konsol) Buka halaman Fungsi konsol Lambda dan pilih fungsi Anda () CreateThumbnail . Pilih Tambahkan pemicu . Pilih S3 . Di bawah Bucket , pilih bucket sumber Anda. Di bawah Jenis acara , pilih Semua objek membuat acara . Di bawah Pemanggilan rekursif , pilih kotak centang untuk mengetahui bahwa tidak disarankan menggunakan bucket Amazon S3 yang sama untuk input dan output. Anda dapat mempelajari lebih lanjut tentang pola pemanggilan rekursif di Lambda dengan membaca pola rekursif yang menyebabkan fungsi Lambda yang tidak terkendali di Tanah Tanpa Server. Pilih Tambahkan . Saat Anda membuat pemicu menggunakan konsol Lambda, Lambda secara otomatis membuat kebijakan berbasis sumber daya untuk memberikan layanan yang Anda pilih izin untuk menjalankan fungsi Anda. AWS CLI Untuk mengonfigurasi pemicu Amazon S3 ()AWS CLI Agar bucket sumber Amazon S3 menjalankan fungsi saat menambahkan file gambar, pertama-tama Anda harus mengonfigurasi izin untuk fungsi menggunakan kebijakan berbasis sumber daya. Pernyataan kebijakan berbasis sumber daya memberikan Layanan AWS izin lain untuk menjalankan fungsi Anda. Untuk memberikan izin Amazon S3 untuk menjalankan fungsi Anda, jalankan perintah CLI berikut. Pastikan untuk mengganti source-account parameter dengan Akun AWS ID Anda sendiri dan menggunakan nama bucket sumber Anda sendiri. aws lambda add-permission --function-name CreateThumbnail \ --principal s3.amazonaws.com --statement-id s3invoke --action "lambda:InvokeFunction" \ --source-arn arn:aws:s3::: amzn-s3-demo-source-bucket \ --source-account 123456789012 Kebijakan yang Anda tetapkan dengan perintah ini memungkinkan Amazon S3 untuk menjalankan fungsi Anda hanya ketika tindakan dilakukan di bucket sumber Anda. catatan Meskipun nama bucket Amazon S3 unik secara global, saat menggunakan kebijakan berbasis sumber daya, praktik terbaik adalah menentukan bahwa bucket harus menjadi milik akun Anda. Ini karena jika Anda menghapus bucket, Anda dapat membuat bucket dengan Amazon Resource Name (ARN) yang sama. Akun AWS Simpan JSON berikut dalam file bernama notification.json . Saat diterapkan ke bucket sumber Anda, JSON ini mengonfigurasi bucket untuk mengirim notifikasi ke fungsi Lambda Anda setiap kali objek baru ditambahkan. Ganti Akun AWS nomor dan Wilayah AWS dalam fungsi Lambda ARN dengan nomor akun dan wilayah Anda sendiri. { "LambdaFunctionConfigurations": [ { "Id": "CreateThumbnailEventConfiguration", "LambdaFunctionArn": "arn:aws:lambda: us-east-1:123456789012 :function:CreateThumbnail", "Events": [ "s3:ObjectCreated:Put" ] } ] } Jalankan perintah CLI berikut untuk menerapkan pengaturan notifikasi dalam file JSON yang Anda buat ke bucket sumber Anda. Ganti amzn-s3-demo-source-bucket dengan nama bucket sumber Anda sendiri. aws s3api put-bucket-notification-configuration --bucket amzn-s3-demo-source-bucket \ --notification-configuration file://notification.json Untuk mempelajari lebih lanjut tentang put-bucket-notification-configuration perintah dan notification-configuration opsi, lihat put-bucket-notification-configuration di Referensi Perintah AWS CLI . Uji fungsi Lambda Anda dengan acara dummy Sebelum menguji seluruh penyiapan dengan menambahkan file gambar ke bucket sumber Amazon S3, Anda menguji apakah fungsi Lambda berfungsi dengan benar dengan memanggilnya dengan acara dummy. Peristiwa di Lambda adalah dokumen berformat JSON yang berisi data untuk diproses fungsi Anda. Saat fungsi Anda dipanggil oleh Amazon S3, peristiwa yang dikirim ke fungsi berisi informasi seperti nama bucket, ARN bucket, dan kunci objek. Konsol Manajemen AWS Untuk menguji fungsi Lambda Anda dengan acara dummy (konsol) Buka halaman Fungsi konsol Lambda dan pilih fungsi Anda () CreateThumbnail . Pilih tab Uji . Untuk membuat acara pengujian, di panel acara Uji , lakukan hal berikut: Di bawah Uji tindakan peristiwa , pilih Buat acara baru . Untuk Nama peristiwa , masukkan myTestEvent . Untuk Template , pilih S3 Put . Ganti nilai untuk parameter berikut dengan nilai Anda sendiri. Untuk awsRegion , ganti us-east-1 dengan bucket Amazon S3 yang Wilayah AWS Anda buat. Untuk name , ganti amzn-s3-demo-bucket dengan nama bucket sumber Amazon S3 Anda sendiri. Untuk key , ganti test%2Fkey dengan nama file objek pengujian yang Anda unggah ke bucket sumber di langkah tersebut. Unggah gambar uji ke bucket sumber Anda { "Records": [ { "eventVersion": "2.0", "eventSource": "aws:s3", "awsRegion": "us-east-1" , "eventTime": "1970-01-01T00:00:00.000Z", "eventName": "ObjectCreated:Put", "userIdentity": { "principalId": "EXAMPLE" }, "requestParameters": { "sourceIPAddress": "127.0.0.1" }, "responseElements": { "x-amz-request-id": "EXAMPLE123456789", "x-amz-id-2": "EXAMPLE123/5678abcdefghijklambdaisawesome/mnopqrstuvwxyzABCDEFGH" }, "s3": { "s3SchemaVersion": "1.0", "configurationId": "testConfigRule", "bucket": { "name": "amzn-s3-demo-bucket" , "ownerIdentity": { "principalId": "EXAMPLE" }, "arn": "arn:aws:s3:::amzn-s3-demo-bucket" }, "object": { "key": "test%2Fkey" , "size": 1024, "eTag": "0123456789abcdef0123456789abcdef", "sequencer": "0A1B2C3D4E5F678901" } } } ] } Pilih Simpan . Di panel acara Uji , pilih Uji . Untuk memeriksa fungsi Anda telah membuat verison yang diubah ukurannya dari gambar Anda dan menyimpannya di bucket Amazon S3 target Anda, lakukan hal berikut: Buka halaman Bucket konsol Amazon S3. Pilih bucket target Anda dan konfirmasikan bahwa file yang diubah ukurannya tercantum di panel Objects . AWS CLI Untuk menguji fungsi Lambda Anda dengan acara dummy ()AWS CLI Simpan JSON berikut dalam file bernama dummyS3Event.json . Ganti nilai untuk parameter berikut dengan nilai Anda sendiri: Untuk awsRegion , ganti us-east-1 dengan bucket Amazon S3 yang Wilayah AWS Anda buat. Untuk name , ganti amzn-s3-demo-bucket dengan nama bucket sumber Amazon S3 Anda sendiri. Untuk key , ganti test%2Fkey dengan nama file objek pengujian yang Anda unggah ke bucket sumber di langkah tersebut. Unggah gambar uji ke bucket sumber Anda { "Records": [ { "eventVersion": "2.0", "eventSource": "aws:s3", "awsRegion": "us-east-1" , "eventTime": "1970-01-01T00:00:00.000Z", "eventName": "ObjectCreated:Put", "userIdentity": { "principalId": "EXAMPLE" }, "requestParameters": { "sourceIPAddress": "127.0.0.1" }, "responseElements": { "x-amz-request-id": "EXAMPLE123456789", "x-amz-id-2": "EXAMPLE123/5678abcdefghijklambdaisawesome/mnopqrstuvwxyzABCDEFGH" }, "s3": { "s3SchemaVersion": "1.0", "configurationId": "testConfigRule", "bucket": { "name": "amzn-s3-demo-bucket" , "ownerIdentity": { "principalId": "EXAMPLE" }, "arn": "arn:aws:s3:::amzn-s3-demo-bucket" }, "object": { "key": "test%2Fkey" , "size": 1024, "eTag": "0123456789abcdef0123456789abcdef", "sequencer": "0A1B2C3D4E5F678901" } } } ] } Dari direktori tempat Anda menyimpan dummyS3Event.json file Anda, panggil fungsi dengan menjalankan perintah CLI berikut. Perintah ini memanggil fungsi Lambda Anda secara sinkron dengan RequestResponse menentukan sebagai nilai parameter tipe pemanggilan. Untuk mempelajari lebih lanjut tentang pemanggilan sinkron dan asinkron, lihat Memanggil fungsi Lambda. aws lambda invoke --function-name CreateThumbnail \ --invocation-type RequestResponse --cli-binary-format raw-in-base64-out \ --payload file://dummyS3Event.json outputfile.txt cli-binary-formatOpsi ini diperlukan jika Anda menggunakan versi 2 dari AWS CLI. Untuk menjadikan ini pengaturan default, jalankan aws configure set cli-binary-format raw-in-base64-out . Untuk informasi selengkapnya, lihat opsi baris perintah global yang AWS CLI didukung . Verifikasi bahwa fungsi Anda telah membuat versi thumbnail gambar Anda dan menyimpannya ke bucket Amazon S3 target Anda. Jalankan perintah CLI berikut, ganti amzn-s3-demo-source-bucket-resized dengan nama bucket tujuan Anda sendiri. aws s3api list-objects-v2 --bucket amzn-s3-demo-source-bucket-resized Anda akan melihat output seperti yang berikut ini. Key Parameter menunjukkan nama file file gambar Anda yang diubah ukurannya. { "Contents": [ { "Key": "resized-HappyFace.jpg", "LastModified": "2023-06-06T21:40:07+00:00", "ETag": "\"d8ca652ffe83ba6b721ffc20d9d7174a\"", "Size": 2633, "StorageClass": "STANDARD" } ] } Uji fungsi Anda menggunakan pemicu Amazon S3 Sekarang setelah Anda mengonfirmasi bahwa fungsi Lambda Anda beroperasi dengan benar, Anda siap untuk menguji penyiapan lengkap Anda dengan menambahkan file gambar ke bucket sumber Amazon S3 Anda. Saat Anda menambahkan gambar ke bucket sumber, fungsi Lambda Anda akan dipanggil secara otomatis. Fungsi Anda membuat versi file yang diubah ukurannya dan menyimpannya di bucket target Anda. Konsol Manajemen AWS Untuk menguji fungsi Lambda Anda menggunakan pemicu Amazon S3 (konsol) Untuk mengunggah gambar ke bucket Amazon S3 Anda, lakukan hal berikut: Buka halaman Bucket di konsol Amazon S3 dan pilih bucket sumber Anda. Pilih Unggah . Pilih Tambahkan file dan gunakan pemilih file untuk memilih file gambar yang ingin Anda unggah. Objek gambar Anda dapat berupa file.jpg atau.png. Pilih Buka , lalu pilih Unggah . Verifikasi bahwa Lambda telah menyimpan versi file gambar yang diubah ukurannya di bucket target dengan melakukan hal berikut: Arahkan kembali ke halaman Bucket di konsol Amazon S3 dan pilih bucket tujuan Anda. Di panel Objects , Anda sekarang akan melihat dua file gambar yang diubah ukurannya, satu dari setiap pengujian fungsi Lambda Anda. Untuk mengunduh gambar yang diubah ukurannya, pilih file, lalu pilih Unduh . AWS CLI Untuk menguji fungsi Lambda Anda menggunakan pemicu Amazon S3 ()AWS CLI Dari direktori yang berisi gambar yang ingin Anda unggah, jalankan perintah CLI berikut. Ganti --bucket parameter dengan nama bucket sumber Anda. Untuk --body parameter --key dan, gunakan nama file gambar pengujian Anda. Gambar uji Anda dapat berupa file.jpg atau.png. aws s3api put-object --bucket amzn-s3-demo-source-bucket --key SmileyFace.jpg --body ./SmileyFace.jpg Verifikasi bahwa fungsi Anda telah membuat versi thumbnail gambar Anda dan menyimpannya ke bucket Amazon S3 target Anda. Jalankan perintah CLI berikut, ganti amzn-s3-demo-source-bucket-resized dengan nama bucket tujuan Anda sendiri. aws s3api list-objects-v2 --bucket amzn-s3-demo-source-bucket-resized Jika fungsi Anda berjalan dengan sukses, Anda akan melihat output yang mirip dengan berikut ini. Bucket target Anda sekarang harus berisi dua file yang diubah ukurannya. { "Contents": [ { "Key": "resized-HappyFace.jpg", "LastModified": "2023-06-07T00:15:50+00:00", "ETag": "\"7781a43e765a8301713f533d70968a1e\"", "Size": 2763, "StorageClass": "STANDARD" }, { "Key": "resized-SmileyFace.jpg", "LastModified": "2023-06-07T00:13:18+00:00", "ETag": "\"ca536e5a1b9e32b22cd549e18792cdbc\"", "Size": 1245, "StorageClass": "STANDARD" } ] } Bersihkan sumber daya Anda Sekarang Anda dapat menghapus sumber daya yang Anda buat untuk tutorial ini, kecuali Anda ingin mempertahankannya. Dengan menghapus AWS sumber daya yang tidak lagi Anda gunakan, Anda mencegah tagihan yang tidak perlu ke Anda Akun AWS. Untuk menghapus fungsi Lambda Buka halaman Fungsi di konsol Lambda. Pilih fungsi yang Anda buat. Pilih Tindakan , Hapus . Ketik confirm kolom input teks dan pilih Hapus . Untuk menghapus kebijakan yang Anda buat. Buka halaman Kebijakan konsol IAM. Pilih kebijakan yang Anda buat ( AWSLambdaS3Policy ). Pilih Tindakan kebijakan , Hapus . Pilih Hapus . Untuk menghapus peran eksekusi Buka halaman Peran dari konsol IAM. Pilih peran eksekusi yang Anda buat. Pilih Hapus . Masukkan nama peran di bidang input teks dan pilih Hapus . Untuk menghapus bucket S3 Buka konsol Amazon S3 . Pilih bucket yang Anda buat. Pilih Hapus . Masukkan nama ember di bidang input teks. Pilih Hapus bucket . Javascript dinonaktifkan atau tidak tersedia di browser Anda. Untuk menggunakan Dokumentasi AWS, Javascript harus diaktifkan. Lihat halaman Bantuan browser Anda untuk petunjuk. Konvensi Dokumen Tutorial: Menggunakan pemicu S3 Secrets Manager Apakah halaman ini membantu Anda? - Ya Terima kasih telah memberitahukan bahwa hasil pekerjaan kami sudah baik. Jika Anda memiliki waktu luang, beri tahu kami aspek apa saja yang sudah bagus, agar kami dapat menerapkannya secara lebih luas. Apakah halaman ini membantu Anda? - Tidak Terima kasih telah memberi tahu kami bahwa halaman ini perlu ditingkatkan. Maaf karena telah mengecewakan Anda. Jika Anda memiliki waktu luang, beri tahu kami bagaimana dokumentasi ini dapat ditingkatkan. | 2026-01-13T09:30:35 |
https://docs.aws.amazon.com/es_es/AmazonCloudFront/latest/DeveloperGuide/lambda-examples.html#lambda-examples-content-based-routing-examples | Funciones de ejemplo de Lambda@Edge - Amazon CloudFront Funciones de ejemplo de Lambda@Edge - Amazon CloudFront Documentación Amazon CloudFront Guía para desarrolladores Ejemplos generales Generación de respuestas: ejemplos Cadenas de consulta: ejemplos Personalización de contenido por encabezados de tipo de dispositivo o país: ejemplos Selección de origen dinámico basada en contenido: ejemplos Actualización de estados de error: ejemplos Acceso al cuerpo de la solicitud: ejemplos Funciones de ejemplo de Lambda@Edge Consulte los ejemplos siguientes para usar funciones de Lambda con Amazon CloudFront. nota Si elige el tiempo de ejecución Node.js 18 o una versión posterior para la función Lambda@Edge, se creará automáticamente un archivo index.mjs . Para usar los siguientes ejemplos de código, cambie el nombre del archivo index.mjs a index.js . Temas Ejemplos generales Generación de respuestas: ejemplos Cadenas de consulta: ejemplos Personalización de contenido por encabezados de tipo de dispositivo o país: ejemplos Selección de origen dinámico basada en contenido: ejemplos Actualización de estados de error: ejemplos Acceso al cuerpo de la solicitud: ejemplos Ejemplos generales Los ejemplos siguientes muestran formas habituales de usar Lambda@Edge en CloudFront. Temas Ejemplo: prueba A/B Ejemplo: Sobrescritura de un encabezado de respuesta Ejemplo: prueba A/B Puede utilizar el siguiente ejemplo para probar dos versiones diferentes de una imagen sin crear redirecciones ni cambiar la dirección URL. En este ejemplo se leen las cookies de la solicitud del lector y se modifica la URL de la solicitud en consecuencia. Si el espectador no envía una cookie con uno de los valores esperados, el ejemplo asigna aleatoriamente al espectador una de las URL. 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; } 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; } } 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" ''' experimentUri = "" 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 Ejemplo: Sobrescritura de un encabezado de respuesta En el ejemplo siguiente, se muestra cómo cambiar el valor de un encabezado de respuesta según el valor de otro encabezado. Node.js export const handler = async (event) => { 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()] = [ { key: headerNameDst, value: headers[headerNameSrc.toLowerCase()][0].value, }]; console.log(`Response header "$ { headerNameDst}" was set to ` + `"$ { headers[headerNameDst.toLowerCase()][0].value}"`); } return response; }; Python import json def lambda_handler(event, context): response = event['Records'][0]['cf']['response'] headers = response['headers'] header_name_src = 'X-Amz-Meta-Last-Modified' header_name_dst = 'Last-Modified' if headers.get(header_name_src.lower()): headers[header_name_dst.lower()] = [ { 'key': header_name_dst, 'value': headers[header_name_src.lower()][0]['value'] }] print(f'Response header " { header_name_dst}" was set to ' f'" { headers[header_name_dst.lower()][0]["value"]}"') return response Generación de respuestas: ejemplos En los ejemplos siguientes se muestra cómo puede usar Lambda@Edge para generar respuestas. Temas Ejemplo: Envío de contenido estático (respuesta generada) Ejemplo: Generación de un redireccionamiento HTTP (respuesta generada) Ejemplo: Envío de contenido estático (respuesta generada) En el siguiente ejemplo se muestra cómo utilizar una función de Lambda para enviar contenido de sitio web estático, lo que reduce la carga en el servidor de origen y la latencia total. nota Puede generar respuestas HTTP para los eventos de solicitud del espectador y al origen. Para obtener más información, consulte Generación de respuestas HTTP en los desencadenadores de solicitud . También puede sustituir o quitar el cuerpo de la respuesta HTTP en eventos de respuesta de origen. Para obtener más información, consulte Actualización de respuestas HTTP en desencadenadores de respuesta de origen . 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' }] }, 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 } return response Ejemplo: Generación de un redireccionamiento HTTP (respuesta generada) En el siguiente ejemplo se muestra cómo generar una redirección HTTP. nota Puede generar respuestas HTTP para los eventos de solicitud del espectador y al origen. Para obtener más información, consulte Generación de respuestas HTTP en los desencadenadores de solicitud . 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. response = { 'status': '302', 'statusDescription': 'Found', 'headers': { 'location': [ { 'key': 'Location', 'value': 'https://docs.aws.amazon.com/lambda/latest/dg/lambda-edge.html' }] } } return response Cadenas de consulta: ejemplos En los ejemplos siguientes se muestran formas de usar Lambda@Edge con cadenas de consulta. Temas Ejemplo: Adición de un encabezado en función de un parámetro de la cadena de consulta Ejemplo: Normalización de parámetros de cadenas de consulta para mejorar la tasa de aciertos de caché Ejemplo: Redireccionamiento de los usuarios no autenticados a una página de inicio de sesión Ejemplo: Adición de un encabezado en función de un parámetro de la cadena de consulta El siguiente ejemplo muestra cómo obtener el par clave-valor de un parámetro de la cadena de consulta y, a continuación, añadir un encabezado en función de dichos valores. 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. * 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 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'] # Update request querystring request['querystring'] = urlencode(params) return request Ejemplo: Normalización de parámetros de cadenas de consulta para mejorar la tasa de aciertos de caché El siguiente ejemplo muestra cómo mejorar la tasa de acceso a la caché haciendo los siguientes cambios en las cadenas de consulta antes de que CloudFront reenvíe las solicitudes a su origen: Alfabetizar los pares de clave-valor por el nombre del parámetro. Cambiar a minúsculas el modelo de mayúsculas y minúsculas de los pares de clave-valor. Para obtener más información, consulte Almacenamiento en caché de contenido en función de parámetros de cadenas de consulta . 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 */ 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 request['querystring'] = urlencode(sortedParams) return request Ejemplo: Redireccionamiento de los usuarios no autenticados a una página de inicio de sesión El siguiente ejemplo muestra cómo redirigir a los usuarios una página de inicio de sesión si no ha introducido sus credenciales. 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; } /* 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 params. ''' # Check for session-id in cookie, if present, then proceed with request parsedCookies = parseCookies(headers) 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 Personalización de contenido por encabezados de tipo de dispositivo o país: ejemplos En los ejemplos siguientes se muestra cómo puede usar Lambda@Edge para personalizar el comportamiento en función de la ubicación o el tipo de dispositivo que usa el lector. Temas Ejemplo: Redireccionamiento de solicitudes de espectadores a una URL específica de un país Ejemplo: Envío de distintas versiones de un objeto en función del dispositivo Ejemplo: Redireccionamiento de solicitudes de espectadores a una URL específica de un país El siguiente ejemplo muestra cómo generar una respuesta de redireccionamiento HTTP con una URL específica del país y devolver la respuesta al espectador. Esto resulta útil cuando se quiere proporcionar respuestas específicas del país. Por ejemplo: Si tiene subdominios específicos de un país, como us.ejemplo.com y tw.ejemplo.com, puede generar una respuesta de redireccionamiento cuando un espectador solicite ejemplo.com. Si está haciendo streaming de video, pero no tiene derechos para transmitir el contenido en un país determinado, puede redirigir a los usuarios de dicho país a una página en la que se explica por qué no pueden ver el video. Tenga en cuenta lo siguiente: Debe configurar la distribución para almacenar en la caché en función del encabezado CloudFront-Viewer-Country . Para obtener más información, consulte Caché en función de encabezados de solicitud seleccionados . CloudFront agrega el encabezado CloudFront-Viewer-Country después del evento de solicitud del lector. Para utilizar este ejemplo, debe crear un activador para el evento de solicitud al origen. 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 = { 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', 'statusDescription': 'Found', 'headers': { 'location': [ { 'key': 'Location', 'value': url }] } } return response Ejemplo: Envío de distintas versiones de un objeto en función del dispositivo El siguiente ejemplo muestra cómo ofrecer distintas versiones de un objeto en función del tipo de dispositivo que el usuario está utilizando; por ejemplo, un dispositivo móvil o una tablet. Tenga en cuenta lo siguiente: Debe configurar la distribución para almacenar en la caché en función de los encabezados CloudFront-Is-*-Viewer . Para obtener más información, consulte Caché en función de encabezados de solicitud seleccionados . CloudFront agrega los encabezados CloudFront-Is-*-Viewer después del evento de solicitud del lector. Para utilizar este ejemplo, debe crear un activador para el evento de solicitud al origen. 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 * 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. ''' desktopPath = '/desktop'; mobilePath = '/mobile'; tabletPath = '/tablet'; smarttvPath = '/smarttv'; 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 Selección de origen dinámico basada en contenido: ejemplos En los ejemplos siguientes se muestra cómo puede usar Lambda@Edge para el direccionamiento a diferentes orígenes en función de la información de la solicitud. Temas Ejemplo: Uso de un desencadenador de solicitud de origen para cambiar desde un origen personalizado a un origen de Amazon S3 Ejemplo: Uso de un desencadenador de solicitud de origen para cambiar la región de origen de Amazon S3 Ejemplo: Uso de un desencadenador de solicitud de origen para cambiar desde un origen de Amazon S3 a un origen personalizado Ejemplo: Uso de un desencadenador de solicitud al origen para transferir gradualmente el tráfico desde un bucket de Amazon S3 a otro Ejemplo: Uso de un desencadenador de solicitud de origen para cambiar el nombre del dominio de origen en función del encabezado de país Ejemplo: Uso de un desencadenador de solicitud de origen para cambiar desde un origen personalizado a un origen de Amazon S3 Esta función demuestra cómo utilizar un desencadenador de solicitud al origen para cambiar desde un origen personalizado a un origen de Amazon S3 desde el que recuperar el contenido, en función de las propiedades de la solicitud. 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: 'origin-access-identity', path: '', customHeaders: { } } }; request.headers['host'] = [ { key: 'host', value: s3DomainName}]; } } 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 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': 'origin-access-identity', 'path': '', 'customHeaders': { } } } request['headers']['host'] = [ { 'key': 'host', 'value': s3DomainName}] return request Ejemplo: Uso de un desencadenador de solicitud de origen para cambiar la región de origen de Amazon S3 Esta función demuestra cómo utilizar un desencadenador de solicitud al origen para cambiar el origen de Amazon S3 desde el que se recupera el contenido, en función de las propiedades de la solicitud. En este ejemplo, utilizamos el valor del encabezado CloudFront-Viewer-Country para actualizar el nombre de dominio del bucket de S3 por un bucket de una región que está más cerca del lector. Esto puede resultar útil de varias maneras: Reduce las latencias cuando la región especificada está más cerca del país del lector. Proporciona soberanía de los datos, al asegurarse de que los datos se distribuyen desde un origen que está en el país del que provino la solicitud. Para utilizar este ejemplo, debe hacer lo siguiente: Configure la distribución para almacenar en la caché en función del encabezado CloudFront-Viewer-Country . Para obtener más información, consulte Caché en función de encabezados de solicitud seleccionados . Crear un disparador para esta función en el evento de solicitud al origen. CloudFront agrega el encabezado CloudFront-Viewer-Country después del evento de solicitud del lector; por lo tanto, para utilizar este ejemplo, debe asegurarse de que la función ejecuta una solicitud de origen. nota El siguiente código de ejemplo usa la misma identidad de acceso de origen (OAI) para todos los buckets de S3 que usa para el origen. Para obtener más información, consulte Identidad de acceso de origen . 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 * 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); }; Python 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: 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: ''' 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 Ejemplo: Uso de un desencadenador de solicitud de origen para cambiar desde un origen de Amazon S3 a un origen personalizado Esta función demuestra cómo utilizar un disparador de solicitud al origen para cambiar el origen personalizado desde el que se recupera el contenido, en función de las propiedades de la solicitud. 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: { 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': { } } } request['headers']['host'] = [ { 'key': 'host', 'value': 'www.example.com'}] return request Ejemplo: Uso de un desencadenador de solicitud al origen para transferir gradualmente el tráfico desde un bucket de Amazon S3 a otro Esta función demuestra cómo transferir gradualmente el tráfico desde un bucket de Amazon S3 a otro de forma controlada. 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}]; } 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 Ejemplo: Uso de un desencadenador de solicitud de origen para cambiar el nombre del dominio de origen en función del encabezado de país Esta función demuestra cómo cambiar el nombre del dominio de origen en función del encabezado CloudFront-Viewer-Country , de forma que el contenido se distribuya desde un origen más cercano al país del lector. La implementación de esta funcionalidad para su distribución puede tener ventajas como las siguientes: Reducir las latencias cuando la región especificada está más cerca del país del lector Proporcionar soberanía de los datos, al asegurarse de que los datos se distribuyen desde un origen que está en el país del que provino la solicitud Tenga en cuenta que para habilitar esta funcionalidad, debe configurar su distribución para almacenar en la caché en función del encabezado CloudFront-Viewer-Country . Para obtener más información, consulte Caché en función de encabezados de solicitud seleccionados . 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 request['headers']['host'] = [ { 'key': 'host', 'value': domainName}] return request Actualización de estados de error: ejemplos En los ejemplos siguientes se proporciona orientación acerca de cómo puede usar Lambda@Edge para cambiar el estado de error que se devuelve a los usuarios. Temas Ejemplo: Uso de un desencadenador de respuesta de origen para actualizar el código de estado de error a 200 Ejemplo: Uso de un desencadenador de respuesta de origen para actualizar el código de estado de error a 302 Ejemplo: Uso de un desencadenador de respuesta de origen para actualizar el código de estado de error a 200 Esta función demuestra cómo actualizar el estado de la respuesta a 200 y generar un cuerpo con contenido estático para devolverlo al espectador en la siguiente situación: La función se desencadena en una respuesta del origen. El estado de la respuesta del servidor de origen es un código de estado de error (4xx o 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'; } callback(null, response); }; Python 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 Ejemplo: Uso de un desencadenador de respuesta de origen para actualizar el código de estado de error a 302 Esta función demuestra cómo actualizar el código de estado HTTP a 302 para la redirección a otra ruta (comportamiento de la caché) en la que se ha configurado un origen diferente. Tenga en cuenta lo siguiente: La función se desencadena en una respuesta del origen. El estado de la respuesta del servidor de origen es un código de estado de error (4xx o 5xx). Node.js 'use strict'; exports.handler = (event, context, callback) => { const response = event.Records[0].cf.response; const 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 (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 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 Acceso al cuerpo de la solicitud: ejemplos En los ejemplos siguientes se muestra cómo puede usar Lambda@Edge para trabajar con las solicitudes POST. nota Para utilizar estos ejemplos, debe habilitar la opción incluir cuerpo en la asociación de funciones Lambda de la distribución. No está habilitada de forma predeterminada. Para habilitar esta configuración en la consola de CloudFront, seleccione la casilla de verificación Incluir cuerpo en la Asociación de funciones Lambda . Para habilitar esta configuración en la API de CloudFront o con CloudFormation, establezca el campo IncludeBody en true en LambdaFunctionAssociation . Temas Ejemplo: Uso de un desencadenador de solicitud para leer un formulario HTML Ejemplo: Uso de un desencadenador de solicitud para modificar un formulario HTML Ejemplo: Uso de un desencadenador de solicitud para leer un formulario HTML Esta función ilustra cómo puede procesar el cuerpo de una solicitud POST generada por un formulario HTML (formulario web), como por ejemplo un formulario tipo "póngase en contacto con nosotros". Por ejemplo, es posible que tenga un formulario HTML como el siguiente: <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> Para la función de ejemplo que se indica a continuación, la función se debe desencadenar en una solicitud al origen o del lector de CloudFront. 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 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 Ejemplo: Uso de un desencadenador de solicitud para modificar un formulario HTML Esta función ilustra cómo puede modificar el cuerpo de una solicitud POST generada por un formulario HTML (formulario web). La función se activa en una solicitud al origen o del lector de CloudFront. 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. * * 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'] | 2026-01-13T09:30:35 |
https://docs.aws.amazon.com/it_it/lambda/latest/dg/with-s3-example.html | Tutorial: uso di un trigger Amazon S3 per richiamare una funzione Lambda - AWS Lambda Tutorial: uso di un trigger Amazon S3 per richiamare una funzione Lambda - AWS Lambda Documentazione AWS Lambda Guida per gli sviluppatori Crea un bucket Amazon S3 Caricamento di un oggetto di test in un bucket Creazione di una policy di autorizzazione Creazione di un ruolo di esecuzione Creazione della funzione Lambda Implementazione del codice della funzione Creazione del trigger Amazon S3 Test della funzione Lambda Pulizia delle risorse Fasi successive Le traduzioni sono generate tramite traduzione automatica. In caso di conflitto tra il contenuto di una traduzione e la versione originale in Inglese, quest'ultima prevarrà. Tutorial: uso di un trigger Amazon S3 per richiamare una funzione Lambda In questo tutorial si utilizzerà la console per creare una funzione Lambda e configurare un trigger per un bucket Amazon Simple Storage Service (Amazon S3). Ogni volta che aggiungi un oggetto al tuo bucket Amazon S3, la funzione viene eseguita e invia il tipo di oggetto in Amazon Logs. CloudWatch Questo tutorial dimostra come: Crea un bucket Amazon S3. Crea una funzione Lambda che restituisce il tipo di oggetto in un bucket Amazon S3. Configura un trigger Lambda che richiami la tua funzione quando gli oggetti vengono caricati nel bucket. Prova la tua funzione, prima con un evento fittizio e poi usando il trigger. Completando questi passaggi, imparerai come configurare una funzione Lambda da eseguire ogni volta che vengono aggiunti o eliminati oggetti da un bucket Amazon S3. Puoi completare questo tutorial soltanto dalla Console di gestione AWS. Crea un bucket Amazon S3 Come creare un bucket Amazon S3. Apri la console Amazon S3 e seleziona la pagina General Purpose bucket . Seleziona quello più Regione AWS vicino alla tua posizione geografica. Puoi modificare la regione utilizzando l'elenco a discesa nella parte superiore dello schermo. Più avanti nel tutorial, è necessario creare la funzione Lambda nella stessa regione. Scegliere Create bucket (Crea bucket) . In General configuration (Configurazione generale) , eseguire le operazioni seguenti: Per Tipo di secchio , assicurati che sia selezionata l' opzione Uso generale . Per Nome del bucket , inserisci un nome univoco globale che soddisfi le regole di denominazione dei bucket di Amazon S3. I nomi dei bucket possono contenere solo lettere minuscole, numeri, punti (.) e trattini (-). Lascia tutte le altre opzioni impostate sui valori predefiniti e scegli Crea bucket . Caricamento di un oggetto di test in un bucket Caricamento di un oggetto di test Apri la pagina Bucket della console Amazon S3 e scegli il bucket che hai creato durante il passaggio precedente. Scegli Carica . Scegli Aggiungi file e seleziona l'oggetto da caricare. È possibile selezionare qualsiasi file (ad esempio, HappyFace.jpg ). Seleziona Apri , quindi Carica . Più avanti nel tutorial, testerai la funzione Lambda utilizzando questo oggetto. Creazione di una policy di autorizzazione Crea una politica di autorizzazioni che consenta a Lambda di ottenere oggetti da un bucket Amazon S3 e di scriverli su Amazon Logs. CloudWatch Come creare la policy Apri la pagina Policies (Policy) nella console IAM. Scegli Crea policy . Scegliere la scheda JSON e quindi incollare la seguente policy personalizzata nell'editor JSON. JSON { "Version":"2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "logs:PutLogEvents", "logs:CreateLogGroup", "logs:CreateLogStream" ], "Resource": "arn:aws:logs:*:*:*" }, { "Effect": "Allow", "Action": [ "s3:GetObject" ], "Resource": "arn:aws:s3:::*/*" } ] } Scegliere Next: Tags (Successivo: Tag) . Scegliere Next:Review (Successivo: Rivedi) . In Rivedi policy , per Nome della policy inserisci s3-trigger-tutorial . Scegli Crea policy . Creazione di un ruolo di esecuzione Un ruolo di esecuzione è un ruolo AWS Identity and Access Management (IAM) che concede a una funzione Lambda l'autorizzazione all' Servizi AWS accesso e alle risorse. In questa fase, creare un ruolo di esecuzione utilizzando la policy di autorizzazioni creata nel passaggio precedente. Creazione di un ruolo di esecuzione e collegamento di una policy di autorizzazione personalizzata Aprire la pagina Roles (Ruoli) della console IAM. Scegli Crea ruolo . Per il tipo di entità attendibile, scegli Servizio AWS , quindi per il caso d'uso seleziona Lambda . Scegli Next (Successivo) . Nella casella di ricerca delle policy, immettere s3-trigger-tutorial . Nei risultati della ricerca, seleziona la policy creata ( s3-trigger-tutorial ), quindi scegli Next (Successivo). In Role details (Dettagli del ruolo), per Role name (Nome del ruolo), specifica lambda-s3-trigger-role , quindi scegli Create role (Crea ruolo). Creazione della funzione Lambda Crea una funzione Lambda nella console usando il runtime Python 3.14. Creazione della funzione Lambda Aprire la pagina Funzioni della console Lambda. Assicurati di lavorare nello stesso bucket in Regione AWS cui hai creato il tuo bucket Amazon S3. Puoi modificare la regione utilizzando l'elenco a discesa nella parte superiore dello schermo. Scegli Crea funzione . Scegli Crea da zero . In Basic information (Informazioni di base) eseguire queste operazioni: Nel campo Nome funzione , inserisci s3-trigger-tutorial . Per Runtime , scegli Python 3.14 . In Architecture (Architettura), scegli x86_64 . Nella scheda Modifica ruolo di esecuzione predefinito , effettua le seguenti operazioni: Espandi la scheda, quindi scegli Utilizza un ruolo esistente . Seleziona il lambda-s3-trigger-role che hai creato in precedenza. Scegli Crea funzione . Implementazione del codice della funzione Questo tutorial utilizza il runtime di Python 3.14, ma abbiamo anche fornito file di codice di esempio per altri runtime. Per visualizzare il codice per il runtime che ti interessa, seleziona la scheda corrispondente nella casella seguente. La funzione Lambda recupera il nome della chiave dell'oggetto caricato e il nome del bucket dal parametro event che riceve da Amazon S3. La funzione utilizza quindi il metodo get_object di AWS SDK per Python (Boto3) per recuperare i metadati dell'oggetto, incluso il tipo di contenuto (tipo MIME) dell'oggetto caricato. Implementazione del codice della funzione Scegli la scheda Python nella casella seguente e copia il codice. .NET SDK per .NET Nota C'è altro su. GitHub Trova l'esempio completo e scopri come eseguire la configurazione e l'esecuzione nel repository di Esempi serverless . Utilizzo di un evento S3 con Lambda tramite .NET. // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System.Threading.Tasks; using Amazon.Lambda.Core; using Amazon.S3; using System; using Amazon.Lambda.S3Events; using System.Web; // Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class. [assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] namespace S3Integration { public class Function { private static AmazonS3Client _s3Client; public Function() : this(null) { } internal Function(AmazonS3Client s3Client) { _s3Client = s3Client ?? new AmazonS3Client(); } public async Task<string> Handler(S3Event evt, ILambdaContext context) { try { if (evt.Records.Count <= 0) { context.Logger.LogLine("Empty S3 Event received"); return string.Empty; } var bucket = evt.Records[0].S3.Bucket.Name; var key = HttpUtility.UrlDecode(evt.Records[0].S3.Object.Key); context.Logger.LogLine($"Request is for { bucket} and { key}"); var objectResult = await _s3Client.GetObjectAsync(bucket, key); context.Logger.LogLine($"Returning { objectResult.Key}"); return objectResult.Key; } catch (Exception e) { context.Logger.LogLine($"Error processing request - { e.Message}"); return string.Empty; } } } } Go SDK per Go V2 Nota C'è dell'altro GitHub. Trova l'esempio completo e scopri come eseguire la configurazione e l'esecuzione nel repository di Esempi serverless . Utilizzo di un evento S3 con Lambda tramite Go. // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package main import ( "context" "log" "github.com/aws/aws-lambda-go/events" "github.com/aws/aws-lambda-go/lambda" "github.com/aws/aws-sdk-go-v2/config" "github.com/aws/aws-sdk-go-v2/service/s3" ) func handler(ctx context.Context, s3Event events.S3Event) error { sdkConfig, err := config.LoadDefaultConfig(ctx) if err != nil { log.Printf("failed to load default config: %s", err) return err } s3Client := s3.NewFromConfig(sdkConfig) for _, record := range s3Event.Records { bucket := record.S3.Bucket.Name key := record.S3.Object.URLDecodedKey headOutput, err := s3Client.HeadObject(ctx, &s3.HeadObjectInput { Bucket: &bucket, Key: &key, }) if err != nil { log.Printf("error getting head of object %s/%s: %s", bucket, key, err) return err } log.Printf("successfully retrieved %s/%s of type %s", bucket, key, *headOutput.ContentType) } return nil } func main() { lambda.Start(handler) } Java SDK per Java 2.x Nota C'è dell'altro GitHub. Trova l'esempio completo e scopri come eseguire la configurazione e l'esecuzione nel repository di Esempi serverless . Utilizzo di un evento S3 con Lambda tramite Java. // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package example; import software.amazon.awssdk.services.s3.model.HeadObjectRequest; import software.amazon.awssdk.services.s3.model.HeadObjectResponse; import software.amazon.awssdk.services.s3.S3Client; import com.amazonaws.services.lambda.runtime.Context; import com.amazonaws.services.lambda.runtime.RequestHandler; import com.amazonaws.services.lambda.runtime.events.S3Event; import com.amazonaws.services.lambda.runtime.events.models.s3.S3EventNotification.S3EventNotificationRecord; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class Handler implements RequestHandler<S3Event, String> { private static final Logger logger = LoggerFactory.getLogger(Handler.class); @Override public String handleRequest(S3Event s3event, Context context) { try { S3EventNotificationRecord record = s3event.getRecords().get(0); String srcBucket = record.getS3().getBucket().getName(); String srcKey = record.getS3().getObject().getUrlDecodedKey(); S3Client s3Client = S3Client.builder().build(); HeadObjectResponse headObject = getHeadObject(s3Client, srcBucket, srcKey); logger.info("Successfully retrieved " + srcBucket + "/" + srcKey + " of type " + headObject.contentType()); return "Ok"; } catch (Exception e) { throw new RuntimeException(e); } } private HeadObjectResponse getHeadObject(S3Client s3Client, String bucket, String key) { HeadObjectRequest headObjectRequest = HeadObjectRequest.builder() .bucket(bucket) .key(key) .build(); return s3Client.headObject(headObjectRequest); } } JavaScript SDK per JavaScript (v3) Nota C'è altro da fare. GitHub Trova l’esempio completo e scopri come eseguire la configurazione e l’esecuzione nel repository di Esempi serverless . Consumo di un evento S3 con JavaScript Lambda utilizzando. import { S3Client, HeadObjectCommand } from "@aws-sdk/client-s3"; const client = new S3Client(); export const handler = async (event, context) => { // Get the object from the event and show its content type const bucket = event.Records[0].s3.bucket.name; const key = decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g, ' ')); try { const { ContentType } = await client.send(new HeadObjectCommand( { Bucket: bucket, Key: key, })); console.log('CONTENT TYPE:', ContentType); return ContentType; } catch (err) { console.log(err); const message = `Error getting object $ { key} from bucket $ { bucket}. Make sure they exist and your bucket is in the same region as this function.`; console.log(message); throw new Error(message); } }; Consumo di un evento S3 con TypeScript Lambda utilizzando. // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 import { S3Event } from 'aws-lambda'; import { S3Client, HeadObjectCommand } from '@aws-sdk/client-s3'; const s3 = new S3Client( { region: process.env.AWS_REGION }); export const handler = async (event: S3Event): Promise<string | undefined> => { // Get the object from the event and show its content type const bucket = event.Records[0].s3.bucket.name; const key = decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g, ' ')); const params = { Bucket: bucket, Key: key, }; try { const { ContentType } = await s3.send(new HeadObjectCommand(params)); console.log('CONTENT TYPE:', ContentType); return ContentType; } catch (err) { console.log(err); const message = `Error getting object $ { key} from bucket $ { bucket}. Make sure they exist and your bucket is in the same region as this function.`; console.log(message); throw new Error(message); } }; PHP SDK per PHP Nota C'è altro da fare. GitHub Trova l’esempio completo e scopri come eseguire la configurazione e l’esecuzione nel repository di Esempi serverless . Utilizzo di un evento S3 con Lambda tramite PHP. <?php use Bref\Context\Context; use Bref\Event\S3\S3Event; use Bref\Event\S3\S3Handler; use Bref\Logger\StderrLogger; require __DIR__ . '/vendor/autoload.php'; class Handler extends S3Handler { private StderrLogger $logger; public function __construct(StderrLogger $logger) { $this->logger = $logger; } public function handleS3(S3Event $event, Context $context) : void { $this->logger->info("Processing S3 records"); // Get the object from the event and show its content type $records = $event->getRecords(); foreach ($records as $record) { $bucket = $record->getBucket()->getName(); $key = urldecode($record->getObject()->getKey()); try { $fileSize = urldecode($record->getObject()->getSize()); echo "File Size: " . $fileSize . "\n"; // TODO: Implement your custom processing logic here } catch (Exception $e) { echo $e->getMessage() . "\n"; echo 'Error getting object ' . $key . ' from bucket ' . $bucket . '. Make sure they exist and your bucket is in the same region as this function.' . "\n"; throw $e; } } } } $logger = new StderrLogger(); return new Handler($logger); Python SDK per Python (Boto3) Nota C'è dell'altro GitHub. Trova l'esempio completo e scopri come eseguire la configurazione e l'esecuzione nel repository di Esempi serverless . Utilizzo di un evento S3 con Lambda tramite Python. # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 import json import urllib.parse import boto3 print('Loading function') s3 = boto3.client('s3') def lambda_handler(event, context): #print("Received event: " + json.dumps(event, indent=2)) # Get the object from the event and show its content type bucket = event['Records'][0]['s3']['bucket']['name'] key = urllib.parse.unquote_plus(event['Records'][0]['s3']['object']['key'], encoding='utf-8') try: response = s3.get_object(Bucket=bucket, Key=key) print("CONTENT TYPE: " + response['ContentType']) return response['ContentType'] except Exception as e: print(e) print('Error getting object { } from bucket { }. Make sure they exist and your bucket is in the same region as this function.'.format(key, bucket)) raise e Ruby SDK per Ruby Nota C'è dell'altro GitHub. Trova l’esempio completo e scopri come eseguire la configurazione e l’esecuzione nel repository di Esempi serverless . Utilizzo di un evento S3 con Lambda tramite Ruby. require 'json' require 'uri' require 'aws-sdk' puts 'Loading function' def lambda_handler(event:, context:) s3 = Aws::S3::Client.new(region: 'region') # Your AWS region # puts "Received event: # { JSON.dump(event)}" # Get the object from the event and show its content type bucket = event['Records'][0]['s3']['bucket']['name'] key = URI.decode_www_form_component(event['Records'][0]['s3']['object']['key'], Encoding::UTF_8) begin response = s3.get_object(bucket: bucket, key: key) puts "CONTENT TYPE: # { response.content_type}" return response.content_type rescue StandardError => e puts e.message puts "Error getting object # { key} from bucket # { bucket}. Make sure they exist and your bucket is in the same region as this function." raise e end end Rust SDK per Rust Nota C'è altro da fare. GitHub Trova l'esempio completo e scopri come eseguire la configurazione e l'esecuzione nel repository di Esempi serverless . Utilizzo di un evento S3 con Lambda tramite Rust. // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 use aws_lambda_events::event::s3::S3Event; use aws_sdk_s3:: { Client}; use lambda_runtime:: { run, service_fn, Error, LambdaEvent}; /// Main function #[tokio::main] async fn main() -> Result<(), Error> { tracing_subscriber::fmt() .with_max_level(tracing::Level::INFO) .with_target(false) .without_time() .init(); // Initialize the AWS SDK for Rust let config = aws_config::load_from_env().await; let s3_client = Client::new(&config); let res = run(service_fn(|request: LambdaEvent<S3Event>| { function_handler(&s3_client, request) })).await; res } async fn function_handler( s3_client: &Client, evt: LambdaEvent<S3Event> ) -> Result<(), Error> { tracing::info!(records = ?evt.payload.records.len(), "Received request from SQS"); if evt.payload.records.len() == 0 { tracing::info!("Empty S3 event received"); } let bucket = evt.payload.records[0].s3.bucket.name.as_ref().expect("Bucket name to exist"); let key = evt.payload.records[0].s3.object.key.as_ref().expect("Object key to exist"); tracing::info!("Request is for { } and object { }", bucket, key); let s3_get_object_result = s3_client .get_object() .bucket(bucket) .key(key) .send() .await; match s3_get_object_result { Ok(_) => tracing::info!("S3 Get Object success, the s3GetObjectResult contains a 'body' property of type ByteStream"), Err(_) => tracing::info!("Failure with S3 Get Object request") } Ok(()) } Nel riquadro Codice sorgente della console Lambda, incolla il codice nell'editor di codice, sostituendo il codice creato da Lambda. Nella sezione DEPLOY , scegli Implementa per aggiornare il codice della tua funzione: Creazione del trigger Amazon S3 Creazione del trigger Amazon S3 Nel riquadro Panoramica della funzione , scegli Aggiungi trigger . Seleziona S3 . In Bucket , seleziona il bucket che hai creato in precedenza nel tutorial. In Tipi di eventi , verifica che sia selezionata l'opzione Tutti gli eventi di creazione di oggetti . In Invocazione ricorsiva , seleziona la casella di controllo per confermare che non è consigliabile utilizzare lo stesso bucket Amazon S3 per input e output. Scegliere Aggiungi . Nota Quando crei un trigger Amazon S3 per una funzione Lambda utilizzando la console Lambda, Amazon S3 configura una notifica degli eventi sul bucket specificato. Prima di configurare questa notifica di evento, Amazon S3 esegue una serie di controlli per confermare che la destinazione dell'evento esista e disponga delle policy IAM richieste. Amazon S3 esegue questi test anche su qualsiasi altra notifica di eventi configurata per quel bucket. A causa di questo controllo, se il bucket ha precedentemente configurato destinazioni di eventi per risorse che non esistono più o per risorse che non dispongono delle policy di autorizzazione richieste, Amazon S3 non sarà in grado di creare la nuova notifica di evento. Verrà visualizzato il seguente messaggio di errore che indica che non è stato possibile creare il trigger: An error occurred when creating the trigger: Unable to validate the following destination configurations. Puoi visualizzare questo errore se in precedenza hai configurato un trigger per un'altra funzione Lambda utilizzando lo stesso bucket e da allora hai eliminato la funzione o modificato le sue policy di autorizzazioni. Test di una funzione Lambda con un evento fittizio Test della funzione Lambda con un evento fittizio Nella pagina della console Lambda della funzione, seleziona la scheda Test . Per Event name (Nome evento) immettere MyTestEvent . Nella sezione JSON dell'evento , incolla il seguente evento di test. Assicurati di sostituire i seguenti valori: Sostituisci us-east-1 con la regione in cui è stato creato il bucket Amazon S3. Sostituisci entrambe le istanze di amzn-s3-demo-bucket con il nome del bucket Amazon S3. Sostituisci test%2FKey con il nome dell'oggetto di test che hai caricato in precedenza nel tuo bucket (ad esempio, HappyFace.jpg ). { "Records": [ { "eventVersion": "2.0", "eventSource": "aws:s3", "awsRegion": " us-east-1 ", "eventTime": "1970-01-01T00:00:00.000Z", "eventName": "ObjectCreated:Put", "userIdentity": { "principalId": "EXAMPLE" }, "requestParameters": { "sourceIPAddress": "127.0.0.1" }, "responseElements": { "x-amz-request-id": "EXAMPLE123456789", "x-amz-id-2": "EXAMPLE123/5678abcdefghijklambdaisawesome/mnopqrstuvwxyzABCDEFGH" }, "s3": { "s3SchemaVersion": "1.0", "configurationId": "testConfigRule", "bucket": { "name": " amzn-s3-demo-bucket ", "ownerIdentity": { "principalId": "EXAMPLE" }, "arn": "arn:aws:s3::: amzn-s3-demo-bucket " }, "object": { "key": " test%2Fkey ", "size": 1024, "eTag": "0123456789abcdef0123456789abcdef", "sequencer": "0A1B2C3D4E5F678901" } } } ] } Scegli Save (Salva). Scegli Test (Esegui test) . Se la tua funzione viene eseguita correttamente, vedrai un output simile al seguente nella scheda Risultati dell'esecuzione . Response "image/jpeg" Function Logs START RequestId: 12b3cae7-5f4e-415e-93e6-416b8f8b66e6 Version: $LATEST 2021-02-18T21:40:59.280Z 12b3cae7-5f4e-415e-93e6-416b8f8b66e6 INFO INPUT BUCKET AND KEY: { Bucket: 'amzn-s3-demo-bucket', Key: 'HappyFace.jpg' } 2021-02-18T21:41:00.215Z 12b3cae7-5f4e-415e-93e6-416b8f8b66e6 INFO CONTENT TYPE: image/jpeg END RequestId: 12b3cae7-5f4e-415e-93e6-416b8f8b66e6 REPORT RequestId: 12b3cae7-5f4e-415e-93e6-416b8f8b66e6 Duration: 976.25 ms Billed Duration: 977 ms Memory Size: 128 MB Max Memory Used: 90 MB Init Duration: 430.47 ms Request ID 12b3cae7-5f4e-415e-93e6-416b8f8b66e6 Test della funzione Lambda mediante il trigger Amazon S3 Per verificare la funzione con il trigger configurato, carica un oggetto sul bucket Amazon S3 utilizzando la console. Per verificare che la funzione Lambda sia stata eseguita come previsto, usa CloudWatch Logs per visualizzare l'output della funzione. Caricamento di un oggetto nel bucket Amazon S3 Apri la pagina Bucket della console Amazon S3 e scegli il bucket che hai creato in precedenza. Scegli Carica . Scegli Aggiungi file e usa il selettore di file per scegliere un oggetto da caricare. Tale oggetto può essere qualsiasi file desideri. Seleziona Apri , quindi Carica . Per verificare l'invocazione della funzione utilizzando Logs CloudWatch Aprire la console CloudWatch . Assicurati di lavorare nella stessa modalità in Regione AWS cui hai creato la funzione Lambda. Puoi modificare la regione utilizzando l'elenco a discesa nella parte superiore dello schermo. Scegli Log e quindi Gruppi di log . Scegli il nome del gruppo di log per la funzione ( /aws/lambda/s3-trigger-tutorial ). In Flussi di log , scegli il flusso di log più recente. Se la tua funzione è stata richiamata correttamente in risposta al trigger Amazon S3, vedrai un output simile al seguente. Il CONTENT TYPE visualizzato dipende dal tipo di file che hai caricato nel bucket. 2022-05-09T23:17:28.702Z 0cae7f5a-b0af-4c73-8563-a3430333cc10 INFO CONTENT TYPE: image/jpeg Pulizia delle risorse Ora è possibile eliminare le risorse create per questo tutorial, a meno che non si voglia conservarle. Eliminando AWS le risorse che non utilizzi più, eviti addebiti inutili a tuo carico. Account AWS Per eliminare la funzione Lambda Aprire la pagina Functions (Funzioni) della console Lambda. Selezionare la funzione creata. Scegliere Operazioni , Elimina . Inserisci confirm nel campo di immissione del testo, quindi scegli Elimina . Come eliminare il ruolo di esecuzione Aprire la pagina Ruoli della console IAM. Selezionare il ruolo di esecuzione creato. Scegliere Elimina . Inserisci il nome del ruolo nel campo di immissione testo e seleziona Delete (Elimina). Per eliminare il bucket S3 Aprire la console Amazon S3 . Selezionare il bucket creato in precedenza. Scegli Elimina . Inserisci il nome del bucket nel campo di immissione testo. Scegli Delete Bucket (Elimina bucket). Fasi successive In Tutorial: uso di un trigger Amazon S3 per creare immagini in miniatura , il trigger Amazon S3 richiama una funzione per creare un'immagine in miniatura per ogni file immagine caricato nel bucket. Questo tutorial richiede un livello moderato di conoscenza del AWS dominio Lambda. Dimostra come creare risorse utilizzando AWS Command Line Interface (AWS CLI) e come creare un pacchetto di distribuzione di archivi di file.zip per la funzione e le sue dipendenze. JavaScript è disabilitato o non è disponibile nel tuo browser. Per usare la documentazione AWS, JavaScript deve essere abilitato. Consulta le pagine della guida del browser per le istruzioni. Convenzioni dei documenti S3 Tutorial: Uso di un trigger Amazon S3 per creare miniature Questa pagina ti è stata utile? - Sì Grazie per averci comunicato che stiamo facendo un buon lavoro! Se hai un momento, ti invitiamo a dirci che cosa abbiamo fatto che ti è piaciuto così possiamo offrirti altri contenuti simili. Questa pagina ti è stata utile? - No Grazie per averci comunicato che questa pagina ha bisogno di essere modificata. Siamo spiacenti di non aver soddisfatto le tue esigenze. Se hai un momento, ti invitiamo a dirci come possiamo migliorare la documentazione. | 2026-01-13T09:30:35 |
https://docs.aws.amazon.com/lambda/latest/dg/access-control-resource-based.html | Viewing resource-based IAM policies in Lambda - AWS Lambda Viewing resource-based IAM policies in Lambda - AWS Lambda Documentation AWS Lambda Developer Guide Supported API actions Viewing resource-based IAM policies in Lambda Lambda supports resource-based permissions policies for Lambda functions and layers. You can use resource-based policies to grant access to other AWS accounts , organizations , or services . Resource-based policies apply to a single function, version, alias, or layer version. Console To view a function's resource-based policy Open the Functions page of the Lambda console. Choose a function. Choose Configuration and then choose Permissions . Scroll down to Resource-based policy and then choose View policy document . The resource-based policy shows the permissions that are applied when another account or AWS service attempts to access the function. The following example shows a statement that allows Amazon S3 to invoke a function named my-function for a bucket named amzn-s3-demo-bucket in account 123456789012 . Example resource-based policy { "Version":"2012-10-17", "Id": "default", "Statement": [ { "Sid": "lambda-allow-s3-my-function", "Effect": "Allow", "Principal": { "Service": "s3.amazonaws.com" }, "Action": "lambda:InvokeFunction", "Resource": "arn:aws:lambda:us-east-2:123456789012:function:my-function", "Condition": { "StringEquals": { "AWS:SourceAccount": "123456789012" }, "ArnLike": { "AWS:SourceArn": "arn:aws:s3:::amzn-s3-demo-bucket" } } } ] } AWS CLI To view a function's resource-based policy, use the get-policy command. aws lambda get-policy \ --function-name my-function \ --output text You should see the following output: { "Version":"2012-10-17", "Id":"default","Statement":[ { "Sid":"sns","Effect":"Allow","Principal": { "Service":"s3.amazonaws.com"},"Action":"lambda:InvokeFunction","Resource":"arn:aws:lambda:us-east-2:123456789012:function:my-function","Condition": { "ArnLike": { "AWS:SourceArn":"arn:aws:sns:us-east-2:123456789012:lambda*"}}}]} For versions and aliases, append the version number or alias to the function name. aws lambda get-policy --function-name my-function:PROD To remove permissions from your function, use remove-permission . aws lambda remove-permission \ --function-name example \ --statement-id sns Use the get-layer-version-policy command to view the permissions on a layer. aws lambda get-layer-version-policy \ --layer-name my-layer \ --version-number 3 \ --output text You should see the following output: b0cd9796-d4eb-4564-939f-de7fe0b42236 { "Sid":"engineering-org","Effect":"Allow","Principal":"*","Action":"lambda:GetLayerVersion","Resource":"arn:aws:lambda:us-west-2:123456789012:layer:my-layer:3","Condition": { "StringEquals": { "aws:PrincipalOrgID":"o-t194hfs8cz"}}}" Use remove-layer-version-permission to remove statements from the policy. aws lambda remove-layer-version-permission --layer-name my-layer --version-number 3 --statement-id engineering-org Supported API actions The following Lambda API actions support resource-based policies: CreateAlias DeleteAlias DeleteFunction DeleteFunctionConcurrency DeleteFunctionEventInvokeConfig DeleteProvisionedConcurrencyConfig GetAlias GetFunction GetFunctionConcurrency GetFunctionConfiguration GetFunctionEventInvokeConfig GetPolicy GetProvisionedConcurrencyConfig Invoke InvokeFunctionUrl (permission only) ListAliases ListFunctionEventInvokeConfigs ListProvisionedConcurrencyConfigs ListTags ListVersionsByFunction PublishVersion PutFunctionConcurrency PutFunctionEventInvokeConfig PutProvisionedConcurrencyConfig TagResource UntagResource UpdateAlias UpdateFunctionCode UpdateFunctionEventInvokeConfig Javascript is disabled or is unavailable in your browser. To use the Amazon Web Services Documentation, Javascript must be enabled. Please refer to your browser's Help pages for instructions. Document Conventions Layer access Function access for AWS services Did this page help you? - Yes Thanks for letting us know we're doing a good job! If you've got a moment, please tell us what we did right so we can do more of it. Did this page help you? - No Thanks for letting us know this page needs work. We're sorry we let you down. If you've got a moment, please tell us how we can make the documentation better. | 2026-01-13T09:30:35 |
https://docs.aws.amazon.com/es_es/AmazonCloudFront/latest/DeveloperGuide/lambda-examples.html#lambda-examples-http-redirect | Funciones de ejemplo de Lambda@Edge - Amazon CloudFront Funciones de ejemplo de Lambda@Edge - Amazon CloudFront Documentación Amazon CloudFront Guía para desarrolladores Ejemplos generales Generación de respuestas: ejemplos Cadenas de consulta: ejemplos Personalización de contenido por encabezados de tipo de dispositivo o país: ejemplos Selección de origen dinámico basada en contenido: ejemplos Actualización de estados de error: ejemplos Acceso al cuerpo de la solicitud: ejemplos Funciones de ejemplo de Lambda@Edge Consulte los ejemplos siguientes para usar funciones de Lambda con Amazon CloudFront. nota Si elige el tiempo de ejecución Node.js 18 o una versión posterior para la función Lambda@Edge, se creará automáticamente un archivo index.mjs . Para usar los siguientes ejemplos de código, cambie el nombre del archivo index.mjs a index.js . Temas Ejemplos generales Generación de respuestas: ejemplos Cadenas de consulta: ejemplos Personalización de contenido por encabezados de tipo de dispositivo o país: ejemplos Selección de origen dinámico basada en contenido: ejemplos Actualización de estados de error: ejemplos Acceso al cuerpo de la solicitud: ejemplos Ejemplos generales Los ejemplos siguientes muestran formas habituales de usar Lambda@Edge en CloudFront. Temas Ejemplo: prueba A/B Ejemplo: Sobrescritura de un encabezado de respuesta Ejemplo: prueba A/B Puede utilizar el siguiente ejemplo para probar dos versiones diferentes de una imagen sin crear redirecciones ni cambiar la dirección URL. En este ejemplo se leen las cookies de la solicitud del lector y se modifica la URL de la solicitud en consecuencia. Si el espectador no envía una cookie con uno de los valores esperados, el ejemplo asigna aleatoriamente al espectador una de las URL. 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; } 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; } } 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" ''' experimentUri = "" 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 Ejemplo: Sobrescritura de un encabezado de respuesta En el ejemplo siguiente, se muestra cómo cambiar el valor de un encabezado de respuesta según el valor de otro encabezado. Node.js export const handler = async (event) => { 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()] = [ { key: headerNameDst, value: headers[headerNameSrc.toLowerCase()][0].value, }]; console.log(`Response header "$ { headerNameDst}" was set to ` + `"$ { headers[headerNameDst.toLowerCase()][0].value}"`); } return response; }; Python import json def lambda_handler(event, context): response = event['Records'][0]['cf']['response'] headers = response['headers'] header_name_src = 'X-Amz-Meta-Last-Modified' header_name_dst = 'Last-Modified' if headers.get(header_name_src.lower()): headers[header_name_dst.lower()] = [ { 'key': header_name_dst, 'value': headers[header_name_src.lower()][0]['value'] }] print(f'Response header " { header_name_dst}" was set to ' f'" { headers[header_name_dst.lower()][0]["value"]}"') return response Generación de respuestas: ejemplos En los ejemplos siguientes se muestra cómo puede usar Lambda@Edge para generar respuestas. Temas Ejemplo: Envío de contenido estático (respuesta generada) Ejemplo: Generación de un redireccionamiento HTTP (respuesta generada) Ejemplo: Envío de contenido estático (respuesta generada) En el siguiente ejemplo se muestra cómo utilizar una función de Lambda para enviar contenido de sitio web estático, lo que reduce la carga en el servidor de origen y la latencia total. nota Puede generar respuestas HTTP para los eventos de solicitud del espectador y al origen. Para obtener más información, consulte Generación de respuestas HTTP en los desencadenadores de solicitud . También puede sustituir o quitar el cuerpo de la respuesta HTTP en eventos de respuesta de origen. Para obtener más información, consulte Actualización de respuestas HTTP en desencadenadores de respuesta de origen . 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' }] }, 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 } return response Ejemplo: Generación de un redireccionamiento HTTP (respuesta generada) En el siguiente ejemplo se muestra cómo generar una redirección HTTP. nota Puede generar respuestas HTTP para los eventos de solicitud del espectador y al origen. Para obtener más información, consulte Generación de respuestas HTTP en los desencadenadores de solicitud . 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. response = { 'status': '302', 'statusDescription': 'Found', 'headers': { 'location': [ { 'key': 'Location', 'value': 'https://docs.aws.amazon.com/lambda/latest/dg/lambda-edge.html' }] } } return response Cadenas de consulta: ejemplos En los ejemplos siguientes se muestran formas de usar Lambda@Edge con cadenas de consulta. Temas Ejemplo: Adición de un encabezado en función de un parámetro de la cadena de consulta Ejemplo: Normalización de parámetros de cadenas de consulta para mejorar la tasa de aciertos de caché Ejemplo: Redireccionamiento de los usuarios no autenticados a una página de inicio de sesión Ejemplo: Adición de un encabezado en función de un parámetro de la cadena de consulta El siguiente ejemplo muestra cómo obtener el par clave-valor de un parámetro de la cadena de consulta y, a continuación, añadir un encabezado en función de dichos valores. 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. * 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 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'] # Update request querystring request['querystring'] = urlencode(params) return request Ejemplo: Normalización de parámetros de cadenas de consulta para mejorar la tasa de aciertos de caché El siguiente ejemplo muestra cómo mejorar la tasa de acceso a la caché haciendo los siguientes cambios en las cadenas de consulta antes de que CloudFront reenvíe las solicitudes a su origen: Alfabetizar los pares de clave-valor por el nombre del parámetro. Cambiar a minúsculas el modelo de mayúsculas y minúsculas de los pares de clave-valor. Para obtener más información, consulte Almacenamiento en caché de contenido en función de parámetros de cadenas de consulta . 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 */ 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 request['querystring'] = urlencode(sortedParams) return request Ejemplo: Redireccionamiento de los usuarios no autenticados a una página de inicio de sesión El siguiente ejemplo muestra cómo redirigir a los usuarios una página de inicio de sesión si no ha introducido sus credenciales. 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; } /* 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 params. ''' # Check for session-id in cookie, if present, then proceed with request parsedCookies = parseCookies(headers) 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 Personalización de contenido por encabezados de tipo de dispositivo o país: ejemplos En los ejemplos siguientes se muestra cómo puede usar Lambda@Edge para personalizar el comportamiento en función de la ubicación o el tipo de dispositivo que usa el lector. Temas Ejemplo: Redireccionamiento de solicitudes de espectadores a una URL específica de un país Ejemplo: Envío de distintas versiones de un objeto en función del dispositivo Ejemplo: Redireccionamiento de solicitudes de espectadores a una URL específica de un país El siguiente ejemplo muestra cómo generar una respuesta de redireccionamiento HTTP con una URL específica del país y devolver la respuesta al espectador. Esto resulta útil cuando se quiere proporcionar respuestas específicas del país. Por ejemplo: Si tiene subdominios específicos de un país, como us.ejemplo.com y tw.ejemplo.com, puede generar una respuesta de redireccionamiento cuando un espectador solicite ejemplo.com. Si está haciendo streaming de video, pero no tiene derechos para transmitir el contenido en un país determinado, puede redirigir a los usuarios de dicho país a una página en la que se explica por qué no pueden ver el video. Tenga en cuenta lo siguiente: Debe configurar la distribución para almacenar en la caché en función del encabezado CloudFront-Viewer-Country . Para obtener más información, consulte Caché en función de encabezados de solicitud seleccionados . CloudFront agrega el encabezado CloudFront-Viewer-Country después del evento de solicitud del lector. Para utilizar este ejemplo, debe crear un activador para el evento de solicitud al origen. 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 = { 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', 'statusDescription': 'Found', 'headers': { 'location': [ { 'key': 'Location', 'value': url }] } } return response Ejemplo: Envío de distintas versiones de un objeto en función del dispositivo El siguiente ejemplo muestra cómo ofrecer distintas versiones de un objeto en función del tipo de dispositivo que el usuario está utilizando; por ejemplo, un dispositivo móvil o una tablet. Tenga en cuenta lo siguiente: Debe configurar la distribución para almacenar en la caché en función de los encabezados CloudFront-Is-*-Viewer . Para obtener más información, consulte Caché en función de encabezados de solicitud seleccionados . CloudFront agrega los encabezados CloudFront-Is-*-Viewer después del evento de solicitud del lector. Para utilizar este ejemplo, debe crear un activador para el evento de solicitud al origen. 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 * 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. ''' desktopPath = '/desktop'; mobilePath = '/mobile'; tabletPath = '/tablet'; smarttvPath = '/smarttv'; 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 Selección de origen dinámico basada en contenido: ejemplos En los ejemplos siguientes se muestra cómo puede usar Lambda@Edge para el direccionamiento a diferentes orígenes en función de la información de la solicitud. Temas Ejemplo: Uso de un desencadenador de solicitud de origen para cambiar desde un origen personalizado a un origen de Amazon S3 Ejemplo: Uso de un desencadenador de solicitud de origen para cambiar la región de origen de Amazon S3 Ejemplo: Uso de un desencadenador de solicitud de origen para cambiar desde un origen de Amazon S3 a un origen personalizado Ejemplo: Uso de un desencadenador de solicitud al origen para transferir gradualmente el tráfico desde un bucket de Amazon S3 a otro Ejemplo: Uso de un desencadenador de solicitud de origen para cambiar el nombre del dominio de origen en función del encabezado de país Ejemplo: Uso de un desencadenador de solicitud de origen para cambiar desde un origen personalizado a un origen de Amazon S3 Esta función demuestra cómo utilizar un desencadenador de solicitud al origen para cambiar desde un origen personalizado a un origen de Amazon S3 desde el que recuperar el contenido, en función de las propiedades de la solicitud. 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: 'origin-access-identity', path: '', customHeaders: { } } }; request.headers['host'] = [ { key: 'host', value: s3DomainName}]; } } 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 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': 'origin-access-identity', 'path': '', 'customHeaders': { } } } request['headers']['host'] = [ { 'key': 'host', 'value': s3DomainName}] return request Ejemplo: Uso de un desencadenador de solicitud de origen para cambiar la región de origen de Amazon S3 Esta función demuestra cómo utilizar un desencadenador de solicitud al origen para cambiar el origen de Amazon S3 desde el que se recupera el contenido, en función de las propiedades de la solicitud. En este ejemplo, utilizamos el valor del encabezado CloudFront-Viewer-Country para actualizar el nombre de dominio del bucket de S3 por un bucket de una región que está más cerca del lector. Esto puede resultar útil de varias maneras: Reduce las latencias cuando la región especificada está más cerca del país del lector. Proporciona soberanía de los datos, al asegurarse de que los datos se distribuyen desde un origen que está en el país del que provino la solicitud. Para utilizar este ejemplo, debe hacer lo siguiente: Configure la distribución para almacenar en la caché en función del encabezado CloudFront-Viewer-Country . Para obtener más información, consulte Caché en función de encabezados de solicitud seleccionados . Crear un disparador para esta función en el evento de solicitud al origen. CloudFront agrega el encabezado CloudFront-Viewer-Country después del evento de solicitud del lector; por lo tanto, para utilizar este ejemplo, debe asegurarse de que la función ejecuta una solicitud de origen. nota El siguiente código de ejemplo usa la misma identidad de acceso de origen (OAI) para todos los buckets de S3 que usa para el origen. Para obtener más información, consulte Identidad de acceso de origen . 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 * 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); }; Python 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: 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: ''' 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 Ejemplo: Uso de un desencadenador de solicitud de origen para cambiar desde un origen de Amazon S3 a un origen personalizado Esta función demuestra cómo utilizar un disparador de solicitud al origen para cambiar el origen personalizado desde el que se recupera el contenido, en función de las propiedades de la solicitud. 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: { 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': { } } } request['headers']['host'] = [ { 'key': 'host', 'value': 'www.example.com'}] return request Ejemplo: Uso de un desencadenador de solicitud al origen para transferir gradualmente el tráfico desde un bucket de Amazon S3 a otro Esta función demuestra cómo transferir gradualmente el tráfico desde un bucket de Amazon S3 a otro de forma controlada. 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}]; } 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 Ejemplo: Uso de un desencadenador de solicitud de origen para cambiar el nombre del dominio de origen en función del encabezado de país Esta función demuestra cómo cambiar el nombre del dominio de origen en función del encabezado CloudFront-Viewer-Country , de forma que el contenido se distribuya desde un origen más cercano al país del lector. La implementación de esta funcionalidad para su distribución puede tener ventajas como las siguientes: Reducir las latencias cuando la región especificada está más cerca del país del lector Proporcionar soberanía de los datos, al asegurarse de que los datos se distribuyen desde un origen que está en el país del que provino la solicitud Tenga en cuenta que para habilitar esta funcionalidad, debe configurar su distribución para almacenar en la caché en función del encabezado CloudFront-Viewer-Country . Para obtener más información, consulte Caché en función de encabezados de solicitud seleccionados . 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 request['headers']['host'] = [ { 'key': 'host', 'value': domainName}] return request Actualización de estados de error: ejemplos En los ejemplos siguientes se proporciona orientación acerca de cómo puede usar Lambda@Edge para cambiar el estado de error que se devuelve a los usuarios. Temas Ejemplo: Uso de un desencadenador de respuesta de origen para actualizar el código de estado de error a 200 Ejemplo: Uso de un desencadenador de respuesta de origen para actualizar el código de estado de error a 302 Ejemplo: Uso de un desencadenador de respuesta de origen para actualizar el código de estado de error a 200 Esta función demuestra cómo actualizar el estado de la respuesta a 200 y generar un cuerpo con contenido estático para devolverlo al espectador en la siguiente situación: La función se desencadena en una respuesta del origen. El estado de la respuesta del servidor de origen es un código de estado de error (4xx o 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'; } callback(null, response); }; Python 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 Ejemplo: Uso de un desencadenador de respuesta de origen para actualizar el código de estado de error a 302 Esta función demuestra cómo actualizar el código de estado HTTP a 302 para la redirección a otra ruta (comportamiento de la caché) en la que se ha configurado un origen diferente. Tenga en cuenta lo siguiente: La función se desencadena en una respuesta del origen. El estado de la respuesta del servidor de origen es un código de estado de error (4xx o 5xx). Node.js 'use strict'; exports.handler = (event, context, callback) => { const response = event.Records[0].cf.response; const 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 (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 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 Acceso al cuerpo de la solicitud: ejemplos En los ejemplos siguientes se muestra cómo puede usar Lambda@Edge para trabajar con las solicitudes POST. nota Para utilizar estos ejemplos, debe habilitar la opción incluir cuerpo en la asociación de funciones Lambda de la distribución. No está habilitada de forma predeterminada. Para habilitar esta configuración en la consola de CloudFront, seleccione la casilla de verificación Incluir cuerpo en la Asociación de funciones Lambda . Para habilitar esta configuración en la API de CloudFront o con CloudFormation, establezca el campo IncludeBody en true en LambdaFunctionAssociation . Temas Ejemplo: Uso de un desencadenador de solicitud para leer un formulario HTML Ejemplo: Uso de un desencadenador de solicitud para modificar un formulario HTML Ejemplo: Uso de un desencadenador de solicitud para leer un formulario HTML Esta función ilustra cómo puede procesar el cuerpo de una solicitud POST generada por un formulario HTML (formulario web), como por ejemplo un formulario tipo "póngase en contacto con nosotros". Por ejemplo, es posible que tenga un formulario HTML como el siguiente: <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> Para la función de ejemplo que se indica a continuación, la función se debe desencadenar en una solicitud al origen o del lector de CloudFront. 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 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 Ejemplo: Uso de un desencadenador de solicitud para modificar un formulario HTML Esta función ilustra cómo puede modificar el cuerpo de una solicitud POST generada por un formulario HTML (formulario web). La función se activa en una solicitud al origen o del lector de CloudFront. 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. * * 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'] | 2026-01-13T09:30:35 |
https://docs.aws.amazon.com/es_es/AmazonCloudFront/latest/DeveloperGuide/lambda-examples.html#lambda-examples-query-string-examples | Funciones de ejemplo de Lambda@Edge - Amazon CloudFront Funciones de ejemplo de Lambda@Edge - Amazon CloudFront Documentación Amazon CloudFront Guía para desarrolladores Ejemplos generales Generación de respuestas: ejemplos Cadenas de consulta: ejemplos Personalización de contenido por encabezados de tipo de dispositivo o país: ejemplos Selección de origen dinámico basada en contenido: ejemplos Actualización de estados de error: ejemplos Acceso al cuerpo de la solicitud: ejemplos Funciones de ejemplo de Lambda@Edge Consulte los ejemplos siguientes para usar funciones de Lambda con Amazon CloudFront. nota Si elige el tiempo de ejecución Node.js 18 o una versión posterior para la función Lambda@Edge, se creará automáticamente un archivo index.mjs . Para usar los siguientes ejemplos de código, cambie el nombre del archivo index.mjs a index.js . Temas Ejemplos generales Generación de respuestas: ejemplos Cadenas de consulta: ejemplos Personalización de contenido por encabezados de tipo de dispositivo o país: ejemplos Selección de origen dinámico basada en contenido: ejemplos Actualización de estados de error: ejemplos Acceso al cuerpo de la solicitud: ejemplos Ejemplos generales Los ejemplos siguientes muestran formas habituales de usar Lambda@Edge en CloudFront. Temas Ejemplo: prueba A/B Ejemplo: Sobrescritura de un encabezado de respuesta Ejemplo: prueba A/B Puede utilizar el siguiente ejemplo para probar dos versiones diferentes de una imagen sin crear redirecciones ni cambiar la dirección URL. En este ejemplo se leen las cookies de la solicitud del lector y se modifica la URL de la solicitud en consecuencia. Si el espectador no envía una cookie con uno de los valores esperados, el ejemplo asigna aleatoriamente al espectador una de las URL. 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; } 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; } } 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" ''' experimentUri = "" 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 Ejemplo: Sobrescritura de un encabezado de respuesta En el ejemplo siguiente, se muestra cómo cambiar el valor de un encabezado de respuesta según el valor de otro encabezado. Node.js export const handler = async (event) => { 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()] = [ { key: headerNameDst, value: headers[headerNameSrc.toLowerCase()][0].value, }]; console.log(`Response header "$ { headerNameDst}" was set to ` + `"$ { headers[headerNameDst.toLowerCase()][0].value}"`); } return response; }; Python import json def lambda_handler(event, context): response = event['Records'][0]['cf']['response'] headers = response['headers'] header_name_src = 'X-Amz-Meta-Last-Modified' header_name_dst = 'Last-Modified' if headers.get(header_name_src.lower()): headers[header_name_dst.lower()] = [ { 'key': header_name_dst, 'value': headers[header_name_src.lower()][0]['value'] }] print(f'Response header " { header_name_dst}" was set to ' f'" { headers[header_name_dst.lower()][0]["value"]}"') return response Generación de respuestas: ejemplos En los ejemplos siguientes se muestra cómo puede usar Lambda@Edge para generar respuestas. Temas Ejemplo: Envío de contenido estático (respuesta generada) Ejemplo: Generación de un redireccionamiento HTTP (respuesta generada) Ejemplo: Envío de contenido estático (respuesta generada) En el siguiente ejemplo se muestra cómo utilizar una función de Lambda para enviar contenido de sitio web estático, lo que reduce la carga en el servidor de origen y la latencia total. nota Puede generar respuestas HTTP para los eventos de solicitud del espectador y al origen. Para obtener más información, consulte Generación de respuestas HTTP en los desencadenadores de solicitud . También puede sustituir o quitar el cuerpo de la respuesta HTTP en eventos de respuesta de origen. Para obtener más información, consulte Actualización de respuestas HTTP en desencadenadores de respuesta de origen . 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' }] }, 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 } return response Ejemplo: Generación de un redireccionamiento HTTP (respuesta generada) En el siguiente ejemplo se muestra cómo generar una redirección HTTP. nota Puede generar respuestas HTTP para los eventos de solicitud del espectador y al origen. Para obtener más información, consulte Generación de respuestas HTTP en los desencadenadores de solicitud . 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. response = { 'status': '302', 'statusDescription': 'Found', 'headers': { 'location': [ { 'key': 'Location', 'value': 'https://docs.aws.amazon.com/lambda/latest/dg/lambda-edge.html' }] } } return response Cadenas de consulta: ejemplos En los ejemplos siguientes se muestran formas de usar Lambda@Edge con cadenas de consulta. Temas Ejemplo: Adición de un encabezado en función de un parámetro de la cadena de consulta Ejemplo: Normalización de parámetros de cadenas de consulta para mejorar la tasa de aciertos de caché Ejemplo: Redireccionamiento de los usuarios no autenticados a una página de inicio de sesión Ejemplo: Adición de un encabezado en función de un parámetro de la cadena de consulta El siguiente ejemplo muestra cómo obtener el par clave-valor de un parámetro de la cadena de consulta y, a continuación, añadir un encabezado en función de dichos valores. 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. * 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 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'] # Update request querystring request['querystring'] = urlencode(params) return request Ejemplo: Normalización de parámetros de cadenas de consulta para mejorar la tasa de aciertos de caché El siguiente ejemplo muestra cómo mejorar la tasa de acceso a la caché haciendo los siguientes cambios en las cadenas de consulta antes de que CloudFront reenvíe las solicitudes a su origen: Alfabetizar los pares de clave-valor por el nombre del parámetro. Cambiar a minúsculas el modelo de mayúsculas y minúsculas de los pares de clave-valor. Para obtener más información, consulte Almacenamiento en caché de contenido en función de parámetros de cadenas de consulta . 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 */ 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 request['querystring'] = urlencode(sortedParams) return request Ejemplo: Redireccionamiento de los usuarios no autenticados a una página de inicio de sesión El siguiente ejemplo muestra cómo redirigir a los usuarios una página de inicio de sesión si no ha introducido sus credenciales. 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; } /* 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 params. ''' # Check for session-id in cookie, if present, then proceed with request parsedCookies = parseCookies(headers) 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 Personalización de contenido por encabezados de tipo de dispositivo o país: ejemplos En los ejemplos siguientes se muestra cómo puede usar Lambda@Edge para personalizar el comportamiento en función de la ubicación o el tipo de dispositivo que usa el lector. Temas Ejemplo: Redireccionamiento de solicitudes de espectadores a una URL específica de un país Ejemplo: Envío de distintas versiones de un objeto en función del dispositivo Ejemplo: Redireccionamiento de solicitudes de espectadores a una URL específica de un país El siguiente ejemplo muestra cómo generar una respuesta de redireccionamiento HTTP con una URL específica del país y devolver la respuesta al espectador. Esto resulta útil cuando se quiere proporcionar respuestas específicas del país. Por ejemplo: Si tiene subdominios específicos de un país, como us.ejemplo.com y tw.ejemplo.com, puede generar una respuesta de redireccionamiento cuando un espectador solicite ejemplo.com. Si está haciendo streaming de video, pero no tiene derechos para transmitir el contenido en un país determinado, puede redirigir a los usuarios de dicho país a una página en la que se explica por qué no pueden ver el video. Tenga en cuenta lo siguiente: Debe configurar la distribución para almacenar en la caché en función del encabezado CloudFront-Viewer-Country . Para obtener más información, consulte Caché en función de encabezados de solicitud seleccionados . CloudFront agrega el encabezado CloudFront-Viewer-Country después del evento de solicitud del lector. Para utilizar este ejemplo, debe crear un activador para el evento de solicitud al origen. 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 = { 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', 'statusDescription': 'Found', 'headers': { 'location': [ { 'key': 'Location', 'value': url }] } } return response Ejemplo: Envío de distintas versiones de un objeto en función del dispositivo El siguiente ejemplo muestra cómo ofrecer distintas versiones de un objeto en función del tipo de dispositivo que el usuario está utilizando; por ejemplo, un dispositivo móvil o una tablet. Tenga en cuenta lo siguiente: Debe configurar la distribución para almacenar en la caché en función de los encabezados CloudFront-Is-*-Viewer . Para obtener más información, consulte Caché en función de encabezados de solicitud seleccionados . CloudFront agrega los encabezados CloudFront-Is-*-Viewer después del evento de solicitud del lector. Para utilizar este ejemplo, debe crear un activador para el evento de solicitud al origen. 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 * 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. ''' desktopPath = '/desktop'; mobilePath = '/mobile'; tabletPath = '/tablet'; smarttvPath = '/smarttv'; 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 Selección de origen dinámico basada en contenido: ejemplos En los ejemplos siguientes se muestra cómo puede usar Lambda@Edge para el direccionamiento a diferentes orígenes en función de la información de la solicitud. Temas Ejemplo: Uso de un desencadenador de solicitud de origen para cambiar desde un origen personalizado a un origen de Amazon S3 Ejemplo: Uso de un desencadenador de solicitud de origen para cambiar la región de origen de Amazon S3 Ejemplo: Uso de un desencadenador de solicitud de origen para cambiar desde un origen de Amazon S3 a un origen personalizado Ejemplo: Uso de un desencadenador de solicitud al origen para transferir gradualmente el tráfico desde un bucket de Amazon S3 a otro Ejemplo: Uso de un desencadenador de solicitud de origen para cambiar el nombre del dominio de origen en función del encabezado de país Ejemplo: Uso de un desencadenador de solicitud de origen para cambiar desde un origen personalizado a un origen de Amazon S3 Esta función demuestra cómo utilizar un desencadenador de solicitud al origen para cambiar desde un origen personalizado a un origen de Amazon S3 desde el que recuperar el contenido, en función de las propiedades de la solicitud. 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: 'origin-access-identity', path: '', customHeaders: { } } }; request.headers['host'] = [ { key: 'host', value: s3DomainName}]; } } 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 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': 'origin-access-identity', 'path': '', 'customHeaders': { } } } request['headers']['host'] = [ { 'key': 'host', 'value': s3DomainName}] return request Ejemplo: Uso de un desencadenador de solicitud de origen para cambiar la región de origen de Amazon S3 Esta función demuestra cómo utilizar un desencadenador de solicitud al origen para cambiar el origen de Amazon S3 desde el que se recupera el contenido, en función de las propiedades de la solicitud. En este ejemplo, utilizamos el valor del encabezado CloudFront-Viewer-Country para actualizar el nombre de dominio del bucket de S3 por un bucket de una región que está más cerca del lector. Esto puede resultar útil de varias maneras: Reduce las latencias cuando la región especificada está más cerca del país del lector. Proporciona soberanía de los datos, al asegurarse de que los datos se distribuyen desde un origen que está en el país del que provino la solicitud. Para utilizar este ejemplo, debe hacer lo siguiente: Configure la distribución para almacenar en la caché en función del encabezado CloudFront-Viewer-Country . Para obtener más información, consulte Caché en función de encabezados de solicitud seleccionados . Crear un disparador para esta función en el evento de solicitud al origen. CloudFront agrega el encabezado CloudFront-Viewer-Country después del evento de solicitud del lector; por lo tanto, para utilizar este ejemplo, debe asegurarse de que la función ejecuta una solicitud de origen. nota El siguiente código de ejemplo usa la misma identidad de acceso de origen (OAI) para todos los buckets de S3 que usa para el origen. Para obtener más información, consulte Identidad de acceso de origen . 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 * 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); }; Python 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: 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: ''' 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 Ejemplo: Uso de un desencadenador de solicitud de origen para cambiar desde un origen de Amazon S3 a un origen personalizado Esta función demuestra cómo utilizar un disparador de solicitud al origen para cambiar el origen personalizado desde el que se recupera el contenido, en función de las propiedades de la solicitud. 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: { 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': { } } } request['headers']['host'] = [ { 'key': 'host', 'value': 'www.example.com'}] return request Ejemplo: Uso de un desencadenador de solicitud al origen para transferir gradualmente el tráfico desde un bucket de Amazon S3 a otro Esta función demuestra cómo transferir gradualmente el tráfico desde un bucket de Amazon S3 a otro de forma controlada. 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}]; } 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 Ejemplo: Uso de un desencadenador de solicitud de origen para cambiar el nombre del dominio de origen en función del encabezado de país Esta función demuestra cómo cambiar el nombre del dominio de origen en función del encabezado CloudFront-Viewer-Country , de forma que el contenido se distribuya desde un origen más cercano al país del lector. La implementación de esta funcionalidad para su distribución puede tener ventajas como las siguientes: Reducir las latencias cuando la región especificada está más cerca del país del lector Proporcionar soberanía de los datos, al asegurarse de que los datos se distribuyen desde un origen que está en el país del que provino la solicitud Tenga en cuenta que para habilitar esta funcionalidad, debe configurar su distribución para almacenar en la caché en función del encabezado CloudFront-Viewer-Country . Para obtener más información, consulte Caché en función de encabezados de solicitud seleccionados . 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 request['headers']['host'] = [ { 'key': 'host', 'value': domainName}] return request Actualización de estados de error: ejemplos En los ejemplos siguientes se proporciona orientación acerca de cómo puede usar Lambda@Edge para cambiar el estado de error que se devuelve a los usuarios. Temas Ejemplo: Uso de un desencadenador de respuesta de origen para actualizar el código de estado de error a 200 Ejemplo: Uso de un desencadenador de respuesta de origen para actualizar el código de estado de error a 302 Ejemplo: Uso de un desencadenador de respuesta de origen para actualizar el código de estado de error a 200 Esta función demuestra cómo actualizar el estado de la respuesta a 200 y generar un cuerpo con contenido estático para devolverlo al espectador en la siguiente situación: La función se desencadena en una respuesta del origen. El estado de la respuesta del servidor de origen es un código de estado de error (4xx o 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'; } callback(null, response); }; Python 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 Ejemplo: Uso de un desencadenador de respuesta de origen para actualizar el código de estado de error a 302 Esta función demuestra cómo actualizar el código de estado HTTP a 302 para la redirección a otra ruta (comportamiento de la caché) en la que se ha configurado un origen diferente. Tenga en cuenta lo siguiente: La función se desencadena en una respuesta del origen. El estado de la respuesta del servidor de origen es un código de estado de error (4xx o 5xx). Node.js 'use strict'; exports.handler = (event, context, callback) => { const response = event.Records[0].cf.response; const 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 (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 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 Acceso al cuerpo de la solicitud: ejemplos En los ejemplos siguientes se muestra cómo puede usar Lambda@Edge para trabajar con las solicitudes POST. nota Para utilizar estos ejemplos, debe habilitar la opción incluir cuerpo en la asociación de funciones Lambda de la distribución. No está habilitada de forma predeterminada. Para habilitar esta configuración en la consola de CloudFront, seleccione la casilla de verificación Incluir cuerpo en la Asociación de funciones Lambda . Para habilitar esta configuración en la API de CloudFront o con CloudFormation, establezca el campo IncludeBody en true en LambdaFunctionAssociation . Temas Ejemplo: Uso de un desencadenador de solicitud para leer un formulario HTML Ejemplo: Uso de un desencadenador de solicitud para modificar un formulario HTML Ejemplo: Uso de un desencadenador de solicitud para leer un formulario HTML Esta función ilustra cómo puede procesar el cuerpo de una solicitud POST generada por un formulario HTML (formulario web), como por ejemplo un formulario tipo "póngase en contacto con nosotros". Por ejemplo, es posible que tenga un formulario HTML como el siguiente: <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> Para la función de ejemplo que se indica a continuación, la función se debe desencadenar en una solicitud al origen o del lector de CloudFront. 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 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 Ejemplo: Uso de un desencadenador de solicitud para modificar un formulario HTML Esta función ilustra cómo puede modificar el cuerpo de una solicitud POST generada por un formulario HTML (formulario web). La función se activa en una solicitud al origen o del lector de CloudFront. 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. * * 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'] | 2026-01-13T09:30:35 |
https://young-programmers.blogspot.com/2012/ | Young Programmers Podcast: 2012 skip to main | skip to sidebar Young Programmers Podcast A video podcast for computer programmers in grades 3 and up. We learn about Scratch, Tynker, Alice, Python, Pygame, and Scala, and interview interesting programmers. From professional software developer and teacher Dave Briccetti, and many special guests. Viewing the Videos or Subscribing to the Podcast Some of the entries have a picture, which you can click to access the video. Otherwise, to see the videos, use this icon to subscribe to or view the feed: Or, subscribe in iTunes Saturday, February 18, 2012 Kojo Wandering Turtles Showing how to create multiple turtles in Kojo, and make them wander around. Uses Scala features map and foreach. at 3:15 PM Labels: Kojo , Scala Saturday, January 14, 2012 Using Python's Input Function with Numbers We show how to use Python's input function to get numbers, without the program breaking if something other than a number is entered. at 1:26 PM Labels: python Newer Posts Older Posts Home Subscribe to: Comments (Atom) About Me Dave Briccetti View my complete profile Where to Get Software Kojo Python Alice Scratch Other Blogs Dave Briccetti’s Blog One of My Best Classes Ever 10 years ago Tags alice (3) Android (1) arduino (1) art (1) audacity (2) dictionary (2) Flickr (1) functions (2) gamedev (1) garageband (1) GIMP (2) Google (2) guest (4) hacker (1) higher-order functions (1) inkscape (1) interview (9) Java (2) JavaFX (2) Jython (3) Kojo (2) lift (1) music (2) physics (1) platform (1) programmer (4) pygame (6) python (31) PythonCard (1) random (6) Sande (2) Scala (5) scratch (10) shdh (2) shdh34 (2) sound (3) sprite (2) Swing (3) teaching (3) twitter (2) Tynker (1) Web Services (1) xturtle (1) Followers Blog Archive ►  2015 (1) ►  February (1) ►  2013 (4) ►  July (1) ►  June (3) ▼  2012 (2) ▼  February (1) Kojo Wandering Turtles ►  January (1) Using Python's Input Function with Numbers ►  2011 (8) ►  November (1) ►  July (3) ►  May (1) ►  February (2) ►  January (1) ►  2010 (6) ►  October (2) ►  June (2) ►  February (2) ►  2009 (37) ►  December (4) ►  November (1) ►  September (7) ►  August (11) ►  July (14)   | 2026-01-13T09:30:35 |
https://docs.aws.amazon.com/ja_jp/lambda/latest/dg/with-s3-example.html | チュートリアル: Amazon S3 トリガーを使用して Lambda 関数を呼び出す - AWS Lambda チュートリアル: Amazon S3 トリガーを使用して Lambda 関数を呼び出す - AWS Lambda ドキュメント AWS Lambda デベロッパーガイド Amazon S3 バケットを作成する テストオブジェクトをバケットにアップロードする 許可ポリシーを作成する 実行ロールを作成する Lambda 関数を作成する 関数コードをデプロイする Amazon S3 トリガーを作成する Lambda 関数をテストする リソースのクリーンアップ 次のステップ チュートリアル: Amazon S3 トリガーを使用して Lambda 関数を呼び出す このチュートリアルでは、コンソールを使用して Lambda 関数を作成し、Amazon Simple Storage Service (Amazon S3) バケットのトリガーを設定します。Amazon S3 バケットにオブジェクトを追加するたびに関数を実行し、Amazon CloudWatch Logs にオブジェクトタイプを出力します。 このチュートリアルでは、次の方法を示します。 Amazon S3 バケットを作成する。 Amazon S3 バケット内のオブジェクトのオブジェクトタイプを返す Lambda 関数を作成します。 オブジェクトがバケットにアップロードされたときに関数を呼び出す Lambda トリガーを設定します。 最初にダミーイベントを使用して関数をテストし、次にトリガーを使用してテストします。 これらのステップを完了することにより、Amazon S3 バケットにオブジェクトが追加されたり、Amazon S3 バケットから削除されたりするたびに実行されるように Lambda 関数を設定する方法を学びます。AWS マネジメントコンソール のみを使って、このチュートリアルを完了できます。 Amazon S3 バケットを作成する Amazon S3 バケットを作成するには [Amazon S3 コンソール] を開き、 [汎用バケット] ページを選択します。 住まいの地域に最も近い AWS リージョン を選択してください。画面上部にあるドロップダウンリストを使用して、リージョンを変更できます。チュートリアルの後半では、同じリージョンで Lambda 関数を作成する必要があります。 [バケットを作成する] を選択します。 [全般設定] で、次の操作を行います。 [バケットタイプ] で、 [汎用] が選択されていることを確認してください。 [バケット名] には、Amazon S3 バケットの命名規則 を満たすグローバルに一意な名前を入力します。バケット名は、小文字、数字、ドット (.)、およびハイフン (-) のみで構成できます。 他のすべてのオプションはデフォルト設定値のままにしておき、 [バケットの作成] を選択します。 テストオブジェクトをバケットにアップロードする テストオブジェクトをアップロードするには Amazon S3 コンソールの バケット ページを開き、前のステップで作成したバケットを選択します。 [アップロード] を選択します。 [ファイルを追加] を選択し、アップロードするファイルを選択します。任意のファイルを選択できます (例えば、 HappyFace.jpg )。 [開く] 、 [アップロード] の順に選択します。 チュートリアルの後半では、このオブジェクトを使用して Lambda 関数をテストします。 許可ポリシーを作成する Lambda が Amazon S3 バケットからオブジェクトを取得し、Amazon CloudWatch Logs に書き込めるようにする許可ポリシーを作成します。 ポリシーを作成するには IAM コンソールの ポリシー ページを開きます。 [ポリシーの作成] を選択します。 [JSON] タブを選択して、次のカスタムポリシーを JSON エディタに貼り付けます。 JSON { "Version":"2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "logs:PutLogEvents", "logs:CreateLogGroup", "logs:CreateLogStream" ], "Resource": "arn:aws:logs:*:*:*" }, { "Effect": "Allow", "Action": [ "s3:GetObject" ], "Resource": "arn:aws:s3:::*/*" } ] } [次へ: タグ] を選択します。 [次へ: レビュー] を選択します。 [ポリシーの確認] でポリシーの [名前] に「 s3-trigger-tutorial 」と入力します。 [ポリシーの作成] を選択します。 実行ロールを作成する 実行ロール とは、AWS のサービス およびリソースに対するアクセス許可を Lambda 関数に付与する AWS Identity and Access Management (IAM) のロールです。この手順では、前のステップで作成したアクセス権限ポリシーを使用して実行ロールを作成します。 実行ロールを作成して、カスタム許可ポリシーをアタッチするには IAM コンソールの ロールページ を開きます。 [ロールの作成] を選択します。 信頼されたエンティティには、 [AWS サービス] を選択し、ユースケースには [Lambda] を選択します。 [次へ] をクリックします。 ポリシー検索ボックスに、「 s3-trigger-tutorial 」と入力します。 検索結果で作成したポリシー ( s3-trigger-tutorial ) を選択し、 [次へ] を選択します。 [ロールの詳細] で [ロール名] に lambda-s3-trigger-role を入力してから、 [ロールの作成] を選択します。 Lambda 関数を作成する Python 3.13 ランタイムを使用してコンソールで Lambda 関数を作成します。 Lambda 関数を作成するには Lambda コンソールの 関数 ページを開きます。 Amazon S3 バケットを作成したときと同じ AWS リージョン で操作していることを確認してください。画面上部にあるドロップダウンリストを使用して、リージョンを変更できます。 [関数の作成] を選択します。 [一から作成] を選択します。 [基本的な情報] で、以下を実行します。 [関数名] に s3-trigger-tutorial と入力します。 [ランタイム] で [Python 3.13] を選択します。 [アーキテクチャ] で [x86_64] を選択します。 [デフォルトの実行ロールの変更] タブで、次の操作を行います。 タブを展開し、 [既存のロールを使用する] を選択します。 先ほど作成した lambda-s3-trigger-role を選択します。 [ 関数の作成 ] を選択してください。 関数コードをデプロイする このチュートリアルでは Python 3.13 ランタイムを使用しますが、他のランタイム用のコードファイルの例も用意しています。次のボックスでタブを選択すると、関心のあるランタイムのコードが表示されます。 Lambda 関数は、Amazon S3 から受信する event パラメータから、アップロードされたオブジェクトのキー名およびバケットの名前を取得します。次に、関数は AWS SDK for Python (Boto3) から「 get_object 」メソッドを使用し、アップロードされたオブジェクトのコンテンツタイプ (MIME タイプ) を含むオブジェクトのメタデータを取得します。 関数コードをデプロイするには 次のボックスで [Python] タブを選択し、コードをコピーします。 .NET SDK for .NET 注記 GitHub には、その他のリソースもあります。 サーバーレスサンプル リポジトリで完全な例を検索し、設定および実行の方法を確認してください。 .NET を使用して Lambda で S3 イベントを消費します。 // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System.Threading.Tasks; using Amazon.Lambda.Core; using Amazon.S3; using System; using Amazon.Lambda.S3Events; using System.Web; // Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class. [assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] namespace S3Integration { public class Function { private static AmazonS3Client _s3Client; public Function() : this(null) { } internal Function(AmazonS3Client s3Client) { _s3Client = s3Client ?? new AmazonS3Client(); } public async Task<string> Handler(S3Event evt, ILambdaContext context) { try { if (evt.Records.Count <= 0) { context.Logger.LogLine("Empty S3 Event received"); return string.Empty; } var bucket = evt.Records[0].S3.Bucket.Name; var key = HttpUtility.UrlDecode(evt.Records[0].S3.Object.Key); context.Logger.LogLine($"Request is for { bucket} and { key}"); var objectResult = await _s3Client.GetObjectAsync(bucket, key); context.Logger.LogLine($"Returning { objectResult.Key}"); return objectResult.Key; } catch (Exception e) { context.Logger.LogLine($"Error processing request - { e.Message}"); return string.Empty; } } } } Go SDK for Go V2 注記 GitHub には、その他のリソースもあります。 サーバーレスサンプル リポジトリで完全な例を検索し、設定および実行の方法を確認してください。 Go を使用して Lambda で S3 イベントを消費します。 // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package main import ( "context" "log" "github.com/aws/aws-lambda-go/events" "github.com/aws/aws-lambda-go/lambda" "github.com/aws/aws-sdk-go-v2/config" "github.com/aws/aws-sdk-go-v2/service/s3" ) func handler(ctx context.Context, s3Event events.S3Event) error { sdkConfig, err := config.LoadDefaultConfig(ctx) if err != nil { log.Printf("failed to load default config: %s", err) return err } s3Client := s3.NewFromConfig(sdkConfig) for _, record := range s3Event.Records { bucket := record.S3.Bucket.Name key := record.S3.Object.URLDecodedKey headOutput, err := s3Client.HeadObject(ctx, &s3.HeadObjectInput { Bucket: &bucket, Key: &key, }) if err != nil { log.Printf("error getting head of object %s/%s: %s", bucket, key, err) return err } log.Printf("successfully retrieved %s/%s of type %s", bucket, key, *headOutput.ContentType) } return nil } func main() { lambda.Start(handler) } Java SDK for Java 2.x 注記 GitHub には、その他のリソースもあります。 サーバーレスサンプル リポジトリで完全な例を検索し、設定および実行の方法を確認してください。 Java を使用して Lambda で S3 イベントを消費します。 // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package example; import software.amazon.awssdk.services.s3.model.HeadObjectRequest; import software.amazon.awssdk.services.s3.model.HeadObjectResponse; import software.amazon.awssdk.services.s3.S3Client; import com.amazonaws.services.lambda.runtime.Context; import com.amazonaws.services.lambda.runtime.RequestHandler; import com.amazonaws.services.lambda.runtime.events.S3Event; import com.amazonaws.services.lambda.runtime.events.models.s3.S3EventNotification.S3EventNotificationRecord; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class Handler implements RequestHandler<S3Event, String> { private static final Logger logger = LoggerFactory.getLogger(Handler.class); @Override public String handleRequest(S3Event s3event, Context context) { try { S3EventNotificationRecord record = s3event.getRecords().get(0); String srcBucket = record.getS3().getBucket().getName(); String srcKey = record.getS3().getObject().getUrlDecodedKey(); S3Client s3Client = S3Client.builder().build(); HeadObjectResponse headObject = getHeadObject(s3Client, srcBucket, srcKey); logger.info("Successfully retrieved " + srcBucket + "/" + srcKey + " of type " + headObject.contentType()); return "Ok"; } catch (Exception e) { throw new RuntimeException(e); } } private HeadObjectResponse getHeadObject(S3Client s3Client, String bucket, String key) { HeadObjectRequest headObjectRequest = HeadObjectRequest.builder() .bucket(bucket) .key(key) .build(); return s3Client.headObject(headObjectRequest); } } JavaScript SDK for JavaScript (v3) 注記 GitHub には、その他のリソースもあります。 サーバーレスサンプル リポジトリで完全な例を検索し、設定および実行の方法を確認してください。 JavaScript を使用して Lambda で S3 イベントを消費します。 import { S3Client, HeadObjectCommand } from "@aws-sdk/client-s3"; const client = new S3Client(); export const handler = async (event, context) => { // Get the object from the event and show its content type const bucket = event.Records[0].s3.bucket.name; const key = decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g, ' ')); try { const { ContentType } = await client.send(new HeadObjectCommand( { Bucket: bucket, Key: key, })); console.log('CONTENT TYPE:', ContentType); return ContentType; } catch (err) { console.log(err); const message = `Error getting object $ { key} from bucket $ { bucket}. Make sure they exist and your bucket is in the same region as this function.`; console.log(message); throw new Error(message); } }; TypeScript を使用して Lambda で S3 イベントを消費する。 // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 import { S3Event } from 'aws-lambda'; import { S3Client, HeadObjectCommand } from '@aws-sdk/client-s3'; const s3 = new S3Client( { region: process.env.AWS_REGION }); export const handler = async (event: S3Event): Promise<string | undefined> => { // Get the object from the event and show its content type const bucket = event.Records[0].s3.bucket.name; const key = decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g, ' ')); const params = { Bucket: bucket, Key: key, }; try { const { ContentType } = await s3.send(new HeadObjectCommand(params)); console.log('CONTENT TYPE:', ContentType); return ContentType; } catch (err) { console.log(err); const message = `Error getting object $ { key} from bucket $ { bucket}. Make sure they exist and your bucket is in the same region as this function.`; console.log(message); throw new Error(message); } }; PHP SDK for PHP 注記 GitHub には、その他のリソースもあります。 サーバーレスサンプル リポジトリで完全な例を検索し、設定および実行の方法を確認してください。 PHP を使用して Lambda で S3 イベントの消費。 <?php use Bref\Context\Context; use Bref\Event\S3\S3Event; use Bref\Event\S3\S3Handler; use Bref\Logger\StderrLogger; require __DIR__ . '/vendor/autoload.php'; class Handler extends S3Handler { private StderrLogger $logger; public function __construct(StderrLogger $logger) { $this->logger = $logger; } public function handleS3(S3Event $event, Context $context) : void { $this->logger->info("Processing S3 records"); // Get the object from the event and show its content type $records = $event->getRecords(); foreach ($records as $record) { $bucket = $record->getBucket()->getName(); $key = urldecode($record->getObject()->getKey()); try { $fileSize = urldecode($record->getObject()->getSize()); echo "File Size: " . $fileSize . "\n"; // TODO: Implement your custom processing logic here } catch (Exception $e) { echo $e->getMessage() . "\n"; echo 'Error getting object ' . $key . ' from bucket ' . $bucket . '. Make sure they exist and your bucket is in the same region as this function.' . "\n"; throw $e; } } } } $logger = new StderrLogger(); return new Handler($logger); Python SDK for Python (Boto3) 注記 GitHub には、その他のリソースもあります。 サーバーレスサンプル リポジトリで完全な例を検索し、設定および実行の方法を確認してください。 Python を使用して Lambda で S3 イベントを消費します。 # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 import json import urllib.parse import boto3 print('Loading function') s3 = boto3.client('s3') def lambda_handler(event, context): #print("Received event: " + json.dumps(event, indent=2)) # Get the object from the event and show its content type bucket = event['Records'][0]['s3']['bucket']['name'] key = urllib.parse.unquote_plus(event['Records'][0]['s3']['object']['key'], encoding='utf-8') try: response = s3.get_object(Bucket=bucket, Key=key) print("CONTENT TYPE: " + response['ContentType']) return response['ContentType'] except Exception as e: print(e) print('Error getting object { } from bucket { }. Make sure they exist and your bucket is in the same region as this function.'.format(key, bucket)) raise e Ruby SDK for Ruby 注記 GitHub には、その他のリソースもあります。 サーバーレスサンプル リポジトリで完全な例を検索し、設定および実行の方法を確認してください。 Ruby を使用して Lambda での S3 イベントの消費。 require 'json' require 'uri' require 'aws-sdk' puts 'Loading function' def lambda_handler(event:, context:) s3 = Aws::S3::Client.new(region: 'region') # Your AWS region # puts "Received event: # { JSON.dump(event)}" # Get the object from the event and show its content type bucket = event['Records'][0]['s3']['bucket']['name'] key = URI.decode_www_form_component(event['Records'][0]['s3']['object']['key'], Encoding::UTF_8) begin response = s3.get_object(bucket: bucket, key: key) puts "CONTENT TYPE: # { response.content_type}" return response.content_type rescue StandardError => e puts e.message puts "Error getting object # { key} from bucket # { bucket}. Make sure they exist and your bucket is in the same region as this function." raise e end end Rust SDK for Rust 注記 GitHub には、その他のリソースもあります。 サーバーレスサンプル リポジトリで完全な例を検索し、設定および実行の方法を確認してください。 Rust を使用して Lambda で S3 イベントを消費します。 // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 use aws_lambda_events::event::s3::S3Event; use aws_sdk_s3:: { Client}; use lambda_runtime:: { run, service_fn, Error, LambdaEvent}; /// Main function #[tokio::main] async fn main() -> Result<(), Error> { tracing_subscriber::fmt() .with_max_level(tracing::Level::INFO) .with_target(false) .without_time() .init(); // Initialize the AWS SDK for Rust let config = aws_config::load_from_env().await; let s3_client = Client::new(&config); let res = run(service_fn(|request: LambdaEvent<S3Event>| { function_handler(&s3_client, request) })).await; res } async fn function_handler( s3_client: &Client, evt: LambdaEvent<S3Event> ) -> Result<(), Error> { tracing::info!(records = ?evt.payload.records.len(), "Received request from SQS"); if evt.payload.records.len() == 0 { tracing::info!("Empty S3 event received"); } let bucket = evt.payload.records[0].s3.bucket.name.as_ref().expect("Bucket name to exist"); let key = evt.payload.records[0].s3.object.key.as_ref().expect("Object key to exist"); tracing::info!("Request is for { } and object { }", bucket, key); let s3_get_object_result = s3_client .get_object() .bucket(bucket) .key(key) .send() .await; match s3_get_object_result { Ok(_) => tracing::info!("S3 Get Object success, the s3GetObjectResult contains a 'body' property of type ByteStream"), Err(_) => tracing::info!("Failure with S3 Get Object request") } Ok(()) } Lambda コンソールの [コードソース] ペインで、コードをコードエディタに貼り付け、Lambda が作成したコードを置き換えます。 [DEPLOY] セクションで、 [デプロイ] を選択して関数のコードを更新します。 Amazon S3 トリガーを作成する Amazon S3 トリガーを作成するには [関数の概要] ペインで、 [トリガーを追加] を選択します。 [S3] を選択します。 [バケット] で、前のチュートリアルで作成したバケットを選択します。 [イベントタイプ] で、 [すべてのオブジェクトの作成イベント] を選択します。 [再帰呼び出し] でチェックボックスを選択して、入力と出力に同じ Amazon S3 バケットを使用することは推奨されないことを確認します。 [Add] (追加) を選択します。 注記 Lambda コンソールを使用して Lambda 関数の Amazon S3 トリガーを作成すると、Amazon S3 は指定したバケットに対して イベント通知 を設定します。このイベント通知を設定する前に、Amazon S3 は一連のチェックを実行して、イベントの送信先が存在し、必要な IAM ポリシーがあることを確認します。また、Amazon S3 は、そのバケットに設定されている他のイベント通知に対してもこれらのテストを実行します。 このチェックが行われるために、既に存在しないリソースや必要なアクセス許可ポリシーを持たないリソースのイベントの送信先がバケットで既に設定されている場合、Amazon S3 は新しいイベント通知を作成できません。トリガーを作成できなかったことを示す次のエラーメッセージが表示されます。 An error occurred when creating the trigger: Unable to validate the following destination configurations. このエラーは、以前に同じバケットを使用して別の Lambda 関数のトリガーを設定しており、その後に関数を削除したり、そのアクセス許可ポリシーを変更したりした場合に表示されます。 Lambda 関数をダミーイベントでテストする Lambda 関数をダミーイベントでテストするには 関数の Lambda コンソールページで、 [テスト] タブを選択します。 イベント名 ()で、 MyTestEvent と入力します。 [イベント JSON] で、次のテストイベントを貼り付けます。次の値を必ず置き換えてください。 us-east-1 を Amazon S3 バケットを作成したリージョンに置き換えます。 amzn-s3-demo-bucket の両方のインスタンスをお使いの Amazon S3 バケットの名前に置き換えます。 test%2FKey を前にバケットにアップロードしたテストオブジェクトの名前 (例えば、 HappyFace.jpg ) に置き換えます。 { "Records": [ { "eventVersion": "2.0", "eventSource": "aws:s3", "awsRegion": " us-east-1 ", "eventTime": "1970-01-01T00:00:00.000Z", "eventName": "ObjectCreated:Put", "userIdentity": { "principalId": "EXAMPLE" }, "requestParameters": { "sourceIPAddress": "127.0.0.1" }, "responseElements": { "x-amz-request-id": "EXAMPLE123456789", "x-amz-id-2": "EXAMPLE123/5678abcdefghijklambdaisawesome/mnopqrstuvwxyzABCDEFGH" }, "s3": { "s3SchemaVersion": "1.0", "configurationId": "testConfigRule", "bucket": { "name": " amzn-s3-demo-bucket ", "ownerIdentity": { "principalId": "EXAMPLE" }, "arn": "arn:aws:s3::: amzn-s3-demo-bucket " }, "object": { "key": " test%2Fkey ", "size": 1024, "eTag": "0123456789abcdef0123456789abcdef", "sequencer": "0A1B2C3D4E5F678901" } } } ] } [保存] を選択します。 [ Test ] を選択します。 関数が正常に実行されると、 [実行結果] タブに次のような出力が表示されます。 Response "image/jpeg" Function Logs START RequestId: 12b3cae7-5f4e-415e-93e6-416b8f8b66e6 Version: $LATEST 2021-02-18T21:40:59.280Z 12b3cae7-5f4e-415e-93e6-416b8f8b66e6 INFO INPUT BUCKET AND KEY: { Bucket: 'amzn-s3-demo-bucket', Key: 'HappyFace.jpg' } 2021-02-18T21:41:00.215Z 12b3cae7-5f4e-415e-93e6-416b8f8b66e6 INFO CONTENT TYPE: image/jpeg END RequestId: 12b3cae7-5f4e-415e-93e6-416b8f8b66e6 REPORT RequestId: 12b3cae7-5f4e-415e-93e6-416b8f8b66e6 Duration: 976.25 ms Billed Duration: 977 ms Memory Size: 128 MB Max Memory Used: 90 MB Init Duration: 430.47 ms Request ID 12b3cae7-5f4e-415e-93e6-416b8f8b66e6 Amazon S3 トリガーを使用して Lambda 関数をテストする 設定したトリガーで関数をテストするには、コンソールを使用して Amazon S3 バケットにオブジェクトをアップロードします。Lambda 関数が予想通りに実行されたことを確認するには、CloudWatch Logs を使用して関数の出力を確認します。 オブジェクトを Amazon S3 バケットにアップロードするには Amazon S3 コンソールの「 バケット 」ページを開き、先ほど作成したバケットを選択します。 [アップロード] を選択します。 [ファイルを追加] を選択し、ファイルセレクターを使用してアップロードするオブジェクトを選択します。このオブジェクトには任意のファイルを選択できます。 [開く] 、 [アップロード] の順に選択します。 CloudWatch Logs を使用して関数の呼び出しを確認する方法 CloudWatch コンソールを開きます。 Lambda 関数を作成したところと同じ AWS リージョン で操作していることを確認してください。画面上部にあるドロップダウンリストを使用して、リージョンを変更できます。 [ログ] 、 [ロググループ] の順に選択します。 関数のロググループの名前を選択します ( /aws/lambda/s3-trigger-tutorial ) 。 [ログストリーム] から、最新のログストリームを選択します。 Amazon S3 トリガーに応答して関数が正しく呼び出される場合、次のような内容と同じような出力が表示されます。表示される CONTENT TYPE は、バケットにアップロードしたファイルのタイプによって異なります。 2022-05-09T23:17:28.702Z 0cae7f5a-b0af-4c73-8563-a3430333cc10 INFO CONTENT TYPE: image/jpeg リソースのクリーンアップ このチュートリアル用に作成したリソースは、保持しない場合は削除できます。使用しなくなった AWS リソースを削除することで、AWS アカウント アカウントに請求される料金の発生を防ぎます。 Lambda 関数を削除するには Lambda コンソールの [関数] ページを開きます。 作成した関数を選択します。 [アクション] で、 [削除] を選択します。 テキスト入力フィールドに confirm と入力し、 [削除] を選択します。 実行ロールを削除する IAM コンソールの [ロール] ページを開きます。 作成した実行ロールを選択します。 [削除] を選択します。 テキスト入力フィールドにロールの名前を入力し、 [削除] を選択します。 S3 バケットを削除するには Amazon S3 コンソール を開きます。 作成したバケットを選択します。 [ 削除 ] を選択します。 テキスト入力フィールドにバケットの名前を入力します。 [バケットを削除] を選択します。 次のステップ チュートリアル: Amazon S3 トリガーを使用してサムネイル画像を作成する では、Amazon S3 トリガーが関数を呼び出します。この感想は、バケットにアップロードされる各イメージファイルにサムネイルイメージを作成します。このチュートリアルでは、AWS と Lambda ドメインに関する中級レベルの知識が必要です。AWS Command Line Interface (AWS CLI) を使用してリソースを作成し、関数およびその依存関係に .zip ファイルアーカイブのデプロイパッケージを作成する方法を示します。 ブラウザで JavaScript が無効になっているか、使用できません。 AWS ドキュメントを使用するには、JavaScript を有効にする必要があります。手順については、使用するブラウザのヘルプページを参照してください。 ドキュメントの表記規則 S3 チュートリアル: Amazon S3 トリガーを使用してサムネイルを作成する このページは役に立ちましたか? - はい ページが役に立ったことをお知らせいただき、ありがとうございます。 お時間がある場合は、何が良かったかお知らせください。今後の参考にさせていただきます。 このページは役に立ちましたか? - いいえ このページは修正が必要なことをお知らせいただき、ありがとうございます。ご期待に沿うことができず申し訳ありません。 お時間がある場合は、ドキュメントを改善する方法についてお知らせください。 | 2026-01-13T09:30:35 |
https://docs.aws.amazon.com/es_es/AmazonCloudFront/latest/DeveloperGuide/lambda-examples.html#lambda-examples-access-request-body-examples | Funciones de ejemplo de Lambda@Edge - Amazon CloudFront Funciones de ejemplo de Lambda@Edge - Amazon CloudFront Documentación Amazon CloudFront Guía para desarrolladores Ejemplos generales Generación de respuestas: ejemplos Cadenas de consulta: ejemplos Personalización de contenido por encabezados de tipo de dispositivo o país: ejemplos Selección de origen dinámico basada en contenido: ejemplos Actualización de estados de error: ejemplos Acceso al cuerpo de la solicitud: ejemplos Funciones de ejemplo de Lambda@Edge Consulte los ejemplos siguientes para usar funciones de Lambda con Amazon CloudFront. nota Si elige el tiempo de ejecución Node.js 18 o una versión posterior para la función Lambda@Edge, se creará automáticamente un archivo index.mjs . Para usar los siguientes ejemplos de código, cambie el nombre del archivo index.mjs a index.js . Temas Ejemplos generales Generación de respuestas: ejemplos Cadenas de consulta: ejemplos Personalización de contenido por encabezados de tipo de dispositivo o país: ejemplos Selección de origen dinámico basada en contenido: ejemplos Actualización de estados de error: ejemplos Acceso al cuerpo de la solicitud: ejemplos Ejemplos generales Los ejemplos siguientes muestran formas habituales de usar Lambda@Edge en CloudFront. Temas Ejemplo: prueba A/B Ejemplo: Sobrescritura de un encabezado de respuesta Ejemplo: prueba A/B Puede utilizar el siguiente ejemplo para probar dos versiones diferentes de una imagen sin crear redirecciones ni cambiar la dirección URL. En este ejemplo se leen las cookies de la solicitud del lector y se modifica la URL de la solicitud en consecuencia. Si el espectador no envía una cookie con uno de los valores esperados, el ejemplo asigna aleatoriamente al espectador una de las URL. 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; } 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; } } 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" ''' experimentUri = "" 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 Ejemplo: Sobrescritura de un encabezado de respuesta En el ejemplo siguiente, se muestra cómo cambiar el valor de un encabezado de respuesta según el valor de otro encabezado. Node.js export const handler = async (event) => { 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()] = [ { key: headerNameDst, value: headers[headerNameSrc.toLowerCase()][0].value, }]; console.log(`Response header "$ { headerNameDst}" was set to ` + `"$ { headers[headerNameDst.toLowerCase()][0].value}"`); } return response; }; Python import json def lambda_handler(event, context): response = event['Records'][0]['cf']['response'] headers = response['headers'] header_name_src = 'X-Amz-Meta-Last-Modified' header_name_dst = 'Last-Modified' if headers.get(header_name_src.lower()): headers[header_name_dst.lower()] = [ { 'key': header_name_dst, 'value': headers[header_name_src.lower()][0]['value'] }] print(f'Response header " { header_name_dst}" was set to ' f'" { headers[header_name_dst.lower()][0]["value"]}"') return response Generación de respuestas: ejemplos En los ejemplos siguientes se muestra cómo puede usar Lambda@Edge para generar respuestas. Temas Ejemplo: Envío de contenido estático (respuesta generada) Ejemplo: Generación de un redireccionamiento HTTP (respuesta generada) Ejemplo: Envío de contenido estático (respuesta generada) En el siguiente ejemplo se muestra cómo utilizar una función de Lambda para enviar contenido de sitio web estático, lo que reduce la carga en el servidor de origen y la latencia total. nota Puede generar respuestas HTTP para los eventos de solicitud del espectador y al origen. Para obtener más información, consulte Generación de respuestas HTTP en los desencadenadores de solicitud . También puede sustituir o quitar el cuerpo de la respuesta HTTP en eventos de respuesta de origen. Para obtener más información, consulte Actualización de respuestas HTTP en desencadenadores de respuesta de origen . 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' }] }, 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 } return response Ejemplo: Generación de un redireccionamiento HTTP (respuesta generada) En el siguiente ejemplo se muestra cómo generar una redirección HTTP. nota Puede generar respuestas HTTP para los eventos de solicitud del espectador y al origen. Para obtener más información, consulte Generación de respuestas HTTP en los desencadenadores de solicitud . 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. response = { 'status': '302', 'statusDescription': 'Found', 'headers': { 'location': [ { 'key': 'Location', 'value': 'https://docs.aws.amazon.com/lambda/latest/dg/lambda-edge.html' }] } } return response Cadenas de consulta: ejemplos En los ejemplos siguientes se muestran formas de usar Lambda@Edge con cadenas de consulta. Temas Ejemplo: Adición de un encabezado en función de un parámetro de la cadena de consulta Ejemplo: Normalización de parámetros de cadenas de consulta para mejorar la tasa de aciertos de caché Ejemplo: Redireccionamiento de los usuarios no autenticados a una página de inicio de sesión Ejemplo: Adición de un encabezado en función de un parámetro de la cadena de consulta El siguiente ejemplo muestra cómo obtener el par clave-valor de un parámetro de la cadena de consulta y, a continuación, añadir un encabezado en función de dichos valores. 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. * 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 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'] # Update request querystring request['querystring'] = urlencode(params) return request Ejemplo: Normalización de parámetros de cadenas de consulta para mejorar la tasa de aciertos de caché El siguiente ejemplo muestra cómo mejorar la tasa de acceso a la caché haciendo los siguientes cambios en las cadenas de consulta antes de que CloudFront reenvíe las solicitudes a su origen: Alfabetizar los pares de clave-valor por el nombre del parámetro. Cambiar a minúsculas el modelo de mayúsculas y minúsculas de los pares de clave-valor. Para obtener más información, consulte Almacenamiento en caché de contenido en función de parámetros de cadenas de consulta . 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 */ 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 request['querystring'] = urlencode(sortedParams) return request Ejemplo: Redireccionamiento de los usuarios no autenticados a una página de inicio de sesión El siguiente ejemplo muestra cómo redirigir a los usuarios una página de inicio de sesión si no ha introducido sus credenciales. 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; } /* 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 params. ''' # Check for session-id in cookie, if present, then proceed with request parsedCookies = parseCookies(headers) 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 Personalización de contenido por encabezados de tipo de dispositivo o país: ejemplos En los ejemplos siguientes se muestra cómo puede usar Lambda@Edge para personalizar el comportamiento en función de la ubicación o el tipo de dispositivo que usa el lector. Temas Ejemplo: Redireccionamiento de solicitudes de espectadores a una URL específica de un país Ejemplo: Envío de distintas versiones de un objeto en función del dispositivo Ejemplo: Redireccionamiento de solicitudes de espectadores a una URL específica de un país El siguiente ejemplo muestra cómo generar una respuesta de redireccionamiento HTTP con una URL específica del país y devolver la respuesta al espectador. Esto resulta útil cuando se quiere proporcionar respuestas específicas del país. Por ejemplo: Si tiene subdominios específicos de un país, como us.ejemplo.com y tw.ejemplo.com, puede generar una respuesta de redireccionamiento cuando un espectador solicite ejemplo.com. Si está haciendo streaming de video, pero no tiene derechos para transmitir el contenido en un país determinado, puede redirigir a los usuarios de dicho país a una página en la que se explica por qué no pueden ver el video. Tenga en cuenta lo siguiente: Debe configurar la distribución para almacenar en la caché en función del encabezado CloudFront-Viewer-Country . Para obtener más información, consulte Caché en función de encabezados de solicitud seleccionados . CloudFront agrega el encabezado CloudFront-Viewer-Country después del evento de solicitud del lector. Para utilizar este ejemplo, debe crear un activador para el evento de solicitud al origen. 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 = { 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', 'statusDescription': 'Found', 'headers': { 'location': [ { 'key': 'Location', 'value': url }] } } return response Ejemplo: Envío de distintas versiones de un objeto en función del dispositivo El siguiente ejemplo muestra cómo ofrecer distintas versiones de un objeto en función del tipo de dispositivo que el usuario está utilizando; por ejemplo, un dispositivo móvil o una tablet. Tenga en cuenta lo siguiente: Debe configurar la distribución para almacenar en la caché en función de los encabezados CloudFront-Is-*-Viewer . Para obtener más información, consulte Caché en función de encabezados de solicitud seleccionados . CloudFront agrega los encabezados CloudFront-Is-*-Viewer después del evento de solicitud del lector. Para utilizar este ejemplo, debe crear un activador para el evento de solicitud al origen. 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 * 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. ''' desktopPath = '/desktop'; mobilePath = '/mobile'; tabletPath = '/tablet'; smarttvPath = '/smarttv'; 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 Selección de origen dinámico basada en contenido: ejemplos En los ejemplos siguientes se muestra cómo puede usar Lambda@Edge para el direccionamiento a diferentes orígenes en función de la información de la solicitud. Temas Ejemplo: Uso de un desencadenador de solicitud de origen para cambiar desde un origen personalizado a un origen de Amazon S3 Ejemplo: Uso de un desencadenador de solicitud de origen para cambiar la región de origen de Amazon S3 Ejemplo: Uso de un desencadenador de solicitud de origen para cambiar desde un origen de Amazon S3 a un origen personalizado Ejemplo: Uso de un desencadenador de solicitud al origen para transferir gradualmente el tráfico desde un bucket de Amazon S3 a otro Ejemplo: Uso de un desencadenador de solicitud de origen para cambiar el nombre del dominio de origen en función del encabezado de país Ejemplo: Uso de un desencadenador de solicitud de origen para cambiar desde un origen personalizado a un origen de Amazon S3 Esta función demuestra cómo utilizar un desencadenador de solicitud al origen para cambiar desde un origen personalizado a un origen de Amazon S3 desde el que recuperar el contenido, en función de las propiedades de la solicitud. 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: 'origin-access-identity', path: '', customHeaders: { } } }; request.headers['host'] = [ { key: 'host', value: s3DomainName}]; } } 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 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': 'origin-access-identity', 'path': '', 'customHeaders': { } } } request['headers']['host'] = [ { 'key': 'host', 'value': s3DomainName}] return request Ejemplo: Uso de un desencadenador de solicitud de origen para cambiar la región de origen de Amazon S3 Esta función demuestra cómo utilizar un desencadenador de solicitud al origen para cambiar el origen de Amazon S3 desde el que se recupera el contenido, en función de las propiedades de la solicitud. En este ejemplo, utilizamos el valor del encabezado CloudFront-Viewer-Country para actualizar el nombre de dominio del bucket de S3 por un bucket de una región que está más cerca del lector. Esto puede resultar útil de varias maneras: Reduce las latencias cuando la región especificada está más cerca del país del lector. Proporciona soberanía de los datos, al asegurarse de que los datos se distribuyen desde un origen que está en el país del que provino la solicitud. Para utilizar este ejemplo, debe hacer lo siguiente: Configure la distribución para almacenar en la caché en función del encabezado CloudFront-Viewer-Country . Para obtener más información, consulte Caché en función de encabezados de solicitud seleccionados . Crear un disparador para esta función en el evento de solicitud al origen. CloudFront agrega el encabezado CloudFront-Viewer-Country después del evento de solicitud del lector; por lo tanto, para utilizar este ejemplo, debe asegurarse de que la función ejecuta una solicitud de origen. nota El siguiente código de ejemplo usa la misma identidad de acceso de origen (OAI) para todos los buckets de S3 que usa para el origen. Para obtener más información, consulte Identidad de acceso de origen . 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 * 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); }; Python 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: 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: ''' 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 Ejemplo: Uso de un desencadenador de solicitud de origen para cambiar desde un origen de Amazon S3 a un origen personalizado Esta función demuestra cómo utilizar un disparador de solicitud al origen para cambiar el origen personalizado desde el que se recupera el contenido, en función de las propiedades de la solicitud. 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: { 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': { } } } request['headers']['host'] = [ { 'key': 'host', 'value': 'www.example.com'}] return request Ejemplo: Uso de un desencadenador de solicitud al origen para transferir gradualmente el tráfico desde un bucket de Amazon S3 a otro Esta función demuestra cómo transferir gradualmente el tráfico desde un bucket de Amazon S3 a otro de forma controlada. 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}]; } 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 Ejemplo: Uso de un desencadenador de solicitud de origen para cambiar el nombre del dominio de origen en función del encabezado de país Esta función demuestra cómo cambiar el nombre del dominio de origen en función del encabezado CloudFront-Viewer-Country , de forma que el contenido se distribuya desde un origen más cercano al país del lector. La implementación de esta funcionalidad para su distribución puede tener ventajas como las siguientes: Reducir las latencias cuando la región especificada está más cerca del país del lector Proporcionar soberanía de los datos, al asegurarse de que los datos se distribuyen desde un origen que está en el país del que provino la solicitud Tenga en cuenta que para habilitar esta funcionalidad, debe configurar su distribución para almacenar en la caché en función del encabezado CloudFront-Viewer-Country . Para obtener más información, consulte Caché en función de encabezados de solicitud seleccionados . 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 request['headers']['host'] = [ { 'key': 'host', 'value': domainName}] return request Actualización de estados de error: ejemplos En los ejemplos siguientes se proporciona orientación acerca de cómo puede usar Lambda@Edge para cambiar el estado de error que se devuelve a los usuarios. Temas Ejemplo: Uso de un desencadenador de respuesta de origen para actualizar el código de estado de error a 200 Ejemplo: Uso de un desencadenador de respuesta de origen para actualizar el código de estado de error a 302 Ejemplo: Uso de un desencadenador de respuesta de origen para actualizar el código de estado de error a 200 Esta función demuestra cómo actualizar el estado de la respuesta a 200 y generar un cuerpo con contenido estático para devolverlo al espectador en la siguiente situación: La función se desencadena en una respuesta del origen. El estado de la respuesta del servidor de origen es un código de estado de error (4xx o 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'; } callback(null, response); }; Python 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 Ejemplo: Uso de un desencadenador de respuesta de origen para actualizar el código de estado de error a 302 Esta función demuestra cómo actualizar el código de estado HTTP a 302 para la redirección a otra ruta (comportamiento de la caché) en la que se ha configurado un origen diferente. Tenga en cuenta lo siguiente: La función se desencadena en una respuesta del origen. El estado de la respuesta del servidor de origen es un código de estado de error (4xx o 5xx). Node.js 'use strict'; exports.handler = (event, context, callback) => { const response = event.Records[0].cf.response; const 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 (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 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 Acceso al cuerpo de la solicitud: ejemplos En los ejemplos siguientes se muestra cómo puede usar Lambda@Edge para trabajar con las solicitudes POST. nota Para utilizar estos ejemplos, debe habilitar la opción incluir cuerpo en la asociación de funciones Lambda de la distribución. No está habilitada de forma predeterminada. Para habilitar esta configuración en la consola de CloudFront, seleccione la casilla de verificación Incluir cuerpo en la Asociación de funciones Lambda . Para habilitar esta configuración en la API de CloudFront o con CloudFormation, establezca el campo IncludeBody en true en LambdaFunctionAssociation . Temas Ejemplo: Uso de un desencadenador de solicitud para leer un formulario HTML Ejemplo: Uso de un desencadenador de solicitud para modificar un formulario HTML Ejemplo: Uso de un desencadenador de solicitud para leer un formulario HTML Esta función ilustra cómo puede procesar el cuerpo de una solicitud POST generada por un formulario HTML (formulario web), como por ejemplo un formulario tipo "póngase en contacto con nosotros". Por ejemplo, es posible que tenga un formulario HTML como el siguiente: <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> Para la función de ejemplo que se indica a continuación, la función se debe desencadenar en una solicitud al origen o del lector de CloudFront. 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 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 Ejemplo: Uso de un desencadenador de solicitud para modificar un formulario HTML Esta función ilustra cómo puede modificar el cuerpo de una solicitud POST generada por un formulario HTML (formulario web). La función se activa en una solicitud al origen o del lector de CloudFront. 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. * * 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'] | 2026-01-13T09:30:35 |
https://docs.aws.amazon.com/id_id/lambda/latest/dg/with-s3-tutorial.html#with-s3-tutorial-test-s3 | Tutorial: Menggunakan pemicu Amazon S3 untuk membuat gambar thumbnail - AWS Lambda Tutorial: Menggunakan pemicu Amazon S3 untuk membuat gambar thumbnail - AWS Lambda Dokumentasi AWS Lambda Panduan Developerr Prasyarat Buat dua ember Amazon S3 Unggah gambar uji ke bucket sumber Anda Membuat kebijakan izin Membuat peran eksekusi Buat paket penerapan fungsi Buat fungsi Lambda Konfigurasikan Amazon S3 untuk menjalankan fungsi Uji fungsi Lambda Anda dengan acara dummy Uji fungsi Anda menggunakan pemicu Amazon S3 Bersihkan sumber daya Anda Terjemahan disediakan oleh mesin penerjemah. Jika konten terjemahan yang diberikan bertentangan dengan versi bahasa Inggris aslinya, utamakan versi bahasa Inggris. Tutorial: Menggunakan pemicu Amazon S3 untuk membuat gambar thumbnail Dalam tutorial ini, Anda membuat dan mengonfigurasi fungsi Lambda yang mengubah ukuran gambar yang ditambahkan ke bucket Amazon Simple Storage Service (Amazon S3). Saat Anda menambahkan file gambar ke bucket, Amazon S3 akan memanggil fungsi Lambda Anda. Fungsi tersebut kemudian membuat versi thumbnail gambar dan mengeluarkannya ke bucket Amazon S3 yang berbeda. Untuk menyelesaikan tutorial ini, Anda melakukan langkah-langkah berikut: Buat bucket Amazon S3 sumber dan tujuan dan unggah gambar sampel. Buat fungsi Lambda yang mengubah ukuran gambar dan mengeluarkan thumbnail ke bucket Amazon S3. Konfigurasikan pemicu Lambda yang memanggil fungsi Anda saat objek diunggah ke bucket sumber Anda. Uji fungsi Anda, pertama dengan acara dummy, lalu dengan mengunggah gambar ke bucket sumber Anda. Dengan menyelesaikan langkah-langkah ini, Anda akan mempelajari cara menggunakan Lambda untuk menjalankan tugas pemrosesan file pada objek yang ditambahkan ke bucket Amazon S3. Anda dapat menyelesaikan tutorial ini menggunakan AWS Command Line Interface (AWS CLI) atau Konsol Manajemen AWS. Jika Anda mencari contoh sederhana untuk mempelajari cara mengonfigurasi pemicu Amazon S3 untuk Lambda, Anda dapat mencoba Tutorial: Menggunakan pemicu Amazon S3 untuk menjalankan fungsi Lambda. Topik Prasyarat Buat dua ember Amazon S3 Unggah gambar uji ke bucket sumber Anda Membuat kebijakan izin Membuat peran eksekusi Buat paket penerapan fungsi Buat fungsi Lambda Konfigurasikan Amazon S3 untuk menjalankan fungsi Uji fungsi Lambda Anda dengan acara dummy Uji fungsi Anda menggunakan pemicu Amazon S3 Bersihkan sumber daya Anda Prasyarat Jika Anda ingin menggunakan AWS CLI untuk menyelesaikan tutorial, instal versi terbaru dari AWS Command Line Interface . Untuk kode fungsi Lambda Anda, Anda dapat menggunakan Python atau Node.js. Instal alat dukungan bahasa dan manajer paket untuk bahasa yang ingin Anda gunakan. Jika Anda belum menginstal AWS Command Line Interface, ikuti langkah-langkah di Menginstal atau memperbarui versi terbaru AWS CLI untuk menginstalnya . Tutorial ini membutuhkan terminal baris perintah atau shell untuk menjalankan perintah. Di Linux dan macOS, gunakan shell dan manajer paket pilihan Anda. catatan Di Windows, beberapa perintah Bash CLI yang biasa Anda gunakan dengan Lambda ( zip seperti) tidak didukung oleh terminal bawaan sistem operasi. Untuk mendapatkan versi terintegrasi Windows dari Ubuntu dan Bash, instal Windows Subsystem untuk Linux. Buat dua ember Amazon S3 Pertama buat dua ember Amazon S3. Bucket pertama adalah bucket sumber tempat Anda akan mengunggah gambar Anda. Bucket kedua digunakan oleh Lambda untuk menyimpan thumbnail yang diubah ukurannya saat Anda menjalankan fungsi. Konsol Manajemen AWS Untuk membuat bucket Amazon S3 (konsol) Buka konsol Amazon S3 dan pilih halaman Bucket tujuan umum . Pilih yang Wilayah AWS paling dekat dengan lokasi geografis Anda. Anda dapat mengubah wilayah Anda menggunakan daftar drop-down di bagian atas layar. Kemudian dalam tutorial, Anda harus membuat fungsi Lambda Anda di Wilayah yang sama. Pilih Buat bucket . Pada Konfigurasi umum , lakukan hal berikut: Untuk jenis Bucket , pastikan Tujuan umum dipilih. Untuk nama Bucket , masukkan nama unik global yang memenuhi aturan penamaan Amazon S3 Bucket . Nama bucket hanya dapat berisi huruf kecil, angka, titik (.), dan tanda hubung (-). Biarkan semua opsi lain disetel ke nilai defaultnya dan pilih Buat bucket . Ulangi langkah 1 hingga 5 untuk membuat bucket tujuan Anda. Untuk nama Bucket amzn-s3-demo-source-bucket-resized , masukkan, di amzn-s3-demo-source-bucket mana nama bucket sumber yang baru saja Anda buat. AWS CLI Untuk membuat bucket Amazon S3 ()AWS CLI Jalankan perintah CLI berikut untuk membuat bucket sumber Anda. Nama yang Anda pilih untuk bucket Anda harus unik secara global dan ikuti aturan penamaan Amazon S3 Bucket . Nama hanya dapat berisi huruf kecil, angka, titik (.), dan tanda hubung (-). Untuk region dan LocationConstraint , pilih yang paling Wilayah AWS dekat dengan lokasi geografis Anda. aws s3api create-bucket --bucket amzn-s3-demo-source-bucket --region us-east-1 \ --create-bucket-configuration LocationConstraint= us-east-1 Kemudian dalam tutorial, Anda harus membuat fungsi Lambda Anda Wilayah AWS sama dengan bucket sumber Anda, jadi catat wilayah yang Anda pilih. Jalankan perintah berikut untuk membuat bucket tujuan Anda. Untuk nama bucket, Anda harus menggunakan amzn-s3-demo-source-bucket-resized , di amzn-s3-demo-source-bucket mana nama bucket sumber yang Anda buat di langkah 1. Untuk region dan LocationConstraint , pilih yang sama dengan yang Wilayah AWS Anda gunakan untuk membuat bucket sumber Anda. aws s3api create-bucket --bucket amzn-s3-demo-source-bucket-resized --region us-east-1 \ --create-bucket-configuration LocationConstraint= us-east-1 Unggah gambar uji ke bucket sumber Anda Kemudian dalam tutorial, Anda akan menguji fungsi Lambda Anda dengan memanggilnya menggunakan atau konsol Lambda. AWS CLI Untuk mengonfirmasi bahwa fungsi Anda beroperasi dengan benar, bucket sumber Anda harus berisi gambar uji. Gambar ini dapat berupa file JPG atau PNG yang Anda pilih. Konsol Manajemen AWS Untuk mengunggah gambar uji ke bucket sumber Anda (konsol) Buka halaman Bucket konsol Amazon S3. Pilih bucket sumber yang Anda buat di langkah sebelumnya. Pilih Unggah . Pilih Tambahkan file dan gunakan pemilih file untuk memilih objek yang ingin Anda unggah. Pilih Buka , lalu pilih Unggah . AWS CLI Untuk mengunggah gambar uji ke bucket sumber Anda (AWS CLI) Dari direktori yang berisi gambar yang ingin Anda unggah, jalankan perintah CLI berikut. Ganti --bucket parameter dengan nama bucket sumber Anda. Untuk --body parameter --key dan, gunakan nama file gambar pengujian Anda. aws s3api put-object --bucket amzn-s3-demo-source-bucket --key HappyFace.jpg --body ./HappyFace.jpg Membuat kebijakan izin Langkah pertama dalam membuat fungsi Lambda Anda adalah membuat kebijakan izin. Kebijakan ini memberi fungsi Anda izin yang diperlukan untuk mengakses AWS sumber daya lain. Untuk tutorial ini, kebijakan memberikan izin baca dan tulis Lambda untuk bucket Amazon S3 dan memungkinkannya untuk menulis ke Amazon Log. CloudWatch Konsol Manajemen AWS Untuk membuat kebijakan (konsol) Buka halaman Kebijakan konsol AWS Identity and Access Management (IAM). Pilih Buat kebijakan . Pilih tab JSON , lalu tempelkan kebijakan khusus berikut ke editor JSON. { "Version":"2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "logs:PutLogEvents", "logs:CreateLogGroup", "logs:CreateLogStream" ], "Resource": "arn:aws:logs:*:*:*" }, { "Effect": "Allow", "Action": [ "s3:GetObject" ], "Resource": "arn:aws:s3:::*/*" }, { "Effect": "Allow", "Action": [ "s3:PutObject" ], "Resource": "arn:aws:s3:::*/*" } ] } Pilih Berikutnya . Di bawah Detail kebijakan , untuk nama Kebijakan , masukkan LambdaS3Policy . Pilih Buat kebijakan . AWS CLI Untuk membuat kebijakan (AWS CLI) Simpan JSON berikut dalam file bernama policy.json . { "Version":"2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "logs:PutLogEvents", "logs:CreateLogGroup", "logs:CreateLogStream" ], "Resource": "arn:aws:logs:*:*:*" }, { "Effect": "Allow", "Action": [ "s3:GetObject" ], "Resource": "arn:aws:s3:::*/*" }, { "Effect": "Allow", "Action": [ "s3:PutObject" ], "Resource": "arn:aws:s3:::*/*" } ] } Dari direktori tempat Anda menyimpan dokumen kebijakan JSON, jalankan perintah CLI berikut. aws iam create-policy --policy-name LambdaS3Policy --policy-document file://policy.json Membuat peran eksekusi Peran eksekusi adalah peran IAM yang memberikan izin fungsi Lambda untuk mengakses dan sumber daya. Layanan AWS Untuk memberikan akses baca dan tulis fungsi ke bucket Amazon S3, Anda melampirkan kebijakan izin yang Anda buat di langkah sebelumnya. Konsol Manajemen AWS Untuk membuat peran eksekusi dan melampirkan kebijakan izin Anda (konsol) Buka halaman Peran konsol (IAM). Pilih Buat peran . Untuk jenis entitas Tepercaya , pilih Layanan AWS , dan untuk kasus Penggunaan , pilih Lambda . Pilih Berikutnya . Tambahkan kebijakan izin yang Anda buat di langkah sebelumnya dengan melakukan hal berikut: Dalam kotak pencarian kebijakan, masukkan LambdaS3Policy . Dalam hasil pencarian, pilih kotak centang untuk LambdaS3Policy . Pilih Berikutnya . Di bawah Rincian peran , untuk nama Peran masuk LambdaS3Role . Pilih Buat peran . AWS CLI Untuk membuat peran eksekusi dan melampirkan kebijakan izin Anda ()AWS CLI Simpan JSON berikut dalam file bernama trust-policy.json . Kebijakan kepercayaan ini memungkinkan Lambda untuk menggunakan izin peran dengan memberikan lambda.amazonaws.com izin utama layanan untuk memanggil tindakan AWS Security Token Service ()AWS STS. AssumeRole { "Version":"2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": { "Service": "lambda.amazonaws.com" }, "Action": "sts:AssumeRole" } ] } Dari direktori tempat Anda menyimpan dokumen kebijakan kepercayaan JSON, jalankan perintah CLI berikut untuk membuat peran eksekusi. aws iam create-role --role-name LambdaS3Role --assume-role-policy-document file://trust-policy.json Untuk melampirkan kebijakan izin yang Anda buat pada langkah sebelumnya, jalankan perintah CLI berikut. Ganti Akun AWS nomor di ARN polis dengan nomor akun Anda sendiri. aws iam attach-role-policy --role-name LambdaS3Role --policy-arn arn:aws:iam:: 123456789012 :policy/LambdaS3Policy Buat paket penerapan fungsi Untuk membuat fungsi Anda, Anda membuat paket deployment yang berisi kode fungsi dan dependensinya. Untuk CreateThumbnail fungsi ini, kode fungsi Anda menggunakan pustaka terpisah untuk mengubah ukuran gambar. Ikuti instruksi untuk bahasa yang Anda pilih untuk membuat paket penyebaran yang berisi pustaka yang diperlukan. Node.js Untuk membuat paket penyebaran (Node.js) Buat direktori bernama lambda-s3 untuk kode fungsi dan dependensi Anda dan navigasikan ke dalamnya. mkdir lambda-s3 cd lambda-s3 Buat proyek Node.js baru dengan npm . Untuk menerima opsi default yang disediakan dalam pengalaman interaktif, tekan Enter . npm init Simpan kode fungsi berikut dalam file bernama index.mjs . Pastikan untuk mengganti us-east-1 dengan Wilayah AWS di mana Anda membuat ember sumber dan tujuan Anda sendiri. // dependencies import { S3Client, GetObjectCommand, PutObjectCommand } from '@aws-sdk/client-s3'; import { Readable } from 'stream'; import sharp from 'sharp'; import util from 'util'; // create S3 client const s3 = new S3Client( { region: 'us-east-1' }); // define the handler function export const handler = async (event, context) => { // Read options from the event parameter and get the source bucket console.log("Reading options from event:\n", util.inspect(event, { depth: 5})); const srcBucket = event.Records[0].s3.bucket.name; // Object key may have spaces or unicode non-ASCII characters const srcKey = decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g, " ")); const dstBucket = srcBucket + "-resized"; const dstKey = "resized-" + srcKey; // Infer the image type from the file suffix const typeMatch = srcKey.match(/\.([^.]*)$/); if (!typeMatch) { console.log("Could not determine the image type."); return; } // Check that the image type is supported const imageType = typeMatch[1].toLowerCase(); if (imageType != "jpg" && imageType != "png") { console.log(`Unsupported image type: $ { imageType}`); return; } // Get the image from the source bucket. GetObjectCommand returns a stream. try { const params = { Bucket: srcBucket, Key: srcKey }; var response = await s3.send(new GetObjectCommand(params)); var stream = response.Body; // Convert stream to buffer to pass to sharp resize function. if (stream instanceof Readable) { var content_buffer = Buffer.concat(await stream.toArray()); } else { throw new Error('Unknown object stream type'); } } catch (error) { console.log(error); return; } // set thumbnail width. Resize will set the height automatically to maintain aspect ratio. const width = 200; // Use the sharp module to resize the image and save in a buffer. try { var output_buffer = await sharp(content_buffer).resize(width).toBuffer(); } catch (error) { console.log(error); return; } // Upload the thumbnail image to the destination bucket try { const destparams = { Bucket: dstBucket, Key: dstKey, Body: output_buffer, ContentType: "image" }; const putResult = await s3.send(new PutObjectCommand(destparams)); } catch (error) { console.log(error); return; } console.log('Successfully resized ' + srcBucket + '/' + srcKey + ' and uploaded to ' + dstBucket + '/' + dstKey); }; Di lambda-s3 direktori Anda, instal perpustakaan tajam menggunakan npm. Perhatikan bahwa versi terbaru dari sharp (0.33) tidak kompatibel dengan Lambda. Instal versi 0.32.6 untuk menyelesaikan tutorial ini. npm install sharp@0.32.6 install Perintah npm membuat node_modules direktori untuk modul Anda. Setelah langkah ini, struktur direktori Anda akan terlihat seperti berikut. lambda-s3 |- index.mjs |- node_modules | |- base64js | |- bl | |- buffer ... |- package-lock.json |- package.json Buat paket deployment .zip yang berisi kode fungsi Anda dan dependensinya. Di macOS dan Linux, jalankan perintah berikut. zip -r function.zip . Di Windows, gunakan utilitas zip pilihan Anda untuk membuat file.zip. Pastikan bahwa package-lock.json file index.mjs package.json ,, dan node_modules direktori Anda semuanya berada di root file.zip Anda. Python Untuk membuat paket penyebaran (Python) Simpan kode contoh sebagai file bernama lambda_function.py . import boto3 import os import sys import uuid from urllib.parse import unquote_plus from PIL import Image import PIL.Image s3_client = boto3.client('s3') def resize_image(image_path, resized_path): with Image.open(image_path) as image: image.thumbnail(tuple(x / 2 for x in image.size)) image.save(resized_path) def lambda_handler(event, context): for record in event['Records']: bucket = record['s3']['bucket']['name'] key = unquote_plus(record['s3']['object']['key']) tmpkey = key.replace('/', '') download_path = '/tmp/ { } { }'.format(uuid.uuid4(), tmpkey) upload_path = '/tmp/resized- { }'.format(tmpkey) s3_client.download_file(bucket, key, download_path) resize_image(download_path, upload_path) s3_client.upload_file(upload_path, ' { }-resized'.format(bucket), 'resized- { }'.format(key)) Di direktori yang sama di mana Anda membuat lambda_function.py file Anda, buat direktori baru bernama package dan instal pustaka Pillow (PIL) dan AWS SDK untuk Python (Boto3). Meskipun runtime Lambda Python menyertakan versi Boto3 SDK, kami menyarankan agar Anda menambahkan semua dependensi fungsi Anda ke paket penerapan Anda, meskipun mereka disertakan dalam runtime. Untuk informasi selengkapnya, lihat Dependensi runtime dengan Python. mkdir package pip install \ --platform manylinux2014_x86_64 \ --target=package \ --implementation cp \ --python-version 3.12 \ --only-binary=:all: --upgrade \ pillow boto3 Pustaka Pillow berisi kode C/C ++. Dengan menggunakan --only-binary=:all: opsi --platform manylinux_2014_x86_64 dan, pip akan mengunduh dan menginstal versi Pillow yang berisi binari pra-kompilasi yang kompatibel dengan sistem operasi Amazon Linux 2. Ini memastikan bahwa paket penerapan Anda akan berfungsi di lingkungan eksekusi Lambda, terlepas dari sistem operasi dan arsitektur mesin build lokal Anda. Buat file.zip yang berisi kode aplikasi Anda dan pustaka Pillow dan Boto3. Di Linux atau macOS, jalankan perintah berikut dari antarmuka baris perintah Anda. cd package zip -r ../lambda_function.zip . cd .. zip lambda_function.zip lambda_function.py Di Windows, gunakan alat zip pilihan Anda untuk membuat file lambda_function.zip . Pastikan bahwa lambda_function.py file Anda dan folder yang berisi dependensi Anda semuanya berada di root file.zip. Anda juga dapat membuat paket deployment menggunakan lingkungan virtual Python. Lihat Bekerja dengan arsip file.zip untuk fungsi Python Lambda Buat fungsi Lambda Anda dapat membuat fungsi Lambda menggunakan konsol Lambda AWS CLI atau Lambda. Ikuti instruksi untuk bahasa yang Anda pilih untuk membuat fungsi. Konsol Manajemen AWS Untuk membuat fungsi (konsol) Untuk membuat fungsi Lambda Anda menggunakan konsol, pertama-tama Anda membuat fungsi dasar yang berisi beberapa kode 'Hello world'. Anda kemudian mengganti kode ini dengan kode fungsi Anda sendiri dengan mengunggah file the.zip atau JAR yang Anda buat pada langkah sebelumnya. Buka halaman Fungsi di konsol Lambda. Pastikan Anda bekerja di tempat yang sama dengan saat Wilayah AWS Anda membuat bucket Amazon S3. Anda dapat mengubah wilayah Anda menggunakan daftar drop-down di bagian atas layar. Pilih Buat fungsi . Pilih Penulis dari scratch . Di bagian Informasi dasar , lakukan hal berikut: Untuk Nama fungsi , masukkan CreateThumbnail . Untuk Runtime , pilih Node.js 22.x atau Python 3.12 sesuai dengan bahasa yang Anda pilih untuk fungsi Anda. Untuk Arsitektur , pilih x86_64 . Di tab Ubah peran eksekusi default , lakukan hal berikut: Perluas tab, lalu pilih Gunakan peran yang ada . Pilih yang LambdaS3Role Anda buat sebelumnya. Pilih Buat fungsi . Untuk mengunggah kode fungsi (konsol) Di panel Sumber kode , pilih Unggah dari . Pilih file.zip . Pilih Unggah . Di pemilih file, pilih file.zip Anda dan pilih Buka. Pilih Simpan . AWS CLI Untuk membuat fungsi (AWS CLI) Jalankan perintah CLI untuk bahasa yang Anda pilih. Untuk role parameter, pastikan untuk mengganti 123456789012 dengan Akun AWS ID Anda sendiri. Untuk region parameternya, ganti us-east-1 dengan wilayah tempat Anda membuat bucket Amazon S3. Untuk Node.js , jalankan perintah berikut dari direktori yang berisi function.zip file Anda. aws lambda create-function --function-name CreateThumbnail \ --zip-file fileb://function.zip --handler index.handler --runtime nodejs24.x \ --timeout 10 --memory-size 1024 \ --role arn:aws:iam:: 123456789012 :role/LambdaS3Role --region us-east-1 Untuk Python , jalankan perintah berikut dari direktori yang berisi file Anda lambda_function.zip . aws lambda create-function --function-name CreateThumbnail \ --zip-file fileb://lambda_function.zip --handler lambda_function.lambda_handler \ --runtime python3.14 --timeout 10 --memory-size 1024 \ --role arn:aws:iam:: 123456789012 :role/LambdaS3Role --region us-east-1 Konfigurasikan Amazon S3 untuk menjalankan fungsi Agar fungsi Lambda dapat berjalan saat mengunggah gambar ke bucket sumber, Anda perlu mengonfigurasi pemicu untuk fungsi Anda. Anda dapat mengonfigurasi pemicu Amazon S3 menggunakan konsol atau. AWS CLI penting Prosedur ini mengonfigurasi bucket Amazon S3 untuk menjalankan fungsi Anda setiap kali objek dibuat di bucket. Pastikan untuk mengonfigurasi ini hanya di bucket sumber. Jika fungsi Lambda Anda membuat objek dalam bucket yang sama yang memanggilnya, fungsi Anda dapat dipanggil terus menerus dalam satu loop. Hal ini dapat mengakibatkan biaya yang tidak diharapkan ditagih ke Anda Akun AWS. Konsol Manajemen AWS Untuk mengonfigurasi pemicu Amazon S3 (konsol) Buka halaman Fungsi konsol Lambda dan pilih fungsi Anda () CreateThumbnail . Pilih Tambahkan pemicu . Pilih S3 . Di bawah Bucket , pilih bucket sumber Anda. Di bawah Jenis acara , pilih Semua objek membuat acara . Di bawah Pemanggilan rekursif , pilih kotak centang untuk mengetahui bahwa tidak disarankan menggunakan bucket Amazon S3 yang sama untuk input dan output. Anda dapat mempelajari lebih lanjut tentang pola pemanggilan rekursif di Lambda dengan membaca pola rekursif yang menyebabkan fungsi Lambda yang tidak terkendali di Tanah Tanpa Server. Pilih Tambahkan . Saat Anda membuat pemicu menggunakan konsol Lambda, Lambda secara otomatis membuat kebijakan berbasis sumber daya untuk memberikan layanan yang Anda pilih izin untuk menjalankan fungsi Anda. AWS CLI Untuk mengonfigurasi pemicu Amazon S3 ()AWS CLI Agar bucket sumber Amazon S3 menjalankan fungsi saat menambahkan file gambar, pertama-tama Anda harus mengonfigurasi izin untuk fungsi menggunakan kebijakan berbasis sumber daya. Pernyataan kebijakan berbasis sumber daya memberikan Layanan AWS izin lain untuk menjalankan fungsi Anda. Untuk memberikan izin Amazon S3 untuk menjalankan fungsi Anda, jalankan perintah CLI berikut. Pastikan untuk mengganti source-account parameter dengan Akun AWS ID Anda sendiri dan menggunakan nama bucket sumber Anda sendiri. aws lambda add-permission --function-name CreateThumbnail \ --principal s3.amazonaws.com --statement-id s3invoke --action "lambda:InvokeFunction" \ --source-arn arn:aws:s3::: amzn-s3-demo-source-bucket \ --source-account 123456789012 Kebijakan yang Anda tetapkan dengan perintah ini memungkinkan Amazon S3 untuk menjalankan fungsi Anda hanya ketika tindakan dilakukan di bucket sumber Anda. catatan Meskipun nama bucket Amazon S3 unik secara global, saat menggunakan kebijakan berbasis sumber daya, praktik terbaik adalah menentukan bahwa bucket harus menjadi milik akun Anda. Ini karena jika Anda menghapus bucket, Anda dapat membuat bucket dengan Amazon Resource Name (ARN) yang sama. Akun AWS Simpan JSON berikut dalam file bernama notification.json . Saat diterapkan ke bucket sumber Anda, JSON ini mengonfigurasi bucket untuk mengirim notifikasi ke fungsi Lambda Anda setiap kali objek baru ditambahkan. Ganti Akun AWS nomor dan Wilayah AWS dalam fungsi Lambda ARN dengan nomor akun dan wilayah Anda sendiri. { "LambdaFunctionConfigurations": [ { "Id": "CreateThumbnailEventConfiguration", "LambdaFunctionArn": "arn:aws:lambda: us-east-1:123456789012 :function:CreateThumbnail", "Events": [ "s3:ObjectCreated:Put" ] } ] } Jalankan perintah CLI berikut untuk menerapkan pengaturan notifikasi dalam file JSON yang Anda buat ke bucket sumber Anda. Ganti amzn-s3-demo-source-bucket dengan nama bucket sumber Anda sendiri. aws s3api put-bucket-notification-configuration --bucket amzn-s3-demo-source-bucket \ --notification-configuration file://notification.json Untuk mempelajari lebih lanjut tentang put-bucket-notification-configuration perintah dan notification-configuration opsi, lihat put-bucket-notification-configuration di Referensi Perintah AWS CLI . Uji fungsi Lambda Anda dengan acara dummy Sebelum menguji seluruh penyiapan dengan menambahkan file gambar ke bucket sumber Amazon S3, Anda menguji apakah fungsi Lambda berfungsi dengan benar dengan memanggilnya dengan acara dummy. Peristiwa di Lambda adalah dokumen berformat JSON yang berisi data untuk diproses fungsi Anda. Saat fungsi Anda dipanggil oleh Amazon S3, peristiwa yang dikirim ke fungsi berisi informasi seperti nama bucket, ARN bucket, dan kunci objek. Konsol Manajemen AWS Untuk menguji fungsi Lambda Anda dengan acara dummy (konsol) Buka halaman Fungsi konsol Lambda dan pilih fungsi Anda () CreateThumbnail . Pilih tab Uji . Untuk membuat acara pengujian, di panel acara Uji , lakukan hal berikut: Di bawah Uji tindakan peristiwa , pilih Buat acara baru . Untuk Nama peristiwa , masukkan myTestEvent . Untuk Template , pilih S3 Put . Ganti nilai untuk parameter berikut dengan nilai Anda sendiri. Untuk awsRegion , ganti us-east-1 dengan bucket Amazon S3 yang Wilayah AWS Anda buat. Untuk name , ganti amzn-s3-demo-bucket dengan nama bucket sumber Amazon S3 Anda sendiri. Untuk key , ganti test%2Fkey dengan nama file objek pengujian yang Anda unggah ke bucket sumber di langkah tersebut. Unggah gambar uji ke bucket sumber Anda { "Records": [ { "eventVersion": "2.0", "eventSource": "aws:s3", "awsRegion": "us-east-1" , "eventTime": "1970-01-01T00:00:00.000Z", "eventName": "ObjectCreated:Put", "userIdentity": { "principalId": "EXAMPLE" }, "requestParameters": { "sourceIPAddress": "127.0.0.1" }, "responseElements": { "x-amz-request-id": "EXAMPLE123456789", "x-amz-id-2": "EXAMPLE123/5678abcdefghijklambdaisawesome/mnopqrstuvwxyzABCDEFGH" }, "s3": { "s3SchemaVersion": "1.0", "configurationId": "testConfigRule", "bucket": { "name": "amzn-s3-demo-bucket" , "ownerIdentity": { "principalId": "EXAMPLE" }, "arn": "arn:aws:s3:::amzn-s3-demo-bucket" }, "object": { "key": "test%2Fkey" , "size": 1024, "eTag": "0123456789abcdef0123456789abcdef", "sequencer": "0A1B2C3D4E5F678901" } } } ] } Pilih Simpan . Di panel acara Uji , pilih Uji . Untuk memeriksa fungsi Anda telah membuat verison yang diubah ukurannya dari gambar Anda dan menyimpannya di bucket Amazon S3 target Anda, lakukan hal berikut: Buka halaman Bucket konsol Amazon S3. Pilih bucket target Anda dan konfirmasikan bahwa file yang diubah ukurannya tercantum di panel Objects . AWS CLI Untuk menguji fungsi Lambda Anda dengan acara dummy ()AWS CLI Simpan JSON berikut dalam file bernama dummyS3Event.json . Ganti nilai untuk parameter berikut dengan nilai Anda sendiri: Untuk awsRegion , ganti us-east-1 dengan bucket Amazon S3 yang Wilayah AWS Anda buat. Untuk name , ganti amzn-s3-demo-bucket dengan nama bucket sumber Amazon S3 Anda sendiri. Untuk key , ganti test%2Fkey dengan nama file objek pengujian yang Anda unggah ke bucket sumber di langkah tersebut. Unggah gambar uji ke bucket sumber Anda { "Records": [ { "eventVersion": "2.0", "eventSource": "aws:s3", "awsRegion": "us-east-1" , "eventTime": "1970-01-01T00:00:00.000Z", "eventName": "ObjectCreated:Put", "userIdentity": { "principalId": "EXAMPLE" }, "requestParameters": { "sourceIPAddress": "127.0.0.1" }, "responseElements": { "x-amz-request-id": "EXAMPLE123456789", "x-amz-id-2": "EXAMPLE123/5678abcdefghijklambdaisawesome/mnopqrstuvwxyzABCDEFGH" }, "s3": { "s3SchemaVersion": "1.0", "configurationId": "testConfigRule", "bucket": { "name": "amzn-s3-demo-bucket" , "ownerIdentity": { "principalId": "EXAMPLE" }, "arn": "arn:aws:s3:::amzn-s3-demo-bucket" }, "object": { "key": "test%2Fkey" , "size": 1024, "eTag": "0123456789abcdef0123456789abcdef", "sequencer": "0A1B2C3D4E5F678901" } } } ] } Dari direktori tempat Anda menyimpan dummyS3Event.json file Anda, panggil fungsi dengan menjalankan perintah CLI berikut. Perintah ini memanggil fungsi Lambda Anda secara sinkron dengan RequestResponse menentukan sebagai nilai parameter tipe pemanggilan. Untuk mempelajari lebih lanjut tentang pemanggilan sinkron dan asinkron, lihat Memanggil fungsi Lambda. aws lambda invoke --function-name CreateThumbnail \ --invocation-type RequestResponse --cli-binary-format raw-in-base64-out \ --payload file://dummyS3Event.json outputfile.txt cli-binary-formatOpsi ini diperlukan jika Anda menggunakan versi 2 dari AWS CLI. Untuk menjadikan ini pengaturan default, jalankan aws configure set cli-binary-format raw-in-base64-out . Untuk informasi selengkapnya, lihat opsi baris perintah global yang AWS CLI didukung . Verifikasi bahwa fungsi Anda telah membuat versi thumbnail gambar Anda dan menyimpannya ke bucket Amazon S3 target Anda. Jalankan perintah CLI berikut, ganti amzn-s3-demo-source-bucket-resized dengan nama bucket tujuan Anda sendiri. aws s3api list-objects-v2 --bucket amzn-s3-demo-source-bucket-resized Anda akan melihat output seperti yang berikut ini. Key Parameter menunjukkan nama file file gambar Anda yang diubah ukurannya. { "Contents": [ { "Key": "resized-HappyFace.jpg", "LastModified": "2023-06-06T21:40:07+00:00", "ETag": "\"d8ca652ffe83ba6b721ffc20d9d7174a\"", "Size": 2633, "StorageClass": "STANDARD" } ] } Uji fungsi Anda menggunakan pemicu Amazon S3 Sekarang setelah Anda mengonfirmasi bahwa fungsi Lambda Anda beroperasi dengan benar, Anda siap untuk menguji penyiapan lengkap Anda dengan menambahkan file gambar ke bucket sumber Amazon S3 Anda. Saat Anda menambahkan gambar ke bucket sumber, fungsi Lambda Anda akan dipanggil secara otomatis. Fungsi Anda membuat versi file yang diubah ukurannya dan menyimpannya di bucket target Anda. Konsol Manajemen AWS Untuk menguji fungsi Lambda Anda menggunakan pemicu Amazon S3 (konsol) Untuk mengunggah gambar ke bucket Amazon S3 Anda, lakukan hal berikut: Buka halaman Bucket di konsol Amazon S3 dan pilih bucket sumber Anda. Pilih Unggah . Pilih Tambahkan file dan gunakan pemilih file untuk memilih file gambar yang ingin Anda unggah. Objek gambar Anda dapat berupa file.jpg atau.png. Pilih Buka , lalu pilih Unggah . Verifikasi bahwa Lambda telah menyimpan versi file gambar yang diubah ukurannya di bucket target dengan melakukan hal berikut: Arahkan kembali ke halaman Bucket di konsol Amazon S3 dan pilih bucket tujuan Anda. Di panel Objects , Anda sekarang akan melihat dua file gambar yang diubah ukurannya, satu dari setiap pengujian fungsi Lambda Anda. Untuk mengunduh gambar yang diubah ukurannya, pilih file, lalu pilih Unduh . AWS CLI Untuk menguji fungsi Lambda Anda menggunakan pemicu Amazon S3 ()AWS CLI Dari direktori yang berisi gambar yang ingin Anda unggah, jalankan perintah CLI berikut. Ganti --bucket parameter dengan nama bucket sumber Anda. Untuk --body parameter --key dan, gunakan nama file gambar pengujian Anda. Gambar uji Anda dapat berupa file.jpg atau.png. aws s3api put-object --bucket amzn-s3-demo-source-bucket --key SmileyFace.jpg --body ./SmileyFace.jpg Verifikasi bahwa fungsi Anda telah membuat versi thumbnail gambar Anda dan menyimpannya ke bucket Amazon S3 target Anda. Jalankan perintah CLI berikut, ganti amzn-s3-demo-source-bucket-resized dengan nama bucket tujuan Anda sendiri. aws s3api list-objects-v2 --bucket amzn-s3-demo-source-bucket-resized Jika fungsi Anda berjalan dengan sukses, Anda akan melihat output yang mirip dengan berikut ini. Bucket target Anda sekarang harus berisi dua file yang diubah ukurannya. { "Contents": [ { "Key": "resized-HappyFace.jpg", "LastModified": "2023-06-07T00:15:50+00:00", "ETag": "\"7781a43e765a8301713f533d70968a1e\"", "Size": 2763, "StorageClass": "STANDARD" }, { "Key": "resized-SmileyFace.jpg", "LastModified": "2023-06-07T00:13:18+00:00", "ETag": "\"ca536e5a1b9e32b22cd549e18792cdbc\"", "Size": 1245, "StorageClass": "STANDARD" } ] } Bersihkan sumber daya Anda Sekarang Anda dapat menghapus sumber daya yang Anda buat untuk tutorial ini, kecuali Anda ingin mempertahankannya. Dengan menghapus AWS sumber daya yang tidak lagi Anda gunakan, Anda mencegah tagihan yang tidak perlu ke Anda Akun AWS. Untuk menghapus fungsi Lambda Buka halaman Fungsi di konsol Lambda. Pilih fungsi yang Anda buat. Pilih Tindakan , Hapus . Ketik confirm kolom input teks dan pilih Hapus . Untuk menghapus kebijakan yang Anda buat. Buka halaman Kebijakan konsol IAM. Pilih kebijakan yang Anda buat ( AWSLambdaS3Policy ). Pilih Tindakan kebijakan , Hapus . Pilih Hapus . Untuk menghapus peran eksekusi Buka halaman Peran dari konsol IAM. Pilih peran eksekusi yang Anda buat. Pilih Hapus . Masukkan nama peran di bidang input teks dan pilih Hapus . Untuk menghapus bucket S3 Buka konsol Amazon S3 . Pilih bucket yang Anda buat. Pilih Hapus . Masukkan nama ember di bidang input teks. Pilih Hapus bucket . Javascript dinonaktifkan atau tidak tersedia di browser Anda. Untuk menggunakan Dokumentasi AWS, Javascript harus diaktifkan. Lihat halaman Bantuan browser Anda untuk petunjuk. Konvensi Dokumen Tutorial: Menggunakan pemicu S3 Secrets Manager Apakah halaman ini membantu Anda? - Ya Terima kasih telah memberitahukan bahwa hasil pekerjaan kami sudah baik. Jika Anda memiliki waktu luang, beri tahu kami aspek apa saja yang sudah bagus, agar kami dapat menerapkannya secara lebih luas. Apakah halaman ini membantu Anda? - Tidak Terima kasih telah memberi tahu kami bahwa halaman ini perlu ditingkatkan. Maaf karena telah mengecewakan Anda. Jika Anda memiliki waktu luang, beri tahu kami bagaimana dokumentasi ini dapat ditingkatkan. | 2026-01-13T09:30:35 |
https://docs.aws.amazon.com/id_id/lambda/latest/dg/with-s3-tutorial.html#with-s3-tutorial-create-policy | Tutorial: Menggunakan pemicu Amazon S3 untuk membuat gambar thumbnail - AWS Lambda Tutorial: Menggunakan pemicu Amazon S3 untuk membuat gambar thumbnail - AWS Lambda Dokumentasi AWS Lambda Panduan Developerr Prasyarat Buat dua ember Amazon S3 Unggah gambar uji ke bucket sumber Anda Membuat kebijakan izin Membuat peran eksekusi Buat paket penerapan fungsi Buat fungsi Lambda Konfigurasikan Amazon S3 untuk menjalankan fungsi Uji fungsi Lambda Anda dengan acara dummy Uji fungsi Anda menggunakan pemicu Amazon S3 Bersihkan sumber daya Anda Terjemahan disediakan oleh mesin penerjemah. Jika konten terjemahan yang diberikan bertentangan dengan versi bahasa Inggris aslinya, utamakan versi bahasa Inggris. Tutorial: Menggunakan pemicu Amazon S3 untuk membuat gambar thumbnail Dalam tutorial ini, Anda membuat dan mengonfigurasi fungsi Lambda yang mengubah ukuran gambar yang ditambahkan ke bucket Amazon Simple Storage Service (Amazon S3). Saat Anda menambahkan file gambar ke bucket, Amazon S3 akan memanggil fungsi Lambda Anda. Fungsi tersebut kemudian membuat versi thumbnail gambar dan mengeluarkannya ke bucket Amazon S3 yang berbeda. Untuk menyelesaikan tutorial ini, Anda melakukan langkah-langkah berikut: Buat bucket Amazon S3 sumber dan tujuan dan unggah gambar sampel. Buat fungsi Lambda yang mengubah ukuran gambar dan mengeluarkan thumbnail ke bucket Amazon S3. Konfigurasikan pemicu Lambda yang memanggil fungsi Anda saat objek diunggah ke bucket sumber Anda. Uji fungsi Anda, pertama dengan acara dummy, lalu dengan mengunggah gambar ke bucket sumber Anda. Dengan menyelesaikan langkah-langkah ini, Anda akan mempelajari cara menggunakan Lambda untuk menjalankan tugas pemrosesan file pada objek yang ditambahkan ke bucket Amazon S3. Anda dapat menyelesaikan tutorial ini menggunakan AWS Command Line Interface (AWS CLI) atau Konsol Manajemen AWS. Jika Anda mencari contoh sederhana untuk mempelajari cara mengonfigurasi pemicu Amazon S3 untuk Lambda, Anda dapat mencoba Tutorial: Menggunakan pemicu Amazon S3 untuk menjalankan fungsi Lambda. Topik Prasyarat Buat dua ember Amazon S3 Unggah gambar uji ke bucket sumber Anda Membuat kebijakan izin Membuat peran eksekusi Buat paket penerapan fungsi Buat fungsi Lambda Konfigurasikan Amazon S3 untuk menjalankan fungsi Uji fungsi Lambda Anda dengan acara dummy Uji fungsi Anda menggunakan pemicu Amazon S3 Bersihkan sumber daya Anda Prasyarat Jika Anda ingin menggunakan AWS CLI untuk menyelesaikan tutorial, instal versi terbaru dari AWS Command Line Interface . Untuk kode fungsi Lambda Anda, Anda dapat menggunakan Python atau Node.js. Instal alat dukungan bahasa dan manajer paket untuk bahasa yang ingin Anda gunakan. Jika Anda belum menginstal AWS Command Line Interface, ikuti langkah-langkah di Menginstal atau memperbarui versi terbaru AWS CLI untuk menginstalnya . Tutorial ini membutuhkan terminal baris perintah atau shell untuk menjalankan perintah. Di Linux dan macOS, gunakan shell dan manajer paket pilihan Anda. catatan Di Windows, beberapa perintah Bash CLI yang biasa Anda gunakan dengan Lambda ( zip seperti) tidak didukung oleh terminal bawaan sistem operasi. Untuk mendapatkan versi terintegrasi Windows dari Ubuntu dan Bash, instal Windows Subsystem untuk Linux. Buat dua ember Amazon S3 Pertama buat dua ember Amazon S3. Bucket pertama adalah bucket sumber tempat Anda akan mengunggah gambar Anda. Bucket kedua digunakan oleh Lambda untuk menyimpan thumbnail yang diubah ukurannya saat Anda menjalankan fungsi. Konsol Manajemen AWS Untuk membuat bucket Amazon S3 (konsol) Buka konsol Amazon S3 dan pilih halaman Bucket tujuan umum . Pilih yang Wilayah AWS paling dekat dengan lokasi geografis Anda. Anda dapat mengubah wilayah Anda menggunakan daftar drop-down di bagian atas layar. Kemudian dalam tutorial, Anda harus membuat fungsi Lambda Anda di Wilayah yang sama. Pilih Buat bucket . Pada Konfigurasi umum , lakukan hal berikut: Untuk jenis Bucket , pastikan Tujuan umum dipilih. Untuk nama Bucket , masukkan nama unik global yang memenuhi aturan penamaan Amazon S3 Bucket . Nama bucket hanya dapat berisi huruf kecil, angka, titik (.), dan tanda hubung (-). Biarkan semua opsi lain disetel ke nilai defaultnya dan pilih Buat bucket . Ulangi langkah 1 hingga 5 untuk membuat bucket tujuan Anda. Untuk nama Bucket amzn-s3-demo-source-bucket-resized , masukkan, di amzn-s3-demo-source-bucket mana nama bucket sumber yang baru saja Anda buat. AWS CLI Untuk membuat bucket Amazon S3 ()AWS CLI Jalankan perintah CLI berikut untuk membuat bucket sumber Anda. Nama yang Anda pilih untuk bucket Anda harus unik secara global dan ikuti aturan penamaan Amazon S3 Bucket . Nama hanya dapat berisi huruf kecil, angka, titik (.), dan tanda hubung (-). Untuk region dan LocationConstraint , pilih yang paling Wilayah AWS dekat dengan lokasi geografis Anda. aws s3api create-bucket --bucket amzn-s3-demo-source-bucket --region us-east-1 \ --create-bucket-configuration LocationConstraint= us-east-1 Kemudian dalam tutorial, Anda harus membuat fungsi Lambda Anda Wilayah AWS sama dengan bucket sumber Anda, jadi catat wilayah yang Anda pilih. Jalankan perintah berikut untuk membuat bucket tujuan Anda. Untuk nama bucket, Anda harus menggunakan amzn-s3-demo-source-bucket-resized , di amzn-s3-demo-source-bucket mana nama bucket sumber yang Anda buat di langkah 1. Untuk region dan LocationConstraint , pilih yang sama dengan yang Wilayah AWS Anda gunakan untuk membuat bucket sumber Anda. aws s3api create-bucket --bucket amzn-s3-demo-source-bucket-resized --region us-east-1 \ --create-bucket-configuration LocationConstraint= us-east-1 Unggah gambar uji ke bucket sumber Anda Kemudian dalam tutorial, Anda akan menguji fungsi Lambda Anda dengan memanggilnya menggunakan atau konsol Lambda. AWS CLI Untuk mengonfirmasi bahwa fungsi Anda beroperasi dengan benar, bucket sumber Anda harus berisi gambar uji. Gambar ini dapat berupa file JPG atau PNG yang Anda pilih. Konsol Manajemen AWS Untuk mengunggah gambar uji ke bucket sumber Anda (konsol) Buka halaman Bucket konsol Amazon S3. Pilih bucket sumber yang Anda buat di langkah sebelumnya. Pilih Unggah . Pilih Tambahkan file dan gunakan pemilih file untuk memilih objek yang ingin Anda unggah. Pilih Buka , lalu pilih Unggah . AWS CLI Untuk mengunggah gambar uji ke bucket sumber Anda (AWS CLI) Dari direktori yang berisi gambar yang ingin Anda unggah, jalankan perintah CLI berikut. Ganti --bucket parameter dengan nama bucket sumber Anda. Untuk --body parameter --key dan, gunakan nama file gambar pengujian Anda. aws s3api put-object --bucket amzn-s3-demo-source-bucket --key HappyFace.jpg --body ./HappyFace.jpg Membuat kebijakan izin Langkah pertama dalam membuat fungsi Lambda Anda adalah membuat kebijakan izin. Kebijakan ini memberi fungsi Anda izin yang diperlukan untuk mengakses AWS sumber daya lain. Untuk tutorial ini, kebijakan memberikan izin baca dan tulis Lambda untuk bucket Amazon S3 dan memungkinkannya untuk menulis ke Amazon Log. CloudWatch Konsol Manajemen AWS Untuk membuat kebijakan (konsol) Buka halaman Kebijakan konsol AWS Identity and Access Management (IAM). Pilih Buat kebijakan . Pilih tab JSON , lalu tempelkan kebijakan khusus berikut ke editor JSON. { "Version":"2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "logs:PutLogEvents", "logs:CreateLogGroup", "logs:CreateLogStream" ], "Resource": "arn:aws:logs:*:*:*" }, { "Effect": "Allow", "Action": [ "s3:GetObject" ], "Resource": "arn:aws:s3:::*/*" }, { "Effect": "Allow", "Action": [ "s3:PutObject" ], "Resource": "arn:aws:s3:::*/*" } ] } Pilih Berikutnya . Di bawah Detail kebijakan , untuk nama Kebijakan , masukkan LambdaS3Policy . Pilih Buat kebijakan . AWS CLI Untuk membuat kebijakan (AWS CLI) Simpan JSON berikut dalam file bernama policy.json . { "Version":"2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "logs:PutLogEvents", "logs:CreateLogGroup", "logs:CreateLogStream" ], "Resource": "arn:aws:logs:*:*:*" }, { "Effect": "Allow", "Action": [ "s3:GetObject" ], "Resource": "arn:aws:s3:::*/*" }, { "Effect": "Allow", "Action": [ "s3:PutObject" ], "Resource": "arn:aws:s3:::*/*" } ] } Dari direktori tempat Anda menyimpan dokumen kebijakan JSON, jalankan perintah CLI berikut. aws iam create-policy --policy-name LambdaS3Policy --policy-document file://policy.json Membuat peran eksekusi Peran eksekusi adalah peran IAM yang memberikan izin fungsi Lambda untuk mengakses dan sumber daya. Layanan AWS Untuk memberikan akses baca dan tulis fungsi ke bucket Amazon S3, Anda melampirkan kebijakan izin yang Anda buat di langkah sebelumnya. Konsol Manajemen AWS Untuk membuat peran eksekusi dan melampirkan kebijakan izin Anda (konsol) Buka halaman Peran konsol (IAM). Pilih Buat peran . Untuk jenis entitas Tepercaya , pilih Layanan AWS , dan untuk kasus Penggunaan , pilih Lambda . Pilih Berikutnya . Tambahkan kebijakan izin yang Anda buat di langkah sebelumnya dengan melakukan hal berikut: Dalam kotak pencarian kebijakan, masukkan LambdaS3Policy . Dalam hasil pencarian, pilih kotak centang untuk LambdaS3Policy . Pilih Berikutnya . Di bawah Rincian peran , untuk nama Peran masuk LambdaS3Role . Pilih Buat peran . AWS CLI Untuk membuat peran eksekusi dan melampirkan kebijakan izin Anda ()AWS CLI Simpan JSON berikut dalam file bernama trust-policy.json . Kebijakan kepercayaan ini memungkinkan Lambda untuk menggunakan izin peran dengan memberikan lambda.amazonaws.com izin utama layanan untuk memanggil tindakan AWS Security Token Service ()AWS STS. AssumeRole { "Version":"2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": { "Service": "lambda.amazonaws.com" }, "Action": "sts:AssumeRole" } ] } Dari direktori tempat Anda menyimpan dokumen kebijakan kepercayaan JSON, jalankan perintah CLI berikut untuk membuat peran eksekusi. aws iam create-role --role-name LambdaS3Role --assume-role-policy-document file://trust-policy.json Untuk melampirkan kebijakan izin yang Anda buat pada langkah sebelumnya, jalankan perintah CLI berikut. Ganti Akun AWS nomor di ARN polis dengan nomor akun Anda sendiri. aws iam attach-role-policy --role-name LambdaS3Role --policy-arn arn:aws:iam:: 123456789012 :policy/LambdaS3Policy Buat paket penerapan fungsi Untuk membuat fungsi Anda, Anda membuat paket deployment yang berisi kode fungsi dan dependensinya. Untuk CreateThumbnail fungsi ini, kode fungsi Anda menggunakan pustaka terpisah untuk mengubah ukuran gambar. Ikuti instruksi untuk bahasa yang Anda pilih untuk membuat paket penyebaran yang berisi pustaka yang diperlukan. Node.js Untuk membuat paket penyebaran (Node.js) Buat direktori bernama lambda-s3 untuk kode fungsi dan dependensi Anda dan navigasikan ke dalamnya. mkdir lambda-s3 cd lambda-s3 Buat proyek Node.js baru dengan npm . Untuk menerima opsi default yang disediakan dalam pengalaman interaktif, tekan Enter . npm init Simpan kode fungsi berikut dalam file bernama index.mjs . Pastikan untuk mengganti us-east-1 dengan Wilayah AWS di mana Anda membuat ember sumber dan tujuan Anda sendiri. // dependencies import { S3Client, GetObjectCommand, PutObjectCommand } from '@aws-sdk/client-s3'; import { Readable } from 'stream'; import sharp from 'sharp'; import util from 'util'; // create S3 client const s3 = new S3Client( { region: 'us-east-1' }); // define the handler function export const handler = async (event, context) => { // Read options from the event parameter and get the source bucket console.log("Reading options from event:\n", util.inspect(event, { depth: 5})); const srcBucket = event.Records[0].s3.bucket.name; // Object key may have spaces or unicode non-ASCII characters const srcKey = decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g, " ")); const dstBucket = srcBucket + "-resized"; const dstKey = "resized-" + srcKey; // Infer the image type from the file suffix const typeMatch = srcKey.match(/\.([^.]*)$/); if (!typeMatch) { console.log("Could not determine the image type."); return; } // Check that the image type is supported const imageType = typeMatch[1].toLowerCase(); if (imageType != "jpg" && imageType != "png") { console.log(`Unsupported image type: $ { imageType}`); return; } // Get the image from the source bucket. GetObjectCommand returns a stream. try { const params = { Bucket: srcBucket, Key: srcKey }; var response = await s3.send(new GetObjectCommand(params)); var stream = response.Body; // Convert stream to buffer to pass to sharp resize function. if (stream instanceof Readable) { var content_buffer = Buffer.concat(await stream.toArray()); } else { throw new Error('Unknown object stream type'); } } catch (error) { console.log(error); return; } // set thumbnail width. Resize will set the height automatically to maintain aspect ratio. const width = 200; // Use the sharp module to resize the image and save in a buffer. try { var output_buffer = await sharp(content_buffer).resize(width).toBuffer(); } catch (error) { console.log(error); return; } // Upload the thumbnail image to the destination bucket try { const destparams = { Bucket: dstBucket, Key: dstKey, Body: output_buffer, ContentType: "image" }; const putResult = await s3.send(new PutObjectCommand(destparams)); } catch (error) { console.log(error); return; } console.log('Successfully resized ' + srcBucket + '/' + srcKey + ' and uploaded to ' + dstBucket + '/' + dstKey); }; Di lambda-s3 direktori Anda, instal perpustakaan tajam menggunakan npm. Perhatikan bahwa versi terbaru dari sharp (0.33) tidak kompatibel dengan Lambda. Instal versi 0.32.6 untuk menyelesaikan tutorial ini. npm install sharp@0.32.6 install Perintah npm membuat node_modules direktori untuk modul Anda. Setelah langkah ini, struktur direktori Anda akan terlihat seperti berikut. lambda-s3 |- index.mjs |- node_modules | |- base64js | |- bl | |- buffer ... |- package-lock.json |- package.json Buat paket deployment .zip yang berisi kode fungsi Anda dan dependensinya. Di macOS dan Linux, jalankan perintah berikut. zip -r function.zip . Di Windows, gunakan utilitas zip pilihan Anda untuk membuat file.zip. Pastikan bahwa package-lock.json file index.mjs package.json ,, dan node_modules direktori Anda semuanya berada di root file.zip Anda. Python Untuk membuat paket penyebaran (Python) Simpan kode contoh sebagai file bernama lambda_function.py . import boto3 import os import sys import uuid from urllib.parse import unquote_plus from PIL import Image import PIL.Image s3_client = boto3.client('s3') def resize_image(image_path, resized_path): with Image.open(image_path) as image: image.thumbnail(tuple(x / 2 for x in image.size)) image.save(resized_path) def lambda_handler(event, context): for record in event['Records']: bucket = record['s3']['bucket']['name'] key = unquote_plus(record['s3']['object']['key']) tmpkey = key.replace('/', '') download_path = '/tmp/ { } { }'.format(uuid.uuid4(), tmpkey) upload_path = '/tmp/resized- { }'.format(tmpkey) s3_client.download_file(bucket, key, download_path) resize_image(download_path, upload_path) s3_client.upload_file(upload_path, ' { }-resized'.format(bucket), 'resized- { }'.format(key)) Di direktori yang sama di mana Anda membuat lambda_function.py file Anda, buat direktori baru bernama package dan instal pustaka Pillow (PIL) dan AWS SDK untuk Python (Boto3). Meskipun runtime Lambda Python menyertakan versi Boto3 SDK, kami menyarankan agar Anda menambahkan semua dependensi fungsi Anda ke paket penerapan Anda, meskipun mereka disertakan dalam runtime. Untuk informasi selengkapnya, lihat Dependensi runtime dengan Python. mkdir package pip install \ --platform manylinux2014_x86_64 \ --target=package \ --implementation cp \ --python-version 3.12 \ --only-binary=:all: --upgrade \ pillow boto3 Pustaka Pillow berisi kode C/C ++. Dengan menggunakan --only-binary=:all: opsi --platform manylinux_2014_x86_64 dan, pip akan mengunduh dan menginstal versi Pillow yang berisi binari pra-kompilasi yang kompatibel dengan sistem operasi Amazon Linux 2. Ini memastikan bahwa paket penerapan Anda akan berfungsi di lingkungan eksekusi Lambda, terlepas dari sistem operasi dan arsitektur mesin build lokal Anda. Buat file.zip yang berisi kode aplikasi Anda dan pustaka Pillow dan Boto3. Di Linux atau macOS, jalankan perintah berikut dari antarmuka baris perintah Anda. cd package zip -r ../lambda_function.zip . cd .. zip lambda_function.zip lambda_function.py Di Windows, gunakan alat zip pilihan Anda untuk membuat file lambda_function.zip . Pastikan bahwa lambda_function.py file Anda dan folder yang berisi dependensi Anda semuanya berada di root file.zip. Anda juga dapat membuat paket deployment menggunakan lingkungan virtual Python. Lihat Bekerja dengan arsip file.zip untuk fungsi Python Lambda Buat fungsi Lambda Anda dapat membuat fungsi Lambda menggunakan konsol Lambda AWS CLI atau Lambda. Ikuti instruksi untuk bahasa yang Anda pilih untuk membuat fungsi. Konsol Manajemen AWS Untuk membuat fungsi (konsol) Untuk membuat fungsi Lambda Anda menggunakan konsol, pertama-tama Anda membuat fungsi dasar yang berisi beberapa kode 'Hello world'. Anda kemudian mengganti kode ini dengan kode fungsi Anda sendiri dengan mengunggah file the.zip atau JAR yang Anda buat pada langkah sebelumnya. Buka halaman Fungsi di konsol Lambda. Pastikan Anda bekerja di tempat yang sama dengan saat Wilayah AWS Anda membuat bucket Amazon S3. Anda dapat mengubah wilayah Anda menggunakan daftar drop-down di bagian atas layar. Pilih Buat fungsi . Pilih Penulis dari scratch . Di bagian Informasi dasar , lakukan hal berikut: Untuk Nama fungsi , masukkan CreateThumbnail . Untuk Runtime , pilih Node.js 22.x atau Python 3.12 sesuai dengan bahasa yang Anda pilih untuk fungsi Anda. Untuk Arsitektur , pilih x86_64 . Di tab Ubah peran eksekusi default , lakukan hal berikut: Perluas tab, lalu pilih Gunakan peran yang ada . Pilih yang LambdaS3Role Anda buat sebelumnya. Pilih Buat fungsi . Untuk mengunggah kode fungsi (konsol) Di panel Sumber kode , pilih Unggah dari . Pilih file.zip . Pilih Unggah . Di pemilih file, pilih file.zip Anda dan pilih Buka. Pilih Simpan . AWS CLI Untuk membuat fungsi (AWS CLI) Jalankan perintah CLI untuk bahasa yang Anda pilih. Untuk role parameter, pastikan untuk mengganti 123456789012 dengan Akun AWS ID Anda sendiri. Untuk region parameternya, ganti us-east-1 dengan wilayah tempat Anda membuat bucket Amazon S3. Untuk Node.js , jalankan perintah berikut dari direktori yang berisi function.zip file Anda. aws lambda create-function --function-name CreateThumbnail \ --zip-file fileb://function.zip --handler index.handler --runtime nodejs24.x \ --timeout 10 --memory-size 1024 \ --role arn:aws:iam:: 123456789012 :role/LambdaS3Role --region us-east-1 Untuk Python , jalankan perintah berikut dari direktori yang berisi file Anda lambda_function.zip . aws lambda create-function --function-name CreateThumbnail \ --zip-file fileb://lambda_function.zip --handler lambda_function.lambda_handler \ --runtime python3.14 --timeout 10 --memory-size 1024 \ --role arn:aws:iam:: 123456789012 :role/LambdaS3Role --region us-east-1 Konfigurasikan Amazon S3 untuk menjalankan fungsi Agar fungsi Lambda dapat berjalan saat mengunggah gambar ke bucket sumber, Anda perlu mengonfigurasi pemicu untuk fungsi Anda. Anda dapat mengonfigurasi pemicu Amazon S3 menggunakan konsol atau. AWS CLI penting Prosedur ini mengonfigurasi bucket Amazon S3 untuk menjalankan fungsi Anda setiap kali objek dibuat di bucket. Pastikan untuk mengonfigurasi ini hanya di bucket sumber. Jika fungsi Lambda Anda membuat objek dalam bucket yang sama yang memanggilnya, fungsi Anda dapat dipanggil terus menerus dalam satu loop. Hal ini dapat mengakibatkan biaya yang tidak diharapkan ditagih ke Anda Akun AWS. Konsol Manajemen AWS Untuk mengonfigurasi pemicu Amazon S3 (konsol) Buka halaman Fungsi konsol Lambda dan pilih fungsi Anda () CreateThumbnail . Pilih Tambahkan pemicu . Pilih S3 . Di bawah Bucket , pilih bucket sumber Anda. Di bawah Jenis acara , pilih Semua objek membuat acara . Di bawah Pemanggilan rekursif , pilih kotak centang untuk mengetahui bahwa tidak disarankan menggunakan bucket Amazon S3 yang sama untuk input dan output. Anda dapat mempelajari lebih lanjut tentang pola pemanggilan rekursif di Lambda dengan membaca pola rekursif yang menyebabkan fungsi Lambda yang tidak terkendali di Tanah Tanpa Server. Pilih Tambahkan . Saat Anda membuat pemicu menggunakan konsol Lambda, Lambda secara otomatis membuat kebijakan berbasis sumber daya untuk memberikan layanan yang Anda pilih izin untuk menjalankan fungsi Anda. AWS CLI Untuk mengonfigurasi pemicu Amazon S3 ()AWS CLI Agar bucket sumber Amazon S3 menjalankan fungsi saat menambahkan file gambar, pertama-tama Anda harus mengonfigurasi izin untuk fungsi menggunakan kebijakan berbasis sumber daya. Pernyataan kebijakan berbasis sumber daya memberikan Layanan AWS izin lain untuk menjalankan fungsi Anda. Untuk memberikan izin Amazon S3 untuk menjalankan fungsi Anda, jalankan perintah CLI berikut. Pastikan untuk mengganti source-account parameter dengan Akun AWS ID Anda sendiri dan menggunakan nama bucket sumber Anda sendiri. aws lambda add-permission --function-name CreateThumbnail \ --principal s3.amazonaws.com --statement-id s3invoke --action "lambda:InvokeFunction" \ --source-arn arn:aws:s3::: amzn-s3-demo-source-bucket \ --source-account 123456789012 Kebijakan yang Anda tetapkan dengan perintah ini memungkinkan Amazon S3 untuk menjalankan fungsi Anda hanya ketika tindakan dilakukan di bucket sumber Anda. catatan Meskipun nama bucket Amazon S3 unik secara global, saat menggunakan kebijakan berbasis sumber daya, praktik terbaik adalah menentukan bahwa bucket harus menjadi milik akun Anda. Ini karena jika Anda menghapus bucket, Anda dapat membuat bucket dengan Amazon Resource Name (ARN) yang sama. Akun AWS Simpan JSON berikut dalam file bernama notification.json . Saat diterapkan ke bucket sumber Anda, JSON ini mengonfigurasi bucket untuk mengirim notifikasi ke fungsi Lambda Anda setiap kali objek baru ditambahkan. Ganti Akun AWS nomor dan Wilayah AWS dalam fungsi Lambda ARN dengan nomor akun dan wilayah Anda sendiri. { "LambdaFunctionConfigurations": [ { "Id": "CreateThumbnailEventConfiguration", "LambdaFunctionArn": "arn:aws:lambda: us-east-1:123456789012 :function:CreateThumbnail", "Events": [ "s3:ObjectCreated:Put" ] } ] } Jalankan perintah CLI berikut untuk menerapkan pengaturan notifikasi dalam file JSON yang Anda buat ke bucket sumber Anda. Ganti amzn-s3-demo-source-bucket dengan nama bucket sumber Anda sendiri. aws s3api put-bucket-notification-configuration --bucket amzn-s3-demo-source-bucket \ --notification-configuration file://notification.json Untuk mempelajari lebih lanjut tentang put-bucket-notification-configuration perintah dan notification-configuration opsi, lihat put-bucket-notification-configuration di Referensi Perintah AWS CLI . Uji fungsi Lambda Anda dengan acara dummy Sebelum menguji seluruh penyiapan dengan menambahkan file gambar ke bucket sumber Amazon S3, Anda menguji apakah fungsi Lambda berfungsi dengan benar dengan memanggilnya dengan acara dummy. Peristiwa di Lambda adalah dokumen berformat JSON yang berisi data untuk diproses fungsi Anda. Saat fungsi Anda dipanggil oleh Amazon S3, peristiwa yang dikirim ke fungsi berisi informasi seperti nama bucket, ARN bucket, dan kunci objek. Konsol Manajemen AWS Untuk menguji fungsi Lambda Anda dengan acara dummy (konsol) Buka halaman Fungsi konsol Lambda dan pilih fungsi Anda () CreateThumbnail . Pilih tab Uji . Untuk membuat acara pengujian, di panel acara Uji , lakukan hal berikut: Di bawah Uji tindakan peristiwa , pilih Buat acara baru . Untuk Nama peristiwa , masukkan myTestEvent . Untuk Template , pilih S3 Put . Ganti nilai untuk parameter berikut dengan nilai Anda sendiri. Untuk awsRegion , ganti us-east-1 dengan bucket Amazon S3 yang Wilayah AWS Anda buat. Untuk name , ganti amzn-s3-demo-bucket dengan nama bucket sumber Amazon S3 Anda sendiri. Untuk key , ganti test%2Fkey dengan nama file objek pengujian yang Anda unggah ke bucket sumber di langkah tersebut. Unggah gambar uji ke bucket sumber Anda { "Records": [ { "eventVersion": "2.0", "eventSource": "aws:s3", "awsRegion": "us-east-1" , "eventTime": "1970-01-01T00:00:00.000Z", "eventName": "ObjectCreated:Put", "userIdentity": { "principalId": "EXAMPLE" }, "requestParameters": { "sourceIPAddress": "127.0.0.1" }, "responseElements": { "x-amz-request-id": "EXAMPLE123456789", "x-amz-id-2": "EXAMPLE123/5678abcdefghijklambdaisawesome/mnopqrstuvwxyzABCDEFGH" }, "s3": { "s3SchemaVersion": "1.0", "configurationId": "testConfigRule", "bucket": { "name": "amzn-s3-demo-bucket" , "ownerIdentity": { "principalId": "EXAMPLE" }, "arn": "arn:aws:s3:::amzn-s3-demo-bucket" }, "object": { "key": "test%2Fkey" , "size": 1024, "eTag": "0123456789abcdef0123456789abcdef", "sequencer": "0A1B2C3D4E5F678901" } } } ] } Pilih Simpan . Di panel acara Uji , pilih Uji . Untuk memeriksa fungsi Anda telah membuat verison yang diubah ukurannya dari gambar Anda dan menyimpannya di bucket Amazon S3 target Anda, lakukan hal berikut: Buka halaman Bucket konsol Amazon S3. Pilih bucket target Anda dan konfirmasikan bahwa file yang diubah ukurannya tercantum di panel Objects . AWS CLI Untuk menguji fungsi Lambda Anda dengan acara dummy ()AWS CLI Simpan JSON berikut dalam file bernama dummyS3Event.json . Ganti nilai untuk parameter berikut dengan nilai Anda sendiri: Untuk awsRegion , ganti us-east-1 dengan bucket Amazon S3 yang Wilayah AWS Anda buat. Untuk name , ganti amzn-s3-demo-bucket dengan nama bucket sumber Amazon S3 Anda sendiri. Untuk key , ganti test%2Fkey dengan nama file objek pengujian yang Anda unggah ke bucket sumber di langkah tersebut. Unggah gambar uji ke bucket sumber Anda { "Records": [ { "eventVersion": "2.0", "eventSource": "aws:s3", "awsRegion": "us-east-1" , "eventTime": "1970-01-01T00:00:00.000Z", "eventName": "ObjectCreated:Put", "userIdentity": { "principalId": "EXAMPLE" }, "requestParameters": { "sourceIPAddress": "127.0.0.1" }, "responseElements": { "x-amz-request-id": "EXAMPLE123456789", "x-amz-id-2": "EXAMPLE123/5678abcdefghijklambdaisawesome/mnopqrstuvwxyzABCDEFGH" }, "s3": { "s3SchemaVersion": "1.0", "configurationId": "testConfigRule", "bucket": { "name": "amzn-s3-demo-bucket" , "ownerIdentity": { "principalId": "EXAMPLE" }, "arn": "arn:aws:s3:::amzn-s3-demo-bucket" }, "object": { "key": "test%2Fkey" , "size": 1024, "eTag": "0123456789abcdef0123456789abcdef", "sequencer": "0A1B2C3D4E5F678901" } } } ] } Dari direktori tempat Anda menyimpan dummyS3Event.json file Anda, panggil fungsi dengan menjalankan perintah CLI berikut. Perintah ini memanggil fungsi Lambda Anda secara sinkron dengan RequestResponse menentukan sebagai nilai parameter tipe pemanggilan. Untuk mempelajari lebih lanjut tentang pemanggilan sinkron dan asinkron, lihat Memanggil fungsi Lambda. aws lambda invoke --function-name CreateThumbnail \ --invocation-type RequestResponse --cli-binary-format raw-in-base64-out \ --payload file://dummyS3Event.json outputfile.txt cli-binary-formatOpsi ini diperlukan jika Anda menggunakan versi 2 dari AWS CLI. Untuk menjadikan ini pengaturan default, jalankan aws configure set cli-binary-format raw-in-base64-out . Untuk informasi selengkapnya, lihat opsi baris perintah global yang AWS CLI didukung . Verifikasi bahwa fungsi Anda telah membuat versi thumbnail gambar Anda dan menyimpannya ke bucket Amazon S3 target Anda. Jalankan perintah CLI berikut, ganti amzn-s3-demo-source-bucket-resized dengan nama bucket tujuan Anda sendiri. aws s3api list-objects-v2 --bucket amzn-s3-demo-source-bucket-resized Anda akan melihat output seperti yang berikut ini. Key Parameter menunjukkan nama file file gambar Anda yang diubah ukurannya. { "Contents": [ { "Key": "resized-HappyFace.jpg", "LastModified": "2023-06-06T21:40:07+00:00", "ETag": "\"d8ca652ffe83ba6b721ffc20d9d7174a\"", "Size": 2633, "StorageClass": "STANDARD" } ] } Uji fungsi Anda menggunakan pemicu Amazon S3 Sekarang setelah Anda mengonfirmasi bahwa fungsi Lambda Anda beroperasi dengan benar, Anda siap untuk menguji penyiapan lengkap Anda dengan menambahkan file gambar ke bucket sumber Amazon S3 Anda. Saat Anda menambahkan gambar ke bucket sumber, fungsi Lambda Anda akan dipanggil secara otomatis. Fungsi Anda membuat versi file yang diubah ukurannya dan menyimpannya di bucket target Anda. Konsol Manajemen AWS Untuk menguji fungsi Lambda Anda menggunakan pemicu Amazon S3 (konsol) Untuk mengunggah gambar ke bucket Amazon S3 Anda, lakukan hal berikut: Buka halaman Bucket di konsol Amazon S3 dan pilih bucket sumber Anda. Pilih Unggah . Pilih Tambahkan file dan gunakan pemilih file untuk memilih file gambar yang ingin Anda unggah. Objek gambar Anda dapat berupa file.jpg atau.png. Pilih Buka , lalu pilih Unggah . Verifikasi bahwa Lambda telah menyimpan versi file gambar yang diubah ukurannya di bucket target dengan melakukan hal berikut: Arahkan kembali ke halaman Bucket di konsol Amazon S3 dan pilih bucket tujuan Anda. Di panel Objects , Anda sekarang akan melihat dua file gambar yang diubah ukurannya, satu dari setiap pengujian fungsi Lambda Anda. Untuk mengunduh gambar yang diubah ukurannya, pilih file, lalu pilih Unduh . AWS CLI Untuk menguji fungsi Lambda Anda menggunakan pemicu Amazon S3 ()AWS CLI Dari direktori yang berisi gambar yang ingin Anda unggah, jalankan perintah CLI berikut. Ganti --bucket parameter dengan nama bucket sumber Anda. Untuk --body parameter --key dan, gunakan nama file gambar pengujian Anda. Gambar uji Anda dapat berupa file.jpg atau.png. aws s3api put-object --bucket amzn-s3-demo-source-bucket --key SmileyFace.jpg --body ./SmileyFace.jpg Verifikasi bahwa fungsi Anda telah membuat versi thumbnail gambar Anda dan menyimpannya ke bucket Amazon S3 target Anda. Jalankan perintah CLI berikut, ganti amzn-s3-demo-source-bucket-resized dengan nama bucket tujuan Anda sendiri. aws s3api list-objects-v2 --bucket amzn-s3-demo-source-bucket-resized Jika fungsi Anda berjalan dengan sukses, Anda akan melihat output yang mirip dengan berikut ini. Bucket target Anda sekarang harus berisi dua file yang diubah ukurannya. { "Contents": [ { "Key": "resized-HappyFace.jpg", "LastModified": "2023-06-07T00:15:50+00:00", "ETag": "\"7781a43e765a8301713f533d70968a1e\"", "Size": 2763, "StorageClass": "STANDARD" }, { "Key": "resized-SmileyFace.jpg", "LastModified": "2023-06-07T00:13:18+00:00", "ETag": "\"ca536e5a1b9e32b22cd549e18792cdbc\"", "Size": 1245, "StorageClass": "STANDARD" } ] } Bersihkan sumber daya Anda Sekarang Anda dapat menghapus sumber daya yang Anda buat untuk tutorial ini, kecuali Anda ingin mempertahankannya. Dengan menghapus AWS sumber daya yang tidak lagi Anda gunakan, Anda mencegah tagihan yang tidak perlu ke Anda Akun AWS. Untuk menghapus fungsi Lambda Buka halaman Fungsi di konsol Lambda. Pilih fungsi yang Anda buat. Pilih Tindakan , Hapus . Ketik confirm kolom input teks dan pilih Hapus . Untuk menghapus kebijakan yang Anda buat. Buka halaman Kebijakan konsol IAM. Pilih kebijakan yang Anda buat ( AWSLambdaS3Policy ). Pilih Tindakan kebijakan , Hapus . Pilih Hapus . Untuk menghapus peran eksekusi Buka halaman Peran dari konsol IAM. Pilih peran eksekusi yang Anda buat. Pilih Hapus . Masukkan nama peran di bidang input teks dan pilih Hapus . Untuk menghapus bucket S3 Buka konsol Amazon S3 . Pilih bucket yang Anda buat. Pilih Hapus . Masukkan nama ember di bidang input teks. Pilih Hapus bucket . Javascript dinonaktifkan atau tidak tersedia di browser Anda. Untuk menggunakan Dokumentasi AWS, Javascript harus diaktifkan. Lihat halaman Bantuan browser Anda untuk petunjuk. Konvensi Dokumen Tutorial: Menggunakan pemicu S3 Secrets Manager Apakah halaman ini membantu Anda? - Ya Terima kasih telah memberitahukan bahwa hasil pekerjaan kami sudah baik. Jika Anda memiliki waktu luang, beri tahu kami aspek apa saja yang sudah bagus, agar kami dapat menerapkannya secara lebih luas. Apakah halaman ini membantu Anda? - Tidak Terima kasih telah memberi tahu kami bahwa halaman ini perlu ditingkatkan. Maaf karena telah mengecewakan Anda. Jika Anda memiliki waktu luang, beri tahu kami bagaimana dokumentasi ini dapat ditingkatkan. | 2026-01-13T09:30:35 |
https://young-programmers.blogspot.com/search/label/scratch#sidebar | Young Programmers Podcast: scratch skip to main | skip to sidebar Young Programmers Podcast A video podcast for computer programmers in grades 3 and up. We learn about Scratch, Tynker, Alice, Python, Pygame, and Scala, and interview interesting programmers. From professional software developer and teacher Dave Briccetti, and many special guests. Viewing the Videos or Subscribing to the Podcast Some of the entries have a picture, which you can click to access the video. Otherwise, to see the videos, use this icon to subscribe to or view the feed: Or, subscribe in iTunes Showing posts with label scratch . Show all posts Showing posts with label scratch . Show all posts Friday, December 25, 2009 Invisible Player Escapes Maze Escape the maze. You are invisible, and so are all the obstacles unless they are close to you. Illustrates use of the ghost effect, and broadcast. http://scratch.mit.edu/projects/davebric/818925 at 1:37 PM Labels: scratch Thursday, December 24, 2009 Growing Player Escapes Maze Escape the maze before you grow too big. Illustrates use of the timer, and “if touching color.” The Scratch project is here: http://scratch.mit.edu/projects/davebric/818258 at 2:59 PM Labels: scratch Wednesday, September 30, 2009 Sound Flies a Helicopter in Scratch Sound (your voice, perhaps) controls the altitude of a helicopter which you try to keep from hitting the mountains. at 3:25 AM Labels: scratch , sound Tuesday, August 4, 2009 Platform Example, Very Simple Here is a sprite that will drop onto red platforms, and gains the ability to fly from a power-up. Scratch project file . at 1:51 AM Labels: scratch Sunday, August 2, 2009 Cat Saves the Villager Scratch Project Walkthrough Here’s a walkthrough of Cat Saves the Villager . It shows several characters that deliver lines and interact using broadcast . Dave Briccetti created it in 35 minutes with six students in class at DVC College for Kids. at 7:31 PM Labels: scratch Friday, July 24, 2009 Recording Music for Computer Games Student, cellist, guitarist and programmer Ethan Kuefner (@jazzcello on Twitter) visited my programming classes and showed how to record music and sound effects, and put them into computer games. We used Scratch, Python and Pygame, GarageBand and Audacity. at 7:15 PM Labels: audacity , garageband , music , pygame , python , scratch , sound Tuesday, July 21, 2009 Using GIMP to Make Graphics for Scratch and Alice Shows using the GIMP (GNU Image Manipulation Program) to create a costume for a Scratch sprite, and a texture for Alice. at 11:16 AM Labels: alice , GIMP , scratch Sunday, July 19, 2009 Power-Up and Shield Shows how to have your character power up with a shield, which diminishes over time and can be reacquired with another power-up. at 1:04 PM Labels: scratch Making Scratch Graphics with Inkscape Shows making a simple drawing with Inkscape, exporting it as a bitmap, and then importing the image into Scratch. at 1:02 PM Labels: art , inkscape , scratch Overview of Scratch, Alice, Python and Pygame Software developer and teacher Dave Briccetti demonstrates software he uses to teach programming to kids: Scratch, Alice, Python and Pygame. at 12:18 PM Labels: alice , pygame , python , scratch Home Subscribe to: Comments (Atom) About Me Dave Briccetti View my complete profile Where to Get Software Kojo Python Alice Scratch Other Blogs Dave Briccetti’s Blog One of My Best Classes Ever 10 years ago Tags alice (3) Android (1) arduino (1) art (1) audacity (2) dictionary (2) Flickr (1) functions (2) gamedev (1) garageband (1) GIMP (2) Google (2) guest (4) hacker (1) higher-order functions (1) inkscape (1) interview (9) Java (2) JavaFX (2) Jython (3) Kojo (2) lift (1) music (2) physics (1) platform (1) programmer (4) pygame (6) python (31) PythonCard (1) random (6) Sande (2) Scala (5) scratch (10) shdh (2) shdh34 (2) sound (3) sprite (2) Swing (3) teaching (3) twitter (2) Tynker (1) Web Services (1) xturtle (1) Followers Blog Archive ▼  2015 (1) ▼  February (1) This Podcast Moves to YouTube ►  2013 (4) ►  July (1) ►  June (3) ►  2012 (2) ►  February (1) ►  January (1) ►  2011 (8) ►  November (1) ►  July (3) ►  May (1) ►  February (2) ►  January (1) ►  2010 (6) ►  October (2) ►  June (2) ►  February (2) ►  2009 (37) ►  December (4) ►  November (1) ►  September (7) ►  August (11) ►  July (14)   | 2026-01-13T09:30:35 |
http://anh.cs.luc.edu/handsonPythonTutorial/ifstatements.html#head-or-tails-exercise | 3.1. If Statements — Hands-on Python Tutorial for Python 3 Navigation index next | previous | Hands-on Python Tutorial » 3. More On Flow of Control » 3.1. If Statements ¶ 3.1.1. Simple Conditions ¶ The statements introduced in this chapter will involve tests or conditions . More syntax for conditions will be introduced later, but for now consider simple arithmetic comparisons that directly translate from math into Python. Try each line separately in the Shell 2 < 5 3 > 7 x = 11 x > 10 2 * x < x type ( True ) You see that conditions are either True or False . These are the only possible Boolean values (named after 19th century mathematician George Boole). In Python the name Boolean is shortened to the type bool . It is the type of the results of true-false conditions or tests. Note The Boolean values True and False have no quotes around them! Just as '123' is a string and 123 without the quotes is not, 'True' is a string, not of type bool. 3.1.2. Simple if Statements ¶ Run this example program, suitcase.py. Try it at least twice, with inputs: 30 and then 55. As you an see, you get an extra result, depending on the input. The main code is: weight = float ( input ( "How many pounds does your suitcase weigh? " )) if weight > 50 : print ( "There is a $25 charge for luggage that heavy." ) print ( "Thank you for your business." ) The middle two line are an if statement. It reads pretty much like English. If it is true that the weight is greater than 50, then print the statement about an extra charge. If it is not true that the weight is greater than 50, then don’t do the indented part: skip printing the extra luggage charge. In any event, when you have finished with the if statement (whether it actually does anything or not), go on to the next statement that is not indented under the if . In this case that is the statement printing “Thank you”. The general Python syntax for a simple if statement is if condition : indentedStatementBlock If the condition is true, then do the indented statements. If the condition is not true, then skip the indented statements. Another fragment as an example: if balance < 0 : transfer = - balance # transfer enough from the backup account: backupAccount = backupAccount - transfer balance = balance + transfer As with other kinds of statements with a heading and an indented block, the block can have more than one statement. The assumption in the example above is that if an account goes negative, it is brought back to 0 by transferring money from a backup account in several steps. In the examples above the choice is between doing something (if the condition is True ) or nothing (if the condition is False ). Often there is a choice of two possibilities, only one of which will be done, depending on the truth of a condition. 3.1.3. if - else Statements ¶ Run the example program, clothes.py . Try it at least twice, with inputs 50 and then 80. As you can see, you get different results, depending on the input. The main code of clothes.py is: temperature = float ( input ( 'What is the temperature? ' )) if temperature > 70 : print ( 'Wear shorts.' ) else : print ( 'Wear long pants.' ) print ( 'Get some exercise outside.' ) The middle four lines are an if-else statement. Again it is close to English, though you might say “otherwise” instead of “else” (but else is shorter!). There are two indented blocks: One, like in the simple if statement, comes right after the if heading and is executed when the condition in the if heading is true. In the if - else form this is followed by an else: line, followed by another indented block that is only executed when the original condition is false . In an if - else statement exactly one of two possible indented blocks is executed. A line is also shown de dented next, removing indentation, about getting exercise. Since it is dedented, it is not a part of the if-else statement: Since its amount of indentation matches the if heading, it is always executed in the normal forward flow of statements, after the if - else statement (whichever block is selected). The general Python if - else syntax is if condition : indentedStatementBlockForTrueCondition else: indentedStatementBlockForFalseCondition These statement blocks can have any number of statements, and can include about any kind of statement. See Graduate Exercise 3.1.4. More Conditional Expressions ¶ All the usual arithmetic comparisons may be made, but many do not use standard mathematical symbolism, mostly for lack of proper keys on a standard keyboard. Meaning Math Symbol Python Symbols Less than < < Greater than > > Less than or equal ≤ <= Greater than or equal ≥ >= Equals = == Not equal ≠ != There should not be space between the two-symbol Python substitutes. Notice that the obvious choice for equals , a single equal sign, is not used to check for equality. An annoying second equal sign is required. This is because the single equal sign is already used for assignment in Python, so it is not available for tests. Warning It is a common error to use only one equal sign when you mean to test for equality, and not make an assignment! Tests for equality do not make an assignment, and they do not require a variable on the left. Any expressions can be tested for equality or inequality ( != ). They do not need to be numbers! Predict the results and try each line in the Shell : x = 5 x x == 5 x == 6 x x != 6 x = 6 6 == x 6 != x 'hi' == 'h' + 'i' 'HI' != 'hi' [ 1 , 2 ] != [ 2 , 1 ] An equality check does not make an assignment. Strings are case sensitive. Order matters in a list. Try in the Shell : 'a' > 5 When the comparison does not make sense, an Exception is caused. [1] Following up on the discussion of the inexactness of float arithmetic in String Formats for Float Precision , confirm that Python does not consider .1 + .2 to be equal to .3: Write a simple condition into the Shell to test. Here is another example: Pay with Overtime. Given a person’s work hours for the week and regular hourly wage, calculate the total pay for the week, taking into account overtime. Hours worked over 40 are overtime, paid at 1.5 times the normal rate. This is a natural place for a function enclosing the calculation. Read the setup for the function: def calcWeeklyWages ( totalHours , hourlyWage ): '''Return the total weekly wages for a worker working totalHours, with a given regular hourlyWage. Include overtime for hours over 40. ''' The problem clearly indicates two cases: when no more than 40 hours are worked or when more than 40 hours are worked. In case more than 40 hours are worked, it is convenient to introduce a variable overtimeHours. You are encouraged to think about a solution before going on and examining mine. You can try running my complete example program, wages.py, also shown below. The format operation at the end of the main function uses the floating point format ( String Formats for Float Precision ) to show two decimal places for the cents in the answer: def calcWeeklyWages ( totalHours , hourlyWage ): '''Return the total weekly wages for a worker working totalHours, with a given regular hourlyWage. Include overtime for hours over 40. ''' if totalHours <= 40 : totalWages = hourlyWage * totalHours else : overtime = totalHours - 40 totalWages = hourlyWage * 40 + ( 1.5 * hourlyWage ) * overtime return totalWages def main (): hours = float ( input ( 'Enter hours worked: ' )) wage = float ( input ( 'Enter dollars paid per hour: ' )) total = calcWeeklyWages ( hours , wage ) print ( 'Wages for {hours} hours at ${wage:.2f} per hour are ${total:.2f}.' . format ( ** locals ())) main () Here the input was intended to be numeric, but it could be decimal so the conversion from string was via float , not int . Below is an equivalent alternative version of the body of calcWeeklyWages , used in wages1.py . It uses just one general calculation formula and sets the parameters for the formula in the if statement. There are generally a number of ways you might solve the same problem! if totalHours <= 40 : regularHours = totalHours overtime = 0 else : overtime = totalHours - 40 regularHours = 40 return hourlyWage * regularHours + ( 1.5 * hourlyWage ) * overtime The in boolean operator : There are also Boolean operators that are applied to types others than numbers. A useful Boolean operator is in , checking membership in a sequence: >>> vals = [ 'this' , 'is' , 'it] >>> 'is' in vals True >>> 'was' in vals False It can also be used with not , as not in , to mean the opposite: >>> vals = [ 'this' , 'is' , 'it] >>> 'is' not in vals False >>> 'was' not in vals True In general the two versions are: item in sequence item not in sequence Detecting the need for if statements : Like with planning programs needing``for`` statements, you want to be able to translate English descriptions of problems that would naturally include if or if - else statements. What are some words or phrases or ideas that suggest the use of these statements? Think of your own and then compare to a few I gave: [2] 3.1.4.1. Graduate Exercise ¶ Write a program, graduate.py , that prompts students for how many credits they have. Print whether of not they have enough credits for graduation. (At Loyola University Chicago 120 credits are needed for graduation.) 3.1.4.2. Head or Tails Exercise ¶ Write a program headstails.py . It should include a function flip() , that simulates a single flip of a coin: It randomly prints either Heads or Tails . Accomplish this by choosing 0 or 1 arbitrarily with random.randrange(2) , and use an if - else statement to print Heads when the result is 0, and Tails otherwise. In your main program have a simple repeat loop that calls flip() 10 times to test it, so you generate a random sequence of 10 Heads and Tails . 3.1.4.3. Strange Function Exercise ¶ Save the example program jumpFuncStub.py as jumpFunc.py , and complete the definitions of functions jump and main as described in the function documentation strings in the program. In the jump function definition use an if - else statement (hint [3] ). In the main function definition use a for -each loop, the range function, and the jump function. The jump function is introduced for use in Strange Sequence Exercise , and others after that. 3.1.5. Multiple Tests and if - elif Statements ¶ Often you want to distinguish between more than two distinct cases, but conditions only have two possible results, True or False , so the only direct choice is between two options. As anyone who has played “20 Questions” knows, you can distinguish more cases by further questions. If there are more than two choices, a single test may only reduce the possibilities, but further tests can reduce the possibilities further and further. Since most any kind of statement can be placed in an indented statement block, one choice is a further if statement. For instance consider a function to convert a numerical grade to a letter grade, ‘A’, ‘B’, ‘C’, ‘D’ or ‘F’, where the cutoffs for ‘A’, ‘B’, ‘C’, and ‘D’ are 90, 80, 70, and 60 respectively. One way to write the function would be test for one grade at a time, and resolve all the remaining possibilities inside the next else clause: def letterGrade ( score ): if score >= 90 : letter = 'A' else : # grade must be B, C, D or F if score >= 80 : letter = 'B' else : # grade must be C, D or F if score >= 70 : letter = 'C' else : # grade must D or F if score >= 60 : letter = 'D' else : letter = 'F' return letter This repeatedly increasing indentation with an if statement as the else block can be annoying and distracting. A preferred alternative in this situation, that avoids all this indentation, is to combine each else and if block into an elif block: def letterGrade ( score ): if score >= 90 : letter = 'A' elif score >= 80 : letter = 'B' elif score >= 70 : letter = 'C' elif score >= 60 : letter = 'D' else : letter = 'F' return letter The most elaborate syntax for an if - elif - else statement is indicated in general below: if condition1 : indentedStatementBlockForTrueCondition1 elif condition2 : indentedStatementBlockForFirstTrueCondition2 elif condition3 : indentedStatementBlockForFirstTrueCondition3 elif condition4 : indentedStatementBlockForFirstTrueCondition4 else: indentedStatementBlockForEachConditionFalse The if , each elif , and the final else lines are all aligned. There can be any number of elif lines, each followed by an indented block. (Three happen to be illustrated above.) With this construction exactly one of the indented blocks is executed. It is the one corresponding to the first True condition, or, if all conditions are False , it is the block after the final else line. Be careful of the strange Python contraction. It is elif , not elseif . A program testing the letterGrade function is in example program grade1.py . See Grade Exercise . A final alternative for if statements: if - elif -.... with no else . This would mean changing the syntax for if - elif - else above so the final else: and the block after it would be omitted. It is similar to the basic if statement without an else , in that it is possible for no indented block to be executed. This happens if none of the conditions in the tests are true. With an else included, exactly one of the indented blocks is executed. Without an else , at most one of the indented blocks is executed. if weight > 120 : print ( 'Sorry, we can not take a suitcase that heavy.' ) elif weight > 50 : print ( 'There is a $25 charge for luggage that heavy.' ) This if - elif statement only prints a line if there is a problem with the weight of the suitcase. 3.1.5.1. Sign Exercise ¶ Write a program sign.py to ask the user for a number. Print out which category the number is in: 'positive' , 'negative' , or 'zero' . 3.1.5.2. Grade Exercise ¶ In Idle, load grade1.py and save it as grade2.py Modify grade2.py so it has an equivalent version of the letterGrade function that tests in the opposite order, first for F, then D, C, .... Hint: How many tests do you need to do? [4] Be sure to run your new version and test with different inputs that test all the different paths through the program. Be careful to test around cut-off points. What does a grade of 79.6 imply? What about exactly 80? 3.1.5.3. Wages Exercise ¶ * Modify the wages.py or the wages1.py example to create a program wages2.py that assumes people are paid double time for hours over 60. Hence they get paid for at most 20 hours overtime at 1.5 times the normal rate. For example, a person working 65 hours with a regular wage of $10 per hour would work at $10 per hour for 40 hours, at 1.5 * $10 for 20 hours of overtime, and 2 * $10 for 5 hours of double time, for a total of 10*40 + 1.5*10*20 + 2*10*5 = $800. You may find wages1.py easier to adapt than wages.py . Be sure to test all paths through the program! Your program is likely to be a modification of a program where some choices worked before, but once you change things, retest for all the cases! Changes can mess up things that worked before. 3.1.6. Nesting Control-Flow Statements ¶ The power of a language like Python comes largely from the variety of ways basic statements can be combined . In particular, for and if statements can be nested inside each other’s indented blocks. For example, suppose you want to print only the positive numbers from an arbitrary list of numbers in a function with the following heading. Read the pieces for now. def printAllPositive ( numberList ): '''Print only the positive numbers in numberList.''' For example, suppose numberList is [3, -5, 2, -1, 0, 7] . You want to process a list, so that suggests a for -each loop, for num in numberList : but a for -each loop runs the same code body for each element of the list, and we only want print ( num ) for some of them. That seems like a major obstacle, but think closer at what needs to happen concretely. As a human, who has eyes of amazing capacity, you are drawn immediately to the actual correct numbers, 3, 2, and 7, but clearly a computer doing this systematically will have to check every number. In fact, there is a consistent action required: Every number must be tested to see if it should be printed. This suggests an if statement, with the condition num > 0 . Try loading into Idle and running the example program onlyPositive.py , whose code is shown below. It ends with a line testing the function: def printAllPositive ( numberList ): '''Print only the positive numbers in numberList.''' for num in numberList : if num > 0 : print ( num ) printAllPositive ([ 3 , - 5 , 2 , - 1 , 0 , 7 ]) This idea of nesting if statements enormously expands the possibilities with loops. Now different things can be done at different times in loops, as long as there is a consistent test to allow a choice between the alternatives. Shortly, while loops will also be introduced, and you will see if statements nested inside of them, too. The rest of this section deals with graphical examples. Run example program bounce1.py . It has a red ball moving and bouncing obliquely off the edges. If you watch several times, you should see that it starts from random locations. Also you can repeat the program from the Shell prompt after you have run the script. For instance, right after running the program, try in the Shell bounceBall ( - 3 , 1 ) The parameters give the amount the shape moves in each animation step. You can try other values in the Shell , preferably with magnitudes less than 10. For the remainder of the description of this example, read the extracted text pieces. The animations before this were totally scripted, saying exactly how many moves in which direction, but in this case the direction of motion changes with every bounce. The program has a graphic object shape and the central animation step is shape . move ( dx , dy ) but in this case, dx and dy have to change when the ball gets to a boundary. For instance, imagine the ball getting to the left side as it is moving to the left and up. The bounce obviously alters the horizontal part of the motion, in fact reversing it, but the ball would still continue up. The reversal of the horizontal part of the motion means that the horizontal shift changes direction and therefore its sign: dx = - dx but dy does not need to change. This switch does not happen at each animation step, but only when the ball reaches the edge of the window. It happens only some of the time - suggesting an if statement. Still the condition must be determined. Suppose the center of the ball has coordinates (x, y). When x reaches some particular x coordinate, call it xLow, the ball should bounce. The edge of the window is at coordinate 0, but xLow should not be 0, or the ball would be half way off the screen before bouncing! For the edge of the ball to hit the edge of the screen, the x coordinate of the center must be the length of the radius away, so actually xLow is the radius of the ball. Animation goes quickly in small steps, so I cheat. I allow the ball to take one (small, quick) step past where it really should go ( xLow ), and then we reverse it so it comes back to where it belongs. In particular if x < xLow : dx = - dx There are similar bounding variables xHigh , yLow and yHigh , all the radius away from the actual edge coordinates, and similar conditions to test for a bounce off each possible edge. Note that whichever edge is hit, one coordinate, either dx or dy, reverses. One way the collection of tests could be written is if x < xLow : dx = - dx if x > xHigh : dx = - dx if y < yLow : dy = - dy if y > yHigh : dy = - dy This approach would cause there to be some extra testing: If it is true that x < xLow , then it is impossible for it to be true that x > xHigh , so we do not need both tests together. We avoid unnecessary tests with an elif clause (for both x and y): if x < xLow : dx = - dx elif x > xHigh : dx = - dx if y < yLow : dy = - dy elif y > yHigh : dy = - dy Note that the middle if is not changed to an elif , because it is possible for the ball to reach a corner , and need both dx and dy reversed. The program also uses several methods to read part of the state of graphics objects that we have not used in examples yet. Various graphics objects, like the circle we are using as the shape, know their center point, and it can be accessed with the getCenter() method. (Actually a clone of the point is returned.) Also each coordinate of a Point can be accessed with the getX() and getY() methods. This explains the new features in the central function defined for bouncing around in a box, bounceInBox . The animation arbitrarily goes on in a simple repeat loop for 600 steps. (A later example will improve this behavior.) def bounceInBox ( shape , dx , dy , xLow , xHigh , yLow , yHigh ): ''' Animate a shape moving in jumps (dx, dy), bouncing when its center reaches the low and high x and y coordinates. ''' delay = . 005 for i in range ( 600 ): shape . move ( dx , dy ) center = shape . getCenter () x = center . getX () y = center . getY () if x < xLow : dx = - dx elif x > xHigh : dx = - dx if y < yLow : dy = - dy elif y > yHigh : dy = - dy time . sleep ( delay ) The program starts the ball from an arbitrary point inside the allowable rectangular bounds. This is encapsulated in a utility function included in the program, getRandomPoint . The getRandomPoint function uses the randrange function from the module random . Note that in parameters for both the functions range and randrange , the end stated is past the last value actually desired: def getRandomPoint ( xLow , xHigh , yLow , yHigh ): '''Return a random Point with coordinates in the range specified.''' x = random . randrange ( xLow , xHigh + 1 ) y = random . randrange ( yLow , yHigh + 1 ) return Point ( x , y ) The full program is listed below, repeating bounceInBox and getRandomPoint for completeness. Several parts that may be useful later, or are easiest to follow as a unit, are separated out as functions. Make sure you see how it all hangs together or ask questions! ''' Show a ball bouncing off the sides of the window. ''' from graphics import * import time , random def bounceInBox ( shape , dx , dy , xLow , xHigh , yLow , yHigh ): ''' Animate a shape moving in jumps (dx, dy), bouncing when its center reaches the low and high x and y coordinates. ''' delay = . 005 for i in range ( 600 ): shape . move ( dx , dy ) center = shape . getCenter () x = center . getX () y = center . getY () if x < xLow : dx = - dx elif x > xHigh : dx = - dx if y < yLow : dy = - dy elif y > yHigh : dy = - dy time . sleep ( delay ) def getRandomPoint ( xLow , xHigh , yLow , yHigh ): '''Return a random Point with coordinates in the range specified.''' x = random . randrange ( xLow , xHigh + 1 ) y = random . randrange ( yLow , yHigh + 1 ) return Point ( x , y ) def makeDisk ( center , radius , win ): '''return a red disk that is drawn in win with given center and radius.''' disk = Circle ( center , radius ) disk . setOutline ( "red" ) disk . setFill ( "red" ) disk . draw ( win ) return disk def bounceBall ( dx , dy ): '''Make a ball bounce around the screen, initially moving by (dx, dy) at each jump.''' win = GraphWin ( 'Ball Bounce' , 290 , 290 ) win . yUp () radius = 10 xLow = radius # center is separated from the wall by the radius at a bounce xHigh = win . getWidth () - radius yLow = radius yHigh = win . getHeight () - radius center = getRandomPoint ( xLow , xHigh , yLow , yHigh ) ball = makeDisk ( center , radius , win ) bounceInBox ( ball , dx , dy , xLow , xHigh , yLow , yHigh ) win . close () bounceBall ( 3 , 5 ) 3.1.6.1. Short String Exercise ¶ Write a program short.py with a function printShort with heading: def printShort ( strings ): '''Given a list of strings, print the ones with at most three characters. >>> printShort(['a', 'long', one']) a one ''' In your main program, test the function, calling it several times with different lists of strings. Hint: Find the length of each string with the len function. The function documentation here models a common approach: illustrating the behavior of the function with a Python Shell interaction. This part begins with a line starting with >>> . Other exercises and examples will also document behavior in the Shell. 3.1.6.2. Even Print Exercise ¶ Write a program even1.py with a function printEven with heading: def printEven ( nums ): '''Given a list of integers nums, print the even ones. >>> printEven([4, 1, 3, 2, 7]) 4 2 ''' In your main program, test the function, calling it several times with different lists of integers. Hint: A number is even if its remainder, when dividing by 2, is 0. 3.1.6.3. Even List Exercise ¶ Write a program even2.py with a function chooseEven with heading: def chooseEven ( nums ): '''Given a list of integers, nums, return a list containing only the even ones. >>> chooseEven([4, 1, 3, 2, 7]) [4, 2] ''' In your main program, test the function, calling it several times with different lists of integers and printing the results in the main program. (The documentation string illustrates the function call in the Python shell, where the return value is automatically printed. Remember, that in a program, you only print what you explicitly say to print.) Hint: In the function, create a new list, and append the appropriate numbers to it, before returning the result. 3.1.6.4. Unique List Exercise ¶ * The madlib2.py program has its getKeys function, which first generates a list of each occurrence of a cue in the story format. This gives the cues in order, but likely includes repetitions. The original version of getKeys uses a quick method to remove duplicates, forming a set from the list. There is a disadvantage in the conversion, though: Sets are not ordered, so when you iterate through the resulting set, the order of the cues will likely bear no resemblance to the order they first appeared in the list. That issue motivates this problem: Copy madlib2.py to madlib2a.py , and add a function with this heading: def uniqueList ( aList ): ''' Return a new list that includes the first occurrence of each value in aList, and omits later repeats. The returned list should include the first occurrences of values in aList in their original order. >>> vals = ['cat', 'dog', 'cat', 'bug', 'dog', 'ant', 'dog', 'bug'] >>> uniqueList(vals) ['cat', 'dog', 'bug', 'ant'] ''' Hint: Process aList in order. Use the in syntax to only append elements to a new list that are not already in the new list. After perfecting the uniqueList function, replace the last line of getKeys , so it uses uniqueList to remove duplicates in keyList . Check that your madlib2a.py prompts you for cue values in the order that the cues first appear in the madlib format string. 3.1.7. Compound Boolean Expressions ¶ To be eligible to graduate from Loyola University Chicago, you must have 120 credits and a GPA of at least 2.0. This translates directly into Python as a compound condition : credits >= 120 and GPA >= 2.0 This is true if both credits >= 120 is true and GPA >= 2.0 is true. A short example program using this would be: credits = float ( input ( 'How many units of credit do you have? ' )) GPA = float ( input ( 'What is your GPA? ' )) if credits >= 120 and GPA >= 2.0 : print ( 'You are eligible to graduate!' ) else : print ( 'You are not eligible to graduate.' ) The new Python syntax is for the operator and : condition1 and condition2 The compound condition is true if both of the component conditions are true. It is false if at least one of the conditions is false. See Congress Exercise . In the last example in the previous section, there was an if - elif statement where both tests had the same block to be done if the condition was true: if x < xLow : dx = - dx elif x > xHigh : dx = - dx There is a simpler way to state this in a sentence: If x < xLow or x > xHigh, switch the sign of dx. That translates directly into Python: if x < xLow or x > xHigh : dx = - dx The word or makes another compound condition: condition1 or condition2 is true if at least one of the conditions is true. It is false if both conditions are false. This corresponds to one way the word “or” is used in English. Other times in English “or” is used to mean exactly one alternative is true. Warning When translating a problem stated in English using “or”, be careful to determine whether the meaning matches Python’s or . It is often convenient to encapsulate complicated tests inside a function. Think how to complete the function starting: def isInside ( rect , point ): '''Return True if the point is inside the Rectangle rect.''' pt1 = rect . getP1 () pt2 = rect . getP2 () Recall that a Rectangle is specified in its constructor by two diagonally oppose Point s. This example gives the first use in the tutorials of the Rectangle methods that recover those two corner points, getP1 and getP2 . The program calls the points obtained this way pt1 and pt2 . The x and y coordinates of pt1 , pt2 , and point can be recovered with the methods of the Point type, getX() and getY() . Suppose that I introduce variables for the x coordinates of pt1 , point , and pt2 , calling these x-coordinates end1 , val , and end2 , respectively. On first try you might decide that the needed mathematical relationship to test is end1 <= val <= end2 Unfortunately, this is not enough: The only requirement for the two corner points is that they be diagonally opposite, not that the coordinates of the second point are higher than the corresponding coordinates of the first point. It could be that end1 is 200; end2 is 100, and val is 120. In this latter case val is between end1 and end2 , but substituting into the expression above 200 <= 120 <= 100 is False. The 100 and 200 need to be reversed in this case. This makes a complicated situation. Also this is an issue which must be revisited for both the x and y coordinates. I introduce an auxiliary function isBetween to deal with one coordinate at a time. It starts: def isBetween ( val , end1 , end2 ): '''Return True if val is between the ends. The ends do not need to be in increasing order.''' Clearly this is true if the original expression, end1 <= val <= end2 , is true. You must also consider the possible case when the order of the ends is reversed: end2 <= val <= end1 . How do we combine these two possibilities? The Boolean connectives to consider are and and or . Which applies? You only need one to be true, so or is the proper connective: A correct but redundant function body would be: if end1 <= val <= end2 or end2 <= val <= end1 : return True else : return False Check the meaning: if the compound expression is True , return True . If the condition is False , return False – in either case return the same value as the test condition. See that a much simpler and neater version is to just return the value of the condition itself! return end1 <= val <= end2 or end2 <= val <= end1 Note In general you should not need an if - else statement to choose between true and false values! Operate directly on the boolean expression. A side comment on expressions like end1 <= val <= end2 Other than the two-character operators, this is like standard math syntax, chaining comparisons. In Python any number of comparisons can be chained in this way, closely approximating mathematical notation. Though this is good Python, be aware that if you try other high-level languages like Java and C++, such an expression is gibberish. Another way the expression can be expressed (and which translates directly to other languages) is: end1 <= val and val <= end2 So much for the auxiliary function isBetween . Back to the isInside function. You can use the isBetween function to check the x coordinates, isBetween ( point . getX (), p1 . getX (), p2 . getX ()) and to check the y coordinates, isBetween ( point . getY (), p1 . getY (), p2 . getY ()) Again the question arises: how do you combine the two tests? In this case we need the point to be both between the sides and between the top and bottom, so the proper connector is and . Think how to finish the isInside method. Hint: [5] Sometimes you want to test the opposite of a condition. As in English you can use the word not . For instance, to test if a Point was not inside Rectangle Rect, you could use the condition not isInside ( rect , point ) In general, not condition is True when condition is False , and False when condition is True . The example program chooseButton1.py , shown below, is a complete program using the isInside function in a simple application, choosing colors. Pardon the length. Do check it out. It will be the starting point for a number of improvements that shorten it and make it more powerful in the next section. First a brief overview: The program includes the functions isBetween and isInside that have already been discussed. The program creates a number of colored rectangles to use as buttons and also as picture components. Aside from specific data values, the code to create each rectangle is the same, so the action is encapsulated in a function, makeColoredRect . All of this is fine, and will be preserved in later versions. The present main function is long, though. It has the usual graphics starting code, draws buttons and picture elements, and then has a number of code sections prompting the user to choose a color for a picture element. Each code section has a long if - elif - else test to see which button was clicked, and sets the color of the picture element appropriately. '''Make a choice of colors via mouse clicks in Rectangles -- A demonstration of Boolean operators and Boolean functions.''' from graphics import * def isBetween ( x , end1 , end2 ): '''Return True if x is between the ends or equal to either. The ends do not need to be in increasing order.''' return end1 <= x <= end2 or end2 <= x <= end1 def isInside ( point , rect ): '''Return True if the point is inside the Rectangle rect.''' pt1 = rect . getP1 () pt2 = rect . getP2 () return isBetween ( point . getX (), pt1 . getX (), pt2 . getX ()) and \ isBetween ( point . getY (), pt1 . getY (), pt2 . getY ()) def makeColoredRect ( corner , width , height , color , win ): ''' Return a Rectangle drawn in win with the upper left corner and color specified.''' corner2 = corner . clone () corner2 . move ( width , - height ) rect = Rectangle ( corner , corner2 ) rect . setFill ( color ) rect . draw ( win ) return rect def main (): win = GraphWin ( 'pick Colors' , 400 , 400 ) win . yUp () # right side up coordinates redButton = makeColoredRect ( Point ( 310 , 350 ), 80 , 30 , 'red' , win ) yellowButton = makeColoredRect ( Point ( 310 , 310 ), 80 , 30 , 'yellow' , win ) blueButton = makeColoredRect ( Point ( 310 , 270 ), 80 , 30 , 'blue' , win ) house = makeColoredRect ( Point ( 60 , 200 ), 180 , 150 , 'gray' , win ) door = makeColoredRect ( Point ( 90 , 150 ), 40 , 100 , 'white' , win ) roof = Polygon ( Point ( 50 , 200 ), Point ( 250 , 200 ), Point ( 150 , 300 )) roof . setFill ( 'black' ) roof . draw ( win ) msg = Text ( Point ( win . getWidth () / 2 , 375 ), 'Click to choose a house color.' ) msg . draw ( win ) pt = win . getMouse () if isInside ( pt , redButton ): color = 'red' elif isInside ( pt , yellowButton ): color = 'yellow' elif isInside ( pt , blueButton ): color = 'blue' else : color = 'white' house . setFill ( color ) msg . setText ( 'Click to choose a door color.' ) pt = win . getMouse () if isInside ( pt , redButton ): color = 'red' elif isInside ( pt , yellowButton ): color = 'yellow' elif isInside ( pt , blueButton ): color = 'blue' else : color = 'white' door . setFill ( color ) win . promptClose ( msg ) main () The only further new feature used is in the long return statement in isInside . return isBetween ( point . getX (), pt1 . getX (), pt2 . getX ()) and \ isBetween ( point . getY (), pt1 . getY (), pt2 . getY ()) Recall that Python is smart enough to realize that a statement continues to the next line if there is an unmatched pair of parentheses or brackets. Above is another situation with a long statement, but there are no unmatched parentheses on a line. For readability it is best not to make an enormous long line that would run off your screen or paper. Continuing to the next line is recommended. You can make the final character on a line be a backslash ( '\\' ) to indicate the statement continues on the next line. This is not particularly neat, but it is a rather rare situation. Most statements fit neatly on one line, and the creator of Python decided it was best to make the syntax simple in the most common situation. (Many other languages require a special statement terminator symbol like ‘;’ and pay no attention to newlines). Extra parentheses here would not hurt, so an alternative would be return ( isBetween ( point . getX (), pt1 . getX (), pt2 . getX ()) and isBetween ( point . getY (), pt1 . getY (), pt2 . getY ()) ) The chooseButton1.py program is long partly because of repeated code. The next section gives another version involving lists. 3.1.7.1. Congress Exercise ¶ A person is eligible to be a US Senator who is at least 30 years old and has been a US citizen for at least 9 years. Write an initial version of a program congress.py to obtain age and length of citizenship from the user and print out if a person is eligible to be a Senator or not. A person is eligible to be a US Representative who is at least 25 years old and has been a US citizen for at least 7 years. Elaborate your program congress.py so it obtains age and length of citizenship and prints out just the one of the following three statements that is accurate: You are eligible for both the House and Senate. You eligible only for the House. You are ineligible for Congress. 3.1.8. More String Methods ¶ Here are a few more string methods useful in the next exercises, assuming the methods are applied to a string s : s .startswith( pre ) returns True if string s starts with string pre : Both '-123'.startswith('-') and 'downstairs'.startswith('down') are True , but '1 - 2 - 3'.startswith('-') is False . s .endswith( suffix ) returns True if string s ends with string suffix : Both 'whoever'.endswith('ever') and 'downstairs'.endswith('airs') are True , but '1 - 2 - 3'.endswith('-') is False . s .replace( sub , replacement , count ) returns a new string with up to the first count occurrences of string sub replaced by replacement . The replacement can be the empty string to delete sub . For example: s = '-123' t = s . replace ( '-' , '' , 1 ) # t equals '123' t = t . replace ( '-' , '' , 1 ) # t is still equal to '123' u = '.2.3.4.' v = u . replace ( '.' , '' , 2 ) # v equals '23.4.' w = u . replace ( '.' , ' dot ' , 5 ) # w equals '2 dot 3 dot 4 dot ' 3.1.8.1. Article Start Exercise ¶ In library alphabetizing, if the initial word is an article (“The”, “A”, “An”), then it is ignored when ordering entries. Write a program completing this function, and then testing it: def startsWithArticle ( title ): '''Return True if the first word of title is "The", "A" or "An".''' Be careful, if the title starts with “There”, it does not start with an article. What should you be testing for? 3.1.8.2. Is Number String Exercise ¶ ** In the later Safe Number Input Exercise , it will be important to know if a string can be converted to the desired type of number. Explore that here. Save example isNumberStringStub.py as isNumberString.py and complete it. It contains headings and documentation strings for the functions in both parts of this exercise. A legal whole number string consists entirely of digits. Luckily strings have an isdigit method, which is true when a nonempty string consists entirely of digits, so '2397'.isdigit() returns True , and '23a'.isdigit() returns False , exactly corresponding to the situations when the string represents a whole number! In both parts be sure to test carefully. Not only confirm that all appropriate strings return True . Also be sure to test that you return False for all sorts of bad strings. Recognizing an integer string is more involved, since it can start with a minus sign (or not). Hence the isdigit method is not enough by itself. This part is the most straightforward if you have worked on the sections String Indices and String Slices . An alternate approach works if you use the count method from Object Orientation , and some methods from this section. Complete the function isIntStr . Complete the function isDecimalStr , which introduces the possibility of a decimal point (though a decimal point is not required). The string methods mentioned in the previous part remain useful. [1] This is an improvement that is new in Python 3. [2] “In this case do ___; otherwise”, “if ___, then”, “when ___ is true, then”, “___ depends on whether”, [3] If you divide an even number by 2, what is the remainder? Use this idea in your if condition. [4] 4 tests to distinguish the 5 cases, as in the previous version [5] Once again, you are calculating and returning a Boolean result. You do not need an if - else statement. Table Of Contents 3.1. If Statements 3.1.1. Simple Conditions 3.1.2. Simple if Statements 3.1.3. if - else Statements 3.1.4. More Conditional Expressions 3.1.4.1. Graduate Exercise 3.1.4.2. Head or Tails Exercise 3.1.4.3. Strange Function Exercise 3.1.5. Multiple Tests and if - elif Statements 3.1.5.1. Sign Exercise 3.1.5.2. Grade Exercise 3.1.5.3. Wages Exercise 3.1.6. Nesting Control-Flow Statements 3.1.6.1. Short String Exercise 3.1.6.2. Even Print Exercise 3.1.6.3. Even List Exercise 3.1.6.4. Unique List Exercise 3.1.7. Compound Boolean Expressions 3.1.7.1. Congress Exercise 3.1.8. More String Methods 3.1.8.1. Article Start Exercise 3.1.8.2. Is Number String Exercise Previous topic 3. More On Flow of Control Next topic 3.2. Loops and Tuples This Page Show Source Quick search Enter search terms or a module, class or function name. Navigation index next | previous | Hands-on Python Tutorial » 3. More On Flow of Control » © Copyright 2019, Dr. Andrew N. Harrington. Last updated on Jan 05, 2020. Created using Sphinx 1.3.1+. | 2026-01-13T09:30:35 |
https://aws.amazon.com/de/products/networking/ | Netzwerke und Inhaltsbereitstellung in AWS – Amazon Web Services Überspringen zum Hauptinhalt Filter: Alle English Kontaktieren Sie uns AWS Marketplace Support Mein Konto Suche Filter: Alle Bei der Konsole anmelden Konto erstellen Netzwerk und Bereitstellung von Inhalten Übersicht Lösungsbereiche Partner Produkte › AWS Networking und Content Delivery AWS Networking und Content Delivery Alle Workloads über ein sicheres und zuverlässiges globales Netzwerk ausführen Übersicht Holen Sie sich mit AWS das breiteste Angebot an Netzwerk- und Inhaltsbereitstellungs-Services der Welt. Führen Sie Anwendungen mit extremer Zuverlässigkeit, Sicherheit und Leistung in der Cloud aus. Abspielen Vorteile Höchstes Sicherheitsniveau Erfüllen Sie die strengsten Sicherheitsanforderungen der Welt mit den AWS-Networking-Funktionen. Stellen Sie die Vertraulichkeit, Integrität und Verfügbarkeit Ihrer Daten durch eine rund um die Uhr Überwachung der Infrastruktur sicher. Höchste Netzwerkverfügbarkeit Verwenden Sie das AWS-Region/Availability-Zone-(AZ)-Modell, um die höchste Verfügbarkeit für Ihre geschäftskritischen Arbeitslasten zu gewährleisten. Branchenanalysten empfehlen das AZ-Modell für die Ausführung von Unternehmensanwendungen, die eine hohe Verfügbarkeit erfordern. Gleichbleibend hohe Leistung Führen Sie Ihre Workloads mit dem Cloud-Netzwerk mit dem höchsten Durchsatz und der niedrigsten Latenz aus. Verwenden Sie das AWS-Netzwerk, um Ihren Kunden schnellere und reaktionsschnellere Anwendungen zur Verfügung zu stellen. Umfassendste, globale Abdeckung Stellen Sie Anwendungen und Inhalte überall auf der Welt über ein spezielles Netzwerk bereit. AWS bietet von allen Anbietern die größte globale Infrastrukturpräsenz. Maximieren Sie die Effizienz und senken Sie die Kosten durch die Migration zu AWS Das Analystenunternehmen Enterprise Strategy Group hat bestätigt, dass Unternehmen durch die Migration zu AWS die Netzwerk-, Rechen- und Speicherkosten um bis zu 66% reduziert haben. Bericht lesen AWS-Netzwerk- und Inhaltsbereitstellungs-Services Netzwerk-Grundlagen Anpassen und Steuern Ihrer Netzwerkumgebung mit Amazon Virtual Private Cloud (VPC) Weitere Informationen AWS Transit Gateway Ihr Netzwerk mit VPCs und On-Premises-Netzwerken vereinfachen, die mit einem einzigen Gateway verbunden sind Weitere Informationen AWS PrivateLink Private Verbindung zwischen VPCs und AWS- oder On-Premises-Services einrichten Weitere Informationen Anwendungsvernetzung Amazon VPC Lattice Konnektivität zwischen den Services, die Sicherheit und die Überwachung vereinfachen Weitere Informationen AWS AppMesh Container und Microservices mit Netzwerken auf Anwendungsebene verbinden Weitere Informationen AWS API Gateway APIs in jeder Dimension erstellen, verwalten und sichern Weitere Informationen AWS Cloud Map Die aktuellsten Service-Ressourcen entdecken und darauf zugreifen Weitere Informationen Elastische Lastenverteilung Netzwerkdatenverkehr zur besseren Skalierbarkeit von Anwendungen verteilen Weitere Informationen Edge-Vernetzung Amazon CloudFront Daten, Videos, Anwendungen und APIs mit hohen Übertragungsgeschwindigkeiten und geringen Latenzzeiten bereitstellen Weitere Informationen Amazon Route 53 Endbenutzer zu Internetanwendungen mit einem kostengünstigen verwalteten Domain Name System (DNS) leiten. Weitere Informationen AWS Global Accelerator Den Benutzerverkehr zu Ihrer Anwendung optimieren Weitere Informationen Hybride Konnektivität AWS Direct Connect Stellen Sie eine private, dedizierte AWS-Verbindung zu Ihrem Rechenzentrum, Ihrem Büro oder Ihrer Co-Location-Umgebung her. Weitere Informationen AWS Site-to-Site VPN Eine verschlüsselte Netzwerkverbindung zu Ihren Amazon VPCs oder AWS Transit Gateways erstellen Weitere Informationen AWS Client VPN Ihre Remote-Mitarbeiter mit AWS oder On-Premises mit einem Virtual Private Network (VPN) verbinden Weitere Informationen AWS-Cloud-WAN Einfaches Erstellen, Verwalten und Überwachen globaler Weitverkehrsnetze Weitere Informationen Netzwerksicherheit AWS Shield AWS-Anwendungen vor verteilten Distributed Denial of Service (DDoS)-Angriffen schützen Weitere Informationen AWS WAF Ihre Webanwendungen vor gängigen Web-Exploits schützen Weitere Informationen AWS Network Firewall Die Netzwerksicherheit für Ihre Amazon VPCs bereitstellen Weitere Informationen AWS Firewall Manager Firewall-Regeln zentral konfigurieren und verwalten Weitere Informationen Lösungsbereiche Bauen Sie starke Netzwerkgrundlagen auf Behalten Sie Ihren komplexen Netzwerkverkehr mit AWS Network Foundations im Auge. Vereinfachen Sie den Ressourcen-Start, das Netzwerkmanagement, die Verbindung und die Überwachung des Datenverkehrs mit Services wie Amazon VPC, AWS Transit Gateway, AWS PrivateLink, Amazon VPC Flow Logs und VPC Traffic Mirroring. Weitere Informationen Hybride Infrastruktur verbinden Verknüpfen Sie Ihre in AWS ausgeführten Services und Ihre Räumlichkeiten mit einer sicheren und effizienten Netzwerkkommunikation. Die hybriden Konnektivitätslösungen von AWS bieten eine Reihe von Verbindungstypen und Services für den Aufbau hybrider Netzwerke, die nahtlos von der Cloud über lokale Standorte bis hin zum Netzwerkrand funktionieren. Weitere Informationen Stellen Sie schnellere, sicherere Anwendungen mit Edge-Netzwerken bereit Stellen Sie Benutzeranwendungen und Daten mithilfe von Edge-Netzwerken mit erhöhter Sicherheit und niedriger Latenz bereit. Verlagern Sie den Datenverkehr vom Internet in das sicherste und leistungsfähigste Cloud-Netzwerk der Welt. Amazon CloudFront, AWS Global Accelerator und Amazon Route 53 stellen Ihre Daten mit geringer Latenz und hohem Durchsatz sicher bereit. Weitere Informationen Optimieren Sie das Anwendungsnetzwerk Vereinfachen und verbessern Sie die Netzwerkarchitektur Ihrer Anwendung mit AWS-Anwendungsnetzwerken. Elastic Load Balancing (ELB), AWS Global Accelerator (AGA) und AWS App Mesh arbeiten zusammen, um verbesserte Sicherheit, Verfügbarkeit, Leistung und optimierte Überwachungsfunktionen zu bieten. Weitere Informationen Ausgewählte Lösungen in AWS Entdecken Sie speziell entwickelte Services, AWS-Lösungen, Partnerlösungen und Anleitungen, mit denen Sie Ihre geschäftlichen und technischen Anwendungsfälle schnell lösen können. Netzwerk-Orchestrierung für AWS Transit Gateway Automatisieren Sie den Prozess der Einrichtung und Verwaltung von Transitnetzwerken in verteilten AWS-Umgebungen. Visualisieren und überwachen Sie Ihr globales Netzwerk von einem einzigen Dashboard in der AWS-Konsole aus, sodass Sie (Transit-)Netzwerkänderungen kontrollieren, prüfen und genehmigen können. Erste Schritte Firewall-Automatisierung für Netzwerkdatenverkehr in AWS Stellen Sie eine Lösung bereit, die den Prozess der Bereitstellung einer zentralen AWS Network Firewall automatisiert, um den Datenverkehr zwischen Ihren Amazon VPCs zu prüfen. Erste Schritte AWS Summit Hamburg 2025: Erleben Sie heute die Cloud von morgen Erleben Sie einen Tag voller praktischer Lern- und Networking-Möglichkeiten mit Branchenvorreitern und Cloud-Experten, die Ihr Unternehmen auf dem Weg in die Cloud voranbringen werden. Jetzt registrieren AWS-Konto erstellen Lernen Was ist AWS? Was ist „Cloud Computing“? Was ist „Agentenbasierte KI“? Hub für Cloud-Computing-Konzepte AWS Cloud Sicherheit Neuerungen Blogs Pressemitteilungen Ressourcen Erste Schritte Training AWS Trust Center AWS-Lösungsportfolio Architekturzentrum Häufig gestellte Fragen zu Produkt und Technik Berichte von Analysten AWS-Partner Entwickler Builder Center SDKs und Tools .NET auf AWS Python in AWS Java in AWS PHP in AWS JavaScript in AWS Hilfe Kontaktieren Sie uns Support-Ticket aufgeben AWS re:Post Wissenscenter AWS Support – Überblick Erhalten Sie Hilfe von Experten Barrierefreiheit bei AWS Rechtlicher Hinweis English Zurück zum Seitenanfang Amazon.com setzt als Arbeitgeber auf Gleichberechtigung: Minderheiten/Frauen/Menschen mit Behinderungen/Veteranen/Geschlechtsidentität/sexuelle Orientierung/Alter. x facebook linkedin instagram twitch youtube podcasts email Datenschutz Allgemeine Geschäftsbedingungen Cookie-Einstellungen © 2026, Amazon Web Services, Inc. bzw. Tochtergesellschaften des Unternehmens. Alle Rechte vorbehalten. | 2026-01-13T09:30:35 |
https://docs.aws.amazon.com/es_es/AmazonCloudFront/latest/DeveloperGuide/lambda-examples.html#lambda-examples-redirecting-examples | Funciones de ejemplo de Lambda@Edge - Amazon CloudFront Funciones de ejemplo de Lambda@Edge - Amazon CloudFront Documentación Amazon CloudFront Guía para desarrolladores Ejemplos generales Generación de respuestas: ejemplos Cadenas de consulta: ejemplos Personalización de contenido por encabezados de tipo de dispositivo o país: ejemplos Selección de origen dinámico basada en contenido: ejemplos Actualización de estados de error: ejemplos Acceso al cuerpo de la solicitud: ejemplos Funciones de ejemplo de Lambda@Edge Consulte los ejemplos siguientes para usar funciones de Lambda con Amazon CloudFront. nota Si elige el tiempo de ejecución Node.js 18 o una versión posterior para la función Lambda@Edge, se creará automáticamente un archivo index.mjs . Para usar los siguientes ejemplos de código, cambie el nombre del archivo index.mjs a index.js . Temas Ejemplos generales Generación de respuestas: ejemplos Cadenas de consulta: ejemplos Personalización de contenido por encabezados de tipo de dispositivo o país: ejemplos Selección de origen dinámico basada en contenido: ejemplos Actualización de estados de error: ejemplos Acceso al cuerpo de la solicitud: ejemplos Ejemplos generales Los ejemplos siguientes muestran formas habituales de usar Lambda@Edge en CloudFront. Temas Ejemplo: prueba A/B Ejemplo: Sobrescritura de un encabezado de respuesta Ejemplo: prueba A/B Puede utilizar el siguiente ejemplo para probar dos versiones diferentes de una imagen sin crear redirecciones ni cambiar la dirección URL. En este ejemplo se leen las cookies de la solicitud del lector y se modifica la URL de la solicitud en consecuencia. Si el espectador no envía una cookie con uno de los valores esperados, el ejemplo asigna aleatoriamente al espectador una de las URL. 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; } 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; } } 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" ''' experimentUri = "" 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 Ejemplo: Sobrescritura de un encabezado de respuesta En el ejemplo siguiente, se muestra cómo cambiar el valor de un encabezado de respuesta según el valor de otro encabezado. Node.js export const handler = async (event) => { 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()] = [ { key: headerNameDst, value: headers[headerNameSrc.toLowerCase()][0].value, }]; console.log(`Response header "$ { headerNameDst}" was set to ` + `"$ { headers[headerNameDst.toLowerCase()][0].value}"`); } return response; }; Python import json def lambda_handler(event, context): response = event['Records'][0]['cf']['response'] headers = response['headers'] header_name_src = 'X-Amz-Meta-Last-Modified' header_name_dst = 'Last-Modified' if headers.get(header_name_src.lower()): headers[header_name_dst.lower()] = [ { 'key': header_name_dst, 'value': headers[header_name_src.lower()][0]['value'] }] print(f'Response header " { header_name_dst}" was set to ' f'" { headers[header_name_dst.lower()][0]["value"]}"') return response Generación de respuestas: ejemplos En los ejemplos siguientes se muestra cómo puede usar Lambda@Edge para generar respuestas. Temas Ejemplo: Envío de contenido estático (respuesta generada) Ejemplo: Generación de un redireccionamiento HTTP (respuesta generada) Ejemplo: Envío de contenido estático (respuesta generada) En el siguiente ejemplo se muestra cómo utilizar una función de Lambda para enviar contenido de sitio web estático, lo que reduce la carga en el servidor de origen y la latencia total. nota Puede generar respuestas HTTP para los eventos de solicitud del espectador y al origen. Para obtener más información, consulte Generación de respuestas HTTP en los desencadenadores de solicitud . También puede sustituir o quitar el cuerpo de la respuesta HTTP en eventos de respuesta de origen. Para obtener más información, consulte Actualización de respuestas HTTP en desencadenadores de respuesta de origen . 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' }] }, 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 } return response Ejemplo: Generación de un redireccionamiento HTTP (respuesta generada) En el siguiente ejemplo se muestra cómo generar una redirección HTTP. nota Puede generar respuestas HTTP para los eventos de solicitud del espectador y al origen. Para obtener más información, consulte Generación de respuestas HTTP en los desencadenadores de solicitud . 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. response = { 'status': '302', 'statusDescription': 'Found', 'headers': { 'location': [ { 'key': 'Location', 'value': 'https://docs.aws.amazon.com/lambda/latest/dg/lambda-edge.html' }] } } return response Cadenas de consulta: ejemplos En los ejemplos siguientes se muestran formas de usar Lambda@Edge con cadenas de consulta. Temas Ejemplo: Adición de un encabezado en función de un parámetro de la cadena de consulta Ejemplo: Normalización de parámetros de cadenas de consulta para mejorar la tasa de aciertos de caché Ejemplo: Redireccionamiento de los usuarios no autenticados a una página de inicio de sesión Ejemplo: Adición de un encabezado en función de un parámetro de la cadena de consulta El siguiente ejemplo muestra cómo obtener el par clave-valor de un parámetro de la cadena de consulta y, a continuación, añadir un encabezado en función de dichos valores. 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. * 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 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'] # Update request querystring request['querystring'] = urlencode(params) return request Ejemplo: Normalización de parámetros de cadenas de consulta para mejorar la tasa de aciertos de caché El siguiente ejemplo muestra cómo mejorar la tasa de acceso a la caché haciendo los siguientes cambios en las cadenas de consulta antes de que CloudFront reenvíe las solicitudes a su origen: Alfabetizar los pares de clave-valor por el nombre del parámetro. Cambiar a minúsculas el modelo de mayúsculas y minúsculas de los pares de clave-valor. Para obtener más información, consulte Almacenamiento en caché de contenido en función de parámetros de cadenas de consulta . 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 */ 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 request['querystring'] = urlencode(sortedParams) return request Ejemplo: Redireccionamiento de los usuarios no autenticados a una página de inicio de sesión El siguiente ejemplo muestra cómo redirigir a los usuarios una página de inicio de sesión si no ha introducido sus credenciales. 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; } /* 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 params. ''' # Check for session-id in cookie, if present, then proceed with request parsedCookies = parseCookies(headers) 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 Personalización de contenido por encabezados de tipo de dispositivo o país: ejemplos En los ejemplos siguientes se muestra cómo puede usar Lambda@Edge para personalizar el comportamiento en función de la ubicación o el tipo de dispositivo que usa el lector. Temas Ejemplo: Redireccionamiento de solicitudes de espectadores a una URL específica de un país Ejemplo: Envío de distintas versiones de un objeto en función del dispositivo Ejemplo: Redireccionamiento de solicitudes de espectadores a una URL específica de un país El siguiente ejemplo muestra cómo generar una respuesta de redireccionamiento HTTP con una URL específica del país y devolver la respuesta al espectador. Esto resulta útil cuando se quiere proporcionar respuestas específicas del país. Por ejemplo: Si tiene subdominios específicos de un país, como us.ejemplo.com y tw.ejemplo.com, puede generar una respuesta de redireccionamiento cuando un espectador solicite ejemplo.com. Si está haciendo streaming de video, pero no tiene derechos para transmitir el contenido en un país determinado, puede redirigir a los usuarios de dicho país a una página en la que se explica por qué no pueden ver el video. Tenga en cuenta lo siguiente: Debe configurar la distribución para almacenar en la caché en función del encabezado CloudFront-Viewer-Country . Para obtener más información, consulte Caché en función de encabezados de solicitud seleccionados . CloudFront agrega el encabezado CloudFront-Viewer-Country después del evento de solicitud del lector. Para utilizar este ejemplo, debe crear un activador para el evento de solicitud al origen. 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 = { 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', 'statusDescription': 'Found', 'headers': { 'location': [ { 'key': 'Location', 'value': url }] } } return response Ejemplo: Envío de distintas versiones de un objeto en función del dispositivo El siguiente ejemplo muestra cómo ofrecer distintas versiones de un objeto en función del tipo de dispositivo que el usuario está utilizando; por ejemplo, un dispositivo móvil o una tablet. Tenga en cuenta lo siguiente: Debe configurar la distribución para almacenar en la caché en función de los encabezados CloudFront-Is-*-Viewer . Para obtener más información, consulte Caché en función de encabezados de solicitud seleccionados . CloudFront agrega los encabezados CloudFront-Is-*-Viewer después del evento de solicitud del lector. Para utilizar este ejemplo, debe crear un activador para el evento de solicitud al origen. 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 * 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. ''' desktopPath = '/desktop'; mobilePath = '/mobile'; tabletPath = '/tablet'; smarttvPath = '/smarttv'; 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 Selección de origen dinámico basada en contenido: ejemplos En los ejemplos siguientes se muestra cómo puede usar Lambda@Edge para el direccionamiento a diferentes orígenes en función de la información de la solicitud. Temas Ejemplo: Uso de un desencadenador de solicitud de origen para cambiar desde un origen personalizado a un origen de Amazon S3 Ejemplo: Uso de un desencadenador de solicitud de origen para cambiar la región de origen de Amazon S3 Ejemplo: Uso de un desencadenador de solicitud de origen para cambiar desde un origen de Amazon S3 a un origen personalizado Ejemplo: Uso de un desencadenador de solicitud al origen para transferir gradualmente el tráfico desde un bucket de Amazon S3 a otro Ejemplo: Uso de un desencadenador de solicitud de origen para cambiar el nombre del dominio de origen en función del encabezado de país Ejemplo: Uso de un desencadenador de solicitud de origen para cambiar desde un origen personalizado a un origen de Amazon S3 Esta función demuestra cómo utilizar un desencadenador de solicitud al origen para cambiar desde un origen personalizado a un origen de Amazon S3 desde el que recuperar el contenido, en función de las propiedades de la solicitud. 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: 'origin-access-identity', path: '', customHeaders: { } } }; request.headers['host'] = [ { key: 'host', value: s3DomainName}]; } } 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 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': 'origin-access-identity', 'path': '', 'customHeaders': { } } } request['headers']['host'] = [ { 'key': 'host', 'value': s3DomainName}] return request Ejemplo: Uso de un desencadenador de solicitud de origen para cambiar la región de origen de Amazon S3 Esta función demuestra cómo utilizar un desencadenador de solicitud al origen para cambiar el origen de Amazon S3 desde el que se recupera el contenido, en función de las propiedades de la solicitud. En este ejemplo, utilizamos el valor del encabezado CloudFront-Viewer-Country para actualizar el nombre de dominio del bucket de S3 por un bucket de una región que está más cerca del lector. Esto puede resultar útil de varias maneras: Reduce las latencias cuando la región especificada está más cerca del país del lector. Proporciona soberanía de los datos, al asegurarse de que los datos se distribuyen desde un origen que está en el país del que provino la solicitud. Para utilizar este ejemplo, debe hacer lo siguiente: Configure la distribución para almacenar en la caché en función del encabezado CloudFront-Viewer-Country . Para obtener más información, consulte Caché en función de encabezados de solicitud seleccionados . Crear un disparador para esta función en el evento de solicitud al origen. CloudFront agrega el encabezado CloudFront-Viewer-Country después del evento de solicitud del lector; por lo tanto, para utilizar este ejemplo, debe asegurarse de que la función ejecuta una solicitud de origen. nota El siguiente código de ejemplo usa la misma identidad de acceso de origen (OAI) para todos los buckets de S3 que usa para el origen. Para obtener más información, consulte Identidad de acceso de origen . 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 * 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); }; Python 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: 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: ''' 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 Ejemplo: Uso de un desencadenador de solicitud de origen para cambiar desde un origen de Amazon S3 a un origen personalizado Esta función demuestra cómo utilizar un disparador de solicitud al origen para cambiar el origen personalizado desde el que se recupera el contenido, en función de las propiedades de la solicitud. 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: { 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': { } } } request['headers']['host'] = [ { 'key': 'host', 'value': 'www.example.com'}] return request Ejemplo: Uso de un desencadenador de solicitud al origen para transferir gradualmente el tráfico desde un bucket de Amazon S3 a otro Esta función demuestra cómo transferir gradualmente el tráfico desde un bucket de Amazon S3 a otro de forma controlada. 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}]; } 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 Ejemplo: Uso de un desencadenador de solicitud de origen para cambiar el nombre del dominio de origen en función del encabezado de país Esta función demuestra cómo cambiar el nombre del dominio de origen en función del encabezado CloudFront-Viewer-Country , de forma que el contenido se distribuya desde un origen más cercano al país del lector. La implementación de esta funcionalidad para su distribución puede tener ventajas como las siguientes: Reducir las latencias cuando la región especificada está más cerca del país del lector Proporcionar soberanía de los datos, al asegurarse de que los datos se distribuyen desde un origen que está en el país del que provino la solicitud Tenga en cuenta que para habilitar esta funcionalidad, debe configurar su distribución para almacenar en la caché en función del encabezado CloudFront-Viewer-Country . Para obtener más información, consulte Caché en función de encabezados de solicitud seleccionados . 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 request['headers']['host'] = [ { 'key': 'host', 'value': domainName}] return request Actualización de estados de error: ejemplos En los ejemplos siguientes se proporciona orientación acerca de cómo puede usar Lambda@Edge para cambiar el estado de error que se devuelve a los usuarios. Temas Ejemplo: Uso de un desencadenador de respuesta de origen para actualizar el código de estado de error a 200 Ejemplo: Uso de un desencadenador de respuesta de origen para actualizar el código de estado de error a 302 Ejemplo: Uso de un desencadenador de respuesta de origen para actualizar el código de estado de error a 200 Esta función demuestra cómo actualizar el estado de la respuesta a 200 y generar un cuerpo con contenido estático para devolverlo al espectador en la siguiente situación: La función se desencadena en una respuesta del origen. El estado de la respuesta del servidor de origen es un código de estado de error (4xx o 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'; } callback(null, response); }; Python 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 Ejemplo: Uso de un desencadenador de respuesta de origen para actualizar el código de estado de error a 302 Esta función demuestra cómo actualizar el código de estado HTTP a 302 para la redirección a otra ruta (comportamiento de la caché) en la que se ha configurado un origen diferente. Tenga en cuenta lo siguiente: La función se desencadena en una respuesta del origen. El estado de la respuesta del servidor de origen es un código de estado de error (4xx o 5xx). Node.js 'use strict'; exports.handler = (event, context, callback) => { const response = event.Records[0].cf.response; const 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 (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 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 Acceso al cuerpo de la solicitud: ejemplos En los ejemplos siguientes se muestra cómo puede usar Lambda@Edge para trabajar con las solicitudes POST. nota Para utilizar estos ejemplos, debe habilitar la opción incluir cuerpo en la asociación de funciones Lambda de la distribución. No está habilitada de forma predeterminada. Para habilitar esta configuración en la consola de CloudFront, seleccione la casilla de verificación Incluir cuerpo en la Asociación de funciones Lambda . Para habilitar esta configuración en la API de CloudFront o con CloudFormation, establezca el campo IncludeBody en true en LambdaFunctionAssociation . Temas Ejemplo: Uso de un desencadenador de solicitud para leer un formulario HTML Ejemplo: Uso de un desencadenador de solicitud para modificar un formulario HTML Ejemplo: Uso de un desencadenador de solicitud para leer un formulario HTML Esta función ilustra cómo puede procesar el cuerpo de una solicitud POST generada por un formulario HTML (formulario web), como por ejemplo un formulario tipo "póngase en contacto con nosotros". Por ejemplo, es posible que tenga un formulario HTML como el siguiente: <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> Para la función de ejemplo que se indica a continuación, la función se debe desencadenar en una solicitud al origen o del lector de CloudFront. 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 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 Ejemplo: Uso de un desencadenador de solicitud para modificar un formulario HTML Esta función ilustra cómo puede modificar el cuerpo de una solicitud POST generada por un formulario HTML (formulario web). La función se activa en una solicitud al origen o del lector de CloudFront. 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. * * 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'] | 2026-01-13T09:30:35 |
https://docs.aws.amazon.com/id_id/lambda/latest/dg/with-s3-tutorial.html#with-s3-tutorial-create-execution-role | Tutorial: Menggunakan pemicu Amazon S3 untuk membuat gambar thumbnail - AWS Lambda Tutorial: Menggunakan pemicu Amazon S3 untuk membuat gambar thumbnail - AWS Lambda Dokumentasi AWS Lambda Panduan Developerr Prasyarat Buat dua ember Amazon S3 Unggah gambar uji ke bucket sumber Anda Membuat kebijakan izin Membuat peran eksekusi Buat paket penerapan fungsi Buat fungsi Lambda Konfigurasikan Amazon S3 untuk menjalankan fungsi Uji fungsi Lambda Anda dengan acara dummy Uji fungsi Anda menggunakan pemicu Amazon S3 Bersihkan sumber daya Anda Terjemahan disediakan oleh mesin penerjemah. Jika konten terjemahan yang diberikan bertentangan dengan versi bahasa Inggris aslinya, utamakan versi bahasa Inggris. Tutorial: Menggunakan pemicu Amazon S3 untuk membuat gambar thumbnail Dalam tutorial ini, Anda membuat dan mengonfigurasi fungsi Lambda yang mengubah ukuran gambar yang ditambahkan ke bucket Amazon Simple Storage Service (Amazon S3). Saat Anda menambahkan file gambar ke bucket, Amazon S3 akan memanggil fungsi Lambda Anda. Fungsi tersebut kemudian membuat versi thumbnail gambar dan mengeluarkannya ke bucket Amazon S3 yang berbeda. Untuk menyelesaikan tutorial ini, Anda melakukan langkah-langkah berikut: Buat bucket Amazon S3 sumber dan tujuan dan unggah gambar sampel. Buat fungsi Lambda yang mengubah ukuran gambar dan mengeluarkan thumbnail ke bucket Amazon S3. Konfigurasikan pemicu Lambda yang memanggil fungsi Anda saat objek diunggah ke bucket sumber Anda. Uji fungsi Anda, pertama dengan acara dummy, lalu dengan mengunggah gambar ke bucket sumber Anda. Dengan menyelesaikan langkah-langkah ini, Anda akan mempelajari cara menggunakan Lambda untuk menjalankan tugas pemrosesan file pada objek yang ditambahkan ke bucket Amazon S3. Anda dapat menyelesaikan tutorial ini menggunakan AWS Command Line Interface (AWS CLI) atau Konsol Manajemen AWS. Jika Anda mencari contoh sederhana untuk mempelajari cara mengonfigurasi pemicu Amazon S3 untuk Lambda, Anda dapat mencoba Tutorial: Menggunakan pemicu Amazon S3 untuk menjalankan fungsi Lambda. Topik Prasyarat Buat dua ember Amazon S3 Unggah gambar uji ke bucket sumber Anda Membuat kebijakan izin Membuat peran eksekusi Buat paket penerapan fungsi Buat fungsi Lambda Konfigurasikan Amazon S3 untuk menjalankan fungsi Uji fungsi Lambda Anda dengan acara dummy Uji fungsi Anda menggunakan pemicu Amazon S3 Bersihkan sumber daya Anda Prasyarat Jika Anda ingin menggunakan AWS CLI untuk menyelesaikan tutorial, instal versi terbaru dari AWS Command Line Interface . Untuk kode fungsi Lambda Anda, Anda dapat menggunakan Python atau Node.js. Instal alat dukungan bahasa dan manajer paket untuk bahasa yang ingin Anda gunakan. Jika Anda belum menginstal AWS Command Line Interface, ikuti langkah-langkah di Menginstal atau memperbarui versi terbaru AWS CLI untuk menginstalnya . Tutorial ini membutuhkan terminal baris perintah atau shell untuk menjalankan perintah. Di Linux dan macOS, gunakan shell dan manajer paket pilihan Anda. catatan Di Windows, beberapa perintah Bash CLI yang biasa Anda gunakan dengan Lambda ( zip seperti) tidak didukung oleh terminal bawaan sistem operasi. Untuk mendapatkan versi terintegrasi Windows dari Ubuntu dan Bash, instal Windows Subsystem untuk Linux. Buat dua ember Amazon S3 Pertama buat dua ember Amazon S3. Bucket pertama adalah bucket sumber tempat Anda akan mengunggah gambar Anda. Bucket kedua digunakan oleh Lambda untuk menyimpan thumbnail yang diubah ukurannya saat Anda menjalankan fungsi. Konsol Manajemen AWS Untuk membuat bucket Amazon S3 (konsol) Buka konsol Amazon S3 dan pilih halaman Bucket tujuan umum . Pilih yang Wilayah AWS paling dekat dengan lokasi geografis Anda. Anda dapat mengubah wilayah Anda menggunakan daftar drop-down di bagian atas layar. Kemudian dalam tutorial, Anda harus membuat fungsi Lambda Anda di Wilayah yang sama. Pilih Buat bucket . Pada Konfigurasi umum , lakukan hal berikut: Untuk jenis Bucket , pastikan Tujuan umum dipilih. Untuk nama Bucket , masukkan nama unik global yang memenuhi aturan penamaan Amazon S3 Bucket . Nama bucket hanya dapat berisi huruf kecil, angka, titik (.), dan tanda hubung (-). Biarkan semua opsi lain disetel ke nilai defaultnya dan pilih Buat bucket . Ulangi langkah 1 hingga 5 untuk membuat bucket tujuan Anda. Untuk nama Bucket amzn-s3-demo-source-bucket-resized , masukkan, di amzn-s3-demo-source-bucket mana nama bucket sumber yang baru saja Anda buat. AWS CLI Untuk membuat bucket Amazon S3 ()AWS CLI Jalankan perintah CLI berikut untuk membuat bucket sumber Anda. Nama yang Anda pilih untuk bucket Anda harus unik secara global dan ikuti aturan penamaan Amazon S3 Bucket . Nama hanya dapat berisi huruf kecil, angka, titik (.), dan tanda hubung (-). Untuk region dan LocationConstraint , pilih yang paling Wilayah AWS dekat dengan lokasi geografis Anda. aws s3api create-bucket --bucket amzn-s3-demo-source-bucket --region us-east-1 \ --create-bucket-configuration LocationConstraint= us-east-1 Kemudian dalam tutorial, Anda harus membuat fungsi Lambda Anda Wilayah AWS sama dengan bucket sumber Anda, jadi catat wilayah yang Anda pilih. Jalankan perintah berikut untuk membuat bucket tujuan Anda. Untuk nama bucket, Anda harus menggunakan amzn-s3-demo-source-bucket-resized , di amzn-s3-demo-source-bucket mana nama bucket sumber yang Anda buat di langkah 1. Untuk region dan LocationConstraint , pilih yang sama dengan yang Wilayah AWS Anda gunakan untuk membuat bucket sumber Anda. aws s3api create-bucket --bucket amzn-s3-demo-source-bucket-resized --region us-east-1 \ --create-bucket-configuration LocationConstraint= us-east-1 Unggah gambar uji ke bucket sumber Anda Kemudian dalam tutorial, Anda akan menguji fungsi Lambda Anda dengan memanggilnya menggunakan atau konsol Lambda. AWS CLI Untuk mengonfirmasi bahwa fungsi Anda beroperasi dengan benar, bucket sumber Anda harus berisi gambar uji. Gambar ini dapat berupa file JPG atau PNG yang Anda pilih. Konsol Manajemen AWS Untuk mengunggah gambar uji ke bucket sumber Anda (konsol) Buka halaman Bucket konsol Amazon S3. Pilih bucket sumber yang Anda buat di langkah sebelumnya. Pilih Unggah . Pilih Tambahkan file dan gunakan pemilih file untuk memilih objek yang ingin Anda unggah. Pilih Buka , lalu pilih Unggah . AWS CLI Untuk mengunggah gambar uji ke bucket sumber Anda (AWS CLI) Dari direktori yang berisi gambar yang ingin Anda unggah, jalankan perintah CLI berikut. Ganti --bucket parameter dengan nama bucket sumber Anda. Untuk --body parameter --key dan, gunakan nama file gambar pengujian Anda. aws s3api put-object --bucket amzn-s3-demo-source-bucket --key HappyFace.jpg --body ./HappyFace.jpg Membuat kebijakan izin Langkah pertama dalam membuat fungsi Lambda Anda adalah membuat kebijakan izin. Kebijakan ini memberi fungsi Anda izin yang diperlukan untuk mengakses AWS sumber daya lain. Untuk tutorial ini, kebijakan memberikan izin baca dan tulis Lambda untuk bucket Amazon S3 dan memungkinkannya untuk menulis ke Amazon Log. CloudWatch Konsol Manajemen AWS Untuk membuat kebijakan (konsol) Buka halaman Kebijakan konsol AWS Identity and Access Management (IAM). Pilih Buat kebijakan . Pilih tab JSON , lalu tempelkan kebijakan khusus berikut ke editor JSON. { "Version":"2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "logs:PutLogEvents", "logs:CreateLogGroup", "logs:CreateLogStream" ], "Resource": "arn:aws:logs:*:*:*" }, { "Effect": "Allow", "Action": [ "s3:GetObject" ], "Resource": "arn:aws:s3:::*/*" }, { "Effect": "Allow", "Action": [ "s3:PutObject" ], "Resource": "arn:aws:s3:::*/*" } ] } Pilih Berikutnya . Di bawah Detail kebijakan , untuk nama Kebijakan , masukkan LambdaS3Policy . Pilih Buat kebijakan . AWS CLI Untuk membuat kebijakan (AWS CLI) Simpan JSON berikut dalam file bernama policy.json . { "Version":"2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "logs:PutLogEvents", "logs:CreateLogGroup", "logs:CreateLogStream" ], "Resource": "arn:aws:logs:*:*:*" }, { "Effect": "Allow", "Action": [ "s3:GetObject" ], "Resource": "arn:aws:s3:::*/*" }, { "Effect": "Allow", "Action": [ "s3:PutObject" ], "Resource": "arn:aws:s3:::*/*" } ] } Dari direktori tempat Anda menyimpan dokumen kebijakan JSON, jalankan perintah CLI berikut. aws iam create-policy --policy-name LambdaS3Policy --policy-document file://policy.json Membuat peran eksekusi Peran eksekusi adalah peran IAM yang memberikan izin fungsi Lambda untuk mengakses dan sumber daya. Layanan AWS Untuk memberikan akses baca dan tulis fungsi ke bucket Amazon S3, Anda melampirkan kebijakan izin yang Anda buat di langkah sebelumnya. Konsol Manajemen AWS Untuk membuat peran eksekusi dan melampirkan kebijakan izin Anda (konsol) Buka halaman Peran konsol (IAM). Pilih Buat peran . Untuk jenis entitas Tepercaya , pilih Layanan AWS , dan untuk kasus Penggunaan , pilih Lambda . Pilih Berikutnya . Tambahkan kebijakan izin yang Anda buat di langkah sebelumnya dengan melakukan hal berikut: Dalam kotak pencarian kebijakan, masukkan LambdaS3Policy . Dalam hasil pencarian, pilih kotak centang untuk LambdaS3Policy . Pilih Berikutnya . Di bawah Rincian peran , untuk nama Peran masuk LambdaS3Role . Pilih Buat peran . AWS CLI Untuk membuat peran eksekusi dan melampirkan kebijakan izin Anda ()AWS CLI Simpan JSON berikut dalam file bernama trust-policy.json . Kebijakan kepercayaan ini memungkinkan Lambda untuk menggunakan izin peran dengan memberikan lambda.amazonaws.com izin utama layanan untuk memanggil tindakan AWS Security Token Service ()AWS STS. AssumeRole { "Version":"2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": { "Service": "lambda.amazonaws.com" }, "Action": "sts:AssumeRole" } ] } Dari direktori tempat Anda menyimpan dokumen kebijakan kepercayaan JSON, jalankan perintah CLI berikut untuk membuat peran eksekusi. aws iam create-role --role-name LambdaS3Role --assume-role-policy-document file://trust-policy.json Untuk melampirkan kebijakan izin yang Anda buat pada langkah sebelumnya, jalankan perintah CLI berikut. Ganti Akun AWS nomor di ARN polis dengan nomor akun Anda sendiri. aws iam attach-role-policy --role-name LambdaS3Role --policy-arn arn:aws:iam:: 123456789012 :policy/LambdaS3Policy Buat paket penerapan fungsi Untuk membuat fungsi Anda, Anda membuat paket deployment yang berisi kode fungsi dan dependensinya. Untuk CreateThumbnail fungsi ini, kode fungsi Anda menggunakan pustaka terpisah untuk mengubah ukuran gambar. Ikuti instruksi untuk bahasa yang Anda pilih untuk membuat paket penyebaran yang berisi pustaka yang diperlukan. Node.js Untuk membuat paket penyebaran (Node.js) Buat direktori bernama lambda-s3 untuk kode fungsi dan dependensi Anda dan navigasikan ke dalamnya. mkdir lambda-s3 cd lambda-s3 Buat proyek Node.js baru dengan npm . Untuk menerima opsi default yang disediakan dalam pengalaman interaktif, tekan Enter . npm init Simpan kode fungsi berikut dalam file bernama index.mjs . Pastikan untuk mengganti us-east-1 dengan Wilayah AWS di mana Anda membuat ember sumber dan tujuan Anda sendiri. // dependencies import { S3Client, GetObjectCommand, PutObjectCommand } from '@aws-sdk/client-s3'; import { Readable } from 'stream'; import sharp from 'sharp'; import util from 'util'; // create S3 client const s3 = new S3Client( { region: 'us-east-1' }); // define the handler function export const handler = async (event, context) => { // Read options from the event parameter and get the source bucket console.log("Reading options from event:\n", util.inspect(event, { depth: 5})); const srcBucket = event.Records[0].s3.bucket.name; // Object key may have spaces or unicode non-ASCII characters const srcKey = decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g, " ")); const dstBucket = srcBucket + "-resized"; const dstKey = "resized-" + srcKey; // Infer the image type from the file suffix const typeMatch = srcKey.match(/\.([^.]*)$/); if (!typeMatch) { console.log("Could not determine the image type."); return; } // Check that the image type is supported const imageType = typeMatch[1].toLowerCase(); if (imageType != "jpg" && imageType != "png") { console.log(`Unsupported image type: $ { imageType}`); return; } // Get the image from the source bucket. GetObjectCommand returns a stream. try { const params = { Bucket: srcBucket, Key: srcKey }; var response = await s3.send(new GetObjectCommand(params)); var stream = response.Body; // Convert stream to buffer to pass to sharp resize function. if (stream instanceof Readable) { var content_buffer = Buffer.concat(await stream.toArray()); } else { throw new Error('Unknown object stream type'); } } catch (error) { console.log(error); return; } // set thumbnail width. Resize will set the height automatically to maintain aspect ratio. const width = 200; // Use the sharp module to resize the image and save in a buffer. try { var output_buffer = await sharp(content_buffer).resize(width).toBuffer(); } catch (error) { console.log(error); return; } // Upload the thumbnail image to the destination bucket try { const destparams = { Bucket: dstBucket, Key: dstKey, Body: output_buffer, ContentType: "image" }; const putResult = await s3.send(new PutObjectCommand(destparams)); } catch (error) { console.log(error); return; } console.log('Successfully resized ' + srcBucket + '/' + srcKey + ' and uploaded to ' + dstBucket + '/' + dstKey); }; Di lambda-s3 direktori Anda, instal perpustakaan tajam menggunakan npm. Perhatikan bahwa versi terbaru dari sharp (0.33) tidak kompatibel dengan Lambda. Instal versi 0.32.6 untuk menyelesaikan tutorial ini. npm install sharp@0.32.6 install Perintah npm membuat node_modules direktori untuk modul Anda. Setelah langkah ini, struktur direktori Anda akan terlihat seperti berikut. lambda-s3 |- index.mjs |- node_modules | |- base64js | |- bl | |- buffer ... |- package-lock.json |- package.json Buat paket deployment .zip yang berisi kode fungsi Anda dan dependensinya. Di macOS dan Linux, jalankan perintah berikut. zip -r function.zip . Di Windows, gunakan utilitas zip pilihan Anda untuk membuat file.zip. Pastikan bahwa package-lock.json file index.mjs package.json ,, dan node_modules direktori Anda semuanya berada di root file.zip Anda. Python Untuk membuat paket penyebaran (Python) Simpan kode contoh sebagai file bernama lambda_function.py . import boto3 import os import sys import uuid from urllib.parse import unquote_plus from PIL import Image import PIL.Image s3_client = boto3.client('s3') def resize_image(image_path, resized_path): with Image.open(image_path) as image: image.thumbnail(tuple(x / 2 for x in image.size)) image.save(resized_path) def lambda_handler(event, context): for record in event['Records']: bucket = record['s3']['bucket']['name'] key = unquote_plus(record['s3']['object']['key']) tmpkey = key.replace('/', '') download_path = '/tmp/ { } { }'.format(uuid.uuid4(), tmpkey) upload_path = '/tmp/resized- { }'.format(tmpkey) s3_client.download_file(bucket, key, download_path) resize_image(download_path, upload_path) s3_client.upload_file(upload_path, ' { }-resized'.format(bucket), 'resized- { }'.format(key)) Di direktori yang sama di mana Anda membuat lambda_function.py file Anda, buat direktori baru bernama package dan instal pustaka Pillow (PIL) dan AWS SDK untuk Python (Boto3). Meskipun runtime Lambda Python menyertakan versi Boto3 SDK, kami menyarankan agar Anda menambahkan semua dependensi fungsi Anda ke paket penerapan Anda, meskipun mereka disertakan dalam runtime. Untuk informasi selengkapnya, lihat Dependensi runtime dengan Python. mkdir package pip install \ --platform manylinux2014_x86_64 \ --target=package \ --implementation cp \ --python-version 3.12 \ --only-binary=:all: --upgrade \ pillow boto3 Pustaka Pillow berisi kode C/C ++. Dengan menggunakan --only-binary=:all: opsi --platform manylinux_2014_x86_64 dan, pip akan mengunduh dan menginstal versi Pillow yang berisi binari pra-kompilasi yang kompatibel dengan sistem operasi Amazon Linux 2. Ini memastikan bahwa paket penerapan Anda akan berfungsi di lingkungan eksekusi Lambda, terlepas dari sistem operasi dan arsitektur mesin build lokal Anda. Buat file.zip yang berisi kode aplikasi Anda dan pustaka Pillow dan Boto3. Di Linux atau macOS, jalankan perintah berikut dari antarmuka baris perintah Anda. cd package zip -r ../lambda_function.zip . cd .. zip lambda_function.zip lambda_function.py Di Windows, gunakan alat zip pilihan Anda untuk membuat file lambda_function.zip . Pastikan bahwa lambda_function.py file Anda dan folder yang berisi dependensi Anda semuanya berada di root file.zip. Anda juga dapat membuat paket deployment menggunakan lingkungan virtual Python. Lihat Bekerja dengan arsip file.zip untuk fungsi Python Lambda Buat fungsi Lambda Anda dapat membuat fungsi Lambda menggunakan konsol Lambda AWS CLI atau Lambda. Ikuti instruksi untuk bahasa yang Anda pilih untuk membuat fungsi. Konsol Manajemen AWS Untuk membuat fungsi (konsol) Untuk membuat fungsi Lambda Anda menggunakan konsol, pertama-tama Anda membuat fungsi dasar yang berisi beberapa kode 'Hello world'. Anda kemudian mengganti kode ini dengan kode fungsi Anda sendiri dengan mengunggah file the.zip atau JAR yang Anda buat pada langkah sebelumnya. Buka halaman Fungsi di konsol Lambda. Pastikan Anda bekerja di tempat yang sama dengan saat Wilayah AWS Anda membuat bucket Amazon S3. Anda dapat mengubah wilayah Anda menggunakan daftar drop-down di bagian atas layar. Pilih Buat fungsi . Pilih Penulis dari scratch . Di bagian Informasi dasar , lakukan hal berikut: Untuk Nama fungsi , masukkan CreateThumbnail . Untuk Runtime , pilih Node.js 22.x atau Python 3.12 sesuai dengan bahasa yang Anda pilih untuk fungsi Anda. Untuk Arsitektur , pilih x86_64 . Di tab Ubah peran eksekusi default , lakukan hal berikut: Perluas tab, lalu pilih Gunakan peran yang ada . Pilih yang LambdaS3Role Anda buat sebelumnya. Pilih Buat fungsi . Untuk mengunggah kode fungsi (konsol) Di panel Sumber kode , pilih Unggah dari . Pilih file.zip . Pilih Unggah . Di pemilih file, pilih file.zip Anda dan pilih Buka. Pilih Simpan . AWS CLI Untuk membuat fungsi (AWS CLI) Jalankan perintah CLI untuk bahasa yang Anda pilih. Untuk role parameter, pastikan untuk mengganti 123456789012 dengan Akun AWS ID Anda sendiri. Untuk region parameternya, ganti us-east-1 dengan wilayah tempat Anda membuat bucket Amazon S3. Untuk Node.js , jalankan perintah berikut dari direktori yang berisi function.zip file Anda. aws lambda create-function --function-name CreateThumbnail \ --zip-file fileb://function.zip --handler index.handler --runtime nodejs24.x \ --timeout 10 --memory-size 1024 \ --role arn:aws:iam:: 123456789012 :role/LambdaS3Role --region us-east-1 Untuk Python , jalankan perintah berikut dari direktori yang berisi file Anda lambda_function.zip . aws lambda create-function --function-name CreateThumbnail \ --zip-file fileb://lambda_function.zip --handler lambda_function.lambda_handler \ --runtime python3.14 --timeout 10 --memory-size 1024 \ --role arn:aws:iam:: 123456789012 :role/LambdaS3Role --region us-east-1 Konfigurasikan Amazon S3 untuk menjalankan fungsi Agar fungsi Lambda dapat berjalan saat mengunggah gambar ke bucket sumber, Anda perlu mengonfigurasi pemicu untuk fungsi Anda. Anda dapat mengonfigurasi pemicu Amazon S3 menggunakan konsol atau. AWS CLI penting Prosedur ini mengonfigurasi bucket Amazon S3 untuk menjalankan fungsi Anda setiap kali objek dibuat di bucket. Pastikan untuk mengonfigurasi ini hanya di bucket sumber. Jika fungsi Lambda Anda membuat objek dalam bucket yang sama yang memanggilnya, fungsi Anda dapat dipanggil terus menerus dalam satu loop. Hal ini dapat mengakibatkan biaya yang tidak diharapkan ditagih ke Anda Akun AWS. Konsol Manajemen AWS Untuk mengonfigurasi pemicu Amazon S3 (konsol) Buka halaman Fungsi konsol Lambda dan pilih fungsi Anda () CreateThumbnail . Pilih Tambahkan pemicu . Pilih S3 . Di bawah Bucket , pilih bucket sumber Anda. Di bawah Jenis acara , pilih Semua objek membuat acara . Di bawah Pemanggilan rekursif , pilih kotak centang untuk mengetahui bahwa tidak disarankan menggunakan bucket Amazon S3 yang sama untuk input dan output. Anda dapat mempelajari lebih lanjut tentang pola pemanggilan rekursif di Lambda dengan membaca pola rekursif yang menyebabkan fungsi Lambda yang tidak terkendali di Tanah Tanpa Server. Pilih Tambahkan . Saat Anda membuat pemicu menggunakan konsol Lambda, Lambda secara otomatis membuat kebijakan berbasis sumber daya untuk memberikan layanan yang Anda pilih izin untuk menjalankan fungsi Anda. AWS CLI Untuk mengonfigurasi pemicu Amazon S3 ()AWS CLI Agar bucket sumber Amazon S3 menjalankan fungsi saat menambahkan file gambar, pertama-tama Anda harus mengonfigurasi izin untuk fungsi menggunakan kebijakan berbasis sumber daya. Pernyataan kebijakan berbasis sumber daya memberikan Layanan AWS izin lain untuk menjalankan fungsi Anda. Untuk memberikan izin Amazon S3 untuk menjalankan fungsi Anda, jalankan perintah CLI berikut. Pastikan untuk mengganti source-account parameter dengan Akun AWS ID Anda sendiri dan menggunakan nama bucket sumber Anda sendiri. aws lambda add-permission --function-name CreateThumbnail \ --principal s3.amazonaws.com --statement-id s3invoke --action "lambda:InvokeFunction" \ --source-arn arn:aws:s3::: amzn-s3-demo-source-bucket \ --source-account 123456789012 Kebijakan yang Anda tetapkan dengan perintah ini memungkinkan Amazon S3 untuk menjalankan fungsi Anda hanya ketika tindakan dilakukan di bucket sumber Anda. catatan Meskipun nama bucket Amazon S3 unik secara global, saat menggunakan kebijakan berbasis sumber daya, praktik terbaik adalah menentukan bahwa bucket harus menjadi milik akun Anda. Ini karena jika Anda menghapus bucket, Anda dapat membuat bucket dengan Amazon Resource Name (ARN) yang sama. Akun AWS Simpan JSON berikut dalam file bernama notification.json . Saat diterapkan ke bucket sumber Anda, JSON ini mengonfigurasi bucket untuk mengirim notifikasi ke fungsi Lambda Anda setiap kali objek baru ditambahkan. Ganti Akun AWS nomor dan Wilayah AWS dalam fungsi Lambda ARN dengan nomor akun dan wilayah Anda sendiri. { "LambdaFunctionConfigurations": [ { "Id": "CreateThumbnailEventConfiguration", "LambdaFunctionArn": "arn:aws:lambda: us-east-1:123456789012 :function:CreateThumbnail", "Events": [ "s3:ObjectCreated:Put" ] } ] } Jalankan perintah CLI berikut untuk menerapkan pengaturan notifikasi dalam file JSON yang Anda buat ke bucket sumber Anda. Ganti amzn-s3-demo-source-bucket dengan nama bucket sumber Anda sendiri. aws s3api put-bucket-notification-configuration --bucket amzn-s3-demo-source-bucket \ --notification-configuration file://notification.json Untuk mempelajari lebih lanjut tentang put-bucket-notification-configuration perintah dan notification-configuration opsi, lihat put-bucket-notification-configuration di Referensi Perintah AWS CLI . Uji fungsi Lambda Anda dengan acara dummy Sebelum menguji seluruh penyiapan dengan menambahkan file gambar ke bucket sumber Amazon S3, Anda menguji apakah fungsi Lambda berfungsi dengan benar dengan memanggilnya dengan acara dummy. Peristiwa di Lambda adalah dokumen berformat JSON yang berisi data untuk diproses fungsi Anda. Saat fungsi Anda dipanggil oleh Amazon S3, peristiwa yang dikirim ke fungsi berisi informasi seperti nama bucket, ARN bucket, dan kunci objek. Konsol Manajemen AWS Untuk menguji fungsi Lambda Anda dengan acara dummy (konsol) Buka halaman Fungsi konsol Lambda dan pilih fungsi Anda () CreateThumbnail . Pilih tab Uji . Untuk membuat acara pengujian, di panel acara Uji , lakukan hal berikut: Di bawah Uji tindakan peristiwa , pilih Buat acara baru . Untuk Nama peristiwa , masukkan myTestEvent . Untuk Template , pilih S3 Put . Ganti nilai untuk parameter berikut dengan nilai Anda sendiri. Untuk awsRegion , ganti us-east-1 dengan bucket Amazon S3 yang Wilayah AWS Anda buat. Untuk name , ganti amzn-s3-demo-bucket dengan nama bucket sumber Amazon S3 Anda sendiri. Untuk key , ganti test%2Fkey dengan nama file objek pengujian yang Anda unggah ke bucket sumber di langkah tersebut. Unggah gambar uji ke bucket sumber Anda { "Records": [ { "eventVersion": "2.0", "eventSource": "aws:s3", "awsRegion": "us-east-1" , "eventTime": "1970-01-01T00:00:00.000Z", "eventName": "ObjectCreated:Put", "userIdentity": { "principalId": "EXAMPLE" }, "requestParameters": { "sourceIPAddress": "127.0.0.1" }, "responseElements": { "x-amz-request-id": "EXAMPLE123456789", "x-amz-id-2": "EXAMPLE123/5678abcdefghijklambdaisawesome/mnopqrstuvwxyzABCDEFGH" }, "s3": { "s3SchemaVersion": "1.0", "configurationId": "testConfigRule", "bucket": { "name": "amzn-s3-demo-bucket" , "ownerIdentity": { "principalId": "EXAMPLE" }, "arn": "arn:aws:s3:::amzn-s3-demo-bucket" }, "object": { "key": "test%2Fkey" , "size": 1024, "eTag": "0123456789abcdef0123456789abcdef", "sequencer": "0A1B2C3D4E5F678901" } } } ] } Pilih Simpan . Di panel acara Uji , pilih Uji . Untuk memeriksa fungsi Anda telah membuat verison yang diubah ukurannya dari gambar Anda dan menyimpannya di bucket Amazon S3 target Anda, lakukan hal berikut: Buka halaman Bucket konsol Amazon S3. Pilih bucket target Anda dan konfirmasikan bahwa file yang diubah ukurannya tercantum di panel Objects . AWS CLI Untuk menguji fungsi Lambda Anda dengan acara dummy ()AWS CLI Simpan JSON berikut dalam file bernama dummyS3Event.json . Ganti nilai untuk parameter berikut dengan nilai Anda sendiri: Untuk awsRegion , ganti us-east-1 dengan bucket Amazon S3 yang Wilayah AWS Anda buat. Untuk name , ganti amzn-s3-demo-bucket dengan nama bucket sumber Amazon S3 Anda sendiri. Untuk key , ganti test%2Fkey dengan nama file objek pengujian yang Anda unggah ke bucket sumber di langkah tersebut. Unggah gambar uji ke bucket sumber Anda { "Records": [ { "eventVersion": "2.0", "eventSource": "aws:s3", "awsRegion": "us-east-1" , "eventTime": "1970-01-01T00:00:00.000Z", "eventName": "ObjectCreated:Put", "userIdentity": { "principalId": "EXAMPLE" }, "requestParameters": { "sourceIPAddress": "127.0.0.1" }, "responseElements": { "x-amz-request-id": "EXAMPLE123456789", "x-amz-id-2": "EXAMPLE123/5678abcdefghijklambdaisawesome/mnopqrstuvwxyzABCDEFGH" }, "s3": { "s3SchemaVersion": "1.0", "configurationId": "testConfigRule", "bucket": { "name": "amzn-s3-demo-bucket" , "ownerIdentity": { "principalId": "EXAMPLE" }, "arn": "arn:aws:s3:::amzn-s3-demo-bucket" }, "object": { "key": "test%2Fkey" , "size": 1024, "eTag": "0123456789abcdef0123456789abcdef", "sequencer": "0A1B2C3D4E5F678901" } } } ] } Dari direktori tempat Anda menyimpan dummyS3Event.json file Anda, panggil fungsi dengan menjalankan perintah CLI berikut. Perintah ini memanggil fungsi Lambda Anda secara sinkron dengan RequestResponse menentukan sebagai nilai parameter tipe pemanggilan. Untuk mempelajari lebih lanjut tentang pemanggilan sinkron dan asinkron, lihat Memanggil fungsi Lambda. aws lambda invoke --function-name CreateThumbnail \ --invocation-type RequestResponse --cli-binary-format raw-in-base64-out \ --payload file://dummyS3Event.json outputfile.txt cli-binary-formatOpsi ini diperlukan jika Anda menggunakan versi 2 dari AWS CLI. Untuk menjadikan ini pengaturan default, jalankan aws configure set cli-binary-format raw-in-base64-out . Untuk informasi selengkapnya, lihat opsi baris perintah global yang AWS CLI didukung . Verifikasi bahwa fungsi Anda telah membuat versi thumbnail gambar Anda dan menyimpannya ke bucket Amazon S3 target Anda. Jalankan perintah CLI berikut, ganti amzn-s3-demo-source-bucket-resized dengan nama bucket tujuan Anda sendiri. aws s3api list-objects-v2 --bucket amzn-s3-demo-source-bucket-resized Anda akan melihat output seperti yang berikut ini. Key Parameter menunjukkan nama file file gambar Anda yang diubah ukurannya. { "Contents": [ { "Key": "resized-HappyFace.jpg", "LastModified": "2023-06-06T21:40:07+00:00", "ETag": "\"d8ca652ffe83ba6b721ffc20d9d7174a\"", "Size": 2633, "StorageClass": "STANDARD" } ] } Uji fungsi Anda menggunakan pemicu Amazon S3 Sekarang setelah Anda mengonfirmasi bahwa fungsi Lambda Anda beroperasi dengan benar, Anda siap untuk menguji penyiapan lengkap Anda dengan menambahkan file gambar ke bucket sumber Amazon S3 Anda. Saat Anda menambahkan gambar ke bucket sumber, fungsi Lambda Anda akan dipanggil secara otomatis. Fungsi Anda membuat versi file yang diubah ukurannya dan menyimpannya di bucket target Anda. Konsol Manajemen AWS Untuk menguji fungsi Lambda Anda menggunakan pemicu Amazon S3 (konsol) Untuk mengunggah gambar ke bucket Amazon S3 Anda, lakukan hal berikut: Buka halaman Bucket di konsol Amazon S3 dan pilih bucket sumber Anda. Pilih Unggah . Pilih Tambahkan file dan gunakan pemilih file untuk memilih file gambar yang ingin Anda unggah. Objek gambar Anda dapat berupa file.jpg atau.png. Pilih Buka , lalu pilih Unggah . Verifikasi bahwa Lambda telah menyimpan versi file gambar yang diubah ukurannya di bucket target dengan melakukan hal berikut: Arahkan kembali ke halaman Bucket di konsol Amazon S3 dan pilih bucket tujuan Anda. Di panel Objects , Anda sekarang akan melihat dua file gambar yang diubah ukurannya, satu dari setiap pengujian fungsi Lambda Anda. Untuk mengunduh gambar yang diubah ukurannya, pilih file, lalu pilih Unduh . AWS CLI Untuk menguji fungsi Lambda Anda menggunakan pemicu Amazon S3 ()AWS CLI Dari direktori yang berisi gambar yang ingin Anda unggah, jalankan perintah CLI berikut. Ganti --bucket parameter dengan nama bucket sumber Anda. Untuk --body parameter --key dan, gunakan nama file gambar pengujian Anda. Gambar uji Anda dapat berupa file.jpg atau.png. aws s3api put-object --bucket amzn-s3-demo-source-bucket --key SmileyFace.jpg --body ./SmileyFace.jpg Verifikasi bahwa fungsi Anda telah membuat versi thumbnail gambar Anda dan menyimpannya ke bucket Amazon S3 target Anda. Jalankan perintah CLI berikut, ganti amzn-s3-demo-source-bucket-resized dengan nama bucket tujuan Anda sendiri. aws s3api list-objects-v2 --bucket amzn-s3-demo-source-bucket-resized Jika fungsi Anda berjalan dengan sukses, Anda akan melihat output yang mirip dengan berikut ini. Bucket target Anda sekarang harus berisi dua file yang diubah ukurannya. { "Contents": [ { "Key": "resized-HappyFace.jpg", "LastModified": "2023-06-07T00:15:50+00:00", "ETag": "\"7781a43e765a8301713f533d70968a1e\"", "Size": 2763, "StorageClass": "STANDARD" }, { "Key": "resized-SmileyFace.jpg", "LastModified": "2023-06-07T00:13:18+00:00", "ETag": "\"ca536e5a1b9e32b22cd549e18792cdbc\"", "Size": 1245, "StorageClass": "STANDARD" } ] } Bersihkan sumber daya Anda Sekarang Anda dapat menghapus sumber daya yang Anda buat untuk tutorial ini, kecuali Anda ingin mempertahankannya. Dengan menghapus AWS sumber daya yang tidak lagi Anda gunakan, Anda mencegah tagihan yang tidak perlu ke Anda Akun AWS. Untuk menghapus fungsi Lambda Buka halaman Fungsi di konsol Lambda. Pilih fungsi yang Anda buat. Pilih Tindakan , Hapus . Ketik confirm kolom input teks dan pilih Hapus . Untuk menghapus kebijakan yang Anda buat. Buka halaman Kebijakan konsol IAM. Pilih kebijakan yang Anda buat ( AWSLambdaS3Policy ). Pilih Tindakan kebijakan , Hapus . Pilih Hapus . Untuk menghapus peran eksekusi Buka halaman Peran dari konsol IAM. Pilih peran eksekusi yang Anda buat. Pilih Hapus . Masukkan nama peran di bidang input teks dan pilih Hapus . Untuk menghapus bucket S3 Buka konsol Amazon S3 . Pilih bucket yang Anda buat. Pilih Hapus . Masukkan nama ember di bidang input teks. Pilih Hapus bucket . Javascript dinonaktifkan atau tidak tersedia di browser Anda. Untuk menggunakan Dokumentasi AWS, Javascript harus diaktifkan. Lihat halaman Bantuan browser Anda untuk petunjuk. Konvensi Dokumen Tutorial: Menggunakan pemicu S3 Secrets Manager Apakah halaman ini membantu Anda? - Ya Terima kasih telah memberitahukan bahwa hasil pekerjaan kami sudah baik. Jika Anda memiliki waktu luang, beri tahu kami aspek apa saja yang sudah bagus, agar kami dapat menerapkannya secara lebih luas. Apakah halaman ini membantu Anda? - Tidak Terima kasih telah memberi tahu kami bahwa halaman ini perlu ditingkatkan. Maaf karena telah mengecewakan Anda. Jika Anda memiliki waktu luang, beri tahu kami bagaimana dokumentasi ini dapat ditingkatkan. | 2026-01-13T09:30:35 |
https://docs.aws.amazon.com/es_es/AmazonCloudFront/latest/DeveloperGuide/lambda-examples.html#lambda-examples-update-error-status-examples | Funciones de ejemplo de Lambda@Edge - Amazon CloudFront Funciones de ejemplo de Lambda@Edge - Amazon CloudFront Documentación Amazon CloudFront Guía para desarrolladores Ejemplos generales Generación de respuestas: ejemplos Cadenas de consulta: ejemplos Personalización de contenido por encabezados de tipo de dispositivo o país: ejemplos Selección de origen dinámico basada en contenido: ejemplos Actualización de estados de error: ejemplos Acceso al cuerpo de la solicitud: ejemplos Funciones de ejemplo de Lambda@Edge Consulte los ejemplos siguientes para usar funciones de Lambda con Amazon CloudFront. nota Si elige el tiempo de ejecución Node.js 18 o una versión posterior para la función Lambda@Edge, se creará automáticamente un archivo index.mjs . Para usar los siguientes ejemplos de código, cambie el nombre del archivo index.mjs a index.js . Temas Ejemplos generales Generación de respuestas: ejemplos Cadenas de consulta: ejemplos Personalización de contenido por encabezados de tipo de dispositivo o país: ejemplos Selección de origen dinámico basada en contenido: ejemplos Actualización de estados de error: ejemplos Acceso al cuerpo de la solicitud: ejemplos Ejemplos generales Los ejemplos siguientes muestran formas habituales de usar Lambda@Edge en CloudFront. Temas Ejemplo: prueba A/B Ejemplo: Sobrescritura de un encabezado de respuesta Ejemplo: prueba A/B Puede utilizar el siguiente ejemplo para probar dos versiones diferentes de una imagen sin crear redirecciones ni cambiar la dirección URL. En este ejemplo se leen las cookies de la solicitud del lector y se modifica la URL de la solicitud en consecuencia. Si el espectador no envía una cookie con uno de los valores esperados, el ejemplo asigna aleatoriamente al espectador una de las URL. 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; } 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; } } 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" ''' experimentUri = "" 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 Ejemplo: Sobrescritura de un encabezado de respuesta En el ejemplo siguiente, se muestra cómo cambiar el valor de un encabezado de respuesta según el valor de otro encabezado. Node.js export const handler = async (event) => { 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()] = [ { key: headerNameDst, value: headers[headerNameSrc.toLowerCase()][0].value, }]; console.log(`Response header "$ { headerNameDst}" was set to ` + `"$ { headers[headerNameDst.toLowerCase()][0].value}"`); } return response; }; Python import json def lambda_handler(event, context): response = event['Records'][0]['cf']['response'] headers = response['headers'] header_name_src = 'X-Amz-Meta-Last-Modified' header_name_dst = 'Last-Modified' if headers.get(header_name_src.lower()): headers[header_name_dst.lower()] = [ { 'key': header_name_dst, 'value': headers[header_name_src.lower()][0]['value'] }] print(f'Response header " { header_name_dst}" was set to ' f'" { headers[header_name_dst.lower()][0]["value"]}"') return response Generación de respuestas: ejemplos En los ejemplos siguientes se muestra cómo puede usar Lambda@Edge para generar respuestas. Temas Ejemplo: Envío de contenido estático (respuesta generada) Ejemplo: Generación de un redireccionamiento HTTP (respuesta generada) Ejemplo: Envío de contenido estático (respuesta generada) En el siguiente ejemplo se muestra cómo utilizar una función de Lambda para enviar contenido de sitio web estático, lo que reduce la carga en el servidor de origen y la latencia total. nota Puede generar respuestas HTTP para los eventos de solicitud del espectador y al origen. Para obtener más información, consulte Generación de respuestas HTTP en los desencadenadores de solicitud . También puede sustituir o quitar el cuerpo de la respuesta HTTP en eventos de respuesta de origen. Para obtener más información, consulte Actualización de respuestas HTTP en desencadenadores de respuesta de origen . 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' }] }, 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 } return response Ejemplo: Generación de un redireccionamiento HTTP (respuesta generada) En el siguiente ejemplo se muestra cómo generar una redirección HTTP. nota Puede generar respuestas HTTP para los eventos de solicitud del espectador y al origen. Para obtener más información, consulte Generación de respuestas HTTP en los desencadenadores de solicitud . 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. response = { 'status': '302', 'statusDescription': 'Found', 'headers': { 'location': [ { 'key': 'Location', 'value': 'https://docs.aws.amazon.com/lambda/latest/dg/lambda-edge.html' }] } } return response Cadenas de consulta: ejemplos En los ejemplos siguientes se muestran formas de usar Lambda@Edge con cadenas de consulta. Temas Ejemplo: Adición de un encabezado en función de un parámetro de la cadena de consulta Ejemplo: Normalización de parámetros de cadenas de consulta para mejorar la tasa de aciertos de caché Ejemplo: Redireccionamiento de los usuarios no autenticados a una página de inicio de sesión Ejemplo: Adición de un encabezado en función de un parámetro de la cadena de consulta El siguiente ejemplo muestra cómo obtener el par clave-valor de un parámetro de la cadena de consulta y, a continuación, añadir un encabezado en función de dichos valores. 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. * 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 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'] # Update request querystring request['querystring'] = urlencode(params) return request Ejemplo: Normalización de parámetros de cadenas de consulta para mejorar la tasa de aciertos de caché El siguiente ejemplo muestra cómo mejorar la tasa de acceso a la caché haciendo los siguientes cambios en las cadenas de consulta antes de que CloudFront reenvíe las solicitudes a su origen: Alfabetizar los pares de clave-valor por el nombre del parámetro. Cambiar a minúsculas el modelo de mayúsculas y minúsculas de los pares de clave-valor. Para obtener más información, consulte Almacenamiento en caché de contenido en función de parámetros de cadenas de consulta . 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 */ 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 request['querystring'] = urlencode(sortedParams) return request Ejemplo: Redireccionamiento de los usuarios no autenticados a una página de inicio de sesión El siguiente ejemplo muestra cómo redirigir a los usuarios una página de inicio de sesión si no ha introducido sus credenciales. 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; } /* 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 params. ''' # Check for session-id in cookie, if present, then proceed with request parsedCookies = parseCookies(headers) 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 Personalización de contenido por encabezados de tipo de dispositivo o país: ejemplos En los ejemplos siguientes se muestra cómo puede usar Lambda@Edge para personalizar el comportamiento en función de la ubicación o el tipo de dispositivo que usa el lector. Temas Ejemplo: Redireccionamiento de solicitudes de espectadores a una URL específica de un país Ejemplo: Envío de distintas versiones de un objeto en función del dispositivo Ejemplo: Redireccionamiento de solicitudes de espectadores a una URL específica de un país El siguiente ejemplo muestra cómo generar una respuesta de redireccionamiento HTTP con una URL específica del país y devolver la respuesta al espectador. Esto resulta útil cuando se quiere proporcionar respuestas específicas del país. Por ejemplo: Si tiene subdominios específicos de un país, como us.ejemplo.com y tw.ejemplo.com, puede generar una respuesta de redireccionamiento cuando un espectador solicite ejemplo.com. Si está haciendo streaming de video, pero no tiene derechos para transmitir el contenido en un país determinado, puede redirigir a los usuarios de dicho país a una página en la que se explica por qué no pueden ver el video. Tenga en cuenta lo siguiente: Debe configurar la distribución para almacenar en la caché en función del encabezado CloudFront-Viewer-Country . Para obtener más información, consulte Caché en función de encabezados de solicitud seleccionados . CloudFront agrega el encabezado CloudFront-Viewer-Country después del evento de solicitud del lector. Para utilizar este ejemplo, debe crear un activador para el evento de solicitud al origen. 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 = { 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', 'statusDescription': 'Found', 'headers': { 'location': [ { 'key': 'Location', 'value': url }] } } return response Ejemplo: Envío de distintas versiones de un objeto en función del dispositivo El siguiente ejemplo muestra cómo ofrecer distintas versiones de un objeto en función del tipo de dispositivo que el usuario está utilizando; por ejemplo, un dispositivo móvil o una tablet. Tenga en cuenta lo siguiente: Debe configurar la distribución para almacenar en la caché en función de los encabezados CloudFront-Is-*-Viewer . Para obtener más información, consulte Caché en función de encabezados de solicitud seleccionados . CloudFront agrega los encabezados CloudFront-Is-*-Viewer después del evento de solicitud del lector. Para utilizar este ejemplo, debe crear un activador para el evento de solicitud al origen. 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 * 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. ''' desktopPath = '/desktop'; mobilePath = '/mobile'; tabletPath = '/tablet'; smarttvPath = '/smarttv'; 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 Selección de origen dinámico basada en contenido: ejemplos En los ejemplos siguientes se muestra cómo puede usar Lambda@Edge para el direccionamiento a diferentes orígenes en función de la información de la solicitud. Temas Ejemplo: Uso de un desencadenador de solicitud de origen para cambiar desde un origen personalizado a un origen de Amazon S3 Ejemplo: Uso de un desencadenador de solicitud de origen para cambiar la región de origen de Amazon S3 Ejemplo: Uso de un desencadenador de solicitud de origen para cambiar desde un origen de Amazon S3 a un origen personalizado Ejemplo: Uso de un desencadenador de solicitud al origen para transferir gradualmente el tráfico desde un bucket de Amazon S3 a otro Ejemplo: Uso de un desencadenador de solicitud de origen para cambiar el nombre del dominio de origen en función del encabezado de país Ejemplo: Uso de un desencadenador de solicitud de origen para cambiar desde un origen personalizado a un origen de Amazon S3 Esta función demuestra cómo utilizar un desencadenador de solicitud al origen para cambiar desde un origen personalizado a un origen de Amazon S3 desde el que recuperar el contenido, en función de las propiedades de la solicitud. 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: 'origin-access-identity', path: '', customHeaders: { } } }; request.headers['host'] = [ { key: 'host', value: s3DomainName}]; } } 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 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': 'origin-access-identity', 'path': '', 'customHeaders': { } } } request['headers']['host'] = [ { 'key': 'host', 'value': s3DomainName}] return request Ejemplo: Uso de un desencadenador de solicitud de origen para cambiar la región de origen de Amazon S3 Esta función demuestra cómo utilizar un desencadenador de solicitud al origen para cambiar el origen de Amazon S3 desde el que se recupera el contenido, en función de las propiedades de la solicitud. En este ejemplo, utilizamos el valor del encabezado CloudFront-Viewer-Country para actualizar el nombre de dominio del bucket de S3 por un bucket de una región que está más cerca del lector. Esto puede resultar útil de varias maneras: Reduce las latencias cuando la región especificada está más cerca del país del lector. Proporciona soberanía de los datos, al asegurarse de que los datos se distribuyen desde un origen que está en el país del que provino la solicitud. Para utilizar este ejemplo, debe hacer lo siguiente: Configure la distribución para almacenar en la caché en función del encabezado CloudFront-Viewer-Country . Para obtener más información, consulte Caché en función de encabezados de solicitud seleccionados . Crear un disparador para esta función en el evento de solicitud al origen. CloudFront agrega el encabezado CloudFront-Viewer-Country después del evento de solicitud del lector; por lo tanto, para utilizar este ejemplo, debe asegurarse de que la función ejecuta una solicitud de origen. nota El siguiente código de ejemplo usa la misma identidad de acceso de origen (OAI) para todos los buckets de S3 que usa para el origen. Para obtener más información, consulte Identidad de acceso de origen . 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 * 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); }; Python 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: 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: ''' 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 Ejemplo: Uso de un desencadenador de solicitud de origen para cambiar desde un origen de Amazon S3 a un origen personalizado Esta función demuestra cómo utilizar un disparador de solicitud al origen para cambiar el origen personalizado desde el que se recupera el contenido, en función de las propiedades de la solicitud. 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: { 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': { } } } request['headers']['host'] = [ { 'key': 'host', 'value': 'www.example.com'}] return request Ejemplo: Uso de un desencadenador de solicitud al origen para transferir gradualmente el tráfico desde un bucket de Amazon S3 a otro Esta función demuestra cómo transferir gradualmente el tráfico desde un bucket de Amazon S3 a otro de forma controlada. 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}]; } 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 Ejemplo: Uso de un desencadenador de solicitud de origen para cambiar el nombre del dominio de origen en función del encabezado de país Esta función demuestra cómo cambiar el nombre del dominio de origen en función del encabezado CloudFront-Viewer-Country , de forma que el contenido se distribuya desde un origen más cercano al país del lector. La implementación de esta funcionalidad para su distribución puede tener ventajas como las siguientes: Reducir las latencias cuando la región especificada está más cerca del país del lector Proporcionar soberanía de los datos, al asegurarse de que los datos se distribuyen desde un origen que está en el país del que provino la solicitud Tenga en cuenta que para habilitar esta funcionalidad, debe configurar su distribución para almacenar en la caché en función del encabezado CloudFront-Viewer-Country . Para obtener más información, consulte Caché en función de encabezados de solicitud seleccionados . 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 request['headers']['host'] = [ { 'key': 'host', 'value': domainName}] return request Actualización de estados de error: ejemplos En los ejemplos siguientes se proporciona orientación acerca de cómo puede usar Lambda@Edge para cambiar el estado de error que se devuelve a los usuarios. Temas Ejemplo: Uso de un desencadenador de respuesta de origen para actualizar el código de estado de error a 200 Ejemplo: Uso de un desencadenador de respuesta de origen para actualizar el código de estado de error a 302 Ejemplo: Uso de un desencadenador de respuesta de origen para actualizar el código de estado de error a 200 Esta función demuestra cómo actualizar el estado de la respuesta a 200 y generar un cuerpo con contenido estático para devolverlo al espectador en la siguiente situación: La función se desencadena en una respuesta del origen. El estado de la respuesta del servidor de origen es un código de estado de error (4xx o 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'; } callback(null, response); }; Python 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 Ejemplo: Uso de un desencadenador de respuesta de origen para actualizar el código de estado de error a 302 Esta función demuestra cómo actualizar el código de estado HTTP a 302 para la redirección a otra ruta (comportamiento de la caché) en la que se ha configurado un origen diferente. Tenga en cuenta lo siguiente: La función se desencadena en una respuesta del origen. El estado de la respuesta del servidor de origen es un código de estado de error (4xx o 5xx). Node.js 'use strict'; exports.handler = (event, context, callback) => { const response = event.Records[0].cf.response; const 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 (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 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 Acceso al cuerpo de la solicitud: ejemplos En los ejemplos siguientes se muestra cómo puede usar Lambda@Edge para trabajar con las solicitudes POST. nota Para utilizar estos ejemplos, debe habilitar la opción incluir cuerpo en la asociación de funciones Lambda de la distribución. No está habilitada de forma predeterminada. Para habilitar esta configuración en la consola de CloudFront, seleccione la casilla de verificación Incluir cuerpo en la Asociación de funciones Lambda . Para habilitar esta configuración en la API de CloudFront o con CloudFormation, establezca el campo IncludeBody en true en LambdaFunctionAssociation . Temas Ejemplo: Uso de un desencadenador de solicitud para leer un formulario HTML Ejemplo: Uso de un desencadenador de solicitud para modificar un formulario HTML Ejemplo: Uso de un desencadenador de solicitud para leer un formulario HTML Esta función ilustra cómo puede procesar el cuerpo de una solicitud POST generada por un formulario HTML (formulario web), como por ejemplo un formulario tipo "póngase en contacto con nosotros". Por ejemplo, es posible que tenga un formulario HTML como el siguiente: <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> Para la función de ejemplo que se indica a continuación, la función se debe desencadenar en una solicitud al origen o del lector de CloudFront. 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 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 Ejemplo: Uso de un desencadenador de solicitud para modificar un formulario HTML Esta función ilustra cómo puede modificar el cuerpo de una solicitud POST generada por un formulario HTML (formulario web). La función se activa en una solicitud al origen o del lector de CloudFront. 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. * * 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'] | 2026-01-13T09:30:35 |
https://young-programmers.blogspot.com/2009/07/using-gimp-to-make-graphics-for-scratch.html | Young Programmers Podcast: Using GIMP to Make Graphics for Scratch and Alice skip to main | skip to sidebar Young Programmers Podcast A video podcast for computer programmers in grades 3 and up. We learn about Scratch, Tynker, Alice, Python, Pygame, and Scala, and interview interesting programmers. From professional software developer and teacher Dave Briccetti, and many special guests. Viewing the Videos or Subscribing to the Podcast Some of the entries have a picture, which you can click to access the video. Otherwise, to see the videos, use this icon to subscribe to or view the feed: Or, subscribe in iTunes Tuesday, July 21, 2009 Using GIMP to Make Graphics for Scratch and Alice Shows using the GIMP (GNU Image Manipulation Program) to create a costume for a Scratch sprite, and a texture for Alice. at 11:16 AM Labels: alice , GIMP , scratch Newer Post Older Post Home About Me Dave Briccetti View my complete profile Where to Get Software Kojo Python Alice Scratch Other Blogs Dave Briccetti’s Blog One of My Best Classes Ever 10 years ago Tags alice (3) Android (1) arduino (1) art (1) audacity (2) dictionary (2) Flickr (1) functions (2) gamedev (1) garageband (1) GIMP (2) Google (2) guest (4) hacker (1) higher-order functions (1) inkscape (1) interview (9) Java (2) JavaFX (2) Jython (3) Kojo (2) lift (1) music (2) physics (1) platform (1) programmer (4) pygame (6) python (31) PythonCard (1) random (6) Sande (2) Scala (5) scratch (10) shdh (2) shdh34 (2) sound (3) sprite (2) Swing (3) teaching (3) twitter (2) Tynker (1) Web Services (1) xturtle (1) Followers Blog Archive ►  2015 (1) ►  February (1) ►  2013 (4) ►  July (1) ►  June (3) ►  2012 (2) ►  February (1) ►  January (1) ►  2011 (8) ►  November (1) ►  July (3) ►  May (1) ►  February (2) ►  January (1) ►  2010 (6) ►  October (2) ►  June (2) ►  February (2) ▼  2009 (37) ►  December (4) ►  November (1) ►  September (7) ►  August (11) ▼  July (14) Tor Norbye Shows JavaFX Recording Music for Computer Games Adding a Second Sprite to SimplePygame (Challenge 4) Solutions to SimplePygame Challenges 1–3 Xturtle With Loops to Make Polygons An Alice Object Reacts to Another Using GIMP to Make Graphics for Scratch and Alice Twitter’s Doug Williams Visits My Programming Class Random Number Problems and Python Solutions Random Numbers in Python: randint and choice Three Simple Python Problems and Their Solutions Power-Up and Shield Making Scratch Graphics with Inkscape Overview of Scratch, Alice, Python and Pygame   | 2026-01-13T09:30:35 |
https://young-programmers.blogspot.com/2013/ | Young Programmers Podcast: 2013 skip to main | skip to sidebar Young Programmers Podcast A video podcast for computer programmers in grades 3 and up. We learn about Scratch, Tynker, Alice, Python, Pygame, and Scala, and interview interesting programmers. From professional software developer and teacher Dave Briccetti, and many special guests. Viewing the Videos or Subscribing to the Podcast Some of the entries have a picture, which you can click to access the video. Otherwise, to see the videos, use this icon to subscribe to or view the feed: Or, subscribe in iTunes Thursday, July 18, 2013 Introduction to Python Functions A look at how to, and why you should, use functions in your Python programs. at 10:06 PM Labels: functions , python , random Wednesday, June 26, 2013 A Simple Python Quiz Program, Part 3 We enhance the quiz program by reading the questions and answers from a file. Source code at 11:49 PM Labels: python Wednesday, June 12, 2013 Tynker—Physics and Cloning Let’s look at two very nice features of Tynker. The physics feature allows you to have falling objects and accurate projectile motion, combined with adjustments for gravity, friction, density, gravity, and much more. Cloning lets you have multiple instances of actors (like Scratch sprites), without having to duplicate code. at 6:38 PM Labels: physics , teaching , Tynker Sunday, June 2, 2013 Simple Python Calculator using a Dictionary and Functions for Operators This lesson creates a simple calculator using a dictionary to look up functions for operators. The point is to practice more with dictionaries, and to learn about higher-order functions. Source code at 10:10 PM Labels: dictionary , higher-order functions , python Newer Posts Older Posts Home Subscribe to: Comments (Atom) About Me Dave Briccetti View my complete profile Where to Get Software Kojo Python Alice Scratch Other Blogs Dave Briccetti’s Blog One of My Best Classes Ever 10 years ago Tags alice (3) Android (1) arduino (1) art (1) audacity (2) dictionary (2) Flickr (1) functions (2) gamedev (1) garageband (1) GIMP (2) Google (2) guest (4) hacker (1) higher-order functions (1) inkscape (1) interview (9) Java (2) JavaFX (2) Jython (3) Kojo (2) lift (1) music (2) physics (1) platform (1) programmer (4) pygame (6) python (31) PythonCard (1) random (6) Sande (2) Scala (5) scratch (10) shdh (2) shdh34 (2) sound (3) sprite (2) Swing (3) teaching (3) twitter (2) Tynker (1) Web Services (1) xturtle (1) Followers Blog Archive ►  2015 (1) ►  February (1) ▼  2013 (4) ▼  July (1) Introduction to Python Functions ►  June (3) A Simple Python Quiz Program, Part 3 Tynker—Physics and Cloning Simple Python Calculator using a Dictionary and Fu... ►  2012 (2) ►  February (1) ►  January (1) ►  2011 (8) ►  November (1) ►  July (3) ►  May (1) ►  February (2) ►  January (1) ►  2010 (6) ►  October (2) ►  June (2) ►  February (2) ►  2009 (37) ►  December (4) ►  November (1) ►  September (7) ►  August (11) ►  July (14)   | 2026-01-13T09:30:35 |
https://docs.aws.amazon.com/es_es/AmazonCloudFront/latest/DeveloperGuide/lambda-examples.html#lambda-examples-a-b-testing | Funciones de ejemplo de Lambda@Edge - Amazon CloudFront Funciones de ejemplo de Lambda@Edge - Amazon CloudFront Documentación Amazon CloudFront Guía para desarrolladores Ejemplos generales Generación de respuestas: ejemplos Cadenas de consulta: ejemplos Personalización de contenido por encabezados de tipo de dispositivo o país: ejemplos Selección de origen dinámico basada en contenido: ejemplos Actualización de estados de error: ejemplos Acceso al cuerpo de la solicitud: ejemplos Funciones de ejemplo de Lambda@Edge Consulte los ejemplos siguientes para usar funciones de Lambda con Amazon CloudFront. nota Si elige el tiempo de ejecución Node.js 18 o una versión posterior para la función Lambda@Edge, se creará automáticamente un archivo index.mjs . Para usar los siguientes ejemplos de código, cambie el nombre del archivo index.mjs a index.js . Temas Ejemplos generales Generación de respuestas: ejemplos Cadenas de consulta: ejemplos Personalización de contenido por encabezados de tipo de dispositivo o país: ejemplos Selección de origen dinámico basada en contenido: ejemplos Actualización de estados de error: ejemplos Acceso al cuerpo de la solicitud: ejemplos Ejemplos generales Los ejemplos siguientes muestran formas habituales de usar Lambda@Edge en CloudFront. Temas Ejemplo: prueba A/B Ejemplo: Sobrescritura de un encabezado de respuesta Ejemplo: prueba A/B Puede utilizar el siguiente ejemplo para probar dos versiones diferentes de una imagen sin crear redirecciones ni cambiar la dirección URL. En este ejemplo se leen las cookies de la solicitud del lector y se modifica la URL de la solicitud en consecuencia. Si el espectador no envía una cookie con uno de los valores esperados, el ejemplo asigna aleatoriamente al espectador una de las URL. 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; } 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; } } 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" ''' experimentUri = "" 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 Ejemplo: Sobrescritura de un encabezado de respuesta En el ejemplo siguiente, se muestra cómo cambiar el valor de un encabezado de respuesta según el valor de otro encabezado. Node.js export const handler = async (event) => { 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()] = [ { key: headerNameDst, value: headers[headerNameSrc.toLowerCase()][0].value, }]; console.log(`Response header "$ { headerNameDst}" was set to ` + `"$ { headers[headerNameDst.toLowerCase()][0].value}"`); } return response; }; Python import json def lambda_handler(event, context): response = event['Records'][0]['cf']['response'] headers = response['headers'] header_name_src = 'X-Amz-Meta-Last-Modified' header_name_dst = 'Last-Modified' if headers.get(header_name_src.lower()): headers[header_name_dst.lower()] = [ { 'key': header_name_dst, 'value': headers[header_name_src.lower()][0]['value'] }] print(f'Response header " { header_name_dst}" was set to ' f'" { headers[header_name_dst.lower()][0]["value"]}"') return response Generación de respuestas: ejemplos En los ejemplos siguientes se muestra cómo puede usar Lambda@Edge para generar respuestas. Temas Ejemplo: Envío de contenido estático (respuesta generada) Ejemplo: Generación de un redireccionamiento HTTP (respuesta generada) Ejemplo: Envío de contenido estático (respuesta generada) En el siguiente ejemplo se muestra cómo utilizar una función de Lambda para enviar contenido de sitio web estático, lo que reduce la carga en el servidor de origen y la latencia total. nota Puede generar respuestas HTTP para los eventos de solicitud del espectador y al origen. Para obtener más información, consulte Generación de respuestas HTTP en los desencadenadores de solicitud . También puede sustituir o quitar el cuerpo de la respuesta HTTP en eventos de respuesta de origen. Para obtener más información, consulte Actualización de respuestas HTTP en desencadenadores de respuesta de origen . 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' }] }, 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 } return response Ejemplo: Generación de un redireccionamiento HTTP (respuesta generada) En el siguiente ejemplo se muestra cómo generar una redirección HTTP. nota Puede generar respuestas HTTP para los eventos de solicitud del espectador y al origen. Para obtener más información, consulte Generación de respuestas HTTP en los desencadenadores de solicitud . 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. response = { 'status': '302', 'statusDescription': 'Found', 'headers': { 'location': [ { 'key': 'Location', 'value': 'https://docs.aws.amazon.com/lambda/latest/dg/lambda-edge.html' }] } } return response Cadenas de consulta: ejemplos En los ejemplos siguientes se muestran formas de usar Lambda@Edge con cadenas de consulta. Temas Ejemplo: Adición de un encabezado en función de un parámetro de la cadena de consulta Ejemplo: Normalización de parámetros de cadenas de consulta para mejorar la tasa de aciertos de caché Ejemplo: Redireccionamiento de los usuarios no autenticados a una página de inicio de sesión Ejemplo: Adición de un encabezado en función de un parámetro de la cadena de consulta El siguiente ejemplo muestra cómo obtener el par clave-valor de un parámetro de la cadena de consulta y, a continuación, añadir un encabezado en función de dichos valores. 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. * 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 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'] # Update request querystring request['querystring'] = urlencode(params) return request Ejemplo: Normalización de parámetros de cadenas de consulta para mejorar la tasa de aciertos de caché El siguiente ejemplo muestra cómo mejorar la tasa de acceso a la caché haciendo los siguientes cambios en las cadenas de consulta antes de que CloudFront reenvíe las solicitudes a su origen: Alfabetizar los pares de clave-valor por el nombre del parámetro. Cambiar a minúsculas el modelo de mayúsculas y minúsculas de los pares de clave-valor. Para obtener más información, consulte Almacenamiento en caché de contenido en función de parámetros de cadenas de consulta . 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 */ 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 request['querystring'] = urlencode(sortedParams) return request Ejemplo: Redireccionamiento de los usuarios no autenticados a una página de inicio de sesión El siguiente ejemplo muestra cómo redirigir a los usuarios una página de inicio de sesión si no ha introducido sus credenciales. 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; } /* 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 params. ''' # Check for session-id in cookie, if present, then proceed with request parsedCookies = parseCookies(headers) 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 Personalización de contenido por encabezados de tipo de dispositivo o país: ejemplos En los ejemplos siguientes se muestra cómo puede usar Lambda@Edge para personalizar el comportamiento en función de la ubicación o el tipo de dispositivo que usa el lector. Temas Ejemplo: Redireccionamiento de solicitudes de espectadores a una URL específica de un país Ejemplo: Envío de distintas versiones de un objeto en función del dispositivo Ejemplo: Redireccionamiento de solicitudes de espectadores a una URL específica de un país El siguiente ejemplo muestra cómo generar una respuesta de redireccionamiento HTTP con una URL específica del país y devolver la respuesta al espectador. Esto resulta útil cuando se quiere proporcionar respuestas específicas del país. Por ejemplo: Si tiene subdominios específicos de un país, como us.ejemplo.com y tw.ejemplo.com, puede generar una respuesta de redireccionamiento cuando un espectador solicite ejemplo.com. Si está haciendo streaming de video, pero no tiene derechos para transmitir el contenido en un país determinado, puede redirigir a los usuarios de dicho país a una página en la que se explica por qué no pueden ver el video. Tenga en cuenta lo siguiente: Debe configurar la distribución para almacenar en la caché en función del encabezado CloudFront-Viewer-Country . Para obtener más información, consulte Caché en función de encabezados de solicitud seleccionados . CloudFront agrega el encabezado CloudFront-Viewer-Country después del evento de solicitud del lector. Para utilizar este ejemplo, debe crear un activador para el evento de solicitud al origen. 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 = { 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', 'statusDescription': 'Found', 'headers': { 'location': [ { 'key': 'Location', 'value': url }] } } return response Ejemplo: Envío de distintas versiones de un objeto en función del dispositivo El siguiente ejemplo muestra cómo ofrecer distintas versiones de un objeto en función del tipo de dispositivo que el usuario está utilizando; por ejemplo, un dispositivo móvil o una tablet. Tenga en cuenta lo siguiente: Debe configurar la distribución para almacenar en la caché en función de los encabezados CloudFront-Is-*-Viewer . Para obtener más información, consulte Caché en función de encabezados de solicitud seleccionados . CloudFront agrega los encabezados CloudFront-Is-*-Viewer después del evento de solicitud del lector. Para utilizar este ejemplo, debe crear un activador para el evento de solicitud al origen. 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 * 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. ''' desktopPath = '/desktop'; mobilePath = '/mobile'; tabletPath = '/tablet'; smarttvPath = '/smarttv'; 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 Selección de origen dinámico basada en contenido: ejemplos En los ejemplos siguientes se muestra cómo puede usar Lambda@Edge para el direccionamiento a diferentes orígenes en función de la información de la solicitud. Temas Ejemplo: Uso de un desencadenador de solicitud de origen para cambiar desde un origen personalizado a un origen de Amazon S3 Ejemplo: Uso de un desencadenador de solicitud de origen para cambiar la región de origen de Amazon S3 Ejemplo: Uso de un desencadenador de solicitud de origen para cambiar desde un origen de Amazon S3 a un origen personalizado Ejemplo: Uso de un desencadenador de solicitud al origen para transferir gradualmente el tráfico desde un bucket de Amazon S3 a otro Ejemplo: Uso de un desencadenador de solicitud de origen para cambiar el nombre del dominio de origen en función del encabezado de país Ejemplo: Uso de un desencadenador de solicitud de origen para cambiar desde un origen personalizado a un origen de Amazon S3 Esta función demuestra cómo utilizar un desencadenador de solicitud al origen para cambiar desde un origen personalizado a un origen de Amazon S3 desde el que recuperar el contenido, en función de las propiedades de la solicitud. 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: 'origin-access-identity', path: '', customHeaders: { } } }; request.headers['host'] = [ { key: 'host', value: s3DomainName}]; } } 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 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': 'origin-access-identity', 'path': '', 'customHeaders': { } } } request['headers']['host'] = [ { 'key': 'host', 'value': s3DomainName}] return request Ejemplo: Uso de un desencadenador de solicitud de origen para cambiar la región de origen de Amazon S3 Esta función demuestra cómo utilizar un desencadenador de solicitud al origen para cambiar el origen de Amazon S3 desde el que se recupera el contenido, en función de las propiedades de la solicitud. En este ejemplo, utilizamos el valor del encabezado CloudFront-Viewer-Country para actualizar el nombre de dominio del bucket de S3 por un bucket de una región que está más cerca del lector. Esto puede resultar útil de varias maneras: Reduce las latencias cuando la región especificada está más cerca del país del lector. Proporciona soberanía de los datos, al asegurarse de que los datos se distribuyen desde un origen que está en el país del que provino la solicitud. Para utilizar este ejemplo, debe hacer lo siguiente: Configure la distribución para almacenar en la caché en función del encabezado CloudFront-Viewer-Country . Para obtener más información, consulte Caché en función de encabezados de solicitud seleccionados . Crear un disparador para esta función en el evento de solicitud al origen. CloudFront agrega el encabezado CloudFront-Viewer-Country después del evento de solicitud del lector; por lo tanto, para utilizar este ejemplo, debe asegurarse de que la función ejecuta una solicitud de origen. nota El siguiente código de ejemplo usa la misma identidad de acceso de origen (OAI) para todos los buckets de S3 que usa para el origen. Para obtener más información, consulte Identidad de acceso de origen . 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 * 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); }; Python 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: 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: ''' 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 Ejemplo: Uso de un desencadenador de solicitud de origen para cambiar desde un origen de Amazon S3 a un origen personalizado Esta función demuestra cómo utilizar un disparador de solicitud al origen para cambiar el origen personalizado desde el que se recupera el contenido, en función de las propiedades de la solicitud. 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: { 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': { } } } request['headers']['host'] = [ { 'key': 'host', 'value': 'www.example.com'}] return request Ejemplo: Uso de un desencadenador de solicitud al origen para transferir gradualmente el tráfico desde un bucket de Amazon S3 a otro Esta función demuestra cómo transferir gradualmente el tráfico desde un bucket de Amazon S3 a otro de forma controlada. 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}]; } 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 Ejemplo: Uso de un desencadenador de solicitud de origen para cambiar el nombre del dominio de origen en función del encabezado de país Esta función demuestra cómo cambiar el nombre del dominio de origen en función del encabezado CloudFront-Viewer-Country , de forma que el contenido se distribuya desde un origen más cercano al país del lector. La implementación de esta funcionalidad para su distribución puede tener ventajas como las siguientes: Reducir las latencias cuando la región especificada está más cerca del país del lector Proporcionar soberanía de los datos, al asegurarse de que los datos se distribuyen desde un origen que está en el país del que provino la solicitud Tenga en cuenta que para habilitar esta funcionalidad, debe configurar su distribución para almacenar en la caché en función del encabezado CloudFront-Viewer-Country . Para obtener más información, consulte Caché en función de encabezados de solicitud seleccionados . 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 request['headers']['host'] = [ { 'key': 'host', 'value': domainName}] return request Actualización de estados de error: ejemplos En los ejemplos siguientes se proporciona orientación acerca de cómo puede usar Lambda@Edge para cambiar el estado de error que se devuelve a los usuarios. Temas Ejemplo: Uso de un desencadenador de respuesta de origen para actualizar el código de estado de error a 200 Ejemplo: Uso de un desencadenador de respuesta de origen para actualizar el código de estado de error a 302 Ejemplo: Uso de un desencadenador de respuesta de origen para actualizar el código de estado de error a 200 Esta función demuestra cómo actualizar el estado de la respuesta a 200 y generar un cuerpo con contenido estático para devolverlo al espectador en la siguiente situación: La función se desencadena en una respuesta del origen. El estado de la respuesta del servidor de origen es un código de estado de error (4xx o 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'; } callback(null, response); }; Python 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 Ejemplo: Uso de un desencadenador de respuesta de origen para actualizar el código de estado de error a 302 Esta función demuestra cómo actualizar el código de estado HTTP a 302 para la redirección a otra ruta (comportamiento de la caché) en la que se ha configurado un origen diferente. Tenga en cuenta lo siguiente: La función se desencadena en una respuesta del origen. El estado de la respuesta del servidor de origen es un código de estado de error (4xx o 5xx). Node.js 'use strict'; exports.handler = (event, context, callback) => { const response = event.Records[0].cf.response; const 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 (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 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 Acceso al cuerpo de la solicitud: ejemplos En los ejemplos siguientes se muestra cómo puede usar Lambda@Edge para trabajar con las solicitudes POST. nota Para utilizar estos ejemplos, debe habilitar la opción incluir cuerpo en la asociación de funciones Lambda de la distribución. No está habilitada de forma predeterminada. Para habilitar esta configuración en la consola de CloudFront, seleccione la casilla de verificación Incluir cuerpo en la Asociación de funciones Lambda . Para habilitar esta configuración en la API de CloudFront o con CloudFormation, establezca el campo IncludeBody en true en LambdaFunctionAssociation . Temas Ejemplo: Uso de un desencadenador de solicitud para leer un formulario HTML Ejemplo: Uso de un desencadenador de solicitud para modificar un formulario HTML Ejemplo: Uso de un desencadenador de solicitud para leer un formulario HTML Esta función ilustra cómo puede procesar el cuerpo de una solicitud POST generada por un formulario HTML (formulario web), como por ejemplo un formulario tipo "póngase en contacto con nosotros". Por ejemplo, es posible que tenga un formulario HTML como el siguiente: <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> Para la función de ejemplo que se indica a continuación, la función se debe desencadenar en una solicitud al origen o del lector de CloudFront. 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 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 Ejemplo: Uso de un desencadenador de solicitud para modificar un formulario HTML Esta función ilustra cómo puede modificar el cuerpo de una solicitud POST generada por un formulario HTML (formulario web). La función se activa en una solicitud al origen o del lector de CloudFront. 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. * * 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'] | 2026-01-13T09:30:35 |
https://young-programmers.blogspot.com/2009/07/random-number-problems-and-python.html | Young Programmers Podcast: Random Number Problems and Python Solutions skip to main | skip to sidebar Young Programmers Podcast A video podcast for computer programmers in grades 3 and up. We learn about Scratch, Tynker, Alice, Python, Pygame, and Scala, and interview interesting programmers. From professional software developer and teacher Dave Briccetti, and many special guests. Viewing the Videos or Subscribing to the Podcast Some of the entries have a picture, which you can click to access the video. Otherwise, to see the videos, use this icon to subscribe to or view the feed: Or, subscribe in iTunes Sunday, July 19, 2009 Random Number Problems and Python Solutions The solutions to these problems are shown: Produce one or more random integers in the range -5,5 Randomly choose from a sequence like ('Sam', 'Sue', 'Bill') Randomly choose a number between 1 and 3. Ask the user for a guess. Tell the user if the guess is right. Display the result of rolling two six-sided dice Use randint or choice to add an element of randomness to a program of your own design at 1:17 PM Labels: python , random Newer Post Older Post Home About Me Dave Briccetti View my complete profile Where to Get Software Kojo Python Alice Scratch Other Blogs Dave Briccetti’s Blog One of My Best Classes Ever 10 years ago Tags alice (3) Android (1) arduino (1) art (1) audacity (2) dictionary (2) Flickr (1) functions (2) gamedev (1) garageband (1) GIMP (2) Google (2) guest (4) hacker (1) higher-order functions (1) inkscape (1) interview (9) Java (2) JavaFX (2) Jython (3) Kojo (2) lift (1) music (2) physics (1) platform (1) programmer (4) pygame (6) python (31) PythonCard (1) random (6) Sande (2) Scala (5) scratch (10) shdh (2) shdh34 (2) sound (3) sprite (2) Swing (3) teaching (3) twitter (2) Tynker (1) Web Services (1) xturtle (1) Followers Blog Archive ►  2015 (1) ►  February (1) ►  2013 (4) ►  July (1) ►  June (3) ►  2012 (2) ►  February (1) ►  January (1) ►  2011 (8) ►  November (1) ►  July (3) ►  May (1) ►  February (2) ►  January (1) ►  2010 (6) ►  October (2) ►  June (2) ►  February (2) ▼  2009 (37) ►  December (4) ►  November (1) ►  September (7) ►  August (11) ▼  July (14) Tor Norbye Shows JavaFX Recording Music for Computer Games Adding a Second Sprite to SimplePygame (Challenge 4) Solutions to SimplePygame Challenges 1–3 Xturtle With Loops to Make Polygons An Alice Object Reacts to Another Using GIMP to Make Graphics for Scratch and Alice Twitter’s Doug Williams Visits My Programming Class Random Number Problems and Python Solutions Random Numbers in Python: randint and choice Three Simple Python Problems and Their Solutions Power-Up and Shield Making Scratch Graphics with Inkscape Overview of Scratch, Alice, Python and Pygame   | 2026-01-13T09:30:35 |
https://young-programmers.blogspot.com/2011/07/carter-sande-teaches-python-functions.html#main | Young Programmers Podcast: Carter Sande Teaches Python Functions skip to main | skip to sidebar Young Programmers Podcast A video podcast for computer programmers in grades 3 and up. We learn about Scratch, Tynker, Alice, Python, Pygame, and Scala, and interview interesting programmers. From professional software developer and teacher Dave Briccetti, and many special guests. Viewing the Videos or Subscribing to the Podcast Some of the entries have a picture, which you can click to access the video. Otherwise, to see the videos, use this icon to subscribe to or view the feed: Or, subscribe in iTunes Tuesday, July 5, 2011 Carter Sande Teaches Python Functions Carter Sande teaches how to use functions to a class at Diablo Valley College College for Kids. A couple of notes on this excellent presentation: At one point Carter says “brackets” when he means parentheses. And for style, I prefer spaces around operators, and whitespace around functions. at 11:49 AM Labels: python Newer Post Older Post Home About Me Dave Briccetti View my complete profile Where to Get Software Kojo Python Alice Scratch Other Blogs Dave Briccetti’s Blog One of My Best Classes Ever 10 years ago Tags alice (3) Android (1) arduino (1) art (1) audacity (2) dictionary (2) Flickr (1) functions (2) gamedev (1) garageband (1) GIMP (2) Google (2) guest (4) hacker (1) higher-order functions (1) inkscape (1) interview (9) Java (2) JavaFX (2) Jython (3) Kojo (2) lift (1) music (2) physics (1) platform (1) programmer (4) pygame (6) python (31) PythonCard (1) random (6) Sande (2) Scala (5) scratch (10) shdh (2) shdh34 (2) sound (3) sprite (2) Swing (3) teaching (3) twitter (2) Tynker (1) Web Services (1) xturtle (1) Followers Blog Archive ►  2015 (1) ►  February (1) ►  2013 (4) ►  July (1) ►  June (3) ►  2012 (2) ►  February (1) ►  January (1) ▼  2011 (8) ►  November (1) ▼  July (3) Demonstration of Audacity for Making Sound Effects Carter Sande Teaches Python Functions Python Simple Text Adventure 3 ►  May (1) ►  February (2) ►  January (1) ►  2010 (6) ►  October (2) ►  June (2) ►  February (2) ►  2009 (37) ►  December (4) ►  November (1) ►  September (7) ►  August (11) ►  July (14)   | 2026-01-13T09:30:35 |
https://docs.aws.amazon.com/es_es/AmazonCloudFront/latest/DeveloperGuide/lambda-examples.html#lambda-examples-header-based-on-query-string | Funciones de ejemplo de Lambda@Edge - Amazon CloudFront Funciones de ejemplo de Lambda@Edge - Amazon CloudFront Documentación Amazon CloudFront Guía para desarrolladores Ejemplos generales Generación de respuestas: ejemplos Cadenas de consulta: ejemplos Personalización de contenido por encabezados de tipo de dispositivo o país: ejemplos Selección de origen dinámico basada en contenido: ejemplos Actualización de estados de error: ejemplos Acceso al cuerpo de la solicitud: ejemplos Funciones de ejemplo de Lambda@Edge Consulte los ejemplos siguientes para usar funciones de Lambda con Amazon CloudFront. nota Si elige el tiempo de ejecución Node.js 18 o una versión posterior para la función Lambda@Edge, se creará automáticamente un archivo index.mjs . Para usar los siguientes ejemplos de código, cambie el nombre del archivo index.mjs a index.js . Temas Ejemplos generales Generación de respuestas: ejemplos Cadenas de consulta: ejemplos Personalización de contenido por encabezados de tipo de dispositivo o país: ejemplos Selección de origen dinámico basada en contenido: ejemplos Actualización de estados de error: ejemplos Acceso al cuerpo de la solicitud: ejemplos Ejemplos generales Los ejemplos siguientes muestran formas habituales de usar Lambda@Edge en CloudFront. Temas Ejemplo: prueba A/B Ejemplo: Sobrescritura de un encabezado de respuesta Ejemplo: prueba A/B Puede utilizar el siguiente ejemplo para probar dos versiones diferentes de una imagen sin crear redirecciones ni cambiar la dirección URL. En este ejemplo se leen las cookies de la solicitud del lector y se modifica la URL de la solicitud en consecuencia. Si el espectador no envía una cookie con uno de los valores esperados, el ejemplo asigna aleatoriamente al espectador una de las URL. 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; } 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; } } 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" ''' experimentUri = "" 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 Ejemplo: Sobrescritura de un encabezado de respuesta En el ejemplo siguiente, se muestra cómo cambiar el valor de un encabezado de respuesta según el valor de otro encabezado. Node.js export const handler = async (event) => { 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()] = [ { key: headerNameDst, value: headers[headerNameSrc.toLowerCase()][0].value, }]; console.log(`Response header "$ { headerNameDst}" was set to ` + `"$ { headers[headerNameDst.toLowerCase()][0].value}"`); } return response; }; Python import json def lambda_handler(event, context): response = event['Records'][0]['cf']['response'] headers = response['headers'] header_name_src = 'X-Amz-Meta-Last-Modified' header_name_dst = 'Last-Modified' if headers.get(header_name_src.lower()): headers[header_name_dst.lower()] = [ { 'key': header_name_dst, 'value': headers[header_name_src.lower()][0]['value'] }] print(f'Response header " { header_name_dst}" was set to ' f'" { headers[header_name_dst.lower()][0]["value"]}"') return response Generación de respuestas: ejemplos En los ejemplos siguientes se muestra cómo puede usar Lambda@Edge para generar respuestas. Temas Ejemplo: Envío de contenido estático (respuesta generada) Ejemplo: Generación de un redireccionamiento HTTP (respuesta generada) Ejemplo: Envío de contenido estático (respuesta generada) En el siguiente ejemplo se muestra cómo utilizar una función de Lambda para enviar contenido de sitio web estático, lo que reduce la carga en el servidor de origen y la latencia total. nota Puede generar respuestas HTTP para los eventos de solicitud del espectador y al origen. Para obtener más información, consulte Generación de respuestas HTTP en los desencadenadores de solicitud . También puede sustituir o quitar el cuerpo de la respuesta HTTP en eventos de respuesta de origen. Para obtener más información, consulte Actualización de respuestas HTTP en desencadenadores de respuesta de origen . 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' }] }, 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 } return response Ejemplo: Generación de un redireccionamiento HTTP (respuesta generada) En el siguiente ejemplo se muestra cómo generar una redirección HTTP. nota Puede generar respuestas HTTP para los eventos de solicitud del espectador y al origen. Para obtener más información, consulte Generación de respuestas HTTP en los desencadenadores de solicitud . 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. response = { 'status': '302', 'statusDescription': 'Found', 'headers': { 'location': [ { 'key': 'Location', 'value': 'https://docs.aws.amazon.com/lambda/latest/dg/lambda-edge.html' }] } } return response Cadenas de consulta: ejemplos En los ejemplos siguientes se muestran formas de usar Lambda@Edge con cadenas de consulta. Temas Ejemplo: Adición de un encabezado en función de un parámetro de la cadena de consulta Ejemplo: Normalización de parámetros de cadenas de consulta para mejorar la tasa de aciertos de caché Ejemplo: Redireccionamiento de los usuarios no autenticados a una página de inicio de sesión Ejemplo: Adición de un encabezado en función de un parámetro de la cadena de consulta El siguiente ejemplo muestra cómo obtener el par clave-valor de un parámetro de la cadena de consulta y, a continuación, añadir un encabezado en función de dichos valores. 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. * 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 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'] # Update request querystring request['querystring'] = urlencode(params) return request Ejemplo: Normalización de parámetros de cadenas de consulta para mejorar la tasa de aciertos de caché El siguiente ejemplo muestra cómo mejorar la tasa de acceso a la caché haciendo los siguientes cambios en las cadenas de consulta antes de que CloudFront reenvíe las solicitudes a su origen: Alfabetizar los pares de clave-valor por el nombre del parámetro. Cambiar a minúsculas el modelo de mayúsculas y minúsculas de los pares de clave-valor. Para obtener más información, consulte Almacenamiento en caché de contenido en función de parámetros de cadenas de consulta . 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 */ 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 request['querystring'] = urlencode(sortedParams) return request Ejemplo: Redireccionamiento de los usuarios no autenticados a una página de inicio de sesión El siguiente ejemplo muestra cómo redirigir a los usuarios una página de inicio de sesión si no ha introducido sus credenciales. 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; } /* 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 params. ''' # Check for session-id in cookie, if present, then proceed with request parsedCookies = parseCookies(headers) 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 Personalización de contenido por encabezados de tipo de dispositivo o país: ejemplos En los ejemplos siguientes se muestra cómo puede usar Lambda@Edge para personalizar el comportamiento en función de la ubicación o el tipo de dispositivo que usa el lector. Temas Ejemplo: Redireccionamiento de solicitudes de espectadores a una URL específica de un país Ejemplo: Envío de distintas versiones de un objeto en función del dispositivo Ejemplo: Redireccionamiento de solicitudes de espectadores a una URL específica de un país El siguiente ejemplo muestra cómo generar una respuesta de redireccionamiento HTTP con una URL específica del país y devolver la respuesta al espectador. Esto resulta útil cuando se quiere proporcionar respuestas específicas del país. Por ejemplo: Si tiene subdominios específicos de un país, como us.ejemplo.com y tw.ejemplo.com, puede generar una respuesta de redireccionamiento cuando un espectador solicite ejemplo.com. Si está haciendo streaming de video, pero no tiene derechos para transmitir el contenido en un país determinado, puede redirigir a los usuarios de dicho país a una página en la que se explica por qué no pueden ver el video. Tenga en cuenta lo siguiente: Debe configurar la distribución para almacenar en la caché en función del encabezado CloudFront-Viewer-Country . Para obtener más información, consulte Caché en función de encabezados de solicitud seleccionados . CloudFront agrega el encabezado CloudFront-Viewer-Country después del evento de solicitud del lector. Para utilizar este ejemplo, debe crear un activador para el evento de solicitud al origen. 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 = { 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', 'statusDescription': 'Found', 'headers': { 'location': [ { 'key': 'Location', 'value': url }] } } return response Ejemplo: Envío de distintas versiones de un objeto en función del dispositivo El siguiente ejemplo muestra cómo ofrecer distintas versiones de un objeto en función del tipo de dispositivo que el usuario está utilizando; por ejemplo, un dispositivo móvil o una tablet. Tenga en cuenta lo siguiente: Debe configurar la distribución para almacenar en la caché en función de los encabezados CloudFront-Is-*-Viewer . Para obtener más información, consulte Caché en función de encabezados de solicitud seleccionados . CloudFront agrega los encabezados CloudFront-Is-*-Viewer después del evento de solicitud del lector. Para utilizar este ejemplo, debe crear un activador para el evento de solicitud al origen. 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 * 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. ''' desktopPath = '/desktop'; mobilePath = '/mobile'; tabletPath = '/tablet'; smarttvPath = '/smarttv'; 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 Selección de origen dinámico basada en contenido: ejemplos En los ejemplos siguientes se muestra cómo puede usar Lambda@Edge para el direccionamiento a diferentes orígenes en función de la información de la solicitud. Temas Ejemplo: Uso de un desencadenador de solicitud de origen para cambiar desde un origen personalizado a un origen de Amazon S3 Ejemplo: Uso de un desencadenador de solicitud de origen para cambiar la región de origen de Amazon S3 Ejemplo: Uso de un desencadenador de solicitud de origen para cambiar desde un origen de Amazon S3 a un origen personalizado Ejemplo: Uso de un desencadenador de solicitud al origen para transferir gradualmente el tráfico desde un bucket de Amazon S3 a otro Ejemplo: Uso de un desencadenador de solicitud de origen para cambiar el nombre del dominio de origen en función del encabezado de país Ejemplo: Uso de un desencadenador de solicitud de origen para cambiar desde un origen personalizado a un origen de Amazon S3 Esta función demuestra cómo utilizar un desencadenador de solicitud al origen para cambiar desde un origen personalizado a un origen de Amazon S3 desde el que recuperar el contenido, en función de las propiedades de la solicitud. 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: 'origin-access-identity', path: '', customHeaders: { } } }; request.headers['host'] = [ { key: 'host', value: s3DomainName}]; } } 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 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': 'origin-access-identity', 'path': '', 'customHeaders': { } } } request['headers']['host'] = [ { 'key': 'host', 'value': s3DomainName}] return request Ejemplo: Uso de un desencadenador de solicitud de origen para cambiar la región de origen de Amazon S3 Esta función demuestra cómo utilizar un desencadenador de solicitud al origen para cambiar el origen de Amazon S3 desde el que se recupera el contenido, en función de las propiedades de la solicitud. En este ejemplo, utilizamos el valor del encabezado CloudFront-Viewer-Country para actualizar el nombre de dominio del bucket de S3 por un bucket de una región que está más cerca del lector. Esto puede resultar útil de varias maneras: Reduce las latencias cuando la región especificada está más cerca del país del lector. Proporciona soberanía de los datos, al asegurarse de que los datos se distribuyen desde un origen que está en el país del que provino la solicitud. Para utilizar este ejemplo, debe hacer lo siguiente: Configure la distribución para almacenar en la caché en función del encabezado CloudFront-Viewer-Country . Para obtener más información, consulte Caché en función de encabezados de solicitud seleccionados . Crear un disparador para esta función en el evento de solicitud al origen. CloudFront agrega el encabezado CloudFront-Viewer-Country después del evento de solicitud del lector; por lo tanto, para utilizar este ejemplo, debe asegurarse de que la función ejecuta una solicitud de origen. nota El siguiente código de ejemplo usa la misma identidad de acceso de origen (OAI) para todos los buckets de S3 que usa para el origen. Para obtener más información, consulte Identidad de acceso de origen . 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 * 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); }; Python 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: 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: ''' 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 Ejemplo: Uso de un desencadenador de solicitud de origen para cambiar desde un origen de Amazon S3 a un origen personalizado Esta función demuestra cómo utilizar un disparador de solicitud al origen para cambiar el origen personalizado desde el que se recupera el contenido, en función de las propiedades de la solicitud. 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: { 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': { } } } request['headers']['host'] = [ { 'key': 'host', 'value': 'www.example.com'}] return request Ejemplo: Uso de un desencadenador de solicitud al origen para transferir gradualmente el tráfico desde un bucket de Amazon S3 a otro Esta función demuestra cómo transferir gradualmente el tráfico desde un bucket de Amazon S3 a otro de forma controlada. 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}]; } 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 Ejemplo: Uso de un desencadenador de solicitud de origen para cambiar el nombre del dominio de origen en función del encabezado de país Esta función demuestra cómo cambiar el nombre del dominio de origen en función del encabezado CloudFront-Viewer-Country , de forma que el contenido se distribuya desde un origen más cercano al país del lector. La implementación de esta funcionalidad para su distribución puede tener ventajas como las siguientes: Reducir las latencias cuando la región especificada está más cerca del país del lector Proporcionar soberanía de los datos, al asegurarse de que los datos se distribuyen desde un origen que está en el país del que provino la solicitud Tenga en cuenta que para habilitar esta funcionalidad, debe configurar su distribución para almacenar en la caché en función del encabezado CloudFront-Viewer-Country . Para obtener más información, consulte Caché en función de encabezados de solicitud seleccionados . 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 request['headers']['host'] = [ { 'key': 'host', 'value': domainName}] return request Actualización de estados de error: ejemplos En los ejemplos siguientes se proporciona orientación acerca de cómo puede usar Lambda@Edge para cambiar el estado de error que se devuelve a los usuarios. Temas Ejemplo: Uso de un desencadenador de respuesta de origen para actualizar el código de estado de error a 200 Ejemplo: Uso de un desencadenador de respuesta de origen para actualizar el código de estado de error a 302 Ejemplo: Uso de un desencadenador de respuesta de origen para actualizar el código de estado de error a 200 Esta función demuestra cómo actualizar el estado de la respuesta a 200 y generar un cuerpo con contenido estático para devolverlo al espectador en la siguiente situación: La función se desencadena en una respuesta del origen. El estado de la respuesta del servidor de origen es un código de estado de error (4xx o 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'; } callback(null, response); }; Python 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 Ejemplo: Uso de un desencadenador de respuesta de origen para actualizar el código de estado de error a 302 Esta función demuestra cómo actualizar el código de estado HTTP a 302 para la redirección a otra ruta (comportamiento de la caché) en la que se ha configurado un origen diferente. Tenga en cuenta lo siguiente: La función se desencadena en una respuesta del origen. El estado de la respuesta del servidor de origen es un código de estado de error (4xx o 5xx). Node.js 'use strict'; exports.handler = (event, context, callback) => { const response = event.Records[0].cf.response; const 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 (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 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 Acceso al cuerpo de la solicitud: ejemplos En los ejemplos siguientes se muestra cómo puede usar Lambda@Edge para trabajar con las solicitudes POST. nota Para utilizar estos ejemplos, debe habilitar la opción incluir cuerpo en la asociación de funciones Lambda de la distribución. No está habilitada de forma predeterminada. Para habilitar esta configuración en la consola de CloudFront, seleccione la casilla de verificación Incluir cuerpo en la Asociación de funciones Lambda . Para habilitar esta configuración en la API de CloudFront o con CloudFormation, establezca el campo IncludeBody en true en LambdaFunctionAssociation . Temas Ejemplo: Uso de un desencadenador de solicitud para leer un formulario HTML Ejemplo: Uso de un desencadenador de solicitud para modificar un formulario HTML Ejemplo: Uso de un desencadenador de solicitud para leer un formulario HTML Esta función ilustra cómo puede procesar el cuerpo de una solicitud POST generada por un formulario HTML (formulario web), como por ejemplo un formulario tipo "póngase en contacto con nosotros". Por ejemplo, es posible que tenga un formulario HTML como el siguiente: <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> Para la función de ejemplo que se indica a continuación, la función se debe desencadenar en una solicitud al origen o del lector de CloudFront. 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 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 Ejemplo: Uso de un desencadenador de solicitud para modificar un formulario HTML Esta función ilustra cómo puede modificar el cuerpo de una solicitud POST generada por un formulario HTML (formulario web). La función se activa en una solicitud al origen o del lector de CloudFront. 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. * * 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'] | 2026-01-13T09:30:35 |
https://docs.aws.amazon.com/es_es/AmazonCloudFront/latest/DeveloperGuide/lambda-examples.html#lambda-examples-static-web-server | Funciones de ejemplo de Lambda@Edge - Amazon CloudFront Funciones de ejemplo de Lambda@Edge - Amazon CloudFront Documentación Amazon CloudFront Guía para desarrolladores Ejemplos generales Generación de respuestas: ejemplos Cadenas de consulta: ejemplos Personalización de contenido por encabezados de tipo de dispositivo o país: ejemplos Selección de origen dinámico basada en contenido: ejemplos Actualización de estados de error: ejemplos Acceso al cuerpo de la solicitud: ejemplos Funciones de ejemplo de Lambda@Edge Consulte los ejemplos siguientes para usar funciones de Lambda con Amazon CloudFront. nota Si elige el tiempo de ejecución Node.js 18 o una versión posterior para la función Lambda@Edge, se creará automáticamente un archivo index.mjs . Para usar los siguientes ejemplos de código, cambie el nombre del archivo index.mjs a index.js . Temas Ejemplos generales Generación de respuestas: ejemplos Cadenas de consulta: ejemplos Personalización de contenido por encabezados de tipo de dispositivo o país: ejemplos Selección de origen dinámico basada en contenido: ejemplos Actualización de estados de error: ejemplos Acceso al cuerpo de la solicitud: ejemplos Ejemplos generales Los ejemplos siguientes muestran formas habituales de usar Lambda@Edge en CloudFront. Temas Ejemplo: prueba A/B Ejemplo: Sobrescritura de un encabezado de respuesta Ejemplo: prueba A/B Puede utilizar el siguiente ejemplo para probar dos versiones diferentes de una imagen sin crear redirecciones ni cambiar la dirección URL. En este ejemplo se leen las cookies de la solicitud del lector y se modifica la URL de la solicitud en consecuencia. Si el espectador no envía una cookie con uno de los valores esperados, el ejemplo asigna aleatoriamente al espectador una de las URL. 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; } 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; } } 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" ''' experimentUri = "" 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 Ejemplo: Sobrescritura de un encabezado de respuesta En el ejemplo siguiente, se muestra cómo cambiar el valor de un encabezado de respuesta según el valor de otro encabezado. Node.js export const handler = async (event) => { 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()] = [ { key: headerNameDst, value: headers[headerNameSrc.toLowerCase()][0].value, }]; console.log(`Response header "$ { headerNameDst}" was set to ` + `"$ { headers[headerNameDst.toLowerCase()][0].value}"`); } return response; }; Python import json def lambda_handler(event, context): response = event['Records'][0]['cf']['response'] headers = response['headers'] header_name_src = 'X-Amz-Meta-Last-Modified' header_name_dst = 'Last-Modified' if headers.get(header_name_src.lower()): headers[header_name_dst.lower()] = [ { 'key': header_name_dst, 'value': headers[header_name_src.lower()][0]['value'] }] print(f'Response header " { header_name_dst}" was set to ' f'" { headers[header_name_dst.lower()][0]["value"]}"') return response Generación de respuestas: ejemplos En los ejemplos siguientes se muestra cómo puede usar Lambda@Edge para generar respuestas. Temas Ejemplo: Envío de contenido estático (respuesta generada) Ejemplo: Generación de un redireccionamiento HTTP (respuesta generada) Ejemplo: Envío de contenido estático (respuesta generada) En el siguiente ejemplo se muestra cómo utilizar una función de Lambda para enviar contenido de sitio web estático, lo que reduce la carga en el servidor de origen y la latencia total. nota Puede generar respuestas HTTP para los eventos de solicitud del espectador y al origen. Para obtener más información, consulte Generación de respuestas HTTP en los desencadenadores de solicitud . También puede sustituir o quitar el cuerpo de la respuesta HTTP en eventos de respuesta de origen. Para obtener más información, consulte Actualización de respuestas HTTP en desencadenadores de respuesta de origen . 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' }] }, 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 } return response Ejemplo: Generación de un redireccionamiento HTTP (respuesta generada) En el siguiente ejemplo se muestra cómo generar una redirección HTTP. nota Puede generar respuestas HTTP para los eventos de solicitud del espectador y al origen. Para obtener más información, consulte Generación de respuestas HTTP en los desencadenadores de solicitud . 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. response = { 'status': '302', 'statusDescription': 'Found', 'headers': { 'location': [ { 'key': 'Location', 'value': 'https://docs.aws.amazon.com/lambda/latest/dg/lambda-edge.html' }] } } return response Cadenas de consulta: ejemplos En los ejemplos siguientes se muestran formas de usar Lambda@Edge con cadenas de consulta. Temas Ejemplo: Adición de un encabezado en función de un parámetro de la cadena de consulta Ejemplo: Normalización de parámetros de cadenas de consulta para mejorar la tasa de aciertos de caché Ejemplo: Redireccionamiento de los usuarios no autenticados a una página de inicio de sesión Ejemplo: Adición de un encabezado en función de un parámetro de la cadena de consulta El siguiente ejemplo muestra cómo obtener el par clave-valor de un parámetro de la cadena de consulta y, a continuación, añadir un encabezado en función de dichos valores. 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. * 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 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'] # Update request querystring request['querystring'] = urlencode(params) return request Ejemplo: Normalización de parámetros de cadenas de consulta para mejorar la tasa de aciertos de caché El siguiente ejemplo muestra cómo mejorar la tasa de acceso a la caché haciendo los siguientes cambios en las cadenas de consulta antes de que CloudFront reenvíe las solicitudes a su origen: Alfabetizar los pares de clave-valor por el nombre del parámetro. Cambiar a minúsculas el modelo de mayúsculas y minúsculas de los pares de clave-valor. Para obtener más información, consulte Almacenamiento en caché de contenido en función de parámetros de cadenas de consulta . 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 */ 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 request['querystring'] = urlencode(sortedParams) return request Ejemplo: Redireccionamiento de los usuarios no autenticados a una página de inicio de sesión El siguiente ejemplo muestra cómo redirigir a los usuarios una página de inicio de sesión si no ha introducido sus credenciales. 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; } /* 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 params. ''' # Check for session-id in cookie, if present, then proceed with request parsedCookies = parseCookies(headers) 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 Personalización de contenido por encabezados de tipo de dispositivo o país: ejemplos En los ejemplos siguientes se muestra cómo puede usar Lambda@Edge para personalizar el comportamiento en función de la ubicación o el tipo de dispositivo que usa el lector. Temas Ejemplo: Redireccionamiento de solicitudes de espectadores a una URL específica de un país Ejemplo: Envío de distintas versiones de un objeto en función del dispositivo Ejemplo: Redireccionamiento de solicitudes de espectadores a una URL específica de un país El siguiente ejemplo muestra cómo generar una respuesta de redireccionamiento HTTP con una URL específica del país y devolver la respuesta al espectador. Esto resulta útil cuando se quiere proporcionar respuestas específicas del país. Por ejemplo: Si tiene subdominios específicos de un país, como us.ejemplo.com y tw.ejemplo.com, puede generar una respuesta de redireccionamiento cuando un espectador solicite ejemplo.com. Si está haciendo streaming de video, pero no tiene derechos para transmitir el contenido en un país determinado, puede redirigir a los usuarios de dicho país a una página en la que se explica por qué no pueden ver el video. Tenga en cuenta lo siguiente: Debe configurar la distribución para almacenar en la caché en función del encabezado CloudFront-Viewer-Country . Para obtener más información, consulte Caché en función de encabezados de solicitud seleccionados . CloudFront agrega el encabezado CloudFront-Viewer-Country después del evento de solicitud del lector. Para utilizar este ejemplo, debe crear un activador para el evento de solicitud al origen. 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 = { 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', 'statusDescription': 'Found', 'headers': { 'location': [ { 'key': 'Location', 'value': url }] } } return response Ejemplo: Envío de distintas versiones de un objeto en función del dispositivo El siguiente ejemplo muestra cómo ofrecer distintas versiones de un objeto en función del tipo de dispositivo que el usuario está utilizando; por ejemplo, un dispositivo móvil o una tablet. Tenga en cuenta lo siguiente: Debe configurar la distribución para almacenar en la caché en función de los encabezados CloudFront-Is-*-Viewer . Para obtener más información, consulte Caché en función de encabezados de solicitud seleccionados . CloudFront agrega los encabezados CloudFront-Is-*-Viewer después del evento de solicitud del lector. Para utilizar este ejemplo, debe crear un activador para el evento de solicitud al origen. 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 * 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. ''' desktopPath = '/desktop'; mobilePath = '/mobile'; tabletPath = '/tablet'; smarttvPath = '/smarttv'; 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 Selección de origen dinámico basada en contenido: ejemplos En los ejemplos siguientes se muestra cómo puede usar Lambda@Edge para el direccionamiento a diferentes orígenes en función de la información de la solicitud. Temas Ejemplo: Uso de un desencadenador de solicitud de origen para cambiar desde un origen personalizado a un origen de Amazon S3 Ejemplo: Uso de un desencadenador de solicitud de origen para cambiar la región de origen de Amazon S3 Ejemplo: Uso de un desencadenador de solicitud de origen para cambiar desde un origen de Amazon S3 a un origen personalizado Ejemplo: Uso de un desencadenador de solicitud al origen para transferir gradualmente el tráfico desde un bucket de Amazon S3 a otro Ejemplo: Uso de un desencadenador de solicitud de origen para cambiar el nombre del dominio de origen en función del encabezado de país Ejemplo: Uso de un desencadenador de solicitud de origen para cambiar desde un origen personalizado a un origen de Amazon S3 Esta función demuestra cómo utilizar un desencadenador de solicitud al origen para cambiar desde un origen personalizado a un origen de Amazon S3 desde el que recuperar el contenido, en función de las propiedades de la solicitud. 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: 'origin-access-identity', path: '', customHeaders: { } } }; request.headers['host'] = [ { key: 'host', value: s3DomainName}]; } } 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 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': 'origin-access-identity', 'path': '', 'customHeaders': { } } } request['headers']['host'] = [ { 'key': 'host', 'value': s3DomainName}] return request Ejemplo: Uso de un desencadenador de solicitud de origen para cambiar la región de origen de Amazon S3 Esta función demuestra cómo utilizar un desencadenador de solicitud al origen para cambiar el origen de Amazon S3 desde el que se recupera el contenido, en función de las propiedades de la solicitud. En este ejemplo, utilizamos el valor del encabezado CloudFront-Viewer-Country para actualizar el nombre de dominio del bucket de S3 por un bucket de una región que está más cerca del lector. Esto puede resultar útil de varias maneras: Reduce las latencias cuando la región especificada está más cerca del país del lector. Proporciona soberanía de los datos, al asegurarse de que los datos se distribuyen desde un origen que está en el país del que provino la solicitud. Para utilizar este ejemplo, debe hacer lo siguiente: Configure la distribución para almacenar en la caché en función del encabezado CloudFront-Viewer-Country . Para obtener más información, consulte Caché en función de encabezados de solicitud seleccionados . Crear un disparador para esta función en el evento de solicitud al origen. CloudFront agrega el encabezado CloudFront-Viewer-Country después del evento de solicitud del lector; por lo tanto, para utilizar este ejemplo, debe asegurarse de que la función ejecuta una solicitud de origen. nota El siguiente código de ejemplo usa la misma identidad de acceso de origen (OAI) para todos los buckets de S3 que usa para el origen. Para obtener más información, consulte Identidad de acceso de origen . 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 * 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); }; Python 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: 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: ''' 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 Ejemplo: Uso de un desencadenador de solicitud de origen para cambiar desde un origen de Amazon S3 a un origen personalizado Esta función demuestra cómo utilizar un disparador de solicitud al origen para cambiar el origen personalizado desde el que se recupera el contenido, en función de las propiedades de la solicitud. 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: { 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': { } } } request['headers']['host'] = [ { 'key': 'host', 'value': 'www.example.com'}] return request Ejemplo: Uso de un desencadenador de solicitud al origen para transferir gradualmente el tráfico desde un bucket de Amazon S3 a otro Esta función demuestra cómo transferir gradualmente el tráfico desde un bucket de Amazon S3 a otro de forma controlada. 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}]; } 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 Ejemplo: Uso de un desencadenador de solicitud de origen para cambiar el nombre del dominio de origen en función del encabezado de país Esta función demuestra cómo cambiar el nombre del dominio de origen en función del encabezado CloudFront-Viewer-Country , de forma que el contenido se distribuya desde un origen más cercano al país del lector. La implementación de esta funcionalidad para su distribución puede tener ventajas como las siguientes: Reducir las latencias cuando la región especificada está más cerca del país del lector Proporcionar soberanía de los datos, al asegurarse de que los datos se distribuyen desde un origen que está en el país del que provino la solicitud Tenga en cuenta que para habilitar esta funcionalidad, debe configurar su distribución para almacenar en la caché en función del encabezado CloudFront-Viewer-Country . Para obtener más información, consulte Caché en función de encabezados de solicitud seleccionados . 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 request['headers']['host'] = [ { 'key': 'host', 'value': domainName}] return request Actualización de estados de error: ejemplos En los ejemplos siguientes se proporciona orientación acerca de cómo puede usar Lambda@Edge para cambiar el estado de error que se devuelve a los usuarios. Temas Ejemplo: Uso de un desencadenador de respuesta de origen para actualizar el código de estado de error a 200 Ejemplo: Uso de un desencadenador de respuesta de origen para actualizar el código de estado de error a 302 Ejemplo: Uso de un desencadenador de respuesta de origen para actualizar el código de estado de error a 200 Esta función demuestra cómo actualizar el estado de la respuesta a 200 y generar un cuerpo con contenido estático para devolverlo al espectador en la siguiente situación: La función se desencadena en una respuesta del origen. El estado de la respuesta del servidor de origen es un código de estado de error (4xx o 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'; } callback(null, response); }; Python 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 Ejemplo: Uso de un desencadenador de respuesta de origen para actualizar el código de estado de error a 302 Esta función demuestra cómo actualizar el código de estado HTTP a 302 para la redirección a otra ruta (comportamiento de la caché) en la que se ha configurado un origen diferente. Tenga en cuenta lo siguiente: La función se desencadena en una respuesta del origen. El estado de la respuesta del servidor de origen es un código de estado de error (4xx o 5xx). Node.js 'use strict'; exports.handler = (event, context, callback) => { const response = event.Records[0].cf.response; const 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 (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 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 Acceso al cuerpo de la solicitud: ejemplos En los ejemplos siguientes se muestra cómo puede usar Lambda@Edge para trabajar con las solicitudes POST. nota Para utilizar estos ejemplos, debe habilitar la opción incluir cuerpo en la asociación de funciones Lambda de la distribución. No está habilitada de forma predeterminada. Para habilitar esta configuración en la consola de CloudFront, seleccione la casilla de verificación Incluir cuerpo en la Asociación de funciones Lambda . Para habilitar esta configuración en la API de CloudFront o con CloudFormation, establezca el campo IncludeBody en true en LambdaFunctionAssociation . Temas Ejemplo: Uso de un desencadenador de solicitud para leer un formulario HTML Ejemplo: Uso de un desencadenador de solicitud para modificar un formulario HTML Ejemplo: Uso de un desencadenador de solicitud para leer un formulario HTML Esta función ilustra cómo puede procesar el cuerpo de una solicitud POST generada por un formulario HTML (formulario web), como por ejemplo un formulario tipo "póngase en contacto con nosotros". Por ejemplo, es posible que tenga un formulario HTML como el siguiente: <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> Para la función de ejemplo que se indica a continuación, la función se debe desencadenar en una solicitud al origen o del lector de CloudFront. 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 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 Ejemplo: Uso de un desencadenador de solicitud para modificar un formulario HTML Esta función ilustra cómo puede modificar el cuerpo de una solicitud POST generada por un formulario HTML (formulario web). La función se activa en una solicitud al origen o del lector de CloudFront. 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. * * 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'] | 2026-01-13T09:30:35 |
https://docs.aws.amazon.com/id_id/lambda/latest/dg/with-s3-example.html | Tutorial: Menggunakan pemicu Amazon S3 untuk memanggil fungsi Lambda - AWS Lambda Tutorial: Menggunakan pemicu Amazon S3 untuk memanggil fungsi Lambda - AWS Lambda Dokumentasi AWS Lambda Panduan Developerr Buat bucket Amazon S3. Unggah objek uji ke bucket Anda Membuat kebijakan izin Membuat peran eksekusi Buat fungsi Lambda Menyebarkan kode fungsi Buat pemicu Amazon S3 Tes fungsi Lambda Bersihkan sumber daya Anda Langkah selanjutnya Terjemahan disediakan oleh mesin penerjemah. Jika konten terjemahan yang diberikan bertentangan dengan versi bahasa Inggris aslinya, utamakan versi bahasa Inggris. Tutorial: Menggunakan pemicu Amazon S3 untuk memanggil fungsi Lambda Dalam tutorial ini, Anda menggunakan konsol untuk membuat fungsi Lambda dan mengonfigurasi pemicu untuk bucket Amazon Simple Storage Service (Amazon S3). Setiap kali Anda menambahkan objek ke bucket Amazon S3, fungsi Anda berjalan dan mengeluarkan jenis objek ke Amazon Logs. CloudWatch Tutorial ini menunjukkan bagaimana untuk: Buat bucket Amazon S3. Buat fungsi Lambda yang mengembalikan jenis objek objek dalam bucket Amazon S3. Konfigurasikan pemicu Lambda yang memanggil fungsi Anda saat objek diunggah ke bucket Anda. Uji fungsi Anda, pertama dengan acara dummy, dan kemudian gunakan pelatuknya. Dengan menyelesaikan langkah-langkah ini, Anda akan mempelajari cara mengonfigurasi fungsi Lambda agar berjalan setiap kali objek ditambahkan atau dihapus dari bucket Amazon S3. Anda dapat menyelesaikan tutorial ini hanya dengan menggunakan Konsol Manajemen AWS. Buat bucket Amazon S3. Untuk membuat bucket Amazon S3 Buka konsol Amazon S3 dan pilih halaman Bucket tujuan umum . Pilih yang Wilayah AWS paling dekat dengan lokasi geografis Anda. Anda dapat mengubah wilayah Anda menggunakan daftar drop-down di bagian atas layar. Kemudian dalam tutorial, Anda harus membuat fungsi Lambda Anda di Wilayah yang sama. Pilih Buat bucket . Pada Konfigurasi umum , lakukan hal berikut: Untuk jenis Bucket , pastikan Tujuan umum dipilih. Untuk nama Bucket , masukkan nama unik global yang memenuhi aturan penamaan Amazon S3 Bucket . Nama bucket hanya dapat berisi huruf kecil, angka, titik (.), dan tanda hubung (-). Biarkan semua opsi lain disetel ke nilai defaultnya dan pilih Buat bucket . Unggah objek uji ke bucket Anda Untuk mengunggah objek uji Buka halaman Bucket di konsol Amazon S3 dan pilih bucket yang Anda buat selama langkah sebelumnya. Pilih Unggah . Pilih Tambahkan file dan pilih objek yang ingin Anda unggah. Anda dapat memilih file apa saja (misalnya, HappyFace.jpg ). Pilih Buka , lalu pilih Unggah . Kemudian dalam tutorial, Anda akan menguji fungsi Lambda Anda menggunakan objek ini. Membuat kebijakan izin Buat kebijakan izin yang memungkinkan Lambda mendapatkan objek dari bucket Amazon S3 dan menulis ke Amazon Log. CloudWatch Untuk membuat kebijakan Buka halaman Kebijakan konsol IAM. Pilih Buat Kebijakan . Pilih tab JSON , lalu tempelkan kebijakan khusus berikut ke editor JSON. JSON { "Version":"2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "logs:PutLogEvents", "logs:CreateLogGroup", "logs:CreateLogStream" ], "Resource": "arn:aws:logs:*:*:*" }, { "Effect": "Allow", "Action": [ "s3:GetObject" ], "Resource": "arn:aws:s3:::*/*" } ] } Pilih Berikutnya: Tanda . Pilih Berikutnya: Tinjau . Di bawah Kebijakan peninjauan , untuk Nama kebijakan, masukkan s3-trigger-tutorial . Pilih Buat kebijakan . Membuat peran eksekusi Peran eksekusi adalah peran AWS Identity and Access Management (IAM) yang memberikan izin fungsi Lambda untuk mengakses dan sumber daya. Layanan AWS Pada langkah ini, buat peran eksekusi menggunakan kebijakan izin yang Anda buat di langkah sebelumnya. Untuk membuat peran eksekusi dan melampirkan kebijakan izin kustom Buka halaman Peran dari konsol IAM. Pilih Buat peran . Untuk jenis entitas tepercaya, pilih AWS layanan , lalu untuk kasus penggunaan, pilih Lambda . Pilih Berikutnya . Dalam kotak pencarian kebijakan, masukkan s3-trigger-tutorial . Di hasil penelusuran, pilih kebijakan yang Anda buat ( s3-trigger-tutorial ), lalu pilih Berikutnya . Di bawah Rincian peran , untuk nama Peran , masukkan lambda-s3-trigger-role , lalu pilih Buat peran . Buat fungsi Lambda Buat fungsi Lambda di konsol menggunakan runtime Python 3.14. Untuk membuat fungsi Lambda Buka halaman Fungsi di konsol Lambda. Pastikan Anda bekerja di tempat yang sama dengan saat Wilayah AWS Anda membuat bucket Amazon S3. Anda dapat mengubah Wilayah Anda menggunakan daftar drop-down di bagian atas layar. Pilih Buat fungsi . Pilih Penulis dari awal Di bagian Informasi dasar , lakukan hal berikut: Untuk nama Fungsi , masukkan s3-trigger-tutorial Untuk Runtime , pilih Python 3.14 . Untuk Arsitektur , pilih x86_64 . Di tab Ubah peran eksekusi default , lakukan hal berikut: Perluas tab, lalu pilih Gunakan peran yang ada . Pilih yang lambda-s3-trigger-role Anda buat sebelumnya. Pilih Buat fungsi . Menyebarkan kode fungsi Tutorial ini menggunakan runtime Python 3.14, tetapi kami juga menyediakan contoh file kode untuk runtime lainnya. Anda dapat memilih tab di kotak berikut untuk melihat kode runtime yang Anda minati. Fungsi Lambda mengambil nama kunci objek yang diunggah dan nama bucket dari event parameter yang diterimanya dari Amazon S3. Fungsi kemudian menggunakan metode get_object dari AWS SDK untuk Python (Boto3) untuk mengambil metadata objek, termasuk tipe konten (tipe MIME) dari objek yang diunggah. Untuk menyebarkan kode fungsi Pilih tab Python di kotak berikut dan salin kodenya. .NET SDK untuk .NET catatan Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara mengatur dan menjalankannya di repositori contoh Nirserver . Menggunakan peristiwa S3 dengan Lambda menggunakan.NET. // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System.Threading.Tasks; using Amazon.Lambda.Core; using Amazon.S3; using System; using Amazon.Lambda.S3Events; using System.Web; // Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class. [assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] namespace S3Integration { public class Function { private static AmazonS3Client _s3Client; public Function() : this(null) { } internal Function(AmazonS3Client s3Client) { _s3Client = s3Client ?? new AmazonS3Client(); } public async Task<string> Handler(S3Event evt, ILambdaContext context) { try { if (evt.Records.Count <= 0) { context.Logger.LogLine("Empty S3 Event received"); return string.Empty; } var bucket = evt.Records[0].S3.Bucket.Name; var key = HttpUtility.UrlDecode(evt.Records[0].S3.Object.Key); context.Logger.LogLine($"Request is for { bucket} and { key}"); var objectResult = await _s3Client.GetObjectAsync(bucket, key); context.Logger.LogLine($"Returning { objectResult.Key}"); return objectResult.Key; } catch (Exception e) { context.Logger.LogLine($"Error processing request - { e.Message}"); return string.Empty; } } } } Go SDK untuk Go V2 catatan Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara mengatur dan menjalankannya di repositori contoh Nirserver . Menggunakan peristiwa S3 dengan Lambda menggunakan Go. // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package main import ( "context" "log" "github.com/aws/aws-lambda-go/events" "github.com/aws/aws-lambda-go/lambda" "github.com/aws/aws-sdk-go-v2/config" "github.com/aws/aws-sdk-go-v2/service/s3" ) func handler(ctx context.Context, s3Event events.S3Event) error { sdkConfig, err := config.LoadDefaultConfig(ctx) if err != nil { log.Printf("failed to load default config: %s", err) return err } s3Client := s3.NewFromConfig(sdkConfig) for _, record := range s3Event.Records { bucket := record.S3.Bucket.Name key := record.S3.Object.URLDecodedKey headOutput, err := s3Client.HeadObject(ctx, &s3.HeadObjectInput { Bucket: &bucket, Key: &key, }) if err != nil { log.Printf("error getting head of object %s/%s: %s", bucket, key, err) return err } log.Printf("successfully retrieved %s/%s of type %s", bucket, key, *headOutput.ContentType) } return nil } func main() { lambda.Start(handler) } Java SDK untuk Java 2.x catatan Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara mengatur dan menjalankannya di repositori contoh Nirserver . Menggunakan peristiwa S3 dengan Lambda menggunakan Java. // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package example; import software.amazon.awssdk.services.s3.model.HeadObjectRequest; import software.amazon.awssdk.services.s3.model.HeadObjectResponse; import software.amazon.awssdk.services.s3.S3Client; import com.amazonaws.services.lambda.runtime.Context; import com.amazonaws.services.lambda.runtime.RequestHandler; import com.amazonaws.services.lambda.runtime.events.S3Event; import com.amazonaws.services.lambda.runtime.events.models.s3.S3EventNotification.S3EventNotificationRecord; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class Handler implements RequestHandler<S3Event, String> { private static final Logger logger = LoggerFactory.getLogger(Handler.class); @Override public String handleRequest(S3Event s3event, Context context) { try { S3EventNotificationRecord record = s3event.getRecords().get(0); String srcBucket = record.getS3().getBucket().getName(); String srcKey = record.getS3().getObject().getUrlDecodedKey(); S3Client s3Client = S3Client.builder().build(); HeadObjectResponse headObject = getHeadObject(s3Client, srcBucket, srcKey); logger.info("Successfully retrieved " + srcBucket + "/" + srcKey + " of type " + headObject.contentType()); return "Ok"; } catch (Exception e) { throw new RuntimeException(e); } } private HeadObjectResponse getHeadObject(S3Client s3Client, String bucket, String key) { HeadObjectRequest headObjectRequest = HeadObjectRequest.builder() .bucket(bucket) .key(key) .build(); return s3Client.headObject(headObjectRequest); } } JavaScript SDK untuk JavaScript (v3) catatan Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara mengatur dan menjalankannya di repositori contoh Nirserver . Mengkonsumsi acara S3 dengan menggunakan JavaScript Lambda. import { S3Client, HeadObjectCommand } from "@aws-sdk/client-s3"; const client = new S3Client(); export const handler = async (event, context) => { // Get the object from the event and show its content type const bucket = event.Records[0].s3.bucket.name; const key = decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g, ' ')); try { const { ContentType } = await client.send(new HeadObjectCommand( { Bucket: bucket, Key: key, })); console.log('CONTENT TYPE:', ContentType); return ContentType; } catch (err) { console.log(err); const message = `Error getting object $ { key} from bucket $ { bucket}. Make sure they exist and your bucket is in the same region as this function.`; console.log(message); throw new Error(message); } }; Mengkonsumsi acara S3 dengan menggunakan TypeScript Lambda. // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 import { S3Event } from 'aws-lambda'; import { S3Client, HeadObjectCommand } from '@aws-sdk/client-s3'; const s3 = new S3Client( { region: process.env.AWS_REGION }); export const handler = async (event: S3Event): Promise<string | undefined> => { // Get the object from the event and show its content type const bucket = event.Records[0].s3.bucket.name; const key = decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g, ' ')); const params = { Bucket: bucket, Key: key, }; try { const { ContentType } = await s3.send(new HeadObjectCommand(params)); console.log('CONTENT TYPE:', ContentType); return ContentType; } catch (err) { console.log(err); const message = `Error getting object $ { key} from bucket $ { bucket}. Make sure they exist and your bucket is in the same region as this function.`; console.log(message); throw new Error(message); } }; PHP SDK untuk PHP catatan Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara mengatur dan menjalankannya di repositori contoh Nirserver . Mengkonsumsi acara S3 dengan Lambda menggunakan PHP. <?php use Bref\Context\Context; use Bref\Event\S3\S3Event; use Bref\Event\S3\S3Handler; use Bref\Logger\StderrLogger; require __DIR__ . '/vendor/autoload.php'; class Handler extends S3Handler { private StderrLogger $logger; public function __construct(StderrLogger $logger) { $this->logger = $logger; } public function handleS3(S3Event $event, Context $context) : void { $this->logger->info("Processing S3 records"); // Get the object from the event and show its content type $records = $event->getRecords(); foreach ($records as $record) { $bucket = $record->getBucket()->getName(); $key = urldecode($record->getObject()->getKey()); try { $fileSize = urldecode($record->getObject()->getSize()); echo "File Size: " . $fileSize . "\n"; // TODO: Implement your custom processing logic here } catch (Exception $e) { echo $e->getMessage() . "\n"; echo 'Error getting object ' . $key . ' from bucket ' . $bucket . '. Make sure they exist and your bucket is in the same region as this function.' . "\n"; throw $e; } } } } $logger = new StderrLogger(); return new Handler($logger); Python SDK untuk Python (Boto3) catatan Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara mengatur dan menjalankannya di repositori contoh Nirserver . Menggunakan peristiwa S3 dengan Lambda menggunakan Python. # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 import json import urllib.parse import boto3 print('Loading function') s3 = boto3.client('s3') def lambda_handler(event, context): #print("Received event: " + json.dumps(event, indent=2)) # Get the object from the event and show its content type bucket = event['Records'][0]['s3']['bucket']['name'] key = urllib.parse.unquote_plus(event['Records'][0]['s3']['object']['key'], encoding='utf-8') try: response = s3.get_object(Bucket=bucket, Key=key) print("CONTENT TYPE: " + response['ContentType']) return response['ContentType'] except Exception as e: print(e) print('Error getting object { } from bucket { }. Make sure they exist and your bucket is in the same region as this function.'.format(key, bucket)) raise e Ruby SDK untuk Ruby catatan Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara mengatur dan menjalankannya di repositori contoh Nirserver . Mengkonsumsi acara S3 dengan Lambda menggunakan Ruby. require 'json' require 'uri' require 'aws-sdk' puts 'Loading function' def lambda_handler(event:, context:) s3 = Aws::S3::Client.new(region: 'region') # Your AWS region # puts "Received event: # { JSON.dump(event)}" # Get the object from the event and show its content type bucket = event['Records'][0]['s3']['bucket']['name'] key = URI.decode_www_form_component(event['Records'][0]['s3']['object']['key'], Encoding::UTF_8) begin response = s3.get_object(bucket: bucket, key: key) puts "CONTENT TYPE: # { response.content_type}" return response.content_type rescue StandardError => e puts e.message puts "Error getting object # { key} from bucket # { bucket}. Make sure they exist and your bucket is in the same region as this function." raise e end end Rust SDK for Rust catatan Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara mengatur dan menjalankannya di repositori contoh Nirserver . Menggunakan peristiwa S3 dengan Lambda menggunakan Rust. // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 use aws_lambda_events::event::s3::S3Event; use aws_sdk_s3:: { Client}; use lambda_runtime:: { run, service_fn, Error, LambdaEvent}; /// Main function #[tokio::main] async fn main() -> Result<(), Error> { tracing_subscriber::fmt() .with_max_level(tracing::Level::INFO) .with_target(false) .without_time() .init(); // Initialize the AWS SDK for Rust let config = aws_config::load_from_env().await; let s3_client = Client::new(&config); let res = run(service_fn(|request: LambdaEvent<S3Event>| { function_handler(&s3_client, request) })).await; res } async fn function_handler( s3_client: &Client, evt: LambdaEvent<S3Event> ) -> Result<(), Error> { tracing::info!(records = ?evt.payload.records.len(), "Received request from SQS"); if evt.payload.records.len() == 0 { tracing::info!("Empty S3 event received"); } let bucket = evt.payload.records[0].s3.bucket.name.as_ref().expect("Bucket name to exist"); let key = evt.payload.records[0].s3.object.key.as_ref().expect("Object key to exist"); tracing::info!("Request is for { } and object { }", bucket, key); let s3_get_object_result = s3_client .get_object() .bucket(bucket) .key(key) .send() .await; match s3_get_object_result { Ok(_) => tracing::info!("S3 Get Object success, the s3GetObjectResult contains a 'body' property of type ByteStream"), Err(_) => tracing::info!("Failure with S3 Get Object request") } Ok(()) } Di panel Sumber kode di konsol Lambda, tempelkan kode ke editor kode, ganti kode yang dibuat Lambda. Di bagian DEPLOY , pilih Deploy untuk memperbarui kode fungsi Anda: Buat pemicu Amazon S3 Untuk membuat pemicu Amazon S3 Di panel Ikhtisar fungsi , pilih Tambah pemicu . Pilih S3 . Di bawah Bucket , pilih bucket yang Anda buat sebelumnya di tutorial. Di bawah Jenis acara , pastikan bahwa Semua peristiwa pembuatan objek dipilih. Di bawah Pemanggilan rekursif , pilih kotak centang untuk mengetahui bahwa tidak disarankan menggunakan bucket Amazon S3 yang sama untuk input dan output. Pilih Tambahkan . catatan Saat Anda membuat pemicu Amazon S3 untuk fungsi Lambda menggunakan konsol Lambda, Amazon S3 mengonfigurasi pemberitahuan peristiwa di bucket yang Anda tentukan. Sebelum mengonfigurasi pemberitahuan peristiwa ini, Amazon S3 melakukan serangkaian pemeriksaan untuk mengonfirmasi bahwa tujuan acara ada dan memiliki kebijakan IAM yang diperlukan. Amazon S3 juga melakukan pengujian ini pada notifikasi acara lain yang dikonfigurasi untuk bucket itu. Karena pemeriksaan ini, jika bucket sebelumnya telah mengonfigurasi tujuan peristiwa untuk sumber daya yang tidak ada lagi, atau untuk sumber daya yang tidak memiliki kebijakan izin yang diperlukan, Amazon S3 tidak akan dapat membuat notifikasi peristiwa baru. Anda akan melihat pesan galat berikut yang menunjukkan bahwa pemicu Anda tidak dapat dibuat: An error occurred when creating the trigger: Unable to validate the following destination configurations. Anda dapat melihat kesalahan ini jika sebelumnya mengonfigurasi pemicu untuk fungsi Lambda lain menggunakan bucket yang sama, dan sejak itu Anda telah menghapus fungsi tersebut atau memodifikasi kebijakan izinnya. Uji fungsi Lambda Anda dengan acara dummy Untuk menguji fungsi Lambda dengan acara dummy Di halaman konsol Lambda untuk fungsi Anda, pilih tab Uji . Untuk Nama peristiwa , masukkan MyTestEvent . Di Event JSON , tempel peristiwa pengujian berikut. Pastikan untuk mengganti nilai-nilai ini: Ganti us-east-1 dengan wilayah tempat Anda membuat bucket Amazon S3. Ganti kedua instance amzn-s3-demo-bucket dengan nama bucket Amazon S3 Anda sendiri. Ganti test%2FKey dengan nama objek pengujian yang Anda unggah ke bucket sebelumnya (misalnya, HappyFace.jpg ). { "Records": [ { "eventVersion": "2.0", "eventSource": "aws:s3", "awsRegion": " us-east-1 ", "eventTime": "1970-01-01T00:00:00.000Z", "eventName": "ObjectCreated:Put", "userIdentity": { "principalId": "EXAMPLE" }, "requestParameters": { "sourceIPAddress": "127.0.0.1" }, "responseElements": { "x-amz-request-id": "EXAMPLE123456789", "x-amz-id-2": "EXAMPLE123/5678abcdefghijklambdaisawesome/mnopqrstuvwxyzABCDEFGH" }, "s3": { "s3SchemaVersion": "1.0", "configurationId": "testConfigRule", "bucket": { "name": " amzn-s3-demo-bucket ", "ownerIdentity": { "principalId": "EXAMPLE" }, "arn": "arn:aws:s3::: amzn-s3-demo-bucket " }, "object": { "key": " test%2Fkey ", "size": 1024, "eTag": "0123456789abcdef0123456789abcdef", "sequencer": "0A1B2C3D4E5F678901" } } } ] } Pilih Simpan . Pilih Uji . Jika fungsi Anda berjalan dengan sukses, Anda akan melihat output yang mirip dengan berikut ini di tab Hasil eksekusi . Response "image/jpeg" Function Logs START RequestId: 12b3cae7-5f4e-415e-93e6-416b8f8b66e6 Version: $LATEST 2021-02-18T21:40:59.280Z 12b3cae7-5f4e-415e-93e6-416b8f8b66e6 INFO INPUT BUCKET AND KEY: { Bucket: 'amzn-s3-demo-bucket', Key: 'HappyFace.jpg' } 2021-02-18T21:41:00.215Z 12b3cae7-5f4e-415e-93e6-416b8f8b66e6 INFO CONTENT TYPE: image/jpeg END RequestId: 12b3cae7-5f4e-415e-93e6-416b8f8b66e6 REPORT RequestId: 12b3cae7-5f4e-415e-93e6-416b8f8b66e6 Duration: 976.25 ms Billed Duration: 977 ms Memory Size: 128 MB Max Memory Used: 90 MB Init Duration: 430.47 ms Request ID 12b3cae7-5f4e-415e-93e6-416b8f8b66e6 Uji fungsi Lambda dengan pemicu Amazon S3 Untuk menguji fungsi Anda dengan pemicu yang dikonfigurasi, unggah objek ke bucket Amazon S3 menggunakan konsol. Untuk memverifikasi bahwa fungsi Lambda Anda berjalan seperti yang diharapkan, gunakan CloudWatch Log untuk melihat output fungsi Anda. Untuk mengunggah objek ke bucket Amazon S3 Anda Buka halaman Bucket di konsol Amazon S3 dan pilih bucket yang Anda buat sebelumnya. Pilih Unggah . Pilih Tambahkan file dan gunakan pemilih file untuk memilih objek yang ingin Anda unggah. Objek ini dapat berupa file apa pun yang Anda pilih. Pilih Buka , lalu pilih Unggah . Untuk memverifikasi pemanggilan fungsi menggunakan Log CloudWatch Buka konsol CloudWatch . Pastikan Anda bekerja sama dengan saat Wilayah AWS Anda membuat fungsi Lambda Anda. Anda dapat mengubah Wilayah Anda menggunakan daftar drop-down di bagian atas layar. Pilih Log , lalu pilih Grup log . Pilih grup log untuk fungsi Anda ( /aws/lambda/s3-trigger-tutorial ). Di bawah Aliran log , pilih aliran log terbaru. Jika fungsi Anda dipanggil dengan benar sebagai respons terhadap pemicu Amazon S3, Anda akan melihat output yang mirip dengan berikut ini. Yang CONTENT TYPE Anda lihat tergantung pada jenis file yang Anda unggah ke bucket Anda. 2022-05-09T23:17:28.702Z 0cae7f5a-b0af-4c73-8563-a3430333cc10 INFO CONTENT TYPE: image/jpeg Bersihkan sumber daya Anda Sekarang Anda dapat menghapus sumber daya yang Anda buat untuk tutorial ini, kecuali Anda ingin mempertahankannya. Dengan menghapus AWS sumber daya yang tidak lagi Anda gunakan, Anda mencegah tagihan yang tidak perlu ke Anda Akun AWS. Untuk menghapus fungsi Lambda Buka halaman Fungsi di konsol Lambda. Pilih fungsi yang Anda buat. Pilih Tindakan , Hapus . Ketik confirm kolom input teks dan pilih Hapus . Untuk menghapus peran eksekusi Buka halaman Peran dari konsol IAM. Pilih peran eksekusi yang Anda buat. Pilih Hapus . Masukkan nama peran di bidang input teks dan pilih Hapus . Untuk menghapus bucket S3 Buka konsol Amazon S3 . Pilih bucket yang Anda buat. Pilih Hapus . Masukkan nama ember di bidang input teks. Pilih Hapus bucket . Langkah selanjutnya Di Tutorial: Menggunakan pemicu Amazon S3 untuk membuat gambar thumbnail , pemicu Amazon S3 memanggil fungsi yang membuat gambar thumbnail untuk setiap file gambar yang diunggah ke bucket. Tutorial ini membutuhkan pengetahuan domain Lambda AWS dan tingkat moderat. Ini menunjukkan cara membuat sumber daya menggunakan AWS Command Line Interface (AWS CLI) dan cara membuat paket penyebaran arsip file.zip untuk fungsi dan dependensinya. Javascript dinonaktifkan atau tidak tersedia di browser Anda. Untuk menggunakan Dokumentasi AWS, Javascript harus diaktifkan. Lihat halaman Bantuan browser Anda untuk petunjuk. Konvensi Dokumen S3 Tutorial: Gunakan pemicu Amazon S3 untuk membuat thumbnail Apakah halaman ini membantu Anda? - Ya Terima kasih telah memberitahukan bahwa hasil pekerjaan kami sudah baik. Jika Anda memiliki waktu luang, beri tahu kami aspek apa saja yang sudah bagus, agar kami dapat menerapkannya secara lebih luas. Apakah halaman ini membantu Anda? - Tidak Terima kasih telah memberi tahu kami bahwa halaman ini perlu ditingkatkan. Maaf karena telah mengecewakan Anda. Jika Anda memiliki waktu luang, beri tahu kami bagaimana dokumentasi ini dapat ditingkatkan. | 2026-01-13T09:30:35 |
https://docs.aws.amazon.com/fr_fr/lambda/latest/dg/with-s3-example.html | Didacticiel : utilisation d’un déclencheur Amazon S3 pour invoquer une fonction Lambda - AWS Lambda Didacticiel : utilisation d’un déclencheur Amazon S3 pour invoquer une fonction Lambda - AWS Lambda Documentation AWS Lambda Guide du développeur Créer un compartiment Amazon S3 Charger un objet de test dans votre compartiment Création d’une stratégie d’autorisations Créer un rôle d’exécution Créer la fonction Lambda Déployer le code de la fonction Création d’un déclencheur Amazon S3 Test de la fonction Lambda Nettoyage de vos ressources Étapes suivantes Les traductions sont fournies par des outils de traduction automatique. En cas de conflit entre le contenu d'une traduction et celui de la version originale en anglais, la version anglaise prévaudra. Didacticiel : utilisation d’un déclencheur Amazon S3 pour invoquer une fonction Lambda Dans ce didacticiel, vous allez utiliser la console pour créer une fonction Lambda et configurer un déclencheur pour un compartiment Amazon Simple Storage Service (Amazon S3). Chaque fois que vous ajoutez un objet à votre compartiment Amazon S3, votre fonction s'exécute et affiche le type d'objet dans Amazon CloudWatch Logs. Ce tutoriel montre comment : Créez un compartiment Amazon S3. Créez une fonction Lambda qui renvoie le type d’objet des objets dans un compartiment Amazon S3. Configurez un déclencheur Lambda qui invoque votre fonction lorsque des objets sont chargés dans votre compartiment. Testez votre fonction, d’abord avec un événement fictif, puis en utilisant le déclencheur. En suivant ces étapes, vous apprendrez à configurer une fonction Lambda pour qu’elle s’exécute chaque fois que des objets sont ajoutés ou supprimés d’un compartiment Amazon S3. Vous pouvez compléter ce didacticiel en n’utilisant que la AWS Management Console. Créer un compartiment Amazon S3 Pour créer un compartiment Amazon S3 Ouvrez la console Amazon S3 et sélectionnez la page Compartiments à usage général . Sélectionnez le Région AWS plus proche de votre situation géographique. Vous pouvez modifier votre région à l’aide de la liste déroulante en haut de l’écran. Plus loin dans le didacticiel, vous devez créer votre fonction Lambda dans la même région. Choisissez Create bucket (Créer un compartiment). Sous Configuration générale , procédez comme suit : Pour le type de compartiment , veillez à sélectionner Usage général . Pour le nom du compartiment , saisissez un nom unique au monde qui respecte les règles de dénomination du compartiment Amazon S3. Les noms de compartiment peuvent contenir uniquement des lettres minuscules, des chiffres, de points (.) et des traits d’union (-). Conservez les valeurs par défaut de toutes les autres options et choisissez Créer un compartiment . Charger un objet de test dans votre compartiment Pour charger un objet de test Ouvrez la page Compartiments de la console Amazon S3 et choisissez le compartiment que vous avez créé à l’étape précédente. Choisissez Charger . Choisissez Ajouter des fichiers et sélectionnez l’objet que vous souhaitez charger. Vous pouvez sélectionner n’importe quel fichier (par exemple, HappyFace.jpg ). Choisissez Ouvrir , puis Charger . Plus loin dans le tutoriel, vous testerez votre fonction Lambda à l’aide de cet objet. Création d’une stratégie d’autorisations Créez une politique d'autorisation qui permet à Lambda d'obtenir des objets depuis un compartiment Amazon S3 et d'écrire dans Amazon CloudWatch Logs. Pour créer la politique Ouvrez la page stratégies de la console IAM. Choisissez Créer une stratégie . Choisissez l’onglet JSON , puis collez la stratégie personnalisée suivante dans l’éditeur JSON. JSON { "Version":"2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "logs:PutLogEvents", "logs:CreateLogGroup", "logs:CreateLogStream" ], "Resource": "arn:aws:logs:*:*:*" }, { "Effect": "Allow", "Action": [ "s3:GetObject" ], "Resource": "arn:aws:s3:::*/*" } ] } Choisissez Suivant : Balises . Choisissez Suivant : Vérification . Sous Examiner une stratégie , pour le Nom de la stratégie, saisissez s3-trigger-tutorial . Choisissez Créer une stratégie . Créer un rôle d’exécution Un rôle d'exécution est un rôle Gestion des identités et des accès AWS (IAM) qui accorde à une fonction Lambda l'autorisation d' Services AWS accès et de ressources. Dans cette étape, vous créez un rôle d’exécution à l’aide de la politique d’autorisations que vous avez créée à l’étape précédente. Pour créer un rôle d’exécution et attacher votre politique d’autorisations personnalisée Ouvrez la page Rôles de la console IAM. Sélectionnez Créer un rôle . Pour le type d’entité de confiance, choisissez Service AWS , puis pour le cas d’utilisation, choisissez Lambda . Choisissez Suivant . Dans la zone de recherche de stratégie, entrez s3-trigger-tutorial . Dans les résultats de la recherche, sélectionnez la stratégie que vous avez créée ( s3-trigger-tutorial ), puis choisissez Suivant . Sous Role details (Détails du rôle), pour Role name (Nom du rôle), saisissez lambda-s3-trigger-role , puis sélectionnez Create role (Créer un rôle). Créer la fonction Lambda Créez une fonction Lambda dans la console à l'aide de l'environnement d'exécution Python 3.14. Pour créer la fonction Lambda Ouvrez la page Functions (Fonctions) de la console Lambda. Assurez-vous de travailler dans le même environnement que celui dans Région AWS lequel vous avez créé votre compartiment Amazon S3. Vous pouvez modifier votre région à l’aide de la liste déroulante en haut de l’écran. Choisissez Créer une fonction . Choisissez Créer à partir de zéro . Sous Basic information (Informations de base), procédez comme suit : Sous Nom de la fonction , saisissez s3-trigger-tutorial . Pour Runtime , choisissez Python 3.14 . Pour Architecture , choisissez x86_64 . Dans l’onglet Modifier le rôle d’exécution par défaut , procédez comme suit : Ouvrez l’onglet, puis choisissez Utiliser un rôle existant . Sélectionnez le lambda-s3-trigger-role que vous avez créé précédemment. Choisissez Créer une fonction . Déployer le code de la fonction Ce didacticiel utilise le moteur d'exécution Python 3.14, mais nous avons également fourni des exemples de fichiers de code pour d'autres environnements d'exécution. Vous pouvez sélectionner l’onglet dans la zone suivante pour voir le code d’exécution qui vous intéresse. La fonction Lambda récupère le nom de la clé de l’objet chargé et le nom du compartiment à partir du paramètre event qu’elle reçoit d’Amazon S3. La fonction utilise ensuite la méthode get_object du AWS SDK pour Python (Boto3) pour récupérer les métadonnées de l'objet, y compris le type de contenu (type MIME) de l'objet chargé. Pour déployer le code de la fonction Choisissez l’onglet Python dans la zone suivante et copiez le code. .NET SDK pour .NET Note Il y en a plus sur GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’ exemples sans serveur . Utilisation d’un événement S3 avec Lambda en utilisant .NET. // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System.Threading.Tasks; using Amazon.Lambda.Core; using Amazon.S3; using System; using Amazon.Lambda.S3Events; using System.Web; // Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class. [assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] namespace S3Integration { public class Function { private static AmazonS3Client _s3Client; public Function() : this(null) { } internal Function(AmazonS3Client s3Client) { _s3Client = s3Client ?? new AmazonS3Client(); } public async Task<string> Handler(S3Event evt, ILambdaContext context) { try { if (evt.Records.Count <= 0) { context.Logger.LogLine("Empty S3 Event received"); return string.Empty; } var bucket = evt.Records[0].S3.Bucket.Name; var key = HttpUtility.UrlDecode(evt.Records[0].S3.Object.Key); context.Logger.LogLine($"Request is for { bucket} and { key}"); var objectResult = await _s3Client.GetObjectAsync(bucket, key); context.Logger.LogLine($"Returning { objectResult.Key}"); return objectResult.Key; } catch (Exception e) { context.Logger.LogLine($"Error processing request - { e.Message}"); return string.Empty; } } } } Go Kit SDK pour Go V2 Note Il y en a plus sur GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’ exemples sans serveur . Utilisation d’un événement S3 avec Lambda en utilisant Go. // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package main import ( "context" "log" "github.com/aws/aws-lambda-go/events" "github.com/aws/aws-lambda-go/lambda" "github.com/aws/aws-sdk-go-v2/config" "github.com/aws/aws-sdk-go-v2/service/s3" ) func handler(ctx context.Context, s3Event events.S3Event) error { sdkConfig, err := config.LoadDefaultConfig(ctx) if err != nil { log.Printf("failed to load default config: %s", err) return err } s3Client := s3.NewFromConfig(sdkConfig) for _, record := range s3Event.Records { bucket := record.S3.Bucket.Name key := record.S3.Object.URLDecodedKey headOutput, err := s3Client.HeadObject(ctx, &s3.HeadObjectInput { Bucket: &bucket, Key: &key, }) if err != nil { log.Printf("error getting head of object %s/%s: %s", bucket, key, err) return err } log.Printf("successfully retrieved %s/%s of type %s", bucket, key, *headOutput.ContentType) } return nil } func main() { lambda.Start(handler) } Java SDK pour Java 2.x Note Il y en a plus sur GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’ exemples sans serveur . Utilisation d’un événement S3 avec Lambda en utilisant Go. // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package example; import software.amazon.awssdk.services.s3.model.HeadObjectRequest; import software.amazon.awssdk.services.s3.model.HeadObjectResponse; import software.amazon.awssdk.services.s3.S3Client; import com.amazonaws.services.lambda.runtime.Context; import com.amazonaws.services.lambda.runtime.RequestHandler; import com.amazonaws.services.lambda.runtime.events.S3Event; import com.amazonaws.services.lambda.runtime.events.models.s3.S3EventNotification.S3EventNotificationRecord; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class Handler implements RequestHandler<S3Event, String> { private static final Logger logger = LoggerFactory.getLogger(Handler.class); @Override public String handleRequest(S3Event s3event, Context context) { try { S3EventNotificationRecord record = s3event.getRecords().get(0); String srcBucket = record.getS3().getBucket().getName(); String srcKey = record.getS3().getObject().getUrlDecodedKey(); S3Client s3Client = S3Client.builder().build(); HeadObjectResponse headObject = getHeadObject(s3Client, srcBucket, srcKey); logger.info("Successfully retrieved " + srcBucket + "/" + srcKey + " of type " + headObject.contentType()); return "Ok"; } catch (Exception e) { throw new RuntimeException(e); } } private HeadObjectResponse getHeadObject(S3Client s3Client, String bucket, String key) { HeadObjectRequest headObjectRequest = HeadObjectRequest.builder() .bucket(bucket) .key(key) .build(); return s3Client.headObject(headObjectRequest); } } JavaScript SDK pour JavaScript (v3) Note Il y en a plus sur GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’ exemples sans serveur . Consommation d'un événement S3 avec Lambda en utilisant. JavaScript import { S3Client, HeadObjectCommand } from "@aws-sdk/client-s3"; const client = new S3Client(); export const handler = async (event, context) => { // Get the object from the event and show its content type const bucket = event.Records[0].s3.bucket.name; const key = decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g, ' ')); try { const { ContentType } = await client.send(new HeadObjectCommand( { Bucket: bucket, Key: key, })); console.log('CONTENT TYPE:', ContentType); return ContentType; } catch (err) { console.log(err); const message = `Error getting object $ { key} from bucket $ { bucket}. Make sure they exist and your bucket is in the same region as this function.`; console.log(message); throw new Error(message); } }; Consommation d'un événement S3 avec Lambda en utilisant. TypeScript // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 import { S3Event } from 'aws-lambda'; import { S3Client, HeadObjectCommand } from '@aws-sdk/client-s3'; const s3 = new S3Client( { region: process.env.AWS_REGION }); export const handler = async (event: S3Event): Promise<string | undefined> => { // Get the object from the event and show its content type const bucket = event.Records[0].s3.bucket.name; const key = decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g, ' ')); const params = { Bucket: bucket, Key: key, }; try { const { ContentType } = await s3.send(new HeadObjectCommand(params)); console.log('CONTENT TYPE:', ContentType); return ContentType; } catch (err) { console.log(err); const message = `Error getting object $ { key} from bucket $ { bucket}. Make sure they exist and your bucket is in the same region as this function.`; console.log(message); throw new Error(message); } }; PHP Kit SDK pour PHP Note Il y en a plus sur GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’ exemples sans serveur . Consommation d’un événement S3 avec Lambda à l’aide de PHP. <?php use Bref\Context\Context; use Bref\Event\S3\S3Event; use Bref\Event\S3\S3Handler; use Bref\Logger\StderrLogger; require __DIR__ . '/vendor/autoload.php'; class Handler extends S3Handler { private StderrLogger $logger; public function __construct(StderrLogger $logger) { $this->logger = $logger; } public function handleS3(S3Event $event, Context $context) : void { $this->logger->info("Processing S3 records"); // Get the object from the event and show its content type $records = $event->getRecords(); foreach ($records as $record) { $bucket = $record->getBucket()->getName(); $key = urldecode($record->getObject()->getKey()); try { $fileSize = urldecode($record->getObject()->getSize()); echo "File Size: " . $fileSize . "\n"; // TODO: Implement your custom processing logic here } catch (Exception $e) { echo $e->getMessage() . "\n"; echo 'Error getting object ' . $key . ' from bucket ' . $bucket . '. Make sure they exist and your bucket is in the same region as this function.' . "\n"; throw $e; } } } } $logger = new StderrLogger(); return new Handler($logger); Python Kit SDK for Python (Boto3) Note Il y en a plus sur GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’ exemples sans serveur . Utilisation d’un événement S3 avec Lambda en utilisant Python. # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 import json import urllib.parse import boto3 print('Loading function') s3 = boto3.client('s3') def lambda_handler(event, context): #print("Received event: " + json.dumps(event, indent=2)) # Get the object from the event and show its content type bucket = event['Records'][0]['s3']['bucket']['name'] key = urllib.parse.unquote_plus(event['Records'][0]['s3']['object']['key'], encoding='utf-8') try: response = s3.get_object(Bucket=bucket, Key=key) print("CONTENT TYPE: " + response['ContentType']) return response['ContentType'] except Exception as e: print(e) print('Error getting object { } from bucket { }. Make sure they exist and your bucket is in the same region as this function.'.format(key, bucket)) raise e Ruby Kit SDK pour Ruby Note Il y en a plus sur GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’ exemples sans serveur . Consommation d’un événement S3 avec Lambda à l’aide de Ruby. require 'json' require 'uri' require 'aws-sdk' puts 'Loading function' def lambda_handler(event:, context:) s3 = Aws::S3::Client.new(region: 'region') # Your AWS region # puts "Received event: # { JSON.dump(event)}" # Get the object from the event and show its content type bucket = event['Records'][0]['s3']['bucket']['name'] key = URI.decode_www_form_component(event['Records'][0]['s3']['object']['key'], Encoding::UTF_8) begin response = s3.get_object(bucket: bucket, key: key) puts "CONTENT TYPE: # { response.content_type}" return response.content_type rescue StandardError => e puts e.message puts "Error getting object # { key} from bucket # { bucket}. Make sure they exist and your bucket is in the same region as this function." raise e end end Rust SDK pour Rust Note Il y en a plus sur GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’ exemples sans serveur . Utilisation d’un événement S3 avec Lambda en utilisant Rust. // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 use aws_lambda_events::event::s3::S3Event; use aws_sdk_s3:: { Client}; use lambda_runtime:: { run, service_fn, Error, LambdaEvent}; /// Main function #[tokio::main] async fn main() -> Result<(), Error> { tracing_subscriber::fmt() .with_max_level(tracing::Level::INFO) .with_target(false) .without_time() .init(); // Initialize the AWS SDK for Rust let config = aws_config::load_from_env().await; let s3_client = Client::new(&config); let res = run(service_fn(|request: LambdaEvent<S3Event>| { function_handler(&s3_client, request) })).await; res } async fn function_handler( s3_client: &Client, evt: LambdaEvent<S3Event> ) -> Result<(), Error> { tracing::info!(records = ?evt.payload.records.len(), "Received request from SQS"); if evt.payload.records.len() == 0 { tracing::info!("Empty S3 event received"); } let bucket = evt.payload.records[0].s3.bucket.name.as_ref().expect("Bucket name to exist"); let key = evt.payload.records[0].s3.object.key.as_ref().expect("Object key to exist"); tracing::info!("Request is for { } and object { }", bucket, key); let s3_get_object_result = s3_client .get_object() .bucket(bucket) .key(key) .send() .await; match s3_get_object_result { Ok(_) => tracing::info!("S3 Get Object success, the s3GetObjectResult contains a 'body' property of type ByteStream"), Err(_) => tracing::info!("Failure with S3 Get Object request") } Ok(()) } Dans le volet Code source de la console Lambda, collez le code dans l’éditeur de code, en remplaçant le code créé par Lambda. Dans la section DÉPLOYER , choisissez Déployer pour mettre à jour le code de votre fonction : Création d’un déclencheur Amazon S3 Pour créer le déclencheur Amazon S3 Dans le volet de Présentation de la fonction , choisissez Ajouter un déclencheur . Sélectionnez S3 . Sous Compartiment , sélectionnez le compartiment que vous avez créé précédemment dans le didacticiel. Sous Types d’événements , assurez-vous que Tous les événements de création d’objet est sélectionné. Sous Invocation récursive , cochez la case pour confirmer qu’il n’est pas recommandé d’utiliser le même compartiment Amazon S3 pour les entrées et les sorties. Choisissez Ajouter . Note Lorsque vous créez un déclencheur Amazon S3 pour une fonction Lambda à l’aide de la console Lambda, Amazon S3 configure une notification d’événement sur le compartiment que vous spécifiez. Avant de configurer cette notification d’événement, Amazon S3 effectue une série de vérifications pour confirmer que la destination de l’événement existe et dispose des politiques IAM requises. Amazon S3 effectue également ces tests sur toutes les autres notifications d’événements configurées pour ce compartiment. En raison de cette vérification, si le compartiment a déjà configuré des destinations d’événements pour des ressources qui n’existent plus ou pour des ressources qui ne disposent pas des politiques d’autorisations requises, Amazon S3 ne sera pas en mesure de créer la nouvelle notification d’événement. Vous verrez le message d’erreur suivant indiquant que votre déclencheur n’a pas pu être créé : An error occurred when creating the trigger: Unable to validate the following destination configurations. Vous pouvez voir cette erreur si vous avez précédemment configuré un déclencheur pour une autre fonction Lambda utilisant le même compartiment, et si vous avez depuis supprimé la fonction ou modifié ses politiques d’autorisations. Test de votre fonction Lambda à l’aide d’un événement fictif Pour tester la fonction Lambda à l’aide d’un événement fictif Dans la page de votre fonction de la console Lambda, choisissez l’onglet Tester . Dans Event name (Nom de l’événement), saisissez MyTestEvent . Dans le JSON d’événement , collez l’événement de test suivant. Veillez à remplacer les valeurs suivantes : Remplacez us-east-1 par la région dans laquelle vous avez créé votre compartiment Amazon S3. Remplacez les deux instances de amzn-s3-demo-bucket par le nom de votre propre compartiment Amazon S3. Remplacez test%2FKey par le nom de l’objet de test que vous avez chargé précédemment dans votre compartiment (par exemple, HappyFace.jpg ). { "Records": [ { "eventVersion": "2.0", "eventSource": "aws:s3", "awsRegion": " us-east-1 ", "eventTime": "1970-01-01T00:00:00.000Z", "eventName": "ObjectCreated:Put", "userIdentity": { "principalId": "EXAMPLE" }, "requestParameters": { "sourceIPAddress": "127.0.0.1" }, "responseElements": { "x-amz-request-id": "EXAMPLE123456789", "x-amz-id-2": "EXAMPLE123/5678abcdefghijklambdaisawesome/mnopqrstuvwxyzABCDEFGH" }, "s3": { "s3SchemaVersion": "1.0", "configurationId": "testConfigRule", "bucket": { "name": " amzn-s3-demo-bucket ", "ownerIdentity": { "principalId": "EXAMPLE" }, "arn": "arn:aws:s3::: amzn-s3-demo-bucket " }, "object": { "key": " test%2Fkey ", "size": 1024, "eTag": "0123456789abcdef0123456789abcdef", "sequencer": "0A1B2C3D4E5F678901" } } } ] } Choisissez Enregistrer . Sélectionnez Tester) . Si votre fonction s’exécute correctement, vous obtiendrez un résultat similaire à celui qui suit dans l’onglet Résultats de l’exécution . Response "image/jpeg" Function Logs START RequestId: 12b3cae7-5f4e-415e-93e6-416b8f8b66e6 Version: $LATEST 2021-02-18T21:40:59.280Z 12b3cae7-5f4e-415e-93e6-416b8f8b66e6 INFO INPUT BUCKET AND KEY: { Bucket: 'amzn-s3-demo-bucket', Key: 'HappyFace.jpg' } 2021-02-18T21:41:00.215Z 12b3cae7-5f4e-415e-93e6-416b8f8b66e6 INFO CONTENT TYPE: image/jpeg END RequestId: 12b3cae7-5f4e-415e-93e6-416b8f8b66e6 REPORT RequestId: 12b3cae7-5f4e-415e-93e6-416b8f8b66e6 Duration: 976.25 ms Billed Duration: 977 ms Memory Size: 128 MB Max Memory Used: 90 MB Init Duration: 430.47 ms Request ID 12b3cae7-5f4e-415e-93e6-416b8f8b66e6 Test de la fonction Lambda avec le déclencheur Amazon S3 Pour tester votre fonction avec le déclencheur configuré, chargez un objet dans votre compartiment Amazon S3 à l’aide de la console. Pour vérifier que votre fonction Lambda s'est exécutée comme prévu, utilisez CloudWatch Logs pour afficher le résultat de votre fonction. Pour charger un objet dans votre compartiment Amazon S3 Ouvrez la page Compartiments de la console Amazon S3 et choisissez le compartiment que vous avez créé précédemment. Choisissez Charger . Choisissez Ajouter des fichiers et utilisez le sélecteur de fichiers pour choisir l’objet que vous souhaitez charger. Cet objet peut être n’importe quel fichier que vous choisissez. Choisissez Ouvrir , puis Charger . Pour vérifier l'invocation de la fonction à l'aide CloudWatch de Logs Ouvrez la console CloudWatch . Assurez-vous de travailler de la même manière que celle dans laquelle Région AWS vous avez créé votre fonction Lambda. Vous pouvez modifier votre région à l’aide de la liste déroulante en haut de l’écran. Choisissez Journaux , puis Groupes de journaux . Choisissez le groupe de journaux de votre fonction ( /aws/lambda/s3-trigger-tutorial ). Sous Flux de journaux , sélectionnez le flux de journaux le plus récent. Si votre fonction a été invoquée correctement en réponse à votre déclencheur Amazon S3, vous obtiendrez une sortie similaire à celle qui suit. Le CONTENT TYPE que vous voyez dépend du type de fichier que vous avez chargé dans votre compartiment. 2022-05-09T23:17:28.702Z 0cae7f5a-b0af-4c73-8563-a3430333cc10 INFO CONTENT TYPE: image/jpeg Nettoyage de vos ressources Vous pouvez maintenant supprimer les ressources que vous avez créées pour ce didacticiel, sauf si vous souhaitez les conserver. En supprimant AWS les ressources que vous n'utilisez plus, vous évitez des frais inutiles pour votre Compte AWS. Pour supprimer la fonction Lambda Ouvrez la page Functions (Fonctions) de la console Lambda. Sélectionnez la fonction que vous avez créée. Sélectionnez Actions , Supprimer . Saisissez confirm dans la zone de saisie de texte et choisissez Delete (Supprimer). Pour supprimer le rôle d’exécution Ouvrez la page Roles (Rôles) de la console IAM. Sélectionnez le rôle d’exécution que vous avez créé. Sélectionnez Delete (Supprimer) . Saisissez le nom du rôle dans le champ de saisie de texte et choisissez Delete (Supprimer). Pour supprimer le compartiment S3 Ouvrez la console Amazon S3 . Sélectionnez le compartiment que vous avez créé. Sélectionnez Delete (Supprimer) . Saisissez le nom du compartiment dans le champ de saisie de texte. Choisissez Supprimer le compartiment . Étapes suivantes Dans Didacticiel : Utilisation d’un déclencheur Amazon S3 pour créer des images miniatures , le déclencheur Amazon S3 invoque une fonction qui crée une image de miniature pour chaque fichier image qui est chargé dans votre compartiment. Ce didacticiel nécessite un niveau modéré de connaissance du AWS domaine Lambda. Il montre comment créer des ressources à l'aide de AWS Command Line Interface (AWS CLI) et comment créer un package de déploiement d'archives de fichiers .zip pour la fonction et ses dépendances. JavaScript est désactivé ou n'est pas disponible dans votre navigateur. Pour que vous puissiez utiliser la documentation AWS, Javascript doit être activé. Vous trouverez des instructions sur les pages d'aide de votre navigateur. Conventions de rédaction S3 Didacticiel : Utilisation d’un déclencheur Amazon S3 pour créer des images miniatures Cette page vous a-t-elle été utile ? - Oui Merci de nous avoir fait part de votre satisfaction. Si vous avez quelques minutes à nous consacrer, merci de nous indiquer ce qui vous a plu afin que nous puissions nous améliorer davantage. Cette page vous a-t-elle été utile ? - Non Merci de nous avoir avertis que cette page avait besoin d'être retravaillée. Nous sommes désolés de ne pas avoir répondu à vos attentes. Si vous avez quelques minutes à nous consacrer, merci de nous indiquer comment nous pourrions améliorer cette documentation. | 2026-01-13T09:30:35 |
https://docs.aws.amazon.com/es_es/AmazonCloudFront/latest/DeveloperGuide/lambda-examples.html#lambda-examples-overriding-response-header | Funciones de ejemplo de Lambda@Edge - Amazon CloudFront Funciones de ejemplo de Lambda@Edge - Amazon CloudFront Documentación Amazon CloudFront Guía para desarrolladores Ejemplos generales Generación de respuestas: ejemplos Cadenas de consulta: ejemplos Personalización de contenido por encabezados de tipo de dispositivo o país: ejemplos Selección de origen dinámico basada en contenido: ejemplos Actualización de estados de error: ejemplos Acceso al cuerpo de la solicitud: ejemplos Funciones de ejemplo de Lambda@Edge Consulte los ejemplos siguientes para usar funciones de Lambda con Amazon CloudFront. nota Si elige el tiempo de ejecución Node.js 18 o una versión posterior para la función Lambda@Edge, se creará automáticamente un archivo index.mjs . Para usar los siguientes ejemplos de código, cambie el nombre del archivo index.mjs a index.js . Temas Ejemplos generales Generación de respuestas: ejemplos Cadenas de consulta: ejemplos Personalización de contenido por encabezados de tipo de dispositivo o país: ejemplos Selección de origen dinámico basada en contenido: ejemplos Actualización de estados de error: ejemplos Acceso al cuerpo de la solicitud: ejemplos Ejemplos generales Los ejemplos siguientes muestran formas habituales de usar Lambda@Edge en CloudFront. Temas Ejemplo: prueba A/B Ejemplo: Sobrescritura de un encabezado de respuesta Ejemplo: prueba A/B Puede utilizar el siguiente ejemplo para probar dos versiones diferentes de una imagen sin crear redirecciones ni cambiar la dirección URL. En este ejemplo se leen las cookies de la solicitud del lector y se modifica la URL de la solicitud en consecuencia. Si el espectador no envía una cookie con uno de los valores esperados, el ejemplo asigna aleatoriamente al espectador una de las URL. 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; } 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; } } 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" ''' experimentUri = "" 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 Ejemplo: Sobrescritura de un encabezado de respuesta En el ejemplo siguiente, se muestra cómo cambiar el valor de un encabezado de respuesta según el valor de otro encabezado. Node.js export const handler = async (event) => { 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()] = [ { key: headerNameDst, value: headers[headerNameSrc.toLowerCase()][0].value, }]; console.log(`Response header "$ { headerNameDst}" was set to ` + `"$ { headers[headerNameDst.toLowerCase()][0].value}"`); } return response; }; Python import json def lambda_handler(event, context): response = event['Records'][0]['cf']['response'] headers = response['headers'] header_name_src = 'X-Amz-Meta-Last-Modified' header_name_dst = 'Last-Modified' if headers.get(header_name_src.lower()): headers[header_name_dst.lower()] = [ { 'key': header_name_dst, 'value': headers[header_name_src.lower()][0]['value'] }] print(f'Response header " { header_name_dst}" was set to ' f'" { headers[header_name_dst.lower()][0]["value"]}"') return response Generación de respuestas: ejemplos En los ejemplos siguientes se muestra cómo puede usar Lambda@Edge para generar respuestas. Temas Ejemplo: Envío de contenido estático (respuesta generada) Ejemplo: Generación de un redireccionamiento HTTP (respuesta generada) Ejemplo: Envío de contenido estático (respuesta generada) En el siguiente ejemplo se muestra cómo utilizar una función de Lambda para enviar contenido de sitio web estático, lo que reduce la carga en el servidor de origen y la latencia total. nota Puede generar respuestas HTTP para los eventos de solicitud del espectador y al origen. Para obtener más información, consulte Generación de respuestas HTTP en los desencadenadores de solicitud . También puede sustituir o quitar el cuerpo de la respuesta HTTP en eventos de respuesta de origen. Para obtener más información, consulte Actualización de respuestas HTTP en desencadenadores de respuesta de origen . 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' }] }, 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 } return response Ejemplo: Generación de un redireccionamiento HTTP (respuesta generada) En el siguiente ejemplo se muestra cómo generar una redirección HTTP. nota Puede generar respuestas HTTP para los eventos de solicitud del espectador y al origen. Para obtener más información, consulte Generación de respuestas HTTP en los desencadenadores de solicitud . 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. response = { 'status': '302', 'statusDescription': 'Found', 'headers': { 'location': [ { 'key': 'Location', 'value': 'https://docs.aws.amazon.com/lambda/latest/dg/lambda-edge.html' }] } } return response Cadenas de consulta: ejemplos En los ejemplos siguientes se muestran formas de usar Lambda@Edge con cadenas de consulta. Temas Ejemplo: Adición de un encabezado en función de un parámetro de la cadena de consulta Ejemplo: Normalización de parámetros de cadenas de consulta para mejorar la tasa de aciertos de caché Ejemplo: Redireccionamiento de los usuarios no autenticados a una página de inicio de sesión Ejemplo: Adición de un encabezado en función de un parámetro de la cadena de consulta El siguiente ejemplo muestra cómo obtener el par clave-valor de un parámetro de la cadena de consulta y, a continuación, añadir un encabezado en función de dichos valores. 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. * 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 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'] # Update request querystring request['querystring'] = urlencode(params) return request Ejemplo: Normalización de parámetros de cadenas de consulta para mejorar la tasa de aciertos de caché El siguiente ejemplo muestra cómo mejorar la tasa de acceso a la caché haciendo los siguientes cambios en las cadenas de consulta antes de que CloudFront reenvíe las solicitudes a su origen: Alfabetizar los pares de clave-valor por el nombre del parámetro. Cambiar a minúsculas el modelo de mayúsculas y minúsculas de los pares de clave-valor. Para obtener más información, consulte Almacenamiento en caché de contenido en función de parámetros de cadenas de consulta . 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 */ 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 request['querystring'] = urlencode(sortedParams) return request Ejemplo: Redireccionamiento de los usuarios no autenticados a una página de inicio de sesión El siguiente ejemplo muestra cómo redirigir a los usuarios una página de inicio de sesión si no ha introducido sus credenciales. 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; } /* 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 params. ''' # Check for session-id in cookie, if present, then proceed with request parsedCookies = parseCookies(headers) 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 Personalización de contenido por encabezados de tipo de dispositivo o país: ejemplos En los ejemplos siguientes se muestra cómo puede usar Lambda@Edge para personalizar el comportamiento en función de la ubicación o el tipo de dispositivo que usa el lector. Temas Ejemplo: Redireccionamiento de solicitudes de espectadores a una URL específica de un país Ejemplo: Envío de distintas versiones de un objeto en función del dispositivo Ejemplo: Redireccionamiento de solicitudes de espectadores a una URL específica de un país El siguiente ejemplo muestra cómo generar una respuesta de redireccionamiento HTTP con una URL específica del país y devolver la respuesta al espectador. Esto resulta útil cuando se quiere proporcionar respuestas específicas del país. Por ejemplo: Si tiene subdominios específicos de un país, como us.ejemplo.com y tw.ejemplo.com, puede generar una respuesta de redireccionamiento cuando un espectador solicite ejemplo.com. Si está haciendo streaming de video, pero no tiene derechos para transmitir el contenido en un país determinado, puede redirigir a los usuarios de dicho país a una página en la que se explica por qué no pueden ver el video. Tenga en cuenta lo siguiente: Debe configurar la distribución para almacenar en la caché en función del encabezado CloudFront-Viewer-Country . Para obtener más información, consulte Caché en función de encabezados de solicitud seleccionados . CloudFront agrega el encabezado CloudFront-Viewer-Country después del evento de solicitud del lector. Para utilizar este ejemplo, debe crear un activador para el evento de solicitud al origen. 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 = { 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', 'statusDescription': 'Found', 'headers': { 'location': [ { 'key': 'Location', 'value': url }] } } return response Ejemplo: Envío de distintas versiones de un objeto en función del dispositivo El siguiente ejemplo muestra cómo ofrecer distintas versiones de un objeto en función del tipo de dispositivo que el usuario está utilizando; por ejemplo, un dispositivo móvil o una tablet. Tenga en cuenta lo siguiente: Debe configurar la distribución para almacenar en la caché en función de los encabezados CloudFront-Is-*-Viewer . Para obtener más información, consulte Caché en función de encabezados de solicitud seleccionados . CloudFront agrega los encabezados CloudFront-Is-*-Viewer después del evento de solicitud del lector. Para utilizar este ejemplo, debe crear un activador para el evento de solicitud al origen. 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 * 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. ''' desktopPath = '/desktop'; mobilePath = '/mobile'; tabletPath = '/tablet'; smarttvPath = '/smarttv'; 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 Selección de origen dinámico basada en contenido: ejemplos En los ejemplos siguientes se muestra cómo puede usar Lambda@Edge para el direccionamiento a diferentes orígenes en función de la información de la solicitud. Temas Ejemplo: Uso de un desencadenador de solicitud de origen para cambiar desde un origen personalizado a un origen de Amazon S3 Ejemplo: Uso de un desencadenador de solicitud de origen para cambiar la región de origen de Amazon S3 Ejemplo: Uso de un desencadenador de solicitud de origen para cambiar desde un origen de Amazon S3 a un origen personalizado Ejemplo: Uso de un desencadenador de solicitud al origen para transferir gradualmente el tráfico desde un bucket de Amazon S3 a otro Ejemplo: Uso de un desencadenador de solicitud de origen para cambiar el nombre del dominio de origen en función del encabezado de país Ejemplo: Uso de un desencadenador de solicitud de origen para cambiar desde un origen personalizado a un origen de Amazon S3 Esta función demuestra cómo utilizar un desencadenador de solicitud al origen para cambiar desde un origen personalizado a un origen de Amazon S3 desde el que recuperar el contenido, en función de las propiedades de la solicitud. 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: 'origin-access-identity', path: '', customHeaders: { } } }; request.headers['host'] = [ { key: 'host', value: s3DomainName}]; } } 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 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': 'origin-access-identity', 'path': '', 'customHeaders': { } } } request['headers']['host'] = [ { 'key': 'host', 'value': s3DomainName}] return request Ejemplo: Uso de un desencadenador de solicitud de origen para cambiar la región de origen de Amazon S3 Esta función demuestra cómo utilizar un desencadenador de solicitud al origen para cambiar el origen de Amazon S3 desde el que se recupera el contenido, en función de las propiedades de la solicitud. En este ejemplo, utilizamos el valor del encabezado CloudFront-Viewer-Country para actualizar el nombre de dominio del bucket de S3 por un bucket de una región que está más cerca del lector. Esto puede resultar útil de varias maneras: Reduce las latencias cuando la región especificada está más cerca del país del lector. Proporciona soberanía de los datos, al asegurarse de que los datos se distribuyen desde un origen que está en el país del que provino la solicitud. Para utilizar este ejemplo, debe hacer lo siguiente: Configure la distribución para almacenar en la caché en función del encabezado CloudFront-Viewer-Country . Para obtener más información, consulte Caché en función de encabezados de solicitud seleccionados . Crear un disparador para esta función en el evento de solicitud al origen. CloudFront agrega el encabezado CloudFront-Viewer-Country después del evento de solicitud del lector; por lo tanto, para utilizar este ejemplo, debe asegurarse de que la función ejecuta una solicitud de origen. nota El siguiente código de ejemplo usa la misma identidad de acceso de origen (OAI) para todos los buckets de S3 que usa para el origen. Para obtener más información, consulte Identidad de acceso de origen . 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 * 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); }; Python 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: 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: ''' 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 Ejemplo: Uso de un desencadenador de solicitud de origen para cambiar desde un origen de Amazon S3 a un origen personalizado Esta función demuestra cómo utilizar un disparador de solicitud al origen para cambiar el origen personalizado desde el que se recupera el contenido, en función de las propiedades de la solicitud. 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: { 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': { } } } request['headers']['host'] = [ { 'key': 'host', 'value': 'www.example.com'}] return request Ejemplo: Uso de un desencadenador de solicitud al origen para transferir gradualmente el tráfico desde un bucket de Amazon S3 a otro Esta función demuestra cómo transferir gradualmente el tráfico desde un bucket de Amazon S3 a otro de forma controlada. 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}]; } 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 Ejemplo: Uso de un desencadenador de solicitud de origen para cambiar el nombre del dominio de origen en función del encabezado de país Esta función demuestra cómo cambiar el nombre del dominio de origen en función del encabezado CloudFront-Viewer-Country , de forma que el contenido se distribuya desde un origen más cercano al país del lector. La implementación de esta funcionalidad para su distribución puede tener ventajas como las siguientes: Reducir las latencias cuando la región especificada está más cerca del país del lector Proporcionar soberanía de los datos, al asegurarse de que los datos se distribuyen desde un origen que está en el país del que provino la solicitud Tenga en cuenta que para habilitar esta funcionalidad, debe configurar su distribución para almacenar en la caché en función del encabezado CloudFront-Viewer-Country . Para obtener más información, consulte Caché en función de encabezados de solicitud seleccionados . 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 request['headers']['host'] = [ { 'key': 'host', 'value': domainName}] return request Actualización de estados de error: ejemplos En los ejemplos siguientes se proporciona orientación acerca de cómo puede usar Lambda@Edge para cambiar el estado de error que se devuelve a los usuarios. Temas Ejemplo: Uso de un desencadenador de respuesta de origen para actualizar el código de estado de error a 200 Ejemplo: Uso de un desencadenador de respuesta de origen para actualizar el código de estado de error a 302 Ejemplo: Uso de un desencadenador de respuesta de origen para actualizar el código de estado de error a 200 Esta función demuestra cómo actualizar el estado de la respuesta a 200 y generar un cuerpo con contenido estático para devolverlo al espectador en la siguiente situación: La función se desencadena en una respuesta del origen. El estado de la respuesta del servidor de origen es un código de estado de error (4xx o 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'; } callback(null, response); }; Python 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 Ejemplo: Uso de un desencadenador de respuesta de origen para actualizar el código de estado de error a 302 Esta función demuestra cómo actualizar el código de estado HTTP a 302 para la redirección a otra ruta (comportamiento de la caché) en la que se ha configurado un origen diferente. Tenga en cuenta lo siguiente: La función se desencadena en una respuesta del origen. El estado de la respuesta del servidor de origen es un código de estado de error (4xx o 5xx). Node.js 'use strict'; exports.handler = (event, context, callback) => { const response = event.Records[0].cf.response; const 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 (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 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 Acceso al cuerpo de la solicitud: ejemplos En los ejemplos siguientes se muestra cómo puede usar Lambda@Edge para trabajar con las solicitudes POST. nota Para utilizar estos ejemplos, debe habilitar la opción incluir cuerpo en la asociación de funciones Lambda de la distribución. No está habilitada de forma predeterminada. Para habilitar esta configuración en la consola de CloudFront, seleccione la casilla de verificación Incluir cuerpo en la Asociación de funciones Lambda . Para habilitar esta configuración en la API de CloudFront o con CloudFormation, establezca el campo IncludeBody en true en LambdaFunctionAssociation . Temas Ejemplo: Uso de un desencadenador de solicitud para leer un formulario HTML Ejemplo: Uso de un desencadenador de solicitud para modificar un formulario HTML Ejemplo: Uso de un desencadenador de solicitud para leer un formulario HTML Esta función ilustra cómo puede procesar el cuerpo de una solicitud POST generada por un formulario HTML (formulario web), como por ejemplo un formulario tipo "póngase en contacto con nosotros". Por ejemplo, es posible que tenga un formulario HTML como el siguiente: <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> Para la función de ejemplo que se indica a continuación, la función se debe desencadenar en una solicitud al origen o del lector de CloudFront. 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 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 Ejemplo: Uso de un desencadenador de solicitud para modificar un formulario HTML Esta función ilustra cómo puede modificar el cuerpo de una solicitud POST generada por un formulario HTML (formulario web). La función se activa en una solicitud al origen o del lector de CloudFront. 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. * * 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'] | 2026-01-13T09:30:35 |
https://aws.amazon.com/app-mesh/ | Application Networking Service – AWS App Mesh – Amazon Web Services Skip to main content Filter: All English Contact us AWS Marketplace Support My account Search Filter: All Sign in to console Create account AWS App Mesh Overview Features Pricing Getting Started FAQs More Products › Networking and Content Delivery › AWS App Mesh End of support notice: On September 30th, 2026, AWS will discontinue support for AWS AppMesh. After September 30th, 2026, you will no longer be able to access the AWS AppMesh console or AWS AppMesh resources. For more information, see the blog post. AWS App Mesh Application-level networking for all your services Why App Mesh? Play Benefits of App Mesh Streamline Streamline operations, implement custom traffic routing rules, and configure and standardize how traffic flows between your services. Optimize Capture metrics, logs, and traces from your applications to quickly identify and isolate issues and optimize your application. Enhance security Enhance network security with authentication controls and encrypted requests between services—even within your private network. Create an AWS account Learn What Is AWS? What Is Cloud Computing? What Is Agentic AI? Cloud Computing Concepts Hub AWS Cloud Security What's New Blogs Press Releases Resources Getting Started Training AWS Trust Center AWS Solutions Library Architecture Center Product and Technical FAQs Analyst Reports AWS Partners Developers Builder Center SDKs & Tools .NET on AWS Python on AWS Java on AWS PHP on AWS JavaScript on AWS Help Contact Us File a Support Ticket AWS re:Post Knowledge Center AWS Support Overview Get Expert Help AWS Accessibility Legal English Back to top Amazon is an Equal Opportunity Employer: Minority / Women / Disability / Veteran / Gender Identity / Sexual Orientation / Age. x facebook linkedin instagram twitch youtube podcasts email Privacy Site terms Cookie Preferences © 2026, Amazon Web Services, Inc. or its affiliates. All rights reserved. | 2026-01-13T09:30:35 |
https://docs.aws.amazon.com/es_es/AmazonCloudFront/latest/DeveloperGuide/lambda-examples.html#lambda-examples-content-based-custom-origin-request-trigger | Funciones de ejemplo de Lambda@Edge - Amazon CloudFront Funciones de ejemplo de Lambda@Edge - Amazon CloudFront Documentación Amazon CloudFront Guía para desarrolladores Ejemplos generales Generación de respuestas: ejemplos Cadenas de consulta: ejemplos Personalización de contenido por encabezados de tipo de dispositivo o país: ejemplos Selección de origen dinámico basada en contenido: ejemplos Actualización de estados de error: ejemplos Acceso al cuerpo de la solicitud: ejemplos Funciones de ejemplo de Lambda@Edge Consulte los ejemplos siguientes para usar funciones de Lambda con Amazon CloudFront. nota Si elige el tiempo de ejecución Node.js 18 o una versión posterior para la función Lambda@Edge, se creará automáticamente un archivo index.mjs . Para usar los siguientes ejemplos de código, cambie el nombre del archivo index.mjs a index.js . Temas Ejemplos generales Generación de respuestas: ejemplos Cadenas de consulta: ejemplos Personalización de contenido por encabezados de tipo de dispositivo o país: ejemplos Selección de origen dinámico basada en contenido: ejemplos Actualización de estados de error: ejemplos Acceso al cuerpo de la solicitud: ejemplos Ejemplos generales Los ejemplos siguientes muestran formas habituales de usar Lambda@Edge en CloudFront. Temas Ejemplo: prueba A/B Ejemplo: Sobrescritura de un encabezado de respuesta Ejemplo: prueba A/B Puede utilizar el siguiente ejemplo para probar dos versiones diferentes de una imagen sin crear redirecciones ni cambiar la dirección URL. En este ejemplo se leen las cookies de la solicitud del lector y se modifica la URL de la solicitud en consecuencia. Si el espectador no envía una cookie con uno de los valores esperados, el ejemplo asigna aleatoriamente al espectador una de las URL. 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; } 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; } } 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" ''' experimentUri = "" 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 Ejemplo: Sobrescritura de un encabezado de respuesta En el ejemplo siguiente, se muestra cómo cambiar el valor de un encabezado de respuesta según el valor de otro encabezado. Node.js export const handler = async (event) => { 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()] = [ { key: headerNameDst, value: headers[headerNameSrc.toLowerCase()][0].value, }]; console.log(`Response header "$ { headerNameDst}" was set to ` + `"$ { headers[headerNameDst.toLowerCase()][0].value}"`); } return response; }; Python import json def lambda_handler(event, context): response = event['Records'][0]['cf']['response'] headers = response['headers'] header_name_src = 'X-Amz-Meta-Last-Modified' header_name_dst = 'Last-Modified' if headers.get(header_name_src.lower()): headers[header_name_dst.lower()] = [ { 'key': header_name_dst, 'value': headers[header_name_src.lower()][0]['value'] }] print(f'Response header " { header_name_dst}" was set to ' f'" { headers[header_name_dst.lower()][0]["value"]}"') return response Generación de respuestas: ejemplos En los ejemplos siguientes se muestra cómo puede usar Lambda@Edge para generar respuestas. Temas Ejemplo: Envío de contenido estático (respuesta generada) Ejemplo: Generación de un redireccionamiento HTTP (respuesta generada) Ejemplo: Envío de contenido estático (respuesta generada) En el siguiente ejemplo se muestra cómo utilizar una función de Lambda para enviar contenido de sitio web estático, lo que reduce la carga en el servidor de origen y la latencia total. nota Puede generar respuestas HTTP para los eventos de solicitud del espectador y al origen. Para obtener más información, consulte Generación de respuestas HTTP en los desencadenadores de solicitud . También puede sustituir o quitar el cuerpo de la respuesta HTTP en eventos de respuesta de origen. Para obtener más información, consulte Actualización de respuestas HTTP en desencadenadores de respuesta de origen . 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' }] }, 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 } return response Ejemplo: Generación de un redireccionamiento HTTP (respuesta generada) En el siguiente ejemplo se muestra cómo generar una redirección HTTP. nota Puede generar respuestas HTTP para los eventos de solicitud del espectador y al origen. Para obtener más información, consulte Generación de respuestas HTTP en los desencadenadores de solicitud . 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. response = { 'status': '302', 'statusDescription': 'Found', 'headers': { 'location': [ { 'key': 'Location', 'value': 'https://docs.aws.amazon.com/lambda/latest/dg/lambda-edge.html' }] } } return response Cadenas de consulta: ejemplos En los ejemplos siguientes se muestran formas de usar Lambda@Edge con cadenas de consulta. Temas Ejemplo: Adición de un encabezado en función de un parámetro de la cadena de consulta Ejemplo: Normalización de parámetros de cadenas de consulta para mejorar la tasa de aciertos de caché Ejemplo: Redireccionamiento de los usuarios no autenticados a una página de inicio de sesión Ejemplo: Adición de un encabezado en función de un parámetro de la cadena de consulta El siguiente ejemplo muestra cómo obtener el par clave-valor de un parámetro de la cadena de consulta y, a continuación, añadir un encabezado en función de dichos valores. 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. * 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 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'] # Update request querystring request['querystring'] = urlencode(params) return request Ejemplo: Normalización de parámetros de cadenas de consulta para mejorar la tasa de aciertos de caché El siguiente ejemplo muestra cómo mejorar la tasa de acceso a la caché haciendo los siguientes cambios en las cadenas de consulta antes de que CloudFront reenvíe las solicitudes a su origen: Alfabetizar los pares de clave-valor por el nombre del parámetro. Cambiar a minúsculas el modelo de mayúsculas y minúsculas de los pares de clave-valor. Para obtener más información, consulte Almacenamiento en caché de contenido en función de parámetros de cadenas de consulta . 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 */ 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 request['querystring'] = urlencode(sortedParams) return request Ejemplo: Redireccionamiento de los usuarios no autenticados a una página de inicio de sesión El siguiente ejemplo muestra cómo redirigir a los usuarios una página de inicio de sesión si no ha introducido sus credenciales. 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; } /* 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 params. ''' # Check for session-id in cookie, if present, then proceed with request parsedCookies = parseCookies(headers) 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 Personalización de contenido por encabezados de tipo de dispositivo o país: ejemplos En los ejemplos siguientes se muestra cómo puede usar Lambda@Edge para personalizar el comportamiento en función de la ubicación o el tipo de dispositivo que usa el lector. Temas Ejemplo: Redireccionamiento de solicitudes de espectadores a una URL específica de un país Ejemplo: Envío de distintas versiones de un objeto en función del dispositivo Ejemplo: Redireccionamiento de solicitudes de espectadores a una URL específica de un país El siguiente ejemplo muestra cómo generar una respuesta de redireccionamiento HTTP con una URL específica del país y devolver la respuesta al espectador. Esto resulta útil cuando se quiere proporcionar respuestas específicas del país. Por ejemplo: Si tiene subdominios específicos de un país, como us.ejemplo.com y tw.ejemplo.com, puede generar una respuesta de redireccionamiento cuando un espectador solicite ejemplo.com. Si está haciendo streaming de video, pero no tiene derechos para transmitir el contenido en un país determinado, puede redirigir a los usuarios de dicho país a una página en la que se explica por qué no pueden ver el video. Tenga en cuenta lo siguiente: Debe configurar la distribución para almacenar en la caché en función del encabezado CloudFront-Viewer-Country . Para obtener más información, consulte Caché en función de encabezados de solicitud seleccionados . CloudFront agrega el encabezado CloudFront-Viewer-Country después del evento de solicitud del lector. Para utilizar este ejemplo, debe crear un activador para el evento de solicitud al origen. 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 = { 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', 'statusDescription': 'Found', 'headers': { 'location': [ { 'key': 'Location', 'value': url }] } } return response Ejemplo: Envío de distintas versiones de un objeto en función del dispositivo El siguiente ejemplo muestra cómo ofrecer distintas versiones de un objeto en función del tipo de dispositivo que el usuario está utilizando; por ejemplo, un dispositivo móvil o una tablet. Tenga en cuenta lo siguiente: Debe configurar la distribución para almacenar en la caché en función de los encabezados CloudFront-Is-*-Viewer . Para obtener más información, consulte Caché en función de encabezados de solicitud seleccionados . CloudFront agrega los encabezados CloudFront-Is-*-Viewer después del evento de solicitud del lector. Para utilizar este ejemplo, debe crear un activador para el evento de solicitud al origen. 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 * 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. ''' desktopPath = '/desktop'; mobilePath = '/mobile'; tabletPath = '/tablet'; smarttvPath = '/smarttv'; 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 Selección de origen dinámico basada en contenido: ejemplos En los ejemplos siguientes se muestra cómo puede usar Lambda@Edge para el direccionamiento a diferentes orígenes en función de la información de la solicitud. Temas Ejemplo: Uso de un desencadenador de solicitud de origen para cambiar desde un origen personalizado a un origen de Amazon S3 Ejemplo: Uso de un desencadenador de solicitud de origen para cambiar la región de origen de Amazon S3 Ejemplo: Uso de un desencadenador de solicitud de origen para cambiar desde un origen de Amazon S3 a un origen personalizado Ejemplo: Uso de un desencadenador de solicitud al origen para transferir gradualmente el tráfico desde un bucket de Amazon S3 a otro Ejemplo: Uso de un desencadenador de solicitud de origen para cambiar el nombre del dominio de origen en función del encabezado de país Ejemplo: Uso de un desencadenador de solicitud de origen para cambiar desde un origen personalizado a un origen de Amazon S3 Esta función demuestra cómo utilizar un desencadenador de solicitud al origen para cambiar desde un origen personalizado a un origen de Amazon S3 desde el que recuperar el contenido, en función de las propiedades de la solicitud. 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: 'origin-access-identity', path: '', customHeaders: { } } }; request.headers['host'] = [ { key: 'host', value: s3DomainName}]; } } 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 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': 'origin-access-identity', 'path': '', 'customHeaders': { } } } request['headers']['host'] = [ { 'key': 'host', 'value': s3DomainName}] return request Ejemplo: Uso de un desencadenador de solicitud de origen para cambiar la región de origen de Amazon S3 Esta función demuestra cómo utilizar un desencadenador de solicitud al origen para cambiar el origen de Amazon S3 desde el que se recupera el contenido, en función de las propiedades de la solicitud. En este ejemplo, utilizamos el valor del encabezado CloudFront-Viewer-Country para actualizar el nombre de dominio del bucket de S3 por un bucket de una región que está más cerca del lector. Esto puede resultar útil de varias maneras: Reduce las latencias cuando la región especificada está más cerca del país del lector. Proporciona soberanía de los datos, al asegurarse de que los datos se distribuyen desde un origen que está en el país del que provino la solicitud. Para utilizar este ejemplo, debe hacer lo siguiente: Configure la distribución para almacenar en la caché en función del encabezado CloudFront-Viewer-Country . Para obtener más información, consulte Caché en función de encabezados de solicitud seleccionados . Crear un disparador para esta función en el evento de solicitud al origen. CloudFront agrega el encabezado CloudFront-Viewer-Country después del evento de solicitud del lector; por lo tanto, para utilizar este ejemplo, debe asegurarse de que la función ejecuta una solicitud de origen. nota El siguiente código de ejemplo usa la misma identidad de acceso de origen (OAI) para todos los buckets de S3 que usa para el origen. Para obtener más información, consulte Identidad de acceso de origen . 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 * 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); }; Python 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: 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: ''' 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 Ejemplo: Uso de un desencadenador de solicitud de origen para cambiar desde un origen de Amazon S3 a un origen personalizado Esta función demuestra cómo utilizar un disparador de solicitud al origen para cambiar el origen personalizado desde el que se recupera el contenido, en función de las propiedades de la solicitud. 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: { 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': { } } } request['headers']['host'] = [ { 'key': 'host', 'value': 'www.example.com'}] return request Ejemplo: Uso de un desencadenador de solicitud al origen para transferir gradualmente el tráfico desde un bucket de Amazon S3 a otro Esta función demuestra cómo transferir gradualmente el tráfico desde un bucket de Amazon S3 a otro de forma controlada. 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}]; } 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 Ejemplo: Uso de un desencadenador de solicitud de origen para cambiar el nombre del dominio de origen en función del encabezado de país Esta función demuestra cómo cambiar el nombre del dominio de origen en función del encabezado CloudFront-Viewer-Country , de forma que el contenido se distribuya desde un origen más cercano al país del lector. La implementación de esta funcionalidad para su distribución puede tener ventajas como las siguientes: Reducir las latencias cuando la región especificada está más cerca del país del lector Proporcionar soberanía de los datos, al asegurarse de que los datos se distribuyen desde un origen que está en el país del que provino la solicitud Tenga en cuenta que para habilitar esta funcionalidad, debe configurar su distribución para almacenar en la caché en función del encabezado CloudFront-Viewer-Country . Para obtener más información, consulte Caché en función de encabezados de solicitud seleccionados . 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 request['headers']['host'] = [ { 'key': 'host', 'value': domainName}] return request Actualización de estados de error: ejemplos En los ejemplos siguientes se proporciona orientación acerca de cómo puede usar Lambda@Edge para cambiar el estado de error que se devuelve a los usuarios. Temas Ejemplo: Uso de un desencadenador de respuesta de origen para actualizar el código de estado de error a 200 Ejemplo: Uso de un desencadenador de respuesta de origen para actualizar el código de estado de error a 302 Ejemplo: Uso de un desencadenador de respuesta de origen para actualizar el código de estado de error a 200 Esta función demuestra cómo actualizar el estado de la respuesta a 200 y generar un cuerpo con contenido estático para devolverlo al espectador en la siguiente situación: La función se desencadena en una respuesta del origen. El estado de la respuesta del servidor de origen es un código de estado de error (4xx o 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'; } callback(null, response); }; Python 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 Ejemplo: Uso de un desencadenador de respuesta de origen para actualizar el código de estado de error a 302 Esta función demuestra cómo actualizar el código de estado HTTP a 302 para la redirección a otra ruta (comportamiento de la caché) en la que se ha configurado un origen diferente. Tenga en cuenta lo siguiente: La función se desencadena en una respuesta del origen. El estado de la respuesta del servidor de origen es un código de estado de error (4xx o 5xx). Node.js 'use strict'; exports.handler = (event, context, callback) => { const response = event.Records[0].cf.response; const 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 (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 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 Acceso al cuerpo de la solicitud: ejemplos En los ejemplos siguientes se muestra cómo puede usar Lambda@Edge para trabajar con las solicitudes POST. nota Para utilizar estos ejemplos, debe habilitar la opción incluir cuerpo en la asociación de funciones Lambda de la distribución. No está habilitada de forma predeterminada. Para habilitar esta configuración en la consola de CloudFront, seleccione la casilla de verificación Incluir cuerpo en la Asociación de funciones Lambda . Para habilitar esta configuración en la API de CloudFront o con CloudFormation, establezca el campo IncludeBody en true en LambdaFunctionAssociation . Temas Ejemplo: Uso de un desencadenador de solicitud para leer un formulario HTML Ejemplo: Uso de un desencadenador de solicitud para modificar un formulario HTML Ejemplo: Uso de un desencadenador de solicitud para leer un formulario HTML Esta función ilustra cómo puede procesar el cuerpo de una solicitud POST generada por un formulario HTML (formulario web), como por ejemplo un formulario tipo "póngase en contacto con nosotros". Por ejemplo, es posible que tenga un formulario HTML como el siguiente: <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> Para la función de ejemplo que se indica a continuación, la función se debe desencadenar en una solicitud al origen o del lector de CloudFront. 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 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 Ejemplo: Uso de un desencadenador de solicitud para modificar un formulario HTML Esta función ilustra cómo puede modificar el cuerpo de una solicitud POST generada por un formulario HTML (formulario web). La función se activa en una solicitud al origen o del lector de CloudFront. 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. * * 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'] | 2026-01-13T09:30:35 |
https://docs.aws.amazon.com/es_es/AmazonCloudFront/latest/DeveloperGuide/lambda-examples.html#lambda-examples-content-based-S3-origin-request-trigger | Funciones de ejemplo de Lambda@Edge - Amazon CloudFront Funciones de ejemplo de Lambda@Edge - Amazon CloudFront Documentación Amazon CloudFront Guía para desarrolladores Ejemplos generales Generación de respuestas: ejemplos Cadenas de consulta: ejemplos Personalización de contenido por encabezados de tipo de dispositivo o país: ejemplos Selección de origen dinámico basada en contenido: ejemplos Actualización de estados de error: ejemplos Acceso al cuerpo de la solicitud: ejemplos Funciones de ejemplo de Lambda@Edge Consulte los ejemplos siguientes para usar funciones de Lambda con Amazon CloudFront. nota Si elige el tiempo de ejecución Node.js 18 o una versión posterior para la función Lambda@Edge, se creará automáticamente un archivo index.mjs . Para usar los siguientes ejemplos de código, cambie el nombre del archivo index.mjs a index.js . Temas Ejemplos generales Generación de respuestas: ejemplos Cadenas de consulta: ejemplos Personalización de contenido por encabezados de tipo de dispositivo o país: ejemplos Selección de origen dinámico basada en contenido: ejemplos Actualización de estados de error: ejemplos Acceso al cuerpo de la solicitud: ejemplos Ejemplos generales Los ejemplos siguientes muestran formas habituales de usar Lambda@Edge en CloudFront. Temas Ejemplo: prueba A/B Ejemplo: Sobrescritura de un encabezado de respuesta Ejemplo: prueba A/B Puede utilizar el siguiente ejemplo para probar dos versiones diferentes de una imagen sin crear redirecciones ni cambiar la dirección URL. En este ejemplo se leen las cookies de la solicitud del lector y se modifica la URL de la solicitud en consecuencia. Si el espectador no envía una cookie con uno de los valores esperados, el ejemplo asigna aleatoriamente al espectador una de las URL. 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; } 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; } } 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" ''' experimentUri = "" 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 Ejemplo: Sobrescritura de un encabezado de respuesta En el ejemplo siguiente, se muestra cómo cambiar el valor de un encabezado de respuesta según el valor de otro encabezado. Node.js export const handler = async (event) => { 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()] = [ { key: headerNameDst, value: headers[headerNameSrc.toLowerCase()][0].value, }]; console.log(`Response header "$ { headerNameDst}" was set to ` + `"$ { headers[headerNameDst.toLowerCase()][0].value}"`); } return response; }; Python import json def lambda_handler(event, context): response = event['Records'][0]['cf']['response'] headers = response['headers'] header_name_src = 'X-Amz-Meta-Last-Modified' header_name_dst = 'Last-Modified' if headers.get(header_name_src.lower()): headers[header_name_dst.lower()] = [ { 'key': header_name_dst, 'value': headers[header_name_src.lower()][0]['value'] }] print(f'Response header " { header_name_dst}" was set to ' f'" { headers[header_name_dst.lower()][0]["value"]}"') return response Generación de respuestas: ejemplos En los ejemplos siguientes se muestra cómo puede usar Lambda@Edge para generar respuestas. Temas Ejemplo: Envío de contenido estático (respuesta generada) Ejemplo: Generación de un redireccionamiento HTTP (respuesta generada) Ejemplo: Envío de contenido estático (respuesta generada) En el siguiente ejemplo se muestra cómo utilizar una función de Lambda para enviar contenido de sitio web estático, lo que reduce la carga en el servidor de origen y la latencia total. nota Puede generar respuestas HTTP para los eventos de solicitud del espectador y al origen. Para obtener más información, consulte Generación de respuestas HTTP en los desencadenadores de solicitud . También puede sustituir o quitar el cuerpo de la respuesta HTTP en eventos de respuesta de origen. Para obtener más información, consulte Actualización de respuestas HTTP en desencadenadores de respuesta de origen . 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' }] }, 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 } return response Ejemplo: Generación de un redireccionamiento HTTP (respuesta generada) En el siguiente ejemplo se muestra cómo generar una redirección HTTP. nota Puede generar respuestas HTTP para los eventos de solicitud del espectador y al origen. Para obtener más información, consulte Generación de respuestas HTTP en los desencadenadores de solicitud . 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. response = { 'status': '302', 'statusDescription': 'Found', 'headers': { 'location': [ { 'key': 'Location', 'value': 'https://docs.aws.amazon.com/lambda/latest/dg/lambda-edge.html' }] } } return response Cadenas de consulta: ejemplos En los ejemplos siguientes se muestran formas de usar Lambda@Edge con cadenas de consulta. Temas Ejemplo: Adición de un encabezado en función de un parámetro de la cadena de consulta Ejemplo: Normalización de parámetros de cadenas de consulta para mejorar la tasa de aciertos de caché Ejemplo: Redireccionamiento de los usuarios no autenticados a una página de inicio de sesión Ejemplo: Adición de un encabezado en función de un parámetro de la cadena de consulta El siguiente ejemplo muestra cómo obtener el par clave-valor de un parámetro de la cadena de consulta y, a continuación, añadir un encabezado en función de dichos valores. 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. * 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 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'] # Update request querystring request['querystring'] = urlencode(params) return request Ejemplo: Normalización de parámetros de cadenas de consulta para mejorar la tasa de aciertos de caché El siguiente ejemplo muestra cómo mejorar la tasa de acceso a la caché haciendo los siguientes cambios en las cadenas de consulta antes de que CloudFront reenvíe las solicitudes a su origen: Alfabetizar los pares de clave-valor por el nombre del parámetro. Cambiar a minúsculas el modelo de mayúsculas y minúsculas de los pares de clave-valor. Para obtener más información, consulte Almacenamiento en caché de contenido en función de parámetros de cadenas de consulta . 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 */ 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 request['querystring'] = urlencode(sortedParams) return request Ejemplo: Redireccionamiento de los usuarios no autenticados a una página de inicio de sesión El siguiente ejemplo muestra cómo redirigir a los usuarios una página de inicio de sesión si no ha introducido sus credenciales. 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; } /* 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 params. ''' # Check for session-id in cookie, if present, then proceed with request parsedCookies = parseCookies(headers) 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 Personalización de contenido por encabezados de tipo de dispositivo o país: ejemplos En los ejemplos siguientes se muestra cómo puede usar Lambda@Edge para personalizar el comportamiento en función de la ubicación o el tipo de dispositivo que usa el lector. Temas Ejemplo: Redireccionamiento de solicitudes de espectadores a una URL específica de un país Ejemplo: Envío de distintas versiones de un objeto en función del dispositivo Ejemplo: Redireccionamiento de solicitudes de espectadores a una URL específica de un país El siguiente ejemplo muestra cómo generar una respuesta de redireccionamiento HTTP con una URL específica del país y devolver la respuesta al espectador. Esto resulta útil cuando se quiere proporcionar respuestas específicas del país. Por ejemplo: Si tiene subdominios específicos de un país, como us.ejemplo.com y tw.ejemplo.com, puede generar una respuesta de redireccionamiento cuando un espectador solicite ejemplo.com. Si está haciendo streaming de video, pero no tiene derechos para transmitir el contenido en un país determinado, puede redirigir a los usuarios de dicho país a una página en la que se explica por qué no pueden ver el video. Tenga en cuenta lo siguiente: Debe configurar la distribución para almacenar en la caché en función del encabezado CloudFront-Viewer-Country . Para obtener más información, consulte Caché en función de encabezados de solicitud seleccionados . CloudFront agrega el encabezado CloudFront-Viewer-Country después del evento de solicitud del lector. Para utilizar este ejemplo, debe crear un activador para el evento de solicitud al origen. 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 = { 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', 'statusDescription': 'Found', 'headers': { 'location': [ { 'key': 'Location', 'value': url }] } } return response Ejemplo: Envío de distintas versiones de un objeto en función del dispositivo El siguiente ejemplo muestra cómo ofrecer distintas versiones de un objeto en función del tipo de dispositivo que el usuario está utilizando; por ejemplo, un dispositivo móvil o una tablet. Tenga en cuenta lo siguiente: Debe configurar la distribución para almacenar en la caché en función de los encabezados CloudFront-Is-*-Viewer . Para obtener más información, consulte Caché en función de encabezados de solicitud seleccionados . CloudFront agrega los encabezados CloudFront-Is-*-Viewer después del evento de solicitud del lector. Para utilizar este ejemplo, debe crear un activador para el evento de solicitud al origen. 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 * 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. ''' desktopPath = '/desktop'; mobilePath = '/mobile'; tabletPath = '/tablet'; smarttvPath = '/smarttv'; 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 Selección de origen dinámico basada en contenido: ejemplos En los ejemplos siguientes se muestra cómo puede usar Lambda@Edge para el direccionamiento a diferentes orígenes en función de la información de la solicitud. Temas Ejemplo: Uso de un desencadenador de solicitud de origen para cambiar desde un origen personalizado a un origen de Amazon S3 Ejemplo: Uso de un desencadenador de solicitud de origen para cambiar la región de origen de Amazon S3 Ejemplo: Uso de un desencadenador de solicitud de origen para cambiar desde un origen de Amazon S3 a un origen personalizado Ejemplo: Uso de un desencadenador de solicitud al origen para transferir gradualmente el tráfico desde un bucket de Amazon S3 a otro Ejemplo: Uso de un desencadenador de solicitud de origen para cambiar el nombre del dominio de origen en función del encabezado de país Ejemplo: Uso de un desencadenador de solicitud de origen para cambiar desde un origen personalizado a un origen de Amazon S3 Esta función demuestra cómo utilizar un desencadenador de solicitud al origen para cambiar desde un origen personalizado a un origen de Amazon S3 desde el que recuperar el contenido, en función de las propiedades de la solicitud. 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: 'origin-access-identity', path: '', customHeaders: { } } }; request.headers['host'] = [ { key: 'host', value: s3DomainName}]; } } 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 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': 'origin-access-identity', 'path': '', 'customHeaders': { } } } request['headers']['host'] = [ { 'key': 'host', 'value': s3DomainName}] return request Ejemplo: Uso de un desencadenador de solicitud de origen para cambiar la región de origen de Amazon S3 Esta función demuestra cómo utilizar un desencadenador de solicitud al origen para cambiar el origen de Amazon S3 desde el que se recupera el contenido, en función de las propiedades de la solicitud. En este ejemplo, utilizamos el valor del encabezado CloudFront-Viewer-Country para actualizar el nombre de dominio del bucket de S3 por un bucket de una región que está más cerca del lector. Esto puede resultar útil de varias maneras: Reduce las latencias cuando la región especificada está más cerca del país del lector. Proporciona soberanía de los datos, al asegurarse de que los datos se distribuyen desde un origen que está en el país del que provino la solicitud. Para utilizar este ejemplo, debe hacer lo siguiente: Configure la distribución para almacenar en la caché en función del encabezado CloudFront-Viewer-Country . Para obtener más información, consulte Caché en función de encabezados de solicitud seleccionados . Crear un disparador para esta función en el evento de solicitud al origen. CloudFront agrega el encabezado CloudFront-Viewer-Country después del evento de solicitud del lector; por lo tanto, para utilizar este ejemplo, debe asegurarse de que la función ejecuta una solicitud de origen. nota El siguiente código de ejemplo usa la misma identidad de acceso de origen (OAI) para todos los buckets de S3 que usa para el origen. Para obtener más información, consulte Identidad de acceso de origen . 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 * 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); }; Python 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: 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: ''' 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 Ejemplo: Uso de un desencadenador de solicitud de origen para cambiar desde un origen de Amazon S3 a un origen personalizado Esta función demuestra cómo utilizar un disparador de solicitud al origen para cambiar el origen personalizado desde el que se recupera el contenido, en función de las propiedades de la solicitud. 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: { 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': { } } } request['headers']['host'] = [ { 'key': 'host', 'value': 'www.example.com'}] return request Ejemplo: Uso de un desencadenador de solicitud al origen para transferir gradualmente el tráfico desde un bucket de Amazon S3 a otro Esta función demuestra cómo transferir gradualmente el tráfico desde un bucket de Amazon S3 a otro de forma controlada. 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}]; } 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 Ejemplo: Uso de un desencadenador de solicitud de origen para cambiar el nombre del dominio de origen en función del encabezado de país Esta función demuestra cómo cambiar el nombre del dominio de origen en función del encabezado CloudFront-Viewer-Country , de forma que el contenido se distribuya desde un origen más cercano al país del lector. La implementación de esta funcionalidad para su distribución puede tener ventajas como las siguientes: Reducir las latencias cuando la región especificada está más cerca del país del lector Proporcionar soberanía de los datos, al asegurarse de que los datos se distribuyen desde un origen que está en el país del que provino la solicitud Tenga en cuenta que para habilitar esta funcionalidad, debe configurar su distribución para almacenar en la caché en función del encabezado CloudFront-Viewer-Country . Para obtener más información, consulte Caché en función de encabezados de solicitud seleccionados . 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 request['headers']['host'] = [ { 'key': 'host', 'value': domainName}] return request Actualización de estados de error: ejemplos En los ejemplos siguientes se proporciona orientación acerca de cómo puede usar Lambda@Edge para cambiar el estado de error que se devuelve a los usuarios. Temas Ejemplo: Uso de un desencadenador de respuesta de origen para actualizar el código de estado de error a 200 Ejemplo: Uso de un desencadenador de respuesta de origen para actualizar el código de estado de error a 302 Ejemplo: Uso de un desencadenador de respuesta de origen para actualizar el código de estado de error a 200 Esta función demuestra cómo actualizar el estado de la respuesta a 200 y generar un cuerpo con contenido estático para devolverlo al espectador en la siguiente situación: La función se desencadena en una respuesta del origen. El estado de la respuesta del servidor de origen es un código de estado de error (4xx o 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'; } callback(null, response); }; Python 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 Ejemplo: Uso de un desencadenador de respuesta de origen para actualizar el código de estado de error a 302 Esta función demuestra cómo actualizar el código de estado HTTP a 302 para la redirección a otra ruta (comportamiento de la caché) en la que se ha configurado un origen diferente. Tenga en cuenta lo siguiente: La función se desencadena en una respuesta del origen. El estado de la respuesta del servidor de origen es un código de estado de error (4xx o 5xx). Node.js 'use strict'; exports.handler = (event, context, callback) => { const response = event.Records[0].cf.response; const 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 (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 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 Acceso al cuerpo de la solicitud: ejemplos En los ejemplos siguientes se muestra cómo puede usar Lambda@Edge para trabajar con las solicitudes POST. nota Para utilizar estos ejemplos, debe habilitar la opción incluir cuerpo en la asociación de funciones Lambda de la distribución. No está habilitada de forma predeterminada. Para habilitar esta configuración en la consola de CloudFront, seleccione la casilla de verificación Incluir cuerpo en la Asociación de funciones Lambda . Para habilitar esta configuración en la API de CloudFront o con CloudFormation, establezca el campo IncludeBody en true en LambdaFunctionAssociation . Temas Ejemplo: Uso de un desencadenador de solicitud para leer un formulario HTML Ejemplo: Uso de un desencadenador de solicitud para modificar un formulario HTML Ejemplo: Uso de un desencadenador de solicitud para leer un formulario HTML Esta función ilustra cómo puede procesar el cuerpo de una solicitud POST generada por un formulario HTML (formulario web), como por ejemplo un formulario tipo "póngase en contacto con nosotros". Por ejemplo, es posible que tenga un formulario HTML como el siguiente: <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> Para la función de ejemplo que se indica a continuación, la función se debe desencadenar en una solicitud al origen o del lector de CloudFront. 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 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 Ejemplo: Uso de un desencadenador de solicitud para modificar un formulario HTML Esta función ilustra cómo puede modificar el cuerpo de una solicitud POST generada por un formulario HTML (formulario web). La función se activa en una solicitud al origen o del lector de CloudFront. 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. * * 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'] | 2026-01-13T09:30:35 |
https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/s3/client/get_object.html | get_object - Boto3 1.42.26 documentation Contents Menu Expand Light mode Dark mode Auto light/dark, in light mode Auto light/dark, in dark mode Close Menu Hide navigation sidebar Hide table of contents sidebar Skip to content Toggle site navigation sidebar Boto3 1.42.26 documentation Toggle Light / Dark / Auto color theme Toggle table of contents sidebar Toggle site navigation sidebar Boto3 1.42.26 documentation Feedback Do you have a suggestion to improve this website or boto3? Give us feedback . Quickstart A Sample Tutorial Code Examples Toggle navigation of Code Examples Amazon CloudWatch examples Toggle navigation of Amazon CloudWatch examples Creating alarms in Amazon CloudWatch Using alarm actions in Amazon CloudWatch Getting metrics from Amazon CloudWatch Sending events to Amazon CloudWatch Events Using subscription filters in Amazon CloudWatch Logs Amazon DynamoDB Amazon EC2 examples Toggle navigation of Amazon EC2 examples Managing Amazon EC2 instances Working with Amazon EC2 key pairs Describe Amazon EC2 Regions and Availability Zones Working with security groups in Amazon EC2 Using Elastic IP addresses in Amazon EC2 AWS Identity and Access Management examples Toggle navigation of AWS Identity and Access Management examples Managing IAM users Working with IAM policies Managing IAM access keys Working with IAM server certificates Managing IAM account aliases AWS Key Management Service (AWS KMS) examples Toggle navigation of AWS Key Management Service (AWS KMS) examples Encrypt and decrypt a file Amazon S3 examples Toggle navigation of Amazon S3 examples Amazon S3 buckets Uploading files Downloading files File transfer configuration Presigned URLs Bucket policies Access permissions Using an Amazon S3 bucket as a static web host Bucket CORS configuration Multi-Region Access Points AWS PrivateLink for Amazon S3 AWS Secrets Manager Amazon SES examples Toggle navigation of Amazon SES examples Verifying email addresses Working with email templates Managing email filters Using email rules Amazon SQS examples Toggle navigation of Amazon SQS examples Using queues in Amazon SQS Sending and receiving messages in Amazon SQS Managing visibility timeout in Amazon SQS Enabling long polling in Amazon SQS Using dead-letter queues in Amazon SQS Developer Guide Toggle navigation of Developer Guide Configuration Credentials Low-level clients Resources Session Collections Paginators Error handling Retries Extensibility guide Cloud9 What’s new Migrating from Boto 2.x Toggle navigation of Migrating from Boto 2.x Amazon S3 Amazon EC2 Migrating to Python 3 Upgrading notes Security Available Services Toggle navigation of Available Services AccessAnalyzer Account ACM ACMPCA AIOps PrometheusService Amplify AmplifyBackend AmplifyUIBuilder APIGateway ApiGatewayManagementApi ApiGatewayV2 AppConfig AppConfigData AppFabric Appflow AppIntegrationsService ApplicationAutoScaling ApplicationInsights CloudWatchApplicationSignals ApplicationCostProfiler AppMesh AppRunner AppStream AppSync ARCRegionswitch ARCZonalShift Artifact Athena AuditManager AutoScaling AutoScalingPlans B2BI Backup BackupGateway BackupSearch Batch BillingandCostManagementDashboards BillingandCostManagementDataExports BillingandCostManagementPricingCalculator BillingandCostManagementRecommendedActions Bedrock AgentsforBedrock AgentsforBedrockRuntime BedrockAgentCore BedrockAgentCoreControl DataAutomationforBedrock RuntimeforBedrockDataAutomation BedrockRuntime Billing BillingConductor Braket Budgets CostExplorer Chatbot Chime ChimeSDKIdentity ChimeSDKMediaPipelines ChimeSDKMeetings ChimeSDKMessaging ChimeSDKVoice CleanRoomsService CleanRoomsML Cloud9 CloudControlApi CloudDirectory CloudFormation CloudFront CloudFrontKeyValueStore CloudHSM CloudHSMV2 CloudSearch CloudSearchDomain CloudTrail CloudTrailDataService CloudWatch CodeArtifact CodeBuild CodeCatalyst CodeCommit CodeConnections CodeDeploy CodeGuruReviewer CodeGuruSecurity CodeGuruProfiler CodePipeline CodeStarconnections CodeStarNotifications CognitoIdentity CognitoIdentityProvider CognitoSync Comprehend ComprehendMedical ComputeOptimizer ComputeOptimizerAutomation ConfigService Connect ConnectContactLens ConnectCampaignService ConnectCampaignServiceV2 ConnectCases ConnectParticipant ControlCatalog ControlTower CostOptimizationHub CostandUsageReportService CustomerProfiles GlueDataBrew DataExchange DataPipeline DataSync DataZone DAX DeadlineCloud Detective DeviceFarm DevOpsGuru DirectConnect ApplicationDiscoveryService DLM DatabaseMigrationService DocDB DocDBElastic drs DirectoryService DirectoryServiceData AuroraDSQL DynamoDB DynamoDBStreams EBS EC2 EC2InstanceConnect ECR ECRPublic ECS EFS EKS EKSAuth ElastiCache ElasticBeanstalk ElasticLoadBalancing ElasticLoadBalancingv2 EMR EMRContainers EMRServerless EntityResolution ElasticsearchService EventBridge CloudWatchEvidently EVS finspace FinSpaceData Firehose FIS FMS ForecastService ForecastQueryService FraudDetector FreeTier FSx GameLift GameLiftStreams LocationServiceMapsV2 LocationServicePlacesV2 LocationServiceRoutesV2 Glacier GlobalAccelerator Glue ManagedGrafana Greengrass GreengrassV2 GroundStation GuardDuty Health HealthLake IAM IdentityStore imagebuilder ImportExport Inspector inspectorscan Inspector2 CloudWatchInternetMonitor Invoicing IoT IoTDataPlane IoTJobsDataPlane ManagedintegrationsforIoTDeviceManagement IoTAnalytics IoTDeviceAdvisor IoTEvents IoTEventsData IoTFleetWise IoTSecureTunneling IoTSiteWise IoTThingsGraph IoTTwinMaker IoTWireless IVS ivsrealtime ivschat Kafka KafkaConnect kendra KendraRanking Keyspaces KeyspacesStreams Kinesis KinesisVideoArchivedMedia KinesisVideoMedia KinesisVideoSignalingChannels KinesisVideoWebRTCStorage KinesisAnalytics KinesisAnalyticsV2 KinesisVideo KMS LakeFormation Lambda LaunchWizard LexModelBuildingService LexRuntimeService LexModelsV2 LexRuntimeV2 LicenseManager LicenseManagerLinuxSubscriptions LicenseManagerUserSubscriptions Lightsail LocationService CloudWatchLogs LookoutEquipment MainframeModernization MachineLearning Macie2 MailManager ManagedBlockchain ManagedBlockchainQuery AgreementService MarketplaceCatalog MarketplaceDeploymentService MarketplaceEntitlementService MarketplaceReportingService MarketplaceCommerceAnalytics MediaConnect MediaConvert MediaLive MediaPackage MediaPackageVod mediapackagev2 MediaStore MediaStoreData MediaTailor HealthImaging MemoryDB MarketplaceMetering MigrationHub mgn MigrationHubRefactorSpaces MigrationHubConfig MigrationHubOrchestrator MigrationHubStrategyRecommendations MultipartyApproval MQ MTurk MWAA MWAAServerless Neptune NeptuneGraph NeptuneData NetworkFirewall NetworkFlowMonitor NetworkManager CloudWatchNetworkMonitor UserNotifications UserNotificationsContacts NovaActService CloudWatchObservabilityAccessManager CloudWatchObservabilityAdminService odb Omics OpenSearchService OpenSearchServiceServerless Organizations OpenSearchIngestion Outposts Panorama PartnerCentralAccountAPI PartnerCentralBenefits PartnerCentralChannelAPI PartnerCentralSellingAPI PaymentCryptographyControlPlane PaymentCryptographyDataPlane PcaConnectorAd PrivateCAConnectorforSCEP ParallelComputingService Personalize PersonalizeEvents PersonalizeRuntime PI Pinpoint PinpointEmail PinpointSMSVoice PinpointSMSVoiceV2 EventBridgePipes Polly Pricing Proton QApps QBusiness QConnect QuickSight RAM RecycleBin RDS RDSDataService Redshift RedshiftDataAPIService RedshiftServerless Rekognition rePostPrivate ResilienceHub ResourceExplorer ResourceGroups ResourceGroupsTaggingAPI IAMRolesAnywhere Route53 Route53RecoveryCluster Route53RecoveryControlConfig Route53RecoveryReadiness Route53Domains Route53GlobalResolver Route53Profiles Route53Resolver RTBFabric CloudWatchRUM S3 S3Control S3Outposts S3Tables S3Vectors SageMaker AugmentedAIRuntime SagemakerEdgeManager SageMakerFeatureStoreRuntime SageMakergeospatialcapabilities SageMakerMetrics SageMakerRuntime SavingsPlans EventBridgeScheduler Schemas SimpleDB SecretsManager SecurityIncidentResponse SecurityHub SecurityLake ServerlessApplicationRepository ServiceQuotas ServiceCatalog AppRegistry ServiceDiscovery SES SESV2 Shield signer SignInService SimSpaceWeaver SnowDeviceManagement Snowball SNS EndUserMessagingSocial SQS SSM SSMContacts SSMGUIConnect SSMIncidents SystemsManagerQuickSetup SsmSap SSO SSOAdmin SSOOIDC SFN StorageGateway STS SupplyChain Support SupportApp SWF Synthetics TaxSettings Textract TimestreamInfluxDB TimestreamQuery TimestreamWrite TelcoNetworkBuilder TranscribeService Transfer Translate TrustedAdvisorPublicAPI VerifiedPermissions VoiceID VPCLattice WAF WAFRegional WAFV2 WellArchitected WickrAdminAPI ConnectWisdomService WorkDocs WorkMail WorkMailMessageFlow WorkSpaces WorkspacesInstances WorkSpacesThinClient WorkSpacesWeb XRay Core References Toggle navigation of Core References Boto3 reference Collections reference Resources reference Session reference Customization References Toggle navigation of Customization References DynamoDB customization reference S3 customization reference Back to top Toggle Light / Dark / Auto color theme Toggle table of contents sidebar S3 / Client / get_object get_object ¶ S3.Client. get_object ( ** kwargs ) ¶ Retrieves an object from Amazon S3. In the GetObject request, specify the full key name for the object. General purpose buckets - Both the virtual-hosted-style requests and the path-style requests are supported. For a virtual hosted-style request example, if you have the object photos/2006/February/sample.jpg , specify the object key name as /photos/2006/February/sample.jpg . For a path-style request example, if you have the object photos/2006/February/sample.jpg in the bucket named examplebucket , specify the object key name as /examplebucket/photos/2006/February/sample.jpg . For more information about request types, see HTTP Host Header Bucket Specification in the Amazon S3 User Guide . Directory buckets - Only virtual-hosted-style requests are supported. For a virtual hosted-style request example, if you have the object photos/2006/February/sample.jpg in the bucket named amzn-s3-demo-bucket--usw2-az1--x-s3 , specify the object key name as /photos/2006/February/sample.jpg . Also, when you make requests to this API operation, your requests are sent to the Zonal endpoint. These endpoints support virtual-hosted-style requests in the format `` https://bucket-name.s3express-zone-id.region-code.amazonaws.com/key-name `` . Path-style requests are not supported. For more information about endpoints in Availability Zones, see Regional and Zonal endpoints for directory buckets in Availability Zones in the Amazon S3 User Guide . For more information about endpoints in Local Zones, see Concepts for directory buckets in Local Zones in the Amazon S3 User Guide . Permissions General purpose bucket permissions - You must have the required permissions in a policy. To use GetObject , you must have the READ access to the object (or version). If you grant READ access to the anonymous user, the GetObject operation returns the object without using an authorization header. For more information, see Specifying permissions in a policy in the Amazon S3 User Guide . If you include a versionId in your request header, you must have the s3:GetObjectVersion permission to access a specific version of an object. The s3:GetObject permission is not required in this scenario. If you request the current version of an object without a specific versionId in the request header, only the s3:GetObject permission is required. The s3:GetObjectVersion permission is not required in this scenario. If the object that you request doesn’t exist, the error that Amazon S3 returns depends on whether you also have the s3:ListBucket permission. If you have the s3:ListBucket permission on the bucket, Amazon S3 returns an HTTP status code 404 Not Found error. If you don’t have the s3:ListBucket permission, Amazon S3 returns an HTTP status code 403 Access Denied error. Directory bucket permissions - To grant access to this API operation on a directory bucket, we recommend that you use the CreateSession API operation for session-based authorization. Specifically, you grant the s3express:CreateSession permission to the directory bucket in a bucket policy or an IAM identity-based policy. Then, you make the CreateSession API call on the bucket to obtain a session token. With the session token in your request header, you can make API requests to this operation. After the session token expires, you make another CreateSession API call to generate a new session token for use. Amazon Web Services CLI or SDKs create session and refresh the session token automatically to avoid service interruptions when a session expires. For more information about authorization, see CreateSession . If the object is encrypted using SSE-KMS, you must also have the kms:GenerateDataKey and kms:Decrypt permissions in IAM identity-based policies and KMS key policies for the KMS key. Storage classes If the object you are retrieving is stored in the S3 Glacier Flexible Retrieval storage class, the S3 Glacier Deep Archive storage class, the S3 Intelligent-Tiering Archive Access tier, or the S3 Intelligent-Tiering Deep Archive Access tier, before you can retrieve the object you must first restore a copy using RestoreObject . Otherwise, this operation returns an InvalidObjectState error. For information about restoring archived objects, see Restoring Archived Objects in the Amazon S3 User Guide . Directory buckets - Directory buckets only support EXPRESS_ONEZONE (the S3 Express One Zone storage class) in Availability Zones and ONEZONE_IA (the S3 One Zone-Infrequent Access storage class) in Dedicated Local Zones. Unsupported storage class values won’t write a destination object and will respond with the HTTP status code 400 Bad Request . Encryption Encryption request headers, like x-amz-server-side-encryption , should not be sent for the GetObject requests, if your object uses server-side encryption with Amazon S3 managed encryption keys (SSE-S3), server-side encryption with Key Management Service (KMS) keys (SSE-KMS), or dual-layer server-side encryption with Amazon Web Services KMS keys (DSSE-KMS). If you include the header in your GetObject requests for the object that uses these types of keys, you’ll get an HTTP 400 Bad Request error. Directory buckets - For directory buckets, there are only two supported options for server-side encryption: SSE-S3 and SSE-KMS. SSE-C isn’t supported. For more information, see Protecting data with server-side encryption in the Amazon S3 User Guide . Overriding response header values through the request There are times when you want to override certain response header values of a GetObject response. For example, you might override the Content-Disposition response header value through your GetObject request. You can override values for a set of response headers. These modified response header values are included only in a successful response, that is, when the HTTP status code 200 OK is returned. The headers you can override using the following query parameters in the request are a subset of the headers that Amazon S3 accepts when you create an object. The response headers that you can override for the GetObject response are Cache-Control , Content-Disposition , Content-Encoding , Content-Language , Content-Type , and Expires . To override values for a set of response headers in the GetObject response, you can use the following query parameters in the request. response-cache-control response-content-disposition response-content-encoding response-content-language response-content-type response-expires Note When you use these parameters, you must sign the request by using either an Authorization header or a presigned URL. These parameters cannot be used with an unsigned (anonymous) request. HTTP Host header syntax Directory buckets - The HTTP Host header syntax is Bucket-name.s3express-zone-id.region-code.amazonaws.com . The following operations are related to GetObject : ListBuckets GetObjectAcl Warning You must URL encode any signed header values that contain spaces. For example, if your header value is my file.txt , containing two spaces after my , you must URL encode this value to my%20%20file.txt . See also: AWS API Documentation Request Syntax response = client . get_object ( Bucket = 'string' , IfMatch = 'string' , IfModifiedSince = datetime ( 2015 , 1 , 1 ), IfNoneMatch = 'string' , IfUnmodifiedSince = datetime ( 2015 , 1 , 1 ), Key = 'string' , Range = 'string' , ResponseCacheControl = 'string' , ResponseContentDisposition = 'string' , ResponseContentEncoding = 'string' , ResponseContentLanguage = 'string' , ResponseContentType = 'string' , ResponseExpires = datetime ( 2015 , 1 , 1 ), VersionId = 'string' , SSECustomerAlgorithm = 'string' , SSECustomerKey = 'string' , RequestPayer = 'requester' , PartNumber = 123 , ExpectedBucketOwner = 'string' , ChecksumMode = 'ENABLED' ) Parameters : Bucket ( string ) – [REQUIRED] The bucket name containing the object. Directory buckets - When you use this operation with a directory bucket, you must use virtual-hosted-style requests in the format Bucket-name.s3express-zone-id.region-code.amazonaws.com . Path-style requests are not supported. Directory bucket names must be unique in the chosen Zone (Availability Zone or Local Zone). Bucket names must follow the format bucket-base-name--zone-id--x-s3 (for example, amzn-s3-demo-bucket--usw2-az1--x-s3 ). For information about bucket naming restrictions, see Directory bucket naming rules in the Amazon S3 User Guide . Access points - When you use this action with an access point for general purpose buckets, you must provide the alias of the access point in place of the bucket name or specify the access point ARN. When you use this action with an access point for directory buckets, you must provide the access point name in place of the bucket name. When using the access point ARN, you must direct requests to the access point hostname. The access point hostname takes the form AccessPointName - AccountId .s3-accesspoint.*Region*.amazonaws.com. When using this action with an access point through the Amazon Web Services SDKs, you provide the access point ARN in place of the bucket name. For more information about access point ARNs, see Using access points in the Amazon S3 User Guide . Object Lambda access points - When you use this action with an Object Lambda access point, you must direct requests to the Object Lambda access point hostname. The Object Lambda access point hostname takes the form AccessPointName - AccountId .s3-object-lambda.*Region*.amazonaws.com. Note Object Lambda access points are not supported by directory buckets. S3 on Outposts - When you use this action with S3 on Outposts, you must direct requests to the S3 on Outposts hostname. The S3 on Outposts hostname takes the form AccessPointName-AccountId.outpostID.s3-outposts.Region.amazonaws.com . When you use this action with S3 on Outposts, the destination bucket must be the Outposts access point ARN or the access point alias. For more information about S3 on Outposts, see What is S3 on Outposts? in the Amazon S3 User Guide . IfMatch ( string ) – Return the object only if its entity tag (ETag) is the same as the one specified in this header; otherwise, return a 412 Precondition Failed error. If both of the If-Match and If-Unmodified-Since headers are present in the request as follows: If-Match condition evaluates to true , and; If-Unmodified-Since condition evaluates to false ; then, S3 returns 200 OK and the data requested. For more information about conditional requests, see RFC 7232 . IfModifiedSince ( datetime ) – Return the object only if it has been modified since the specified time; otherwise, return a 304 Not Modified error. If both of the If-None-Match and If-Modified-Since headers are present in the request as follows: `` If-None-Match`` condition evaluates to false , and; If-Modified-Since condition evaluates to true ; then, S3 returns 304 Not Modified status code. For more information about conditional requests, see RFC 7232 . IfNoneMatch ( string ) – Return the object only if its entity tag (ETag) is different from the one specified in this header; otherwise, return a 304 Not Modified error. If both of the If-None-Match and If-Modified-Since headers are present in the request as follows: `` If-None-Match`` condition evaluates to false , and; If-Modified-Since condition evaluates to true ; then, S3 returns 304 Not Modified HTTP status code. For more information about conditional requests, see RFC 7232 . IfUnmodifiedSince ( datetime ) – Return the object only if it has not been modified since the specified time; otherwise, return a 412 Precondition Failed error. If both of the If-Match and If-Unmodified-Since headers are present in the request as follows: If-Match condition evaluates to true , and; If-Unmodified-Since condition evaluates to false ; then, S3 returns 200 OK and the data requested. For more information about conditional requests, see RFC 7232 . Key ( string ) – [REQUIRED] Key of the object to get. Range ( string ) – Downloads the specified byte range of an object. For more information about the HTTP Range header, see https://www.rfc-editor.org/rfc/rfc9110.html#name-range . Note Amazon S3 doesn’t support retrieving multiple ranges of data per GET request. ResponseCacheControl ( string ) – Sets the Cache-Control header of the response. ResponseContentDisposition ( string ) – Sets the Content-Disposition header of the response. ResponseContentEncoding ( string ) – Sets the Content-Encoding header of the response. ResponseContentLanguage ( string ) – Sets the Content-Language header of the response. ResponseContentType ( string ) – Sets the Content-Type header of the response. ResponseExpires ( datetime ) – Sets the Expires header of the response. VersionId ( string ) – Version ID used to reference a specific version of the object. By default, the GetObject operation returns the current version of an object. To return a different version, use the versionId subresource. Note If you include a versionId in your request header, you must have the s3:GetObjectVersion permission to access a specific version of an object. The s3:GetObject permission is not required in this scenario. If you request the current version of an object without a specific versionId in the request header, only the s3:GetObject permission is required. The s3:GetObjectVersion permission is not required in this scenario. Directory buckets - S3 Versioning isn’t enabled and supported for directory buckets. For this API operation, only the null value of the version ID is supported by directory buckets. You can only specify null to the versionId query parameter in the request. For more information about versioning, see PutBucketVersioning . SSECustomerAlgorithm ( string ) – Specifies the algorithm to use when decrypting the object (for example, AES256 ). If you encrypt an object by using server-side encryption with customer-provided encryption keys (SSE-C) when you store the object in Amazon S3, then when you GET the object, you must use the following headers: x-amz-server-side-encryption-customer-algorithm x-amz-server-side-encryption-customer-key x-amz-server-side-encryption-customer-key-MD5 For more information about SSE-C, see Server-Side Encryption (Using Customer-Provided Encryption Keys) in the Amazon S3 User Guide . Note This functionality is not supported for directory buckets. SSECustomerKey ( string ) – Specifies the customer-provided encryption key that you originally provided for Amazon S3 to encrypt the data before storing it. This value is used to decrypt the object when recovering it and must match the one used when storing the data. The key must be appropriate for use with the algorithm specified in the x-amz-server-side-encryption-customer-algorithm header. If you encrypt an object by using server-side encryption with customer-provided encryption keys (SSE-C) when you store the object in Amazon S3, then when you GET the object, you must use the following headers: x-amz-server-side-encryption-customer-algorithm x-amz-server-side-encryption-customer-key x-amz-server-side-encryption-customer-key-MD5 For more information about SSE-C, see Server-Side Encryption (Using Customer-Provided Encryption Keys) in the Amazon S3 User Guide . Note This functionality is not supported for directory buckets. SSECustomerKeyMD5 ( string ) – Specifies the 128-bit MD5 digest of the customer-provided encryption key according to RFC 1321. Amazon S3 uses this header for a message integrity check to ensure that the encryption key was transmitted without error. If you encrypt an object by using server-side encryption with customer-provided encryption keys (SSE-C) when you store the object in Amazon S3, then when you GET the object, you must use the following headers: x-amz-server-side-encryption-customer-algorithm x-amz-server-side-encryption-customer-key x-amz-server-side-encryption-customer-key-MD5 For more information about SSE-C, see Server-Side Encryption (Using Customer-Provided Encryption Keys) in the Amazon S3 User Guide . Note This functionality is not supported for directory buckets. Please note that this parameter is automatically populated if it is not provided. Including this parameter is not required RequestPayer ( string ) – Confirms that the requester knows that they will be charged for the request. Bucket owners need not specify this parameter in their requests. If either the source or destination S3 bucket has Requester Pays enabled, the requester will pay for corresponding charges to copy the object. For information about downloading objects from Requester Pays buckets, see Downloading Objects in Requester Pays Buckets in the Amazon S3 User Guide . Note This functionality is not supported for directory buckets. PartNumber ( integer ) – Part number of the object being read. This is a positive integer between 1 and 10,000. Effectively performs a ‘ranged’ GET request for the part specified. Useful for downloading just a part of an object. ExpectedBucketOwner ( string ) – The account ID of the expected bucket owner. If the account ID that you provide does not match the actual owner of the bucket, the request fails with the HTTP status code 403 Forbidden (access denied). ChecksumMode ( string ) – To retrieve the checksum, this mode must be enabled. Return type : dict Returns : Response Syntax { 'Body' : StreamingBody (), 'DeleteMarker' : True | False , 'AcceptRanges' : 'string' , 'Expiration' : 'string' , 'Restore' : 'string' , 'LastModified' : datetime ( 2015 , 1 , 1 ), 'ContentLength' : 123 , 'ETag' : 'string' , 'ChecksumCRC32' : 'string' , 'ChecksumCRC32C' : 'string' , 'ChecksumCRC64NVME' : 'string' , 'ChecksumSHA1' : 'string' , 'ChecksumSHA256' : 'string' , 'ChecksumType' : 'COMPOSITE' | 'FULL_OBJECT' , 'MissingMeta' : 123 , 'VersionId' : 'string' , 'CacheControl' : 'string' , 'ContentDisposition' : 'string' , 'ContentEncoding' : 'string' , 'ContentLanguage' : 'string' , 'ContentRange' : 'string' , 'ContentType' : 'string' , 'Expires' : datetime ( 2015 , 1 , 1 ), 'ExpiresString' : 'string' , 'WebsiteRedirectLocation' : 'string' , 'ServerSideEncryption' : 'AES256' | 'aws:fsx' | 'aws:kms' | 'aws:kms:dsse' , 'Metadata' : { 'string' : 'string' }, 'SSECustomerAlgorithm' : 'string' , 'SSECustomerKeyMD5' : 'string' , 'SSEKMSKeyId' : 'string' , 'BucketKeyEnabled' : True | False , 'StorageClass' : 'STANDARD' | 'REDUCED_REDUNDANCY' | 'STANDARD_IA' | 'ONEZONE_IA' | 'INTELLIGENT_TIERING' | 'GLACIER' | 'DEEP_ARCHIVE' | 'OUTPOSTS' | 'GLACIER_IR' | 'SNOW' | 'EXPRESS_ONEZONE' | 'FSX_OPENZFS' | 'FSX_ONTAP' , 'RequestCharged' : 'requester' , 'ReplicationStatus' : 'COMPLETE' | 'PENDING' | 'FAILED' | 'REPLICA' | 'COMPLETED' , 'PartsCount' : 123 , 'TagCount' : 123 , 'ObjectLockMode' : 'GOVERNANCE' | 'COMPLIANCE' , 'ObjectLockRetainUntilDate' : datetime ( 2015 , 1 , 1 ), 'ObjectLockLegalHoldStatus' : 'ON' | 'OFF' } Response Structure (dict) – Body ( StreamingBody ) – Object data. DeleteMarker (boolean) – Indicates whether the object retrieved was (true) or was not (false) a Delete Marker. If false, this response header does not appear in the response. Note If the current version of the object is a delete marker, Amazon S3 behaves as if the object was deleted and includes x-amz-delete-marker: true in the response. If the specified version in the request is a delete marker, the response returns a 405 Method Not Allowed error and the Last-Modified: timestamp response header. AcceptRanges (string) – Indicates that a range of bytes was specified in the request. Expiration (string) – If the object expiration is configured (see PutBucketLifecycleConfiguration ), the response includes this header. It includes the expiry-date and rule-id key-value pairs providing object expiration information. The value of the rule-id is URL-encoded. Note Object expiration information is not returned in directory buckets and this header returns the value “ NotImplemented ” in all responses for directory buckets. Restore (string) – Provides information about object restoration action and expiration time of the restored object copy. Note This functionality is not supported for directory buckets. Directory buckets only support EXPRESS_ONEZONE (the S3 Express One Zone storage class) in Availability Zones and ONEZONE_IA (the S3 One Zone-Infrequent Access storage class) in Dedicated Local Zones. LastModified (datetime) – Date and time when the object was last modified. General purpose buckets - When you specify a versionId of the object in your request, if the specified version in the request is a delete marker, the response returns a 405 Method Not Allowed error and the Last-Modified: timestamp response header. ContentLength (integer) – Size of the body in bytes. ETag (string) – An entity tag (ETag) is an opaque identifier assigned by a web server to a specific version of a resource found at a URL. ChecksumCRC32 (string) – The Base64 encoded, 32-bit CRC32 checksum of the object. This checksum is only present if the object was uploaded with the object. For more information, see Checking object integrity in the Amazon S3 User Guide . ChecksumCRC32C (string) – The Base64 encoded, 32-bit CRC32C checksum of the object. This checksum is only present if the checksum was uploaded with the object. For more information, see Checking object integrity in the Amazon S3 User Guide . ChecksumCRC64NVME (string) – The Base64 encoded, 64-bit CRC64NVME checksum of the object. For more information, see Checking object integrity in the Amazon S3 User Guide . ChecksumSHA1 (string) – The Base64 encoded, 160-bit SHA1 digest of the object. This checksum is only present if the checksum was uploaded with the object. For more information, see Checking object integrity in the Amazon S3 User Guide . ChecksumSHA256 (string) – The Base64 encoded, 256-bit SHA256 digest of the object. This checksum is only present if the checksum was uploaded with the object. For more information, see Checking object integrity in the Amazon S3 User Guide . ChecksumType (string) – The checksum type, which determines how part-level checksums are combined to create an object-level checksum for multipart objects. You can use this header response to verify that the checksum type that is received is the same checksum type that was specified in the CreateMultipartUpload request. For more information, see Checking object integrity in the Amazon S3 User Guide . MissingMeta (integer) – This is set to the number of metadata entries not returned in the headers that are prefixed with x-amz-meta- . This can happen if you create metadata using an API like SOAP that supports more flexible metadata than the REST API. For example, using SOAP, you can create metadata whose values are not legal HTTP headers. Note This functionality is not supported for directory buckets. VersionId (string) – Version ID of the object. Note This functionality is not supported for directory buckets. CacheControl (string) – Specifies caching behavior along the request/reply chain. ContentDisposition (string) – Specifies presentational information for the object. ContentEncoding (string) – Indicates what content encodings have been applied to the object and thus what decoding mechanisms must be applied to obtain the media-type referenced by the Content-Type header field. ContentLanguage (string) – The language the content is in. ContentRange (string) – The portion of the object returned in the response. ContentType (string) – A standard MIME type describing the format of the object data. Expires (datetime) – The date and time at which the object is no longer cacheable. Note This member has been deprecated. Please use ExpiresString instead. ExpiresString (string) – The raw, unparsed value of the Expires field. WebsiteRedirectLocation (string) – If the bucket is configured as a website, redirects requests for this object to another object in the same bucket or to an external URL. Amazon S3 stores the value of this header in the object metadata. Note This functionality is not supported for directory buckets. ServerSideEncryption (string) – The server-side encryption algorithm used when you store this object in Amazon S3 or Amazon FSx. Note When accessing data stored in Amazon FSx file systems using S3 access points, the only valid server side encryption option is aws:fsx . Metadata (dict) – A map of metadata to store with the object in S3. (string) – (string) – SSECustomerAlgorithm (string) – If server-side encryption with a customer-provided encryption key was requested, the response will include this header to confirm the encryption algorithm that’s used. Note This functionality is not supported for directory buckets. SSECustomerKeyMD5 (string) – If server-side encryption with a customer-provided encryption key was requested, the response will include this header to provide the round-trip message integrity verification of the customer-provided encryption key. Note This functionality is not supported for directory buckets. SSEKMSKeyId (string) – If present, indicates the ID of the KMS key that was used for object encryption. BucketKeyEnabled (boolean) – Indicates whether the object uses an S3 Bucket Key for server-side encryption with Key Management Service (KMS) keys (SSE-KMS). StorageClass (string) – Provides storage class information of the object. Amazon S3 returns this header for all objects except for S3 Standard storage class objects. Note Directory buckets - Directory buckets only support EXPRESS_ONEZONE (the S3 Express One Zone storage class) in Availability Zones and ONEZONE_IA (the S3 One Zone-Infrequent Access storage class) in Dedicated Local Zones. RequestCharged (string) – If present, indicates that the requester was successfully charged for the request. For more information, see Using Requester Pays buckets for storage transfers and usage in the Amazon Simple Storage Service user guide . Note This functionality is not supported for directory buckets. ReplicationStatus (string) – Amazon S3 can return this if your request involves a bucket that is either a source or destination in a replication rule. Note This functionality is not supported for directory buckets. PartsCount (integer) – The count of parts this object has. This value is only returned if you specify partNumber in your request and the object was uploaded as a multipart upload. TagCount (integer) – The number of tags, if any, on the object, when you have the relevant permission to read object tags. You can use GetObjectTagging to retrieve the tag set associated with an object. Note This functionality is not supported for directory buckets. ObjectLockMode (string) – The Object Lock mode that’s currently in place for this object. Note This functionality is not supported for directory buckets. ObjectLockRetainUntilDate (datetime) – The date and time when this object’s Object Lock will expire. Note This functionality is not supported for directory buckets. ObjectLockLegalHoldStatus (string) – Indicates whether this object has an active legal hold. This field is only returned if you have permission to view an object’s legal hold status. Note This functionality is not supported for directory buckets. Exceptions S3.Client.exceptions.NoSuchKey S3.Client.exceptions.InvalidObjectState Examples The following example retrieves an object for an S3 bucket. response = client . get_object ( Bucket = 'examplebucket' , Key = 'HappyFace.jpg' , ) print ( response ) Expected Output: { 'AcceptRanges' : 'bytes' , 'ContentLength' : '3191' , 'ContentType' : 'image/jpeg' , 'ETag' : '"6805f2cfc46c0f04559748bb039d69ae"' , 'LastModified' : datetime ( 2016 , 12 , 15 , 1 , 19 , 41 , 3 , 350 , 0 ), 'Metadata' : { }, 'TagCount' : 2 , 'VersionId' : 'null' , 'ResponseMetadata' : { '...' : '...' , }, } The following example retrieves an object for an S3 bucket. The request specifies the range header to retrieve a specific byte range. response = client . get_object ( Bucket = 'examplebucket' , Key = 'SampleFile.txt' , Range = 'bytes=0-9' , ) print ( response ) Expected Output: { 'AcceptRanges' : 'bytes' , 'ContentLength' : '10' , 'ContentRange' : 'bytes 0-9/43' , 'ContentType' : 'text/plain' , 'ETag' : '"0d94420ffd0bc68cd3d152506b97a9cc"' , 'LastModified' : datetime ( 2014 , 10 , 9 , 22 , 57 , 28 , 3 , 282 , 0 ), 'Metadata' : { }, 'VersionId' : 'null' , 'ResponseMetadata' : { '...' : '...' , }, } Next get_object_acl Previous get_bucket_website Copyright © 2026, Amazon Web Services, Inc Made with Sphinx and @pradyunsg 's Furo Privacy | Site Terms | Cookie preferences Toggle site table of content right sidebar On this page get_object S3.Client.get_object() | 2026-01-13T09:30:35 |
https://docs.aws.amazon.com/es_es/AmazonCloudFront/latest/DeveloperGuide/lambda-examples.html#lambda-examples-redirect-to-signin-page | Funciones de ejemplo de Lambda@Edge - Amazon CloudFront Funciones de ejemplo de Lambda@Edge - Amazon CloudFront Documentación Amazon CloudFront Guía para desarrolladores Ejemplos generales Generación de respuestas: ejemplos Cadenas de consulta: ejemplos Personalización de contenido por encabezados de tipo de dispositivo o país: ejemplos Selección de origen dinámico basada en contenido: ejemplos Actualización de estados de error: ejemplos Acceso al cuerpo de la solicitud: ejemplos Funciones de ejemplo de Lambda@Edge Consulte los ejemplos siguientes para usar funciones de Lambda con Amazon CloudFront. nota Si elige el tiempo de ejecución Node.js 18 o una versión posterior para la función Lambda@Edge, se creará automáticamente un archivo index.mjs . Para usar los siguientes ejemplos de código, cambie el nombre del archivo index.mjs a index.js . Temas Ejemplos generales Generación de respuestas: ejemplos Cadenas de consulta: ejemplos Personalización de contenido por encabezados de tipo de dispositivo o país: ejemplos Selección de origen dinámico basada en contenido: ejemplos Actualización de estados de error: ejemplos Acceso al cuerpo de la solicitud: ejemplos Ejemplos generales Los ejemplos siguientes muestran formas habituales de usar Lambda@Edge en CloudFront. Temas Ejemplo: prueba A/B Ejemplo: Sobrescritura de un encabezado de respuesta Ejemplo: prueba A/B Puede utilizar el siguiente ejemplo para probar dos versiones diferentes de una imagen sin crear redirecciones ni cambiar la dirección URL. En este ejemplo se leen las cookies de la solicitud del lector y se modifica la URL de la solicitud en consecuencia. Si el espectador no envía una cookie con uno de los valores esperados, el ejemplo asigna aleatoriamente al espectador una de las URL. 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; } 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; } } 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" ''' experimentUri = "" 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 Ejemplo: Sobrescritura de un encabezado de respuesta En el ejemplo siguiente, se muestra cómo cambiar el valor de un encabezado de respuesta según el valor de otro encabezado. Node.js export const handler = async (event) => { 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()] = [ { key: headerNameDst, value: headers[headerNameSrc.toLowerCase()][0].value, }]; console.log(`Response header "$ { headerNameDst}" was set to ` + `"$ { headers[headerNameDst.toLowerCase()][0].value}"`); } return response; }; Python import json def lambda_handler(event, context): response = event['Records'][0]['cf']['response'] headers = response['headers'] header_name_src = 'X-Amz-Meta-Last-Modified' header_name_dst = 'Last-Modified' if headers.get(header_name_src.lower()): headers[header_name_dst.lower()] = [ { 'key': header_name_dst, 'value': headers[header_name_src.lower()][0]['value'] }] print(f'Response header " { header_name_dst}" was set to ' f'" { headers[header_name_dst.lower()][0]["value"]}"') return response Generación de respuestas: ejemplos En los ejemplos siguientes se muestra cómo puede usar Lambda@Edge para generar respuestas. Temas Ejemplo: Envío de contenido estático (respuesta generada) Ejemplo: Generación de un redireccionamiento HTTP (respuesta generada) Ejemplo: Envío de contenido estático (respuesta generada) En el siguiente ejemplo se muestra cómo utilizar una función de Lambda para enviar contenido de sitio web estático, lo que reduce la carga en el servidor de origen y la latencia total. nota Puede generar respuestas HTTP para los eventos de solicitud del espectador y al origen. Para obtener más información, consulte Generación de respuestas HTTP en los desencadenadores de solicitud . También puede sustituir o quitar el cuerpo de la respuesta HTTP en eventos de respuesta de origen. Para obtener más información, consulte Actualización de respuestas HTTP en desencadenadores de respuesta de origen . 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' }] }, 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 } return response Ejemplo: Generación de un redireccionamiento HTTP (respuesta generada) En el siguiente ejemplo se muestra cómo generar una redirección HTTP. nota Puede generar respuestas HTTP para los eventos de solicitud del espectador y al origen. Para obtener más información, consulte Generación de respuestas HTTP en los desencadenadores de solicitud . 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. response = { 'status': '302', 'statusDescription': 'Found', 'headers': { 'location': [ { 'key': 'Location', 'value': 'https://docs.aws.amazon.com/lambda/latest/dg/lambda-edge.html' }] } } return response Cadenas de consulta: ejemplos En los ejemplos siguientes se muestran formas de usar Lambda@Edge con cadenas de consulta. Temas Ejemplo: Adición de un encabezado en función de un parámetro de la cadena de consulta Ejemplo: Normalización de parámetros de cadenas de consulta para mejorar la tasa de aciertos de caché Ejemplo: Redireccionamiento de los usuarios no autenticados a una página de inicio de sesión Ejemplo: Adición de un encabezado en función de un parámetro de la cadena de consulta El siguiente ejemplo muestra cómo obtener el par clave-valor de un parámetro de la cadena de consulta y, a continuación, añadir un encabezado en función de dichos valores. 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. * 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 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'] # Update request querystring request['querystring'] = urlencode(params) return request Ejemplo: Normalización de parámetros de cadenas de consulta para mejorar la tasa de aciertos de caché El siguiente ejemplo muestra cómo mejorar la tasa de acceso a la caché haciendo los siguientes cambios en las cadenas de consulta antes de que CloudFront reenvíe las solicitudes a su origen: Alfabetizar los pares de clave-valor por el nombre del parámetro. Cambiar a minúsculas el modelo de mayúsculas y minúsculas de los pares de clave-valor. Para obtener más información, consulte Almacenamiento en caché de contenido en función de parámetros de cadenas de consulta . 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 */ 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 request['querystring'] = urlencode(sortedParams) return request Ejemplo: Redireccionamiento de los usuarios no autenticados a una página de inicio de sesión El siguiente ejemplo muestra cómo redirigir a los usuarios una página de inicio de sesión si no ha introducido sus credenciales. 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; } /* 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 params. ''' # Check for session-id in cookie, if present, then proceed with request parsedCookies = parseCookies(headers) 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 Personalización de contenido por encabezados de tipo de dispositivo o país: ejemplos En los ejemplos siguientes se muestra cómo puede usar Lambda@Edge para personalizar el comportamiento en función de la ubicación o el tipo de dispositivo que usa el lector. Temas Ejemplo: Redireccionamiento de solicitudes de espectadores a una URL específica de un país Ejemplo: Envío de distintas versiones de un objeto en función del dispositivo Ejemplo: Redireccionamiento de solicitudes de espectadores a una URL específica de un país El siguiente ejemplo muestra cómo generar una respuesta de redireccionamiento HTTP con una URL específica del país y devolver la respuesta al espectador. Esto resulta útil cuando se quiere proporcionar respuestas específicas del país. Por ejemplo: Si tiene subdominios específicos de un país, como us.ejemplo.com y tw.ejemplo.com, puede generar una respuesta de redireccionamiento cuando un espectador solicite ejemplo.com. Si está haciendo streaming de video, pero no tiene derechos para transmitir el contenido en un país determinado, puede redirigir a los usuarios de dicho país a una página en la que se explica por qué no pueden ver el video. Tenga en cuenta lo siguiente: Debe configurar la distribución para almacenar en la caché en función del encabezado CloudFront-Viewer-Country . Para obtener más información, consulte Caché en función de encabezados de solicitud seleccionados . CloudFront agrega el encabezado CloudFront-Viewer-Country después del evento de solicitud del lector. Para utilizar este ejemplo, debe crear un activador para el evento de solicitud al origen. 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 = { 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', 'statusDescription': 'Found', 'headers': { 'location': [ { 'key': 'Location', 'value': url }] } } return response Ejemplo: Envío de distintas versiones de un objeto en función del dispositivo El siguiente ejemplo muestra cómo ofrecer distintas versiones de un objeto en función del tipo de dispositivo que el usuario está utilizando; por ejemplo, un dispositivo móvil o una tablet. Tenga en cuenta lo siguiente: Debe configurar la distribución para almacenar en la caché en función de los encabezados CloudFront-Is-*-Viewer . Para obtener más información, consulte Caché en función de encabezados de solicitud seleccionados . CloudFront agrega los encabezados CloudFront-Is-*-Viewer después del evento de solicitud del lector. Para utilizar este ejemplo, debe crear un activador para el evento de solicitud al origen. 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 * 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. ''' desktopPath = '/desktop'; mobilePath = '/mobile'; tabletPath = '/tablet'; smarttvPath = '/smarttv'; 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 Selección de origen dinámico basada en contenido: ejemplos En los ejemplos siguientes se muestra cómo puede usar Lambda@Edge para el direccionamiento a diferentes orígenes en función de la información de la solicitud. Temas Ejemplo: Uso de un desencadenador de solicitud de origen para cambiar desde un origen personalizado a un origen de Amazon S3 Ejemplo: Uso de un desencadenador de solicitud de origen para cambiar la región de origen de Amazon S3 Ejemplo: Uso de un desencadenador de solicitud de origen para cambiar desde un origen de Amazon S3 a un origen personalizado Ejemplo: Uso de un desencadenador de solicitud al origen para transferir gradualmente el tráfico desde un bucket de Amazon S3 a otro Ejemplo: Uso de un desencadenador de solicitud de origen para cambiar el nombre del dominio de origen en función del encabezado de país Ejemplo: Uso de un desencadenador de solicitud de origen para cambiar desde un origen personalizado a un origen de Amazon S3 Esta función demuestra cómo utilizar un desencadenador de solicitud al origen para cambiar desde un origen personalizado a un origen de Amazon S3 desde el que recuperar el contenido, en función de las propiedades de la solicitud. 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: 'origin-access-identity', path: '', customHeaders: { } } }; request.headers['host'] = [ { key: 'host', value: s3DomainName}]; } } 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 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': 'origin-access-identity', 'path': '', 'customHeaders': { } } } request['headers']['host'] = [ { 'key': 'host', 'value': s3DomainName}] return request Ejemplo: Uso de un desencadenador de solicitud de origen para cambiar la región de origen de Amazon S3 Esta función demuestra cómo utilizar un desencadenador de solicitud al origen para cambiar el origen de Amazon S3 desde el que se recupera el contenido, en función de las propiedades de la solicitud. En este ejemplo, utilizamos el valor del encabezado CloudFront-Viewer-Country para actualizar el nombre de dominio del bucket de S3 por un bucket de una región que está más cerca del lector. Esto puede resultar útil de varias maneras: Reduce las latencias cuando la región especificada está más cerca del país del lector. Proporciona soberanía de los datos, al asegurarse de que los datos se distribuyen desde un origen que está en el país del que provino la solicitud. Para utilizar este ejemplo, debe hacer lo siguiente: Configure la distribución para almacenar en la caché en función del encabezado CloudFront-Viewer-Country . Para obtener más información, consulte Caché en función de encabezados de solicitud seleccionados . Crear un disparador para esta función en el evento de solicitud al origen. CloudFront agrega el encabezado CloudFront-Viewer-Country después del evento de solicitud del lector; por lo tanto, para utilizar este ejemplo, debe asegurarse de que la función ejecuta una solicitud de origen. nota El siguiente código de ejemplo usa la misma identidad de acceso de origen (OAI) para todos los buckets de S3 que usa para el origen. Para obtener más información, consulte Identidad de acceso de origen . 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 * 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); }; Python 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: 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: ''' 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 Ejemplo: Uso de un desencadenador de solicitud de origen para cambiar desde un origen de Amazon S3 a un origen personalizado Esta función demuestra cómo utilizar un disparador de solicitud al origen para cambiar el origen personalizado desde el que se recupera el contenido, en función de las propiedades de la solicitud. 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: { 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': { } } } request['headers']['host'] = [ { 'key': 'host', 'value': 'www.example.com'}] return request Ejemplo: Uso de un desencadenador de solicitud al origen para transferir gradualmente el tráfico desde un bucket de Amazon S3 a otro Esta función demuestra cómo transferir gradualmente el tráfico desde un bucket de Amazon S3 a otro de forma controlada. 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}]; } 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 Ejemplo: Uso de un desencadenador de solicitud de origen para cambiar el nombre del dominio de origen en función del encabezado de país Esta función demuestra cómo cambiar el nombre del dominio de origen en función del encabezado CloudFront-Viewer-Country , de forma que el contenido se distribuya desde un origen más cercano al país del lector. La implementación de esta funcionalidad para su distribución puede tener ventajas como las siguientes: Reducir las latencias cuando la región especificada está más cerca del país del lector Proporcionar soberanía de los datos, al asegurarse de que los datos se distribuyen desde un origen que está en el país del que provino la solicitud Tenga en cuenta que para habilitar esta funcionalidad, debe configurar su distribución para almacenar en la caché en función del encabezado CloudFront-Viewer-Country . Para obtener más información, consulte Caché en función de encabezados de solicitud seleccionados . 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 request['headers']['host'] = [ { 'key': 'host', 'value': domainName}] return request Actualización de estados de error: ejemplos En los ejemplos siguientes se proporciona orientación acerca de cómo puede usar Lambda@Edge para cambiar el estado de error que se devuelve a los usuarios. Temas Ejemplo: Uso de un desencadenador de respuesta de origen para actualizar el código de estado de error a 200 Ejemplo: Uso de un desencadenador de respuesta de origen para actualizar el código de estado de error a 302 Ejemplo: Uso de un desencadenador de respuesta de origen para actualizar el código de estado de error a 200 Esta función demuestra cómo actualizar el estado de la respuesta a 200 y generar un cuerpo con contenido estático para devolverlo al espectador en la siguiente situación: La función se desencadena en una respuesta del origen. El estado de la respuesta del servidor de origen es un código de estado de error (4xx o 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'; } callback(null, response); }; Python 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 Ejemplo: Uso de un desencadenador de respuesta de origen para actualizar el código de estado de error a 302 Esta función demuestra cómo actualizar el código de estado HTTP a 302 para la redirección a otra ruta (comportamiento de la caché) en la que se ha configurado un origen diferente. Tenga en cuenta lo siguiente: La función se desencadena en una respuesta del origen. El estado de la respuesta del servidor de origen es un código de estado de error (4xx o 5xx). Node.js 'use strict'; exports.handler = (event, context, callback) => { const response = event.Records[0].cf.response; const 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 (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 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 Acceso al cuerpo de la solicitud: ejemplos En los ejemplos siguientes se muestra cómo puede usar Lambda@Edge para trabajar con las solicitudes POST. nota Para utilizar estos ejemplos, debe habilitar la opción incluir cuerpo en la asociación de funciones Lambda de la distribución. No está habilitada de forma predeterminada. Para habilitar esta configuración en la consola de CloudFront, seleccione la casilla de verificación Incluir cuerpo en la Asociación de funciones Lambda . Para habilitar esta configuración en la API de CloudFront o con CloudFormation, establezca el campo IncludeBody en true en LambdaFunctionAssociation . Temas Ejemplo: Uso de un desencadenador de solicitud para leer un formulario HTML Ejemplo: Uso de un desencadenador de solicitud para modificar un formulario HTML Ejemplo: Uso de un desencadenador de solicitud para leer un formulario HTML Esta función ilustra cómo puede procesar el cuerpo de una solicitud POST generada por un formulario HTML (formulario web), como por ejemplo un formulario tipo "póngase en contacto con nosotros". Por ejemplo, es posible que tenga un formulario HTML como el siguiente: <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> Para la función de ejemplo que se indica a continuación, la función se debe desencadenar en una solicitud al origen o del lector de CloudFront. 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 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 Ejemplo: Uso de un desencadenador de solicitud para modificar un formulario HTML Esta función ilustra cómo puede modificar el cuerpo de una solicitud POST generada por un formulario HTML (formulario web). La función se activa en una solicitud al origen o del lector de CloudFront. 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. * * 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'] | 2026-01-13T09:30:35 |
https://www.php.net/x-myracloud-5958a2bbbed300a9b9ac631223924e0b/1768296244.861 | PHP update page now Downloads Documentation Get Involved Help Search docs Getting Started Introduction A simple tutorial Language Reference Basic syntax Types Variables Constants Expressions Operators Control Structures Functions Classes and Objects Namespaces Enumerations Errors Exceptions Fibers Generators Attributes References Explained Predefined Variables Predefined Exceptions Predefined Interfaces and Classes Predefined Attributes Context options and parameters Supported Protocols and Wrappers Security Introduction General considerations Installed as CGI binary Installed as an Apache module Session Security Filesystem Security Database Security Error Reporting User Submitted Data Hiding PHP Keeping Current Features HTTP authentication with PHP Cookies Sessions Handling file uploads Using remote files Connection handling Persistent Database Connections Command line usage Garbage Collection DTrace Dynamic Tracing Function Reference Affecting PHP's Behaviour Audio Formats Manipulation Authentication Services Command Line Specific Extensions Compression and Archive Extensions Cryptography Extensions Database Extensions Date and Time Related Extensions File System Related Extensions Human Language and Character Encoding Support Image Processing and Generation Mail Related Extensions Mathematical Extensions Non-Text MIME Output Process Control Extensions Other Basic Extensions Other Services Search Engine Extensions Server Specific Extensions Session Extensions Text Processing Variable and Type Related Extensions Web Services Windows Only Extensions XML Manipulation GUI Extensions Keyboard Shortcuts ? This help j Next menu item k Previous menu item g p Previous man page g n Next man page G Scroll to bottom g g Scroll to top g h Goto homepage g s Goto search (current page) / Focus search box A popular general-purpose scripting language that is especially suited to web development. Fast, flexible and pragmatic, PHP powers everything from your blog to the most popular websites in the world. What's new in 8.5 Download 8.5.1 · Changelog · Upgrading 8.4.16 · Changelog · Upgrading 8.3.29 · Changelog · Upgrading 8.2.30 · Changelog · Upgrading 18 Dec 2025 PHP 8.1.34 Released! The PHP development team announces the immediate availability of PHP 8.1.34. This is a security release. All PHP 8.1 users are encouraged to upgrade to this version. For source downloads of PHP 8.1.34 please visit our downloads page , Windows source and binaries can also be found there . The list of changes is recorded in the ChangeLog . 18 Dec 2025 PHP 8.4.16 Released! The PHP development team announces the immediate availability of PHP 8.4.16. This is a security release. All PHP 8.4 users are encouraged to upgrade to this version. For source downloads of PHP 8.4.16 please visit our downloads page , Windows source and binaries can also be found there . The list of changes is recorded in the ChangeLog . 18 Dec 2025 PHP 8.2.30 Released! The PHP development team announces the immediate availability of PHP 8.2.30. This is a security release. All PHP 8.2 users are encouraged to upgrade to this version. For source downloads of PHP 8.2.30 please visit our downloads page , Windows source and binaries can also be found there . The list of changes is recorded in the ChangeLog . 18 Dec 2025 PHP 8.3.29 Released! The PHP development team announces the immediate availability of PHP 8.3.29. This is a security release. All PHP 8.3 users are encouraged to upgrade to this version. For source downloads of PHP 8.3.29 please visit our downloads page , Windows source and binaries can also be found there . The list of changes is recorded in the ChangeLog . 18 Dec 2025 PHP 8.5.1 Released! The PHP development team announces the immediate availability of PHP 8.5.1. This is a security release. All PHP 8.5 users are encouraged to upgrade to this version. For source downloads of PHP 8.5.1 please visit our downloads page , Windows source and binaries can also be found there . The list of changes is recorded in the ChangeLog . 20 Nov 2025 PHP 8.5.0 Released! The PHP development team announces the immediate availability of PHP 8.5.0. This release marks the latest minor release of the PHP language. PHP 8.5 comes with numerous improvements and new features such as: New "URI" extension New pipe operator (|>) Clone With New #[\NoDiscard] attribute Support for closures, casts, and first class callables in constant expressions And much much more... For source downloads of PHP 8.5.0 please visit our downloads page , Windows source and binaries can also be found there . The list of changes is recorded in the ChangeLog . The migration guide is available in the PHP Manual. Please consult it for the detailed list of new features and backward incompatible changes. Kudos to all the contributors and supporters! 20 Nov 2025 PHP 8.4.15 Released! The PHP development team announces the immediate availability of PHP 8.4.15. This is a bug fix release. All PHP 8.4 users are encouraged to upgrade to this version. For source downloads of PHP 8.4.15 please visit our downloads page , Windows source and binaries can also be found there . The list of changes is recorded in the ChangeLog . 20 Nov 2025 PHP 8.3.28 Released! The PHP development team announces the immediate availability of PHP 8.3.28. This is a bug fix release. All PHP 8.3 users are encouraged to upgrade to this version. For source downloads of PHP 8.3.28 please visit our downloads page , Windows source and binaries can also be found there . The list of changes is recorded in the ChangeLog . 13 Nov 2025 PHP 8.5.0 RC 5 available for testing The PHP team is pleased to announce the fifth release candidate of PHP 8.5.0, RC 5. This continues the PHP 8.5 release cycle, the rough outline of which is specified in the PHP Wiki . For source downloads of PHP 8.5.0 RC5, please visit the download page . Please carefully test this version and report any issues found on GitHub . Please DO NOT use this version in production, it is a test version. For more information on the new features and other changes, you can read the NEWS file, or the UPGRADING file for a complete list of upgrading notes. These files can also be found in the release archive. The next release will be the GA release of PHP 8.5.0, planned for 20 Nov 2025. The signatures for the release can be found in the manifest or on the Release Candidates page . Thank you for helping us make PHP better. 06 Nov 2025 PHP 8.5.0 RC4 available for testing The PHP team is pleased to announce the final planned release candidate of PHP 8.5.0, RC 4. This continues the PHP 8.5 release cycle, the rough outline of which is specified in the PHP Wiki . For source downloads of PHP 8.5.0 RC4, please visit the download page . Please carefully test this version and report any issues found on GitHub . Please DO NOT use this version in production, it is a test version. For more information on the new features and other changes, you can read the NEWS file, or the UPGRADING file for a complete list of upgrading notes. These files can also be found in the release archive. The next release will be the GA release of PHP 8.5.0, planned for 20 Nov 2025. The signatures for the release can be found in the manifest or on the Release Candidates page . Thank you for helping us make PHP better. 23 Oct 2025 PHP 8.3.27 Released! The PHP development team announces the immediate availability of PHP 8.3.27. This is a bug fix release. All PHP 8.3 users are encouraged to upgrade to this version. For source downloads of PHP 8.3.27 please visit our downloads page , Windows source and binaries can be found on windows.php.net/download/ . The list of changes is recorded in the ChangeLog . 23 Oct 2025 PHP 8.4.14 Released! The PHP development team announces the immediate availability of PHP 8.4.14. This is a bug fix release. All PHP 8.4 users are encouraged to upgrade to this version. For source downloads of PHP 8.4.14 please visit our downloads page , Windows source and binaries can be found on windows.php.net/download/ . The list of changes is recorded in the ChangeLog . 23 Oct 2025 PHP 8.5.0 RC 3 available for testing The PHP team is pleased to announce the third release candidate of PHP 8.5.0, RC 3. This continues the PHP 8.5 release cycle, the rough outline of which is specified in the PHP Wiki . For source downloads of PHP 8.5.0 RC3, please visit the download page . Please carefully test this version and report any issues found on GitHub . Please DO NOT use this version in production, it is an early test version. For more information on the new features and other changes, you can read the NEWS file, or the UPGRADING file for a complete list of upgrading notes. These files can also be found in the release archive. The next release will be RC4, planned for 6 Nov 2025. The signatures for the release can be found in the manifest or on the Release Candidates page . Thank you for helping us make PHP better. 09 Oct 2025 PHP 8.5.0 RC 2 available for testing The PHP team is pleased to announce the second release candidate of PHP 8.5.0, RC 2. This continues the PHP 8.5 release cycle, the rough outline of which is specified in the PHP Wiki . For source downloads of PHP 8.5.0 RC2, please visit the download page . Please carefully test this version and report any issues found on GitHub . Please DO NOT use this version in production, it is an early test version. For more information on the new features and other changes, you can read the NEWS file, or the UPGRADING file for a complete list of upgrading notes. These files can also be found in the release archive. The next release will be RC3, planned for 23 Oct 2025. The signatures for the release can be found in the manifest or on the Release Candidates page . Thank you for helping us make PHP better. 25 Sep 2025 PHP 8.5.0 RC 1 available for testing The PHP team is pleased to announce the first release candidate of PHP 8.5.0, RC 1. This continues the PHP 8.5 release cycle, the rough outline of which is specified in the PHP Wiki . For source downloads of PHP 8.5.0 RC1, please visit the download page . Please carefully test this version and report any issues found on GitHub . Please DO NOT use this version in production, it is an early test version. For more information on the new features and other changes, you can read the NEWS file, or the UPGRADING file for a complete list of upgrading notes. These files can also be found in the release archive. The next release will be RC2, planned for 9 Oct 2025. The signatures for the release can be found in the manifest or on the Release Candidates page . Thank you for helping us make PHP better. 25 Sep 2025 PHP 8.3.26 Released! The PHP development team announces the immediate availability of PHP 8.3.26. This is a bug fix release. All PHP 8.3 users are encouraged to upgrade to this version. For source downloads of PHP 8.3.26 please visit our downloads page , Windows source and binaries can be found on windows.php.net/download/ . The list of changes is recorded in the ChangeLog . 25 Sep 2025 PHP 8.4.13 Released! The PHP development team announces the immediate availability of PHP 8.4.13. This is a bug fix release. All PHP 8.4 users are encouraged to upgrade to this version. For source downloads of PHP 8.4.13 please visit our downloads page , Windows source and binaries can be found on windows.php.net/download/ . The list of changes is recorded in the ChangeLog . 11 Sep 2025 PHP 8.5.0 Beta 3 available for testing The PHP team is pleased to announce the third beta release of PHP 8.5.0, Beta 3. This continues the PHP 8.5 release cycle, the rough outline of which is specified in the PHP Wiki . For source downloads of PHP 8.5.0 Beta 3, please visit the download page . Please carefully test this version and report any issues found on GitHub . Please DO NOT use this version in production, it is an early test version. For more information on the new features and other changes, you can read the NEWS file, or the UPGRADING file for a complete list of upgrading notes. These files can also be found in the release archive. The next release will be RC1, planned for 25 Sep 2025. The signatures for the release can be found in the manifest or on the Release Candidates page . Thank you for helping us make PHP better. 28 Aug 2025 PHP 8.5.0 Beta 2 available for testing The PHP team is pleased to announce the second beta release of PHP 8.5.0, Beta 2. This continues the PHP 8.5 release cycle, the rough outline of which is specified in the PHP Wiki . For source downloads of PHP 8.5.0 Beta 2 please visit the download page . Please carefully test this version and report any issues found on GitHub . Please DO NOT use this version in production, it is an early test version. For more information on the new features and other changes, you can read the NEWS file, or the UPGRADING file for a complete list of upgrading notes. These files can also be found in the release archive. The next release will be Beta 3, planned for 11 Sep 2025. The signatures for the release can be found in the manifest or on the Release Candidates page . Thank you for helping us make PHP better. 28 Aug 2025 PHP 8.3.25 Released! The PHP development team announces the immediate availability of PHP 8.3.25. This is a bug fix release. All PHP 8.3 users are encouraged to upgrade to this version. For source downloads of PHP 8.3.25 please visit our downloads page , Windows source and binaries can be found on windows.php.net/download/ . The list of changes is recorded in the ChangeLog . 28 Aug 2025 PHP 8.4.12 Released! The PHP development team announces the immediate availability of PHP 8.4.12. This is a bug fix release. All PHP 8.4 users are encouraged to upgrade to this version. For source downloads of PHP 8.4.12 please visit our downloads page , Windows source and binaries can be found on windows.php.net/download/ . The list of changes is recorded in the ChangeLog . 14 Aug 2025 PHP 8.5.0 Beta 1 available for testing The PHP team is pleased to announce the first beta release of PHP 8.5.0, Beta 1. This continues the PHP 8.5 release cycle, the rough outline of which is specified in the PHP Wiki . For source downloads of PHP 8.5.0 Beta 1 please visit the download page . Please carefully test this version and report any issues found on GitHub . Please DO NOT use this version in production, it is an early test version. For more information on the new features and other changes, you can read the NEWS file, or the UPGRADING file for a complete list of upgrading notes. These files can also be found in the release archive. The next release will be Beta 2, planned for 28 Aug 2025. The signatures for the release can be found in the manifest or on the Release Candidates page . Thank you for helping us make PHP better. 01 Aug 2025 PHP 8.5.0 Alpha 4 available for testing The PHP team is pleased to announce the third testing release of PHP 8.5.0, Alpha 4. This continues the PHP 8.5 release cycle, the rough outline of which is specified in the PHP Wiki . For source downloads of PHP 8.5.0 Alpha 4 please visit the download page . Please carefully test this version and report any issues found on GitHub . Please DO NOT use this version in production, it is an early test version. For more information on the new features and other changes, you can read the NEWS file, or the UPGRADING file for a complete list of upgrading notes. These files can also be found in the release archive. The next release will be Beta 1, planned for 14 Aug 2025. The signatures for the release can be found in the manifest or on the Release Candidates page . Thank you for helping us make PHP better. 31 Jul 2025 PHP 8.4.11 Released! The PHP development team announces the immediate availability of PHP 8.4.11. This is a bug fix release. All PHP 8.4 users are encouraged to upgrade to this version. For source downloads of PHP 8.4.11 please visit our downloads page , Windows source and binaries can be found on windows.php.net/download/ . The list of changes is recorded in the ChangeLog . 31 Jul 2025 PHP 8.3.24 Released! The PHP development team announces the immediate availability of PHP 8.3.24. This is a bug fix release. All PHP 8.3 users are encouraged to upgrade to this version. For source downloads of PHP 8.3.24 please visit our downloads page , Windows source and binaries can be found on windows.php.net/download/ . The list of changes is recorded in the ChangeLog . Older News Entries The PHP Foundation The PHP Foundation is a collective of people and organizations, united in the mission to ensure the long-term prosperity of the PHP language. Donate Upcoming conferences International PHP Conference Berlin 2026 Laravel Live Japan Conferences calling for papers Dutch PHP Conference 2026 User Group Events Special Thanks Social media @official_php @php@fosstodon.org @phpnet Copyright © 2001-2026 The PHP Group My PHP.net Contact Other PHP.net sites Privacy policy View Source ↑ and ↓ to navigate • Enter to select • Esc to close • / to open Press Enter without selection to search using Google | 2026-01-13T09:30:35 |
https://logging.apache.org/log4j/2.x/plugin-reference.html | Plugin reference :: Apache Log4j a subproject of Apache Logging Services Home Download Release notes Support Versioning and maintenance policy Security Manual Getting started Installation API Loggers Event Logger Simple Logger Status Logger Fluent API Fish tagging Levels Markers Thread Context Messages Flow Tracing Implementation Architecture Configuration Configuration file Configuration properties Programmatic configuration Appenders File appenders Rolling file appenders Database appenders Network Appenders Message queue appenders Delegating Appenders Layouts JSON Template Layout Pattern Layout Lookups Filters Scripts JMX Extending Plugins Performance Asynchronous loggers Garbage-free logging References Plugin reference Java API reference Resources F.A.Q. Migrating from Log4j 1 Migrating from Logback Migrating from SLF4J Building GraalVM native images Integrating with Hibernate Integrating with Jakarta EE Integrating with service-oriented architectures Development Components Log4j IOStreams Log4j Spring Boot Support Log4j Spring Cloud Configuration JUL-to-Log4j bridge Log4j-to-JUL bridge Related projects Log4j Jakarta EE Log4j JMX GUI Log4j Kotlin Log4j Scala Log4j Tools Log4j Transformation Tools Home References Plugin reference Edit this Page Plugin reference This page is a Javadoc-on-steroids specialized for Log4j plugins. This reference manual is derived from the source code of all Log4j plugins and types associated with them. You can use this reference manual to precisely customize your log4j2.xml . Every running Log4j system is a constellation of plugins , which is analogous to beans in Java EE and Spring. This not only allows Log4j itself to be developed in individual components, but also enables extensibility users can leverage. Shortcuts The <Configuration> element assembly in a log4j2.xml The type hierarchy of appenders The type hierarchy of layouts The type hierarchy of filters Index Below is a list of all types reachable by plugins grouped by the Maven coordinate of the artifact bundling them. log4j-1.2-api AbstractBuilder Class org.apache.log4j.builders.AbstractBuilder Provider org.apache.logging.log4j:log4j-1.2-api Base class for Log4j 1 component builders. Known implementations AsyncAppenderBuilder ConsoleAppenderBuilder DailyRollingFileAppenderBuilder EnhancedRollingFileAppenderBuilder FileAppenderBuilder RewriteAppenderBuilder RollingFileAppenderBuilder SocketAppenderBuilder SyslogAppenderBuilder LevelMatchFilterBuilder LevelRangeFilterBuilder StringMatchFilterBuilder HtmlLayoutBuilder PatternLayoutBuilder TTCCLayoutBuilder XmlLayoutBuilder CompositeTriggeringPolicyBuilder SizeBasedTriggeringPolicyBuilder TimeBasedRollingPolicyBuilder Builder Class org.apache.log4j.builders.Builder Provider org.apache.logging.log4j:log4j-1.2-api A marker interface for Log4j 1.x component builders. Known implementations AsyncAppenderBuilder ConsoleAppenderBuilder DailyRollingFileAppenderBuilder EnhancedRollingFileAppenderBuilder FileAppenderBuilder NullAppenderBuilder RewriteAppenderBuilder RollingFileAppenderBuilder SocketAppenderBuilder SyslogAppenderBuilder DenyAllFilterBuilder LevelMatchFilterBuilder LevelRangeFilterBuilder StringMatchFilterBuilder HtmlLayoutBuilder PatternLayoutBuilder SimpleLayoutBuilder TTCCLayoutBuilder XmlLayoutBuilder CompositeTriggeringPolicyBuilder SizeBasedTriggeringPolicyBuilder TimeBasedRollingPolicyBuilder Parser Class org.apache.log4j.builders.Parser Provider org.apache.logging.log4j:log4j-1.2-api Parses DOM and properties. Known implementations DenyAllFilterBuilder LevelMatchFilterBuilder LevelRangeFilterBuilder StringMatchFilterBuilder HtmlLayoutBuilder PatternLayoutBuilder SimpleLayoutBuilder TTCCLayoutBuilder XmlLayoutBuilder CompositeTriggeringPolicyBuilder SizeBasedTriggeringPolicyBuilder TimeBasedRollingPolicyBuilder AppenderBuilder Class org.apache.log4j.builders.appender.AppenderBuilder Provider org.apache.logging.log4j:log4j-1.2-api Define an Appender Builder. Known implementations AsyncAppenderBuilder ConsoleAppenderBuilder DailyRollingFileAppenderBuilder EnhancedRollingFileAppenderBuilder FileAppenderBuilder NullAppenderBuilder RewriteAppenderBuilder RollingFileAppenderBuilder SocketAppenderBuilder SyslogAppenderBuilder org.apache.log4j.AsyncAppender Class org.apache.log4j.builders.appender.AsyncAppenderBuilder Provider org.apache.logging.log4j:log4j-1.2-api Build an Async Appender XML snippet <org.apache.log4j.AsyncAppender/> org.apache.log4j.ConsoleAppender Class org.apache.log4j.builders.appender.ConsoleAppenderBuilder Provider org.apache.logging.log4j:log4j-1.2-api Build a Console Appender XML snippet <org.apache.log4j.ConsoleAppender/> org.apache.log4j.DailyRollingFileAppender Class org.apache.log4j.builders.appender.DailyRollingFileAppenderBuilder Provider org.apache.logging.log4j:log4j-1.2-api Build a Daily Rolling File Appender XML snippet <org.apache.log4j.DailyRollingFileAppender/> org.apache.log4j.rolling.RollingFileAppender Class org.apache.log4j.builders.appender.EnhancedRollingFileAppenderBuilder Provider org.apache.logging.log4j:log4j-1.2-api Build a File Appender XML snippet <org.apache.log4j.rolling.RollingFileAppender/> org.apache.log4j.FileAppender Class org.apache.log4j.builders.appender.FileAppenderBuilder Provider org.apache.logging.log4j:log4j-1.2-api Build a File Appender XML snippet <org.apache.log4j.FileAppender/> org.apache.log4j.varia.NullAppender Class org.apache.log4j.builders.appender.NullAppenderBuilder Provider org.apache.logging.log4j:log4j-1.2-api Build a Null Appender XML snippet <org.apache.log4j.varia.NullAppender/> org.apache.log4j.rewrite.RewriteAppender Class org.apache.log4j.builders.appender.RewriteAppenderBuilder Provider org.apache.logging.log4j:log4j-1.2-api Build a Rewrite Appender XML snippet <org.apache.log4j.rewrite.RewriteAppender/> org.apache.log4j.RollingFileAppender Class org.apache.log4j.builders.appender.RollingFileAppenderBuilder Provider org.apache.logging.log4j:log4j-1.2-api Build a File Appender XML snippet <org.apache.log4j.RollingFileAppender/> org.apache.log4j.net.SocketAppender Class org.apache.log4j.builders.appender.SocketAppenderBuilder Provider org.apache.logging.log4j:log4j-1.2-api Build a Console Appender XML snippet <org.apache.log4j.net.SocketAppender/> org.apache.log4j.net.SyslogAppender Class org.apache.log4j.builders.appender.SyslogAppenderBuilder Provider org.apache.logging.log4j:log4j-1.2-api Build a File Appender XML snippet <org.apache.log4j.net.SyslogAppender/> org.apache.log4j.varia.DenyAllFilter Class org.apache.log4j.builders.filter.DenyAllFilterBuilder Provider org.apache.logging.log4j:log4j-1.2-api Build a Pattern Layout XML snippet <org.apache.log4j.varia.DenyAllFilter/> FilterBuilder Class org.apache.log4j.builders.filter.FilterBuilder Provider org.apache.logging.log4j:log4j-1.2-api Define a Filter Builder. Known implementations DenyAllFilterBuilder LevelMatchFilterBuilder LevelRangeFilterBuilder StringMatchFilterBuilder org.apache.log4j.varia.LevelMatchFilter Class org.apache.log4j.builders.filter.LevelMatchFilterBuilder Provider org.apache.logging.log4j:log4j-1.2-api Build a Level match filter. XML snippet <org.apache.log4j.varia.LevelMatchFilter/> org.apache.log4j.varia.LevelRangeFilter Class org.apache.log4j.builders.filter.LevelRangeFilterBuilder Provider org.apache.logging.log4j:log4j-1.2-api Build a Level range filter. In this class, order of Level is log4j1 way, i.e., Level and Level have minimum and maximum order, respectively. (see: LOG4J2-2315) XML snippet <org.apache.log4j.varia.LevelRangeFilter/> org.apache.log4j.varia.StringMatchFilter Class org.apache.log4j.builders.filter.StringMatchFilterBuilder Provider org.apache.logging.log4j:log4j-1.2-api Build a String match filter. XML snippet <org.apache.log4j.varia.StringMatchFilter/> org.apache.log4j.HTMLLayout Class org.apache.log4j.builders.layout.HtmlLayoutBuilder Provider org.apache.logging.log4j:log4j-1.2-api Build a Pattern Layout XML snippet <org.apache.log4j.HTMLLayout/> LayoutBuilder Class org.apache.log4j.builders.layout.LayoutBuilder Provider org.apache.logging.log4j:log4j-1.2-api Define a Layout Builder. Known implementations HtmlLayoutBuilder PatternLayoutBuilder SimpleLayoutBuilder TTCCLayoutBuilder XmlLayoutBuilder org.apache.log4j.PatternLayout Class org.apache.log4j.builders.layout.PatternLayoutBuilder Provider org.apache.logging.log4j:log4j-1.2-api Build a Pattern Layout XML snippet <org.apache.log4j.PatternLayout/> org.apache.log4j.SimpleLayout Class org.apache.log4j.builders.layout.SimpleLayoutBuilder Provider org.apache.logging.log4j:log4j-1.2-api Build a Pattern Layout XML snippet <org.apache.log4j.SimpleLayout/> org.apache.log4j.TTCCLayout Class org.apache.log4j.builders.layout.TTCCLayoutBuilder Provider org.apache.logging.log4j:log4j-1.2-api Build a Pattern Layout XML snippet <org.apache.log4j.TTCCLayout/> org.apache.log4j.xml.XMLLayout Class org.apache.log4j.builders.layout.XmlLayoutBuilder Provider org.apache.logging.log4j:log4j-1.2-api Build an XML Layout XML snippet <org.apache.log4j.xml.XMLLayout/> org.apache.log4j.rolling.CompositeTriggeringPolicy Class org.apache.log4j.builders.rolling.CompositeTriggeringPolicyBuilder Provider org.apache.logging.log4j:log4j-1.2-api XML snippet <org.apache.log4j.rolling.CompositeTriggeringPolicy/> org.apache.log4j.rolling.SizeBasedTriggeringPolicy Class org.apache.log4j.builders.rolling.SizeBasedTriggeringPolicyBuilder Provider org.apache.logging.log4j:log4j-1.2-api XML snippet <org.apache.log4j.rolling.SizeBasedTriggeringPolicy/> org.apache.log4j.rolling.TimeBasedRollingPolicy Class org.apache.log4j.builders.rolling.TimeBasedRollingPolicyBuilder Provider org.apache.logging.log4j:log4j-1.2-api XML snippet <org.apache.log4j.rolling.TimeBasedRollingPolicy/> TriggeringPolicyBuilder Class org.apache.log4j.builders.rolling.TriggeringPolicyBuilder Provider org.apache.logging.log4j:log4j-1.2-api Known implementations CompositeTriggeringPolicyBuilder SizeBasedTriggeringPolicyBuilder TimeBasedRollingPolicyBuilder Log4j1PropertiesConfigurationFactory Class org.apache.log4j.config.PropertiesConfigurationFactory Provider org.apache.logging.log4j:log4j-1.2-api Configures Log4j from a log4j 1 format properties file. XML snippet <Log4j1PropertiesConfigurationFactory/> Log4j1SyslogLayout Class org.apache.log4j.layout.Log4j1SyslogLayout Provider org.apache.logging.log4j:log4j-1.2-api Port of the layout used by SyslogAppender in Log4j 1.x. Provided for compatibility with existing Log4j 1 configurations. Originally developed by Ceki Glc and Anders Kristensen. XML snippet <Log4j1SyslogLayout charset="" facility="" facilityPrinting="" footer="" header=""> <a-Layout-implementation/> <a-Serializer-implementation/> </Log4j1SyslogLayout> Attributes Optional attributes are denoted by ? -suffixed types. Name Type Default Description charset Charset? facility Facility ? facilityPrinting boolean? footer String? header boolean? Nested components Optional components are denoted by ? -suffixed types. Tag Type Description Layout ? Serializer? Log4j1XmlLayout Class org.apache.log4j.layout.Log4j1XmlLayout Provider org.apache.logging.log4j:log4j-1.2-api Port of XMLLayout in Log4j 1.x. Provided for compatibility with existing Log4j 1 configurations. Originally developed by Ceki Glc, Mathias Bogaert. XML snippet <Log4j1XmlLayout locationInfo="" properties=""/> Attributes Optional attributes are denoted by ? -suffixed types. Name Type Default Description locationInfo boolean? properties boolean? Log4j1LevelPatternConverter Class org.apache.log4j.pattern.Log4j1LevelPatternConverter Provider org.apache.logging.log4j:log4j-1.2-api Outputs the Log4j 1.x level name. XML snippet <Log4j1LevelPatternConverter/> Log4j1MdcPatternConverter Class org.apache.log4j.pattern.Log4j1MdcPatternConverter Provider org.apache.logging.log4j:log4j-1.2-api Able to handle the contents of the LogEvent’s MDC and either output the entire contents of the properties, or to output the value of a specific key within the property bundle when this pattern converter has the option set. XML snippet <Log4j1MdcPatternConverter/> Log4j1NdcPatternConverter Class org.apache.log4j.pattern.Log4j1NdcPatternConverter Provider org.apache.logging.log4j:log4j-1.2-api Returns the event’s NDC in a StringBuilder. XML snippet <Log4j1NdcPatternConverter/> Log4j1XmlConfigurationFactory Class org.apache.log4j.xml.XmlConfigurationFactory Provider org.apache.logging.log4j:log4j-1.2-api Constructs a Configuration usable in Log4j 2 from a Log4j 1 configuration file. XML snippet <Log4j1XmlConfigurationFactory/> log4j-cassandra Type Class com.datastax.driver.core.BatchStatement.Type Provider org.apache.logging.log4j:log4j-cassandra Cassandra Class org.apache.logging.log4j.cassandra.CassandraAppender Provider org.apache.logging.log4j:log4j-cassandra Appender plugin that uses a Cassandra database. XML snippet <Cassandra batched="" batchType="" bufferSize="" clusterName="" ignoreExceptions="" keyspace="" name="" password="" table="" useClockForTimestampGenerator="" username="" useTls=""> <a-Filter-implementation/> <a-Layout-implementation/> <ColumnMapping/><!-- multiple occurrences allowed --> <Property/><!-- multiple occurrences allowed --> <SocketAddress/><!-- multiple occurrences allowed --> </Cassandra> Attributes Optional attributes are denoted by ? -suffixed types. Name Type Default Description batched boolean? Whether or not to use batch statements when inserting records. batchType Type ? If batch statements are enabled, use this type of batch statement. bufferSize int? Number of LogEvents to buffer before writing. Can be used with or without batch statements. clusterName String ignoreExceptions boolean? keyspace String name String password String? table String useClockForTimestampGenerator boolean? Override the default TimestampGenerator with one based on the configured org.apache.logging.log4j.core.util.Clock . username String? useTls boolean? Nested components Optional components are denoted by ? -suffixed types. Tag Type Description ColumnMapping ColumnMapping List of column mappings to convert a LogEvent into a database row. Property Property ? Filter ? Layout ? SocketAddress SocketAddress List of Cassandra node contact points. Addresses without a port (or port set to 0) will use the default Cassandra port (9042). log4j-core SpinPolicy Class com.conversantmedia.util.concurrent.SpinPolicy Provider org.apache.logging.log4j:log4j-core QuoteMode Class org.apache.commons.csv.QuoteMode Provider org.apache.logging.log4j:log4j-core Level Class org.apache.logging.log4j.Level Provider org.apache.logging.log4j:log4j-core Represents a logging level. NOTE: The Log4j API supports custom levels, the following list contains only the standard ones. AbstractLifeCycle Class org.apache.logging.log4j.core.AbstractLifeCycle Provider org.apache.logging.log4j:log4j-core A life cycle to be extended. Wraps a org.apache.logging.log4j.core.LifeCycle.State . Known implementations CassandraAppender AsyncAppender ConsoleAppender CountingNoOpAppender FailoverAppender FileAppender HttpAppender MemoryMappedFileAppender NullAppender OutputStreamAppender RandomAccessFileAppender RollingFileAppender RollingRandomAccessFileAppender ScriptAppenderSelector SmtpAppender SocketAppender SyslogAppender WriterAppender DataSourceConnectionSource DriverManagerConnectionSource FactoryMethodConnectionSource JdbcAppender PoolingDriverConnectionSource JpaAppender JmsAppender JmsAppender JeroMqAppender KafkaAppender NoSqlAppender RewriteAppender CompositeTriggeringPolicy CronTriggeringPolicy NoOpTriggeringPolicy OnStartupTriggeringPolicy SizeBasedTriggeringPolicy TimeBasedTriggeringPolicy IdlePurgePolicy RoutingAppender AsyncLoggerConfig RootLogger LoggerConfig RootLogger BurstFilter CompositeFilter DenyAllFilter DynamicThresholdFilter LevelMatchFilter LevelRangeFilter MapFilter MarkerFilter MutableThreadContextMapFilter NoMarkerFilter RegexFilter ScriptFilter StringMatchFilter StructuredDataFilter ThreadContextMapFilter ThresholdFilter TimeFilter ServletAppender Appender Class org.apache.logging.log4j.core.Appender Provider org.apache.logging.log4j:log4j-core Appends org.apache.logging.log4j.core.LogEvent s. An Appender can contain a Layout if applicable as well as an org.apache.logging.log4j.core.ErrorHandler . Typical Appender implementations coordinate with an implementation of org.apache.logging.log4j.core.appender.AbstractManager to handle external resources such as streams, connections, and other shared state. As Appenders are plugins, concrete implementations need to be annotated with org.apache.logging.log4j.core.config.plugins.Plugin and need to provide a static factory method annotated with org.apache.logging.log4j.core.config.plugins.PluginFactory . Most core plugins are written using a related Manager class that handle the actual task of serializing a org.apache.logging.log4j.core.LogEvent to some output location. For instance, many Appenders can take advantage of the org.apache.logging.log4j.core.appender.OutputStreamManager class. It is recommended that Appenders don’t do any heavy lifting since there can be many instances of the class being used at any given time. When resources require locking (e.g., through org.apache.logging.log4j.core.java.nio.channels.FileLock ), it is important to isolate synchronized code to prevent concurrency issues. Known implementations CassandraAppender AsyncAppender ConsoleAppender CountingNoOpAppender FailoverAppender FileAppender HttpAppender MemoryMappedFileAppender NullAppender OutputStreamAppender RandomAccessFileAppender RollingFileAppender RollingRandomAccessFileAppender ScriptAppenderSelector SmtpAppender SocketAppender SyslogAppender WriterAppender JdbcAppender JpaAppender JmsAppender JmsAppender JeroMqAppender KafkaAppender NoSqlAppender RewriteAppender RoutingAppender ServletAppender Filter Class org.apache.logging.log4j.core.Filter Provider org.apache.logging.log4j:log4j-core Interface that must be implemented to allow custom event filtering. It is highly recommended that applications make use of the Filters provided with this implementation before creating their own. This interface supports "global" filters (i.e. - all events must pass through them first), attached to specific loggers and associated with Appenders. It is recommended that, where possible, Filter implementations create a generic filtering method that can be called from any of the filter methods. Known implementations BurstFilter CompositeFilter DenyAllFilter DynamicThresholdFilter LevelMatchFilter LevelRangeFilter MapFilter MarkerFilter MutableThreadContextMapFilter NoMarkerFilter RegexFilter ScriptFilter StringMatchFilter StructuredDataFilter ThreadContextMapFilter ThresholdFilter TimeFilter Result Class org.apache.logging.log4j.core.Filter.Result Provider org.apache.logging.log4j:log4j-core The result that can returned from a filter method call. Layout Class org.apache.logging.log4j.core.Layout Provider org.apache.logging.log4j:log4j-core Lays out a org.apache.logging.log4j.core.LogEvent in different formats. The formats are: byte[] an implementer of java.io.Serializable , like byte[] java.lang.String org.apache.logging.log4j.core.LogEvent Since 2.6, Layouts can encode a LogEvent directly to a org.apache.logging.log4j.core.layout.ByteBufferDestination without creating temporary intermediary objects. Known implementations Log4j1SyslogLayout Log4j1XmlLayout CsvLogEventLayout CsvParameterLayout GelfLayout HtmlLayout JsonLayout MessageLayout PatternLayout Rfc5424Layout SerializedLayout SyslogLayout XmlLayout YamlLayout JsonTemplateLayout LifeCycle Class org.apache.logging.log4j.core.LifeCycle Provider org.apache.logging.log4j:log4j-core All proper Java frameworks implement some sort of object life cycle. In Log4j, the main interface for handling the life cycle context of an object is this one. An object first starts in the org.apache.logging.log4j.core.State#INITIALIZED state by default to indicate the class has been loaded. From here, calling the LifeCycle method will change this state to org.apache.logging.log4j.core.State#STARTING . After successfully being started, this state is changed to org.apache.logging.log4j.core.State#STARTED . When the LifeCycle is called, this goes into the org.apache.logging.log4j.core.State#STOPPING state. After successfully being stopped, this goes into the org.apache.logging.log4j.core.State#STOPPED state. In most circumstances, implementation classes should store their org.apache.logging.log4j.core.State in a volatile field or inside an org.apache.logging.log4j.core.java.util.concurrent.atomic.AtomicReference dependent on synchronization and concurrency requirements. Known implementations CassandraAppender AsyncAppender ConsoleAppender CountingNoOpAppender FailoverAppender FileAppender HttpAppender MemoryMappedFileAppender NullAppender OutputStreamAppender RandomAccessFileAppender RollingFileAppender RollingRandomAccessFileAppender ScriptAppenderSelector SmtpAppender SocketAppender SyslogAppender WriterAppender DataSourceConnectionSource DriverManagerConnectionSource FactoryMethodConnectionSource JdbcAppender PoolingDriverConnectionSource JpaAppender JmsAppender JmsAppender JeroMqAppender KafkaAppender NoSqlAppender RewriteAppender CompositeTriggeringPolicy CronTriggeringPolicy NoOpTriggeringPolicy OnStartupTriggeringPolicy SizeBasedTriggeringPolicy TimeBasedTriggeringPolicy IdlePurgePolicy RoutingAppender AsyncLoggerConfig RootLogger LoggerConfig RootLogger BurstFilter CompositeFilter DenyAllFilter DynamicThresholdFilter LevelMatchFilter LevelRangeFilter MapFilter MarkerFilter MutableThreadContextMapFilter NoMarkerFilter RegexFilter ScriptFilter StringMatchFilter StructuredDataFilter ThreadContextMapFilter ThresholdFilter TimeFilter ServletAppender LifeCycle2 Class org.apache.logging.log4j.core.LifeCycle2 Provider org.apache.logging.log4j:log4j-core Extends the LifeCycle interface. This interface should be merged with the super-interface in 3.0. Known implementations CassandraAppender AsyncAppender ConsoleAppender CountingNoOpAppender FailoverAppender FileAppender HttpAppender MemoryMappedFileAppender NullAppender OutputStreamAppender RandomAccessFileAppender RollingFileAppender RollingRandomAccessFileAppender ScriptAppenderSelector SmtpAppender SocketAppender SyslogAppender WriterAppender DataSourceConnectionSource DriverManagerConnectionSource FactoryMethodConnectionSource JdbcAppender PoolingDriverConnectionSource JpaAppender JmsAppender JmsAppender JeroMqAppender KafkaAppender NoSqlAppender RewriteAppender CompositeTriggeringPolicy CronTriggeringPolicy NoOpTriggeringPolicy OnStartupTriggeringPolicy SizeBasedTriggeringPolicy TimeBasedTriggeringPolicy IdlePurgePolicy RoutingAppender AsyncLoggerConfig RootLogger LoggerConfig RootLogger BurstFilter CompositeFilter DenyAllFilter DynamicThresholdFilter LevelMatchFilter LevelRangeFilter MapFilter MarkerFilter MutableThreadContextMapFilter NoMarkerFilter RegexFilter ScriptFilter StringMatchFilter StructuredDataFilter ThreadContextMapFilter ThresholdFilter TimeFilter ServletAppender StringLayout Class org.apache.logging.log4j.core.StringLayout Provider org.apache.logging.log4j:log4j-core Instantiates the Layout type for String-based layouts. Known implementations Log4j1SyslogLayout Log4j1XmlLayout CsvLogEventLayout CsvParameterLayout GelfLayout HtmlLayout JsonLayout PatternLayout Rfc5424Layout SyslogLayout XmlLayout YamlLayout JsonTemplateLayout AbstractAppender Class org.apache.logging.log4j.core.appender.AbstractAppender Provider org.apache.logging.log4j:log4j-core Abstract base class for Appenders. Although Appenders do not have to extend this class, doing so will simplify their implementation. Known implementations CassandraAppender AsyncAppender ConsoleAppender CountingNoOpAppender FailoverAppender FileAppender HttpAppender MemoryMappedFileAppender NullAppender OutputStreamAppender RandomAccessFileAppender RollingFileAppender RollingRandomAccessFileAppender ScriptAppenderSelector SmtpAppender SocketAppender SyslogAppender WriterAppender JdbcAppender JpaAppender JmsAppender JmsAppender JeroMqAppender KafkaAppender NoSqlAppender RewriteAppender RoutingAppender ServletAppender AbstractOutputStreamAppender Class org.apache.logging.log4j.core.appender.AbstractOutputStreamAppender Provider org.apache.logging.log4j:log4j-core Appends log events as bytes to a byte output stream. The stream encoding is defined in the layout. Known implementations ConsoleAppender FileAppender MemoryMappedFileAppender OutputStreamAppender RandomAccessFileAppender RollingFileAppender RollingRandomAccessFileAppender SocketAppender SyslogAppender AbstractWriterAppender Class org.apache.logging.log4j.core.appender.AbstractWriterAppender Provider org.apache.logging.log4j:log4j-core Appends log events as strings to a writer. Known implementations WriterAppender AppenderSet Class org.apache.logging.log4j.core.appender.AppenderSet Provider org.apache.logging.log4j:log4j-core A deferred plugin for appenders. XML snippet <AppenderSet/> Async Class org.apache.logging.log4j.core.appender.AsyncAppender Provider org.apache.logging.log4j:log4j-core Appends to one or more Appenders asynchronously. You can configure an AsyncAppender with one or more Appenders and an Appender to append to if the queue is full. The AsyncAppender does not allow a filter to be specified on the Appender references. XML snippet <Async blocking="" bufferSize="" errorRef="" ignoreExceptions="" includeLocation="" name="" shutdownTimeout=""> <a-Filter-implementation/> <a-BlockingQueueFactory-implementation/> <AppenderRef/><!-- multiple occurrences allowed --> <Property/><!-- multiple occurrences allowed --> </Async> Attributes Optional attributes are denoted by ? -suffixed types. Name Type Default Description blocking boolean? bufferSize int? errorRef String? ignoreExceptions boolean? includeLocation boolean? name String shutdownTimeout long? Nested components Optional components are denoted by ? -suffixed types. Tag Type Description BlockingQueueFactory ? AppenderRef AppenderRef Property Property ? Filter ? Console Class org.apache.logging.log4j.core.appender.ConsoleAppender Provider org.apache.logging.log4j:log4j-core Appends log events to System. out or System. err using a layout specified by the user. The default target is System. out . TODO Accessing System. out or System. err as a byte stream instead of a writer bypasses the JVM’s knowledge of the proper encoding. (RG) Encoding is handled within the Layout. Typically, a Layout will generate a String and then call getBytes which may use a configured encoding or the system default. OTOH, a Writer cannot print byte streams. XML snippet <Console bufferedIo="" bufferSize="" direct="" follow="" ignoreExceptions="" immediateFlush="" name="" target=""> <a-Filter-implementation/> <a-Layout-implementation/> <Property/><!-- multiple occurrences allowed --> </Console> Attributes Optional attributes are denoted by ? -suffixed types. Name Type Default Description bufferedIo boolean? bufferSize int? direct boolean? follow boolean? ignoreExceptions boolean? immediateFlush boolean? name String target Target Nested components Optional components are denoted by ? -suffixed types. Tag Type Description Property Property ? Filter ? Layout ? Target Class org.apache.logging.log4j.core.appender.ConsoleAppender.Target Provider org.apache.logging.log4j:log4j-core Enumeration of console destinations. CountingNoOp Class org.apache.logging.log4j.core.appender.CountingNoOpAppender Provider org.apache.logging.log4j:log4j-core No-Operation Appender that counts events. XML snippet <CountingNoOp name=""/> Attributes Optional attributes are denoted by ? -suffixed types. Name Type Default Description name String? Failover Class org.apache.logging.log4j.core.appender.FailoverAppender Provider org.apache.logging.log4j:log4j-core The FailoverAppender will capture exceptions in an Appender and then route the event to a different appender. Hopefully it is obvious that the Appenders must be configured to not suppress exceptions for the FailoverAppender to work. XML snippet <Failover ignoreExceptions="" name="" primary="" retryIntervalSeconds=""> <a-String-implementation/><!-- multiple occurrences allowed --> <a-Filter-implementation/> </Failover> Attributes Optional attributes are denoted by ? -suffixed types. Name Type Default Description ignoreExceptions String? If "true" (default) exceptions encountered when appending events are logged; otherwise they are propagated to the caller. name String? The name of the Appender (required). primary String? The name of the primary Appender (required). retryIntervalSeconds String? The retry interval in seconds. Nested components Optional components are denoted by ? -suffixed types. Tag Type Description String? The name of one or more Appenders to fail over to (at least one is required). Filter ? A Filter (optional). Failovers Class org.apache.logging.log4j.core.appender.FailoversPlugin Provider org.apache.logging.log4j:log4j-core The array of failover Appenders. XML snippet <Failovers/> Nested components Optional components are denoted by ? -suffixed types. Tag Type Description AppenderRef AppenderRef ? The references to return. File Class org.apache.logging.log4j.core.appender.FileAppender Provider org.apache.logging.log4j:log4j-core File Appender. XML snippet <File advertise="" advertiseUri="" append="" bufferedIo="" bufferSize="" createOnDemand="" fileGroup="" fileName="" fileOwner="" filePermissions="" ignoreExceptions="" immediateFlush="" locking="" name=""> <a-Filter-implementation/> <a-Layout-implementation/> <Property/><!-- multiple occurrences allowed --> </File> Attributes Optional attributes are denoted by ? -suffixed types. Name Type Default Description advertise boolean? advertiseUri String? append boolean? bufferedIo boolean? bufferSize int? createOnDemand boolean? fileGroup String? fileName String fileOwner String? filePermissions String? ignoreExceptions boolean? immediateFlush boolean? locking boolean? name String Nested components Optional components are denoted by ? -suffixed types. Tag Type Description Property Property ? Filter ? Layout ? Http Class org.apache.logging.log4j.core.appender.HttpAppender Provider org.apache.logging.log4j:log4j-core XML snippet <Http connectTimeoutMillis="" ignoreExceptions="" method="" name="" readTimeoutMillis="" url="" verifyHostname=""> <a-Filter-implementation/> <a-Layout-implementation/> <Property/><!-- multiple occurrences allowed --> <Ssl/> </Http> Attributes Optional attributes are denoted by ? -suffixed types. Name Type Default Description connectTimeoutMillis int? ignoreExceptions boolean? method String? name String readTimeoutMillis int? url URL verifyHostname boolean? Nested components Optional components are denoted by ? -suffixed types. Tag Type Description Property Property ? Filter ? Layout ? Ssl SslConfiguration ? MemoryMappedFile Class org.apache.logging.log4j.core.appender.MemoryMappedFileAppender Provider org.apache.logging.log4j:log4j-core Memory Mapped File Appender. XML snippet <MemoryMappedFile advertise="" advertiseURI="" append="" bufferedIo="" bufferSize="" fileName="" ignoreExceptions="" immediateFlush="" name="" regionLength=""> <a-Filter-implementation/> <a-Layout-implementation/> <Property/><!-- multiple occurrences allowed --> </MemoryMappedFile> Attributes Optional attributes are denoted by ? -suffixed types. Name Type Default Description advertise boolean? advertiseURI String? append boolean? bufferedIo boolean? bufferSize int? fileName String? ignoreExceptions boolean? immediateFlush boolean? name String regionLength int? Nested components Optional components are denoted by ? -suffixed types. Tag Type Description Property Property ? Filter ? Layout ? Null Class org.apache.logging.log4j.core.appender.NullAppender Provider org.apache.logging.log4j:log4j-core An Appender that ignores log events. Use for compatibility with version 1.2 and handy for composing a ScriptAppenderSelector . XML snippet <Null name=""/> Attributes Optional attributes are denoted by ? -suffixed types. Name Type Default Description name String? OutputStream Class org.apache.logging.log4j.core.appender.OutputStreamAppender Provider org.apache.logging.log4j:log4j-core Appends log events to a given output stream using a layout. Character encoding is handled within the Layout. XML snippet <OutputStream bufferedIo="" bufferSize="" ignoreExceptions="" immediateFlush="" name=""> <a-Filter-implementation/> <a-Layout-implementation/> <Property/><!-- multiple occurrences allowed --> </OutputStream> Attributes Optional attributes are denoted by ? -suffixed types. Name Type Default Description bufferedIo boolean? bufferSize int? ignoreExceptions boolean? immediateFlush boolean? name String Nested components Optional components are denoted by ? -suffixed types. Tag Type Description Property Property ? Filter ? Layout ? RandomAccessFile Class org.apache.logging.log4j.core.appender.RandomAccessFileAppender Provider org.apache.logging.log4j:log4j-core File Appender. XML snippet <RandomAccessFile advertise="" advertiseURI="" append="" bufferedIo="" bufferSize="" fileName="" ignoreExceptions="" immediateFlush="" name=""> <a-Filter-implementation/> <a-Layout-implementation/> <Property/><!-- multiple occurrences allowed --> </RandomAccessFile> Attributes Optional attributes are denoted by ? -suffixed types. Name Type Default Description advertise boolean? advertiseURI String? append boolean? bufferedIo boolean? bufferSize int? fileName String? ignoreExceptions boolean? immediateFlush boolean? name String Nested components Optional components are denoted by ? -suffixed types. Tag Type Description Property Property ? Filter ? Layout ? RollingFile Class org.apache.logging.log4j.core.appender.RollingFileAppender Provider org.apache.logging.log4j:log4j-core An appender that writes to files and can roll over at intervals. XML snippet <RollingFile advertise="" advertiseUri="" append="" bufferedIo="" bufferSize="" createOnDemand="" fileGroup="" fileName="" fileOwner="" filePattern="" filePermissions="" ignoreExceptions="" immediateFlush="" locking="" name=""> <a-Filter-implementation/> <a-Layout-implementation/> <a-RolloverStrategy-implementation/> <a-TriggeringPolicy-implementation/> <Property/><!-- multiple occurrences allowed --> </RollingFile> Attributes Optional attributes are denoted by ? -suffixed types. Name Type Default Description advertise boolean? advertiseUri String? append boolean? bufferedIo boolean? bufferSize int? createOnDemand boolean? fileGroup String? fileName String? fileOwner String? filePattern String filePermissions String? ignoreExceptions boolean? immediateFlush boolean? locking boolean? name String Nested components Optional components are denoted by ? -suffixed types. Tag Type Description RolloverStrategy ? TriggeringPolicy Property Property ? Filter ? Layout ? RollingRandomAccessFile Class org.apache.logging.log4j.core.appender.RollingRandomAccessFileAppender Provider org.apache.logging.log4j:log4j-core An appender that writes to random access files and can roll over at intervals. XML snippet <RollingRandomAccessFile advertise="" advertiseURI="" append="" bufferedIo="" bufferSize="" fileGroup="" fileName="" fileOwner="" filePattern="" filePermissions="" ignoreExceptions="" immediateFlush="" name=""> <a-Filter-implementation/> <a-Layout-implementation/> <a-RolloverStrategy-implementation/> <a-TriggeringPolicy-implementation/> <Property/><!-- multiple occurrences allowed --> </RollingRandomAccessFile> Attributes Optional attributes are denoted by ? -suffixed types. Name Type Default Description advertise boolean? advertiseURI String? append boolean? bufferedIo boolean? bufferSize int? fileGroup String? fileName String? fileOwner String? filePattern String? filePermissions String? ignoreExceptions boolean? immediateFlush boolean? name String Nested components Optional components are denoted by ? -suffixed types. Tag Type Description RolloverStrategy ? TriggeringPolicy ? Property Property ? Filter ? Layout ? ScriptAppenderSelector Class org.apache.logging.log4j.core.appender.ScriptAppenderSelector Provider org.apache.logging.log4j:log4j-core XML snippet <ScriptAppenderSelector name=""> <AppenderSet/> <a-AbstractScript-implementation/> </ScriptAppenderSelector> Attributes Optional attributes are denoted by ? -suffixed types. Name Type Default Description name String Nested components Optional components are denoted by ? -suffixed types. Tag Type Description AppenderSet AppenderSet AbstractScript SMTP Class org.apache.logging.log4j.core.appender.SmtpAppender Provider org.apache.logging.log4j:log4j-core Send an e-mail when a specific logging event occurs, typically on errors or fatal errors. The number of logging events delivered in this e-mail depend on the value of BufferSize option. The SmtpAppender keeps only the last BufferSize logging events in its cyclic buffer. This keeps memory requirements at a reasonable level while still delivering useful application context. By default, an email message will formatted as HTML. This can be modified by setting a layout for the appender. By default, an email message will be sent when an ERROR or higher severity message is appended. This can be modified by setting a filter for the appender. XML snippet <SMTP bcc="" bufferSize="" cc="" from="" ignoreExceptions="" name="" replyTo="" smtpDebug="" smtpHost="" smtpPassword="" smtpPort="" smtpProtocol="" smtpUsername="" subject="" to=""> <a-Filter-implementation/> <a-Layout-implementation/> <Property/><!-- multiple occurrences allowed --> <Ssl/> </SMTP> Attributes Optional attributes are denoted by ? -suffixed types. Name Type Default Description bcc String? Comma-separated list of BCC email addresses. bufferSize int? Number of log events to buffer before sending an email. Defaults to . cc String? Comma-separated list of CC email addresses. from String? Email address of the sender. ignoreExceptions boolean? name String replyTo String? Comma-separated list of Reply-To email addresses. smtpDebug boolean? Enables or disables mail session debugging on STDOUT. Disabled by default. smtpHost String? Host name of SMTP server to send messages through. smtpPassword String? Password to authenticate with SMTP server. smtpPort int? Port number of SMTP server to send messages through. smtpProtocol String? Transport protocol to use for SMTP such as "smtp" or "smtps". Defaults to "smtp". smtpUsername String? Username to authenticate with SMTP server. subject String? Subject template for the email messages. to String? Comma-separated list of recipient email addresses. Nested components Optional components are denoted by ? -suffixed types. Tag Type Description Property Property ? Filter ? Specifies the filter used for this appender. By default, uses a ThresholdFilter with a level of ERROR. Layout ? Specifies the layout used for the email message body. By default, this uses the default HTML layout . Ssl SslConfiguration ? Specifies an SSL configuration for smtps connections. Socket Class org.apache.logging.log4j.core.appender.SocketAppender Provider org.apache.logging.log4j:log4j-core An Appender that delivers events over socket connections. Supports both TCP and UDP. XML snippet <Socket advertise="" bufferedIo="" bufferSize="" connectTimeoutMillis="" host="" ignoreExceptions="" immediateFail="" immediateFlush="" name="" port="" protocol="" reconnectDelayMillis=""> <a-Filter-implementation/> <a-Layout-implementation/> <Property/><!-- multiple occurrences allowed --> <SocketOptions/> <Ssl/> </Socket> Attributes Optional attributes are denoted by ? -suffixed types. Name Type Default Description advertise boolean? bufferedIo boolean? bufferSize int? connectTimeoutMillis int? host String? ignoreExceptions boolean? immediateFail boolean? immediateFlush boolean? name String port int? protocol Protocol ? reconnectDelayMillis int? Nested components Optional components are denoted by ? -suffixed types. Tag Type Description Property Property ? Filter ? Layout ? SocketOptions SocketOptions ? Ssl SslConfiguration ? Known implementations SyslogAppender Syslog Class org.apache.logging.log4j.core.appender.SyslogAppender Provider org.apache.logging.log4j:log4j-core The Syslog Appender. XML snippet <Syslog advertise="" appName="" bufferedIo="" bufferSize="" charset="" connectTimeoutMillis="" enterpriseNumber="" eventPrefix="" exceptionPattern="" facility="" format="" host="" id="" ignoreExceptions="" immediateFail="" immediateFlush="" includeMdc="" mdcExcludes="" mdcId="" mdcIncludes="" mdcPrefix="" mdcRequired="" messageId="" name="" newLine="" newLineEscape="" port="" protocol="" reconnectDelayMillis=""> <a-Filter-implementation/> <a-Layout-implementation/> <Property/><!-- multiple occurrences allowed --> <LoggerFields/><!-- multiple occurrences allowed --> <SocketOptions/> <Ssl/> </Syslog> Attributes Optional attributes are denoted by ? -suffixed types. Name Type Default Description advertise boolean? appName String? bufferedIo boolean? bufferSize int? charset Charset? connectTimeoutMillis int? enterpriseNumber String? eventPrefix String? exceptionPattern String? facility Facility ? format String? host String? id String? ignoreExceptions boolean? immediateFail boolean? immediateFlush boolean? includeMdc boolean? mdcExcludes String? mdcId String? mdcIncludes String? mdcPrefix String? mdcRequired String? messageId String? name String newLine boolean? newLineEscape String? port int? protocol Protocol ? reconnectDelayMillis int? Nested components Optional components are denoted by ? -suffixed types. Tag Type Description Property Property ? Filter ? Layout ? LoggerFields LoggerFields ? SocketOptions SocketOptions ? Ssl SslConfiguration ? Writer Class org.apache.logging.log4j.core.appender.WriterAppender Provider org.apache.logging.log4j:log4j-core Appends log events to a java.io.Writer . XML snippet <Writer ignoreExceptions="" name=""> <a-Filter-implementation/> <a-Layout-implementation/> <Property/><!-- multiple occurrences allowed --> </Writer> Attributes Optional attributes are denoted by ? -suffixed types. Name Type Default Description ignoreExceptions boolean? name String Nested components Optional components are denoted by ? -suffixed types. Tag Type Description Property Property ? Filter ? Layout ? AbstractDatabaseAppender Class org.apache.logging.log4j.core.appender.db.AbstractDatabaseAppender Provider org.apache.logging.log4j:log4j-core An abstract Appender for writing events to a database of some type, be it relational or NoSQL. All database appenders should inherit from this base appender. Known implementations CassandraAppender JdbcAppender JpaAppender NoSqlAppender ColumnMapping Class org.apache.logging.log4j.core.appender.db.ColumnMapping Provider org.apache.logging.log4j:log4j-core A configuration element for specifying a database column name mapping. XML snippet <ColumnMapping columnType="" literal="" name="" parameter="" pattern="" source="" type=""> <a-StringLayout-implementation/> </ColumnMapping> Attributes Optional attributes are denoted by ? -suffixed types. Name Type Default Description columnType Class Class to convert value to before storing in database. If the type is compatible with org.apache.logging.log4j.spi.ThreadContextMap or org.apache.logging.log4j.util.ReadOnlyStringMap , then the MDC will be used. If the type is compatible with org.apache.logging.log4j.spi.ThreadContextStack , then the NDC will be used. If the type is compatible with java.util.Date , then the event timestamp will be used. literal String? Literal value to use for populating a column. This is generally useful for functions, stored procedures, etc. No escaping will be done on this value. name String Column name. parameter String? Parameter value to use for populating a column, MUST contain a single parameter marker '?'. This is generally useful for functions, stored procedures, etc. No escaping will be done on this value. pattern String? Pattern to use as a PatternLayout . Convenient shorthand for ColumnMapping with a PatternLayout. source String? Source name. Useful when combined with a org.apache.logging.log4j.core.appender.db.org.apache.logging.log4j.message.MapMessage depending on the appender. type Class? Nested components Optional components are denoted by ? -suffixed types. Tag Type Description StringLayout ? Layout of value to write to database (before type conversion). Not applicable if ColumnMapping is a org.apache.logging.log4j.util.ReadOnlyStringMap , org.apache.logging.log4j.spi.ThreadContextMap , or org.apache.logging.log4j.spi.ThreadContextStack . AbstractConnectionSource Class org.apache.logging.log4j.core.appender.db.jdbc.AbstractConnectionSource Provider org.apache.logging.log4j:log4j-core Known implementations DataSourceConnectionSource DriverManagerConnectionSource FactoryMethodConnectionSource PoolingDriverConnectionSource AbstractDriverManagerConnectionSource Class org.apache.logging.log4j.core.appender.db.jdbc.AbstractDriverManagerConnectionSource Provider org.apache.logging.log4j:log4j-core A ConnectionSource that uses a JDBC connection string, a user name, and a password to call java.sql.DriverManager#getConnection(String,String,String) . This plugin does not provide any connection pooling unless it is available through the connection string and driver itself. This handy to get you off the ground without having to deal with JNDI. Known implementations DriverManagerConnectionSource PoolingDriverConnectionSource Column Class org.apache.logging.log4j.core.appender.db.jdbc.ColumnConfig Provider org.apache.logging.log4j:log4j-core A configuration element used to configure which event properties are logged to which columns in the database table. XML snippet <Column isClob="" isEventTimestamp="" isUnicode="" literal="" name="" pattern=""/> Attributes Optional attributes are denoted by ? -suffixed types. Name Type Default Description isClob boolean? isEventTimestamp boolean? isUnicode boolean? literal String? The literal value to insert into the column as-is without any quoting or escaping. Mutually exclusive with pattern! =null and eventTimestamp=true . name String The name of the database column as it exists within the database table. pattern String? The PatternLayout pattern to insert in this column. Mutually exclusive with literal! =null and eventTimestamp=true ConnectionSource Class org.apache.logging.log4j.core.appender.db.jdbc.ConnectionSource Provider org.apache.logging.log4j:log4j-core Configuration element for JdbcAppender . If you want to use the JdbcAppender but none of the provided connection sources meet your needs, you can simply create your own connection source. Known implementations DataSourceConnectionSource DriverManagerConnectionSource FactoryMethodConnectionSource PoolingDriverConnectionSource DataSource Class org.apache.logging.log4j.core.appender.db.jdbc.DataSourceConnectionSource Provider org.apache.logging.log4j:log4j-core A JdbcAppender connection source that uses a javax.sql.DataSource to connect to the database. XML snippet <DataSource jndiName=""/> Attributes Optional attributes are denoted by ? -suffixed types. Name Type Default Description jndiName String? The full JNDI path where the data source is bound. Must start with java:/comp/env or environment-equivalent. DriverManager Class org.apache.logging.log4j.core.appender.db.jdbc.DriverManagerConnectionSource Provider org.apache.logging.log4j:log4j-core A ConnectionSource that uses a JDBC connection string, a user name, and a password to call java.sql.DriverManager#getConnection(String,String,String) . This plugin does not provide any connection pooling unless it is available through the connection string and driver itself. This handy to get you off the ground without having to deal with JNDI. XML snippet <DriverManager connectionString="" driverClassName="" password="" userName=""> <Property/><!-- multiple occurrences allowed --> </DriverManager> Attributes Optional attributes are denoted by ? -suffixed types. Name Type Default Description connectionString String driverClassName String? password String? userName String? Nested components Optional components are denoted by ? -suffixed types. Tag Type Description Property Property ? ConnectionFactory Class org.apache.logging.log4j.core.appender.db.jdbc.FactoryMethodConnectionSource Provider org.apache.logging.log4j:log4j-core A JdbcAppender connection source that uses a public static factory method to obtain a java.sql.Connection or javax.sql.DataSource . XML snippet <ConnectionFactory class="" method=""/> Attributes Optional attributes are denoted by ? -suffixed types. Name Type Default Description class String? The name of a public class that contains a static method capable of returning either a javax.sql.DataSource or a java.sql.Connection . method String? The name of the public static method on the aforementioned cla | 2026-01-13T09:30:35 |
https://aws.amazon.com/tw/products/networking/ | AWS 上的網路和內容交付 – Amazon Web Services 跳至主要內容 Filter: 全部 English 聯絡我們 AWS Marketplace 支援 我的帳戶 搜尋 Filter: 全部 登入主控台 建立帳戶 聯網和內容交付 概觀 解決方案領域 合作夥伴 產品 › AWS 聯網和內容交付 AWS 聯網和內容交付 在安全和可靠的全球網路上執行每個工作負載 概觀 使用 AWS 獲得世界上最廣泛、最深入的網路和內容交付服務。在雲端中以最高級別的可靠性、安全性和效能執行應用程式。 娛樂 優勢 最安全 AWS 聯網功能旨在滿足全球最嚴格的安全要求。透過全天候基礎設施監控,確保資料的機密性、完整性和可用性。 最高網路可用性 使用 AWS 區域/可用區域 (AZ) 模型,為您的任務關鍵型工作負載保持最高可用性級別。產業分析師將 AZ 模型認可為執行需要高可用性企業應用程式的推薦方法。 穩定高效能 使用最高輸送量和最低延遲的雲端網路執行您的工作負載。使用 AWS 網路為客戶提供最快、回應迅速的應用程式。 最廣全球涵蓋範圍 透過專用網路在世界任何地方交付應用程式和內容。AWS 提供了所有供應商中最大的全球基礎設施規模。 透過移轉至 AWS,最大化效率並降低成本 分析公司 Enterprise Strategy Group 經過驗證確認,組織透過移轉至 AWS,將聯網、運算和儲存成本降低高達 66%。 閱讀報告 AWS 聯網和內容交付服務 網路基礎 使用 Amazon Virtual Private Cloud (VPC) 自訂和控制您的聯網環境 進一步了解 AWS Transit Gateway 使用 VPC 和連接至單一閘道的內部部署網路簡化您的網路 進一步了解 AWS PrivateLink 在 VPC、AWS 或內部部署服務之間建立私有連線 進一步了解 應用程式聯網 Amazon VPC Lattice 簡化服務對服務的連線能力、安全和監控 進一步了解 AWS AppMesh 使用應用程式級網路連接容器和微型服務 進一步了解 AWS API Gateway 建立、維護和保護任何規模的 API 進一步了解 AWS Cloud Map 探索和存取最新的服務資源 進一步了解 Elastic Load Balancing 分配網路流量以提高應用程式可擴展性 進一步了解 邊緣聯網 Amazon CloudFront 以低延遲和高傳輸速度交付資料、影片、應用程式和 API 進一步了解 Amazon Route 53 以低成本受管網域名稱系統 (DNS) 推動最終用戶使用網際網路應用程式 進一步了解 AWS Global Accelerator 最佳化應用程式的使用者流量 進一步了解 連線 AWS Direct Connect 建立至您的資料中心、辦公室或主機代管環境的建立私有、專有 AWS 連線 進一步了解 AWS Site-to-Site VPN 建立至 Amazon VPC 或 AWS Transit Gateway 的加密網路連線 進一步了解 AWS Client VPN 使用虛擬私有網路 (VPN) 將遠端人力連線至 AWS 或內部部署 進一步了解 AWS 雲端 WAN 輕鬆建置、管理和監控全球區域網路 進一步了解 AWS 互連 – 多雲端 (預覽版) 與其他雲端服務供應商建立簡單、具備恢復能力、高速的私有連線 進一步了解 AWS 互連 – 最後一哩路 (封閉預覽版) 只需按幾下即可連線遠端位置到 AWS 進一步了解 網路安全 AWS Shield 保護 AWS 應用程式免受分散式阻斷服務 (DDoS) 攻擊 進一步了解 AWS WAF 保護您的 Web 應用程式免於受常見 Web 入侵程式的危害 進一步了解 AWS Network Firewall 在您的 Amazon VPC 部署網路安全 進一步了解 AWS Firewall Manager 集中設定和管理防火牆規則 進一步了解 解決方案領域 建置強大的網路基礎 使用 AWS 網路基礎密切關注複雜的網路流量。使用 Amazon VPC、AWS Transit Gateway、AWS PrivateLink、Amazon VPC Flow Logs 和 VPC Traffic Mirroring 等服務簡化資源啟動、網路管理、連接和流量監控。 進一步了解 連接混合基礎結構 使用安全且高效的網路通訊連結 AWS 中執行的服務和內部部署。AWS 混合連接解決方案提供一系列連線類型和服務,用於建置從雲端到內部部署再到網路邊緣無縫工作的混合網路。 進一步了解 使用邊緣聯網交付更快、更安全的應用程式 使用邊緣聯網,透過提高的安全性和低延遲交付使用應用程式和資料。將流量從網際網路轉移到世界上最安全、效能最佳的雲端網路。Amazon CloudFront、AWS Global Accelerator 和 Amazon Route 53 透過低延遲和高輸送量安全地交付資料。 進一步了解 簡化應用程式聯網 使用 AWS 應用程式聯網簡化並提升您應用程式的網路架構。Elastic Load Balancing (ELB)、AWS Global Accelerator (AGA) 和 AWS App Mesh 搭配使用可提供提高的安全性、可用性、效能和精簡的監控功能。 進一步了解 AWS 上的特色解決方案 探索專門打造的服務、AWS 解決方案、合作夥伴解決方案和指導,以快速解決您的商業和技術使用案例。 適用於 AWS Transit Gateway 的網路協同運作 在分散式 AWS 環境中達成設定和管理傳輸網路程序自動化。從 AWS Console 的單一儀表板視覺化和監控您的全球網路,以便您控制、稽核和核准 (傳輸) 網路變更。 開始使用 Firewall Automation for Network Traffic on AWS 部署解決方案,自動佈建集中式 AWS Network Firewall 來檢查 Amazon VPC 之間流量的過程。 開始使用 AWS Summit Hamburg 2025︰立即體驗明天的雲端 與業界先驅及雲端專家一同參與這場為期一天的活動,您將獲得實際操作學習與拓展人脈的機會,徹底改變您企業的雲端之旅。 立即報名 建立 AWS 帳戶 了解 什麼是 AWS? 什麼是雲端運算? 什麼是代理式 AI? 雲端運算概念中心 AWS 雲端安全 最新消息 部落格 新聞稿 資源 入門 培訓 AWS 信任中心 AWS 解決方案程式庫 架構中心 產品和技術常見問答集 分析師報告 AWS 合作夥伴 開發人員 建置者中心 軟體開發套件與工具 .NET on AWS 在 AWS 上執行的 Python 在 AWS 上執行的 Java 在 AWS 上執行的 PHP 在 AWS 上執行的 JavaScript 說明 聯絡我們 提交支援申請單 AWS re:Post 知識中心 AWS Support 概觀 取得專家協助 AWS 可存取性 法律 English 回到頁首 Amazon 是支持平等就業機會的雇主:少數民族/女性/殘障人士/退伍軍人/性別認同/性取向/年齡。 x facebook linkedin instagram twitch youtube podcasts email 隱私權 網站條款 Cookie 偏好設定 © 2026, Amazon Web Services, Inc. 或其關係企業。保留所有權利。 | 2026-01-13T09:30:35 |
https://aws.amazon.com/cloud-map/ | IT Asset Discovery - Amazon Cloud Map - AWS Skip to main content Filter: All English Contact us AWS Marketplace Support My account Search Filter: All Sign in to console Create account AWS Cloud Map Overview Pricing Products › Networking and Content Delivery › AWS Cloud Map AWS Cloud Map Service discovery for cloud resources Get started with AWS Cloud Map Why AWS Cloud Map? AWS Cloud Map is a cloud resource discovery service. With Cloud Map, you can define custom names for your application resources, and it maintains the updated location of these dynamically changing resources. This increases your application availability because your web service always discovers the most up-to-date locations of its resources. Modern applications are typically composed of multiple services that are accessible over an API and perform a specific function. Each service interacts with a variety of other resources, such as databases, queues, object stores, and customer-defined microservices, and it needs to be able to find the location of all the infrastructure resources on which it depends in order to function. In most cases, you manage all these resource names and their locations manually within the application code. However, manual resource management becomes time consuming and error-prone as the number of dependent infrastructure resources increases or the number of microservices dynamically scale up and down based on traffic. You can also use third-party service discovery products, but this requires installing and managing additional software and infrastructure. Cloud Map allows you to register any application resources, such as databases, queues, microservices, and other cloud resources, with custom names. Cloud Map then constantly checks the health of resources to make sure the location is up-to-date. The application can then query the registry for the location of the resources needed based on the application version and deployment environment. Play Benefits Increase application availability Cloud Map constantly monitors the health of every IP-based component of your application and dynamically updates the location of each microservice as it is added or removed. This ensures that your applications only discover the most up-to-date location of its resources, increasing the availability of the application. Increase developer productivity Cloud Map provides a single registry for all your application services which you can define with custom names. This ensures that your development teams don’t have to constantly store, track, and update resource name and location information or make changes directly within the application code. Use cases Service discovery Microservices are typically implemented using dynamic resources, such as containers, and can quickly launch and terminate. These resources communicate over API and need to specify the location of their dependent resources from within the application code. However, each of these resources is dynamic with constantly changing locations, making it challenging for individual resources to constantly track and find the locations of all their dependencies. Cloud Map provides a single up-to-date registry of service names and locations, that enables microservices to easily locate one another. Continuous integration and delivery Deploying application code across multiple environments, regions, and versions requires you to update multiple configuration files with the location of every service. Cloud Map maintains an up-to-date registry of service names and locations. You update the location of the resource based on the environment, region, or application version to which you are deploying, and your application will automatically discover the correct resource. Automated health monitoring Your applications are typically a combination of AWS services and custom resources. However, it is challenging to reliably obtain up-to-date health statuses of all your application resources. Cloud Map helps you achieve this by keeping an up-to-date registry of only healthy resources through automated health checks. This ensures that traffic is always served to only healthy endpoints. Blog posts and articles Introducing Cloud Map AWS Cloud Map keeps track of all your application components, their locations, attributes, and health status. Now your applications can simply query AWS Cloud Map using AWS SDK, API, or even DNS to discover the locations of its dependencies. Keep reading AWS Cloud Map service discovery for serverless applications AWS Cloud Map enables the journey to microservices by acting as the glue that binds all of business logic. At Peak.ai, we use the serverless framework very heavily, so we wanted to look into ways of integrating AWS Cloud Map into the serverless framework workflow. Keep reading Get started Features page Check out the AWS Cloud Map features Cloud Map features Free tier Sign up for a free account Sign up Create an AWS account Learn What Is AWS? What Is Cloud Computing? What Is Agentic AI? Cloud Computing Concepts Hub AWS Cloud Security What's New Blogs Press Releases Resources Getting Started Training AWS Trust Center AWS Solutions Library Architecture Center Product and Technical FAQs Analyst Reports AWS Partners Developers Builder Center SDKs & Tools .NET on AWS Python on AWS Java on AWS PHP on AWS JavaScript on AWS Help Contact Us File a Support Ticket AWS re:Post Knowledge Center AWS Support Overview Get Expert Help AWS Accessibility Legal English Back to top Amazon is an Equal Opportunity Employer: Minority / Women / Disability / Veteran / Gender Identity / Sexual Orientation / Age. x facebook linkedin instagram twitch youtube podcasts email Privacy Site terms Cookie Preferences © 2026, Amazon Web Services, Inc. or its affiliates. All rights reserved. | 2026-01-13T09:30:35 |
https://docs.aws.amazon.com/es_es/AmazonCloudFront/latest/DeveloperGuide/lambda-examples.html#lambda-examples-redirect-based-on-country | Funciones de ejemplo de Lambda@Edge - Amazon CloudFront Funciones de ejemplo de Lambda@Edge - Amazon CloudFront Documentación Amazon CloudFront Guía para desarrolladores Ejemplos generales Generación de respuestas: ejemplos Cadenas de consulta: ejemplos Personalización de contenido por encabezados de tipo de dispositivo o país: ejemplos Selección de origen dinámico basada en contenido: ejemplos Actualización de estados de error: ejemplos Acceso al cuerpo de la solicitud: ejemplos Funciones de ejemplo de Lambda@Edge Consulte los ejemplos siguientes para usar funciones de Lambda con Amazon CloudFront. nota Si elige el tiempo de ejecución Node.js 18 o una versión posterior para la función Lambda@Edge, se creará automáticamente un archivo index.mjs . Para usar los siguientes ejemplos de código, cambie el nombre del archivo index.mjs a index.js . Temas Ejemplos generales Generación de respuestas: ejemplos Cadenas de consulta: ejemplos Personalización de contenido por encabezados de tipo de dispositivo o país: ejemplos Selección de origen dinámico basada en contenido: ejemplos Actualización de estados de error: ejemplos Acceso al cuerpo de la solicitud: ejemplos Ejemplos generales Los ejemplos siguientes muestran formas habituales de usar Lambda@Edge en CloudFront. Temas Ejemplo: prueba A/B Ejemplo: Sobrescritura de un encabezado de respuesta Ejemplo: prueba A/B Puede utilizar el siguiente ejemplo para probar dos versiones diferentes de una imagen sin crear redirecciones ni cambiar la dirección URL. En este ejemplo se leen las cookies de la solicitud del lector y se modifica la URL de la solicitud en consecuencia. Si el espectador no envía una cookie con uno de los valores esperados, el ejemplo asigna aleatoriamente al espectador una de las URL. 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; } 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; } } 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" ''' experimentUri = "" 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 Ejemplo: Sobrescritura de un encabezado de respuesta En el ejemplo siguiente, se muestra cómo cambiar el valor de un encabezado de respuesta según el valor de otro encabezado. Node.js export const handler = async (event) => { 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()] = [ { key: headerNameDst, value: headers[headerNameSrc.toLowerCase()][0].value, }]; console.log(`Response header "$ { headerNameDst}" was set to ` + `"$ { headers[headerNameDst.toLowerCase()][0].value}"`); } return response; }; Python import json def lambda_handler(event, context): response = event['Records'][0]['cf']['response'] headers = response['headers'] header_name_src = 'X-Amz-Meta-Last-Modified' header_name_dst = 'Last-Modified' if headers.get(header_name_src.lower()): headers[header_name_dst.lower()] = [ { 'key': header_name_dst, 'value': headers[header_name_src.lower()][0]['value'] }] print(f'Response header " { header_name_dst}" was set to ' f'" { headers[header_name_dst.lower()][0]["value"]}"') return response Generación de respuestas: ejemplos En los ejemplos siguientes se muestra cómo puede usar Lambda@Edge para generar respuestas. Temas Ejemplo: Envío de contenido estático (respuesta generada) Ejemplo: Generación de un redireccionamiento HTTP (respuesta generada) Ejemplo: Envío de contenido estático (respuesta generada) En el siguiente ejemplo se muestra cómo utilizar una función de Lambda para enviar contenido de sitio web estático, lo que reduce la carga en el servidor de origen y la latencia total. nota Puede generar respuestas HTTP para los eventos de solicitud del espectador y al origen. Para obtener más información, consulte Generación de respuestas HTTP en los desencadenadores de solicitud . También puede sustituir o quitar el cuerpo de la respuesta HTTP en eventos de respuesta de origen. Para obtener más información, consulte Actualización de respuestas HTTP en desencadenadores de respuesta de origen . 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' }] }, 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 } return response Ejemplo: Generación de un redireccionamiento HTTP (respuesta generada) En el siguiente ejemplo se muestra cómo generar una redirección HTTP. nota Puede generar respuestas HTTP para los eventos de solicitud del espectador y al origen. Para obtener más información, consulte Generación de respuestas HTTP en los desencadenadores de solicitud . 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. response = { 'status': '302', 'statusDescription': 'Found', 'headers': { 'location': [ { 'key': 'Location', 'value': 'https://docs.aws.amazon.com/lambda/latest/dg/lambda-edge.html' }] } } return response Cadenas de consulta: ejemplos En los ejemplos siguientes se muestran formas de usar Lambda@Edge con cadenas de consulta. Temas Ejemplo: Adición de un encabezado en función de un parámetro de la cadena de consulta Ejemplo: Normalización de parámetros de cadenas de consulta para mejorar la tasa de aciertos de caché Ejemplo: Redireccionamiento de los usuarios no autenticados a una página de inicio de sesión Ejemplo: Adición de un encabezado en función de un parámetro de la cadena de consulta El siguiente ejemplo muestra cómo obtener el par clave-valor de un parámetro de la cadena de consulta y, a continuación, añadir un encabezado en función de dichos valores. 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. * 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 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'] # Update request querystring request['querystring'] = urlencode(params) return request Ejemplo: Normalización de parámetros de cadenas de consulta para mejorar la tasa de aciertos de caché El siguiente ejemplo muestra cómo mejorar la tasa de acceso a la caché haciendo los siguientes cambios en las cadenas de consulta antes de que CloudFront reenvíe las solicitudes a su origen: Alfabetizar los pares de clave-valor por el nombre del parámetro. Cambiar a minúsculas el modelo de mayúsculas y minúsculas de los pares de clave-valor. Para obtener más información, consulte Almacenamiento en caché de contenido en función de parámetros de cadenas de consulta . 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 */ 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 request['querystring'] = urlencode(sortedParams) return request Ejemplo: Redireccionamiento de los usuarios no autenticados a una página de inicio de sesión El siguiente ejemplo muestra cómo redirigir a los usuarios una página de inicio de sesión si no ha introducido sus credenciales. 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; } /* 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 params. ''' # Check for session-id in cookie, if present, then proceed with request parsedCookies = parseCookies(headers) 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 Personalización de contenido por encabezados de tipo de dispositivo o país: ejemplos En los ejemplos siguientes se muestra cómo puede usar Lambda@Edge para personalizar el comportamiento en función de la ubicación o el tipo de dispositivo que usa el lector. Temas Ejemplo: Redireccionamiento de solicitudes de espectadores a una URL específica de un país Ejemplo: Envío de distintas versiones de un objeto en función del dispositivo Ejemplo: Redireccionamiento de solicitudes de espectadores a una URL específica de un país El siguiente ejemplo muestra cómo generar una respuesta de redireccionamiento HTTP con una URL específica del país y devolver la respuesta al espectador. Esto resulta útil cuando se quiere proporcionar respuestas específicas del país. Por ejemplo: Si tiene subdominios específicos de un país, como us.ejemplo.com y tw.ejemplo.com, puede generar una respuesta de redireccionamiento cuando un espectador solicite ejemplo.com. Si está haciendo streaming de video, pero no tiene derechos para transmitir el contenido en un país determinado, puede redirigir a los usuarios de dicho país a una página en la que se explica por qué no pueden ver el video. Tenga en cuenta lo siguiente: Debe configurar la distribución para almacenar en la caché en función del encabezado CloudFront-Viewer-Country . Para obtener más información, consulte Caché en función de encabezados de solicitud seleccionados . CloudFront agrega el encabezado CloudFront-Viewer-Country después del evento de solicitud del lector. Para utilizar este ejemplo, debe crear un activador para el evento de solicitud al origen. 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 = { 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', 'statusDescription': 'Found', 'headers': { 'location': [ { 'key': 'Location', 'value': url }] } } return response Ejemplo: Envío de distintas versiones de un objeto en función del dispositivo El siguiente ejemplo muestra cómo ofrecer distintas versiones de un objeto en función del tipo de dispositivo que el usuario está utilizando; por ejemplo, un dispositivo móvil o una tablet. Tenga en cuenta lo siguiente: Debe configurar la distribución para almacenar en la caché en función de los encabezados CloudFront-Is-*-Viewer . Para obtener más información, consulte Caché en función de encabezados de solicitud seleccionados . CloudFront agrega los encabezados CloudFront-Is-*-Viewer después del evento de solicitud del lector. Para utilizar este ejemplo, debe crear un activador para el evento de solicitud al origen. 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 * 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. ''' desktopPath = '/desktop'; mobilePath = '/mobile'; tabletPath = '/tablet'; smarttvPath = '/smarttv'; 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 Selección de origen dinámico basada en contenido: ejemplos En los ejemplos siguientes se muestra cómo puede usar Lambda@Edge para el direccionamiento a diferentes orígenes en función de la información de la solicitud. Temas Ejemplo: Uso de un desencadenador de solicitud de origen para cambiar desde un origen personalizado a un origen de Amazon S3 Ejemplo: Uso de un desencadenador de solicitud de origen para cambiar la región de origen de Amazon S3 Ejemplo: Uso de un desencadenador de solicitud de origen para cambiar desde un origen de Amazon S3 a un origen personalizado Ejemplo: Uso de un desencadenador de solicitud al origen para transferir gradualmente el tráfico desde un bucket de Amazon S3 a otro Ejemplo: Uso de un desencadenador de solicitud de origen para cambiar el nombre del dominio de origen en función del encabezado de país Ejemplo: Uso de un desencadenador de solicitud de origen para cambiar desde un origen personalizado a un origen de Amazon S3 Esta función demuestra cómo utilizar un desencadenador de solicitud al origen para cambiar desde un origen personalizado a un origen de Amazon S3 desde el que recuperar el contenido, en función de las propiedades de la solicitud. 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: 'origin-access-identity', path: '', customHeaders: { } } }; request.headers['host'] = [ { key: 'host', value: s3DomainName}]; } } 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 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': 'origin-access-identity', 'path': '', 'customHeaders': { } } } request['headers']['host'] = [ { 'key': 'host', 'value': s3DomainName}] return request Ejemplo: Uso de un desencadenador de solicitud de origen para cambiar la región de origen de Amazon S3 Esta función demuestra cómo utilizar un desencadenador de solicitud al origen para cambiar el origen de Amazon S3 desde el que se recupera el contenido, en función de las propiedades de la solicitud. En este ejemplo, utilizamos el valor del encabezado CloudFront-Viewer-Country para actualizar el nombre de dominio del bucket de S3 por un bucket de una región que está más cerca del lector. Esto puede resultar útil de varias maneras: Reduce las latencias cuando la región especificada está más cerca del país del lector. Proporciona soberanía de los datos, al asegurarse de que los datos se distribuyen desde un origen que está en el país del que provino la solicitud. Para utilizar este ejemplo, debe hacer lo siguiente: Configure la distribución para almacenar en la caché en función del encabezado CloudFront-Viewer-Country . Para obtener más información, consulte Caché en función de encabezados de solicitud seleccionados . Crear un disparador para esta función en el evento de solicitud al origen. CloudFront agrega el encabezado CloudFront-Viewer-Country después del evento de solicitud del lector; por lo tanto, para utilizar este ejemplo, debe asegurarse de que la función ejecuta una solicitud de origen. nota El siguiente código de ejemplo usa la misma identidad de acceso de origen (OAI) para todos los buckets de S3 que usa para el origen. Para obtener más información, consulte Identidad de acceso de origen . 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 * 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); }; Python 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: 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: ''' 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 Ejemplo: Uso de un desencadenador de solicitud de origen para cambiar desde un origen de Amazon S3 a un origen personalizado Esta función demuestra cómo utilizar un disparador de solicitud al origen para cambiar el origen personalizado desde el que se recupera el contenido, en función de las propiedades de la solicitud. 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: { 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': { } } } request['headers']['host'] = [ { 'key': 'host', 'value': 'www.example.com'}] return request Ejemplo: Uso de un desencadenador de solicitud al origen para transferir gradualmente el tráfico desde un bucket de Amazon S3 a otro Esta función demuestra cómo transferir gradualmente el tráfico desde un bucket de Amazon S3 a otro de forma controlada. 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}]; } 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 Ejemplo: Uso de un desencadenador de solicitud de origen para cambiar el nombre del dominio de origen en función del encabezado de país Esta función demuestra cómo cambiar el nombre del dominio de origen en función del encabezado CloudFront-Viewer-Country , de forma que el contenido se distribuya desde un origen más cercano al país del lector. La implementación de esta funcionalidad para su distribución puede tener ventajas como las siguientes: Reducir las latencias cuando la región especificada está más cerca del país del lector Proporcionar soberanía de los datos, al asegurarse de que los datos se distribuyen desde un origen que está en el país del que provino la solicitud Tenga en cuenta que para habilitar esta funcionalidad, debe configurar su distribución para almacenar en la caché en función del encabezado CloudFront-Viewer-Country . Para obtener más información, consulte Caché en función de encabezados de solicitud seleccionados . 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 request['headers']['host'] = [ { 'key': 'host', 'value': domainName}] return request Actualización de estados de error: ejemplos En los ejemplos siguientes se proporciona orientación acerca de cómo puede usar Lambda@Edge para cambiar el estado de error que se devuelve a los usuarios. Temas Ejemplo: Uso de un desencadenador de respuesta de origen para actualizar el código de estado de error a 200 Ejemplo: Uso de un desencadenador de respuesta de origen para actualizar el código de estado de error a 302 Ejemplo: Uso de un desencadenador de respuesta de origen para actualizar el código de estado de error a 200 Esta función demuestra cómo actualizar el estado de la respuesta a 200 y generar un cuerpo con contenido estático para devolverlo al espectador en la siguiente situación: La función se desencadena en una respuesta del origen. El estado de la respuesta del servidor de origen es un código de estado de error (4xx o 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'; } callback(null, response); }; Python 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 Ejemplo: Uso de un desencadenador de respuesta de origen para actualizar el código de estado de error a 302 Esta función demuestra cómo actualizar el código de estado HTTP a 302 para la redirección a otra ruta (comportamiento de la caché) en la que se ha configurado un origen diferente. Tenga en cuenta lo siguiente: La función se desencadena en una respuesta del origen. El estado de la respuesta del servidor de origen es un código de estado de error (4xx o 5xx). Node.js 'use strict'; exports.handler = (event, context, callback) => { const response = event.Records[0].cf.response; const 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 (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 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 Acceso al cuerpo de la solicitud: ejemplos En los ejemplos siguientes se muestra cómo puede usar Lambda@Edge para trabajar con las solicitudes POST. nota Para utilizar estos ejemplos, debe habilitar la opción incluir cuerpo en la asociación de funciones Lambda de la distribución. No está habilitada de forma predeterminada. Para habilitar esta configuración en la consola de CloudFront, seleccione la casilla de verificación Incluir cuerpo en la Asociación de funciones Lambda . Para habilitar esta configuración en la API de CloudFront o con CloudFormation, establezca el campo IncludeBody en true en LambdaFunctionAssociation . Temas Ejemplo: Uso de un desencadenador de solicitud para leer un formulario HTML Ejemplo: Uso de un desencadenador de solicitud para modificar un formulario HTML Ejemplo: Uso de un desencadenador de solicitud para leer un formulario HTML Esta función ilustra cómo puede procesar el cuerpo de una solicitud POST generada por un formulario HTML (formulario web), como por ejemplo un formulario tipo "póngase en contacto con nosotros". Por ejemplo, es posible que tenga un formulario HTML como el siguiente: <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> Para la función de ejemplo que se indica a continuación, la función se debe desencadenar en una solicitud al origen o del lector de CloudFront. 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 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 Ejemplo: Uso de un desencadenador de solicitud para modificar un formulario HTML Esta función ilustra cómo puede modificar el cuerpo de una solicitud POST generada por un formulario HTML (formulario web). La función se activa en una solicitud al origen o del lector de CloudFront. 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. * * 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'] | 2026-01-13T09:30:35 |
https://ko-kr.facebook.com/login/?next=https%3A%2F%2Fl.facebook.com%2Fl.php%3Fu%3Dhttps%253A%252F%252Fwww.instagram.com%252F%26amp%253Bh%3DAT227S6RLSVOG9uqMoLGzXl7Gon6H7HOwsjdtbwTQ3oC3RMYt_ZYYvp1_n9qGt7qoMZtZ5bwV2AW307H4Ny6jqQJc0QaRR7dGQwhihehPTFIINMd_4zsHDip6hg3ceq33Fyw51jZaDbKnbRS_5Wdeg | Facebook Facebook 이메일 또는 휴대폰 비밀번호 계정을 잊으셨나요? 새 계정 만들기 일시적으로 차단됨 일시적으로 차단됨 회원님의 이 기능 사용 속도가 너무 빠른 것 같습니다. 이 기능 사용에서 일시적으로 차단되었습니다. Back 한국어 English (US) Tiếng Việt Bahasa Indonesia ภาษาไทย Español 中文(简体) 日本語 Português (Brasil) Français (France) Deutsch 가입하기 로그인 Messenger Facebook Lite 동영상 Meta Pay Meta 스토어 Meta Quest Ray-Ban Meta Meta AI Meta AI 콘텐츠 더 보기 Instagram Threads 투표 정보 센터 개인정보처리방침 개인정보 보호 센터 정보 광고 만들기 페이지 만들기 개발자 채용 정보 쿠키 AdChoices 이용 약관 고객 센터 연락처 업로드 및 비사용자 설정 활동 로그 Meta © 2026 | 2026-01-13T09:30:35 |
https://aws.amazon.com/products/networking/?nc=sn&loc=1 | Networking and Content Delivery on AWS – Amazon Web Services Skip to main content Filter: All English Contact us AWS Marketplace Support My account Search Filter: All Sign in to console Create account Networking & Content Delivery Overview Solution Areas Partners Products › AWS Networking and Content Delivery AWS Networking and Content Delivery Run every workload on a secure and reliable global network Overview Get the broadest and deepest set of networking and content delivery services in the world with AWS. Run applications with the highest level of reliability, security, and performance in the cloud. Play Benefits Most secure Meet the most stringent security requirements in the world with AWS networking capabilities. Ensure the confidentiality, integrity, and availability of your data through 24/7 infrastructure monitoring. Highest network availability Maintain the highest availability levels for your mission-critical workloads using the AWS Region/Availability Zone (AZ) model. Industry analysts recognize the AZ model as the recommended approach for running enterprise applications requiring high availability. Consistent high performance Run your workloads using the highest throughput and lowest latency cloud network. Use the AWS network to provide your customers with faster, more responsive applications. Broadest global coverage Deliver applications and content anywhere in the world over a purpose-built network. AWS offers the largest global infrastructure footprint of any provider. Maximize efficiency and lower costs by migrating to AWS Analyst firm, Enterprise Strategy Group, validated that organizations reduced networking, compute, and storage costs by up to 66% by migrating to AWS. Read the report AWS networking and content delivery services Network foundations Customize and control your networking environment with Amazon Virtual Private Cloud (VPC) Learn more AWS Transit Gateway Simplify your network with VPCs and on-premises networks connected to a single gateway Learn more AWS PrivateLink Establish private connectivity between VPCs and AWS or on- premises services Learn more Application networking Amazon VPC Lattice Simplify service-to-service connectivity, security, and monitoring Learn more AWS AppMesh Connect containers and microservices with application-level networking Learn more AWS API Gateway Create, maintain, and secure APIs at any scale Learn more AWS Cloud Map Discover and access the most up-to-date service resources Learn more Elastic Load Balancing Distribute network traffic to improve application scalability Learn more Edge networking Amazon CloudFront Deliver data, videos, applications, and APIs at high transfer speeds with low latency Learn more Amazon Route 53 Drive end users to internet applications with a low-cost managed Domain Name System (DNS) Learn more AWS Global Accelerator Optimize user traffic to your application Learn more Connectivity AWS Direct Connect Establish a private, dedicated AWS connection to your data center, office, or colocation environment Learn more AWS Site-to-Site VPN Create an encrypted network connection to your Amazon VPCs or AWS Transit Gateways Learn more AWS Client VPN Connect your remote workforce to AWS or on-premises with a Virtual Private Network (VPN) Learn more AWS Cloud WAN Easily build, manage, and monitor global wide area networks Learn more AWS Interconnect – multicloud (Preview) Simple, resilient, high-speed private connections to other cloud service providers Learn more AWS Interconnect - last mile (Gated Preview) Connect your remote locations to AWS with just a few clicks Learn more Network security AWS Shield Safeguard AWS applications against distributed denial of service (DDoS) attacks Learn more AWS WAF Protect your web applications from common web exploits Learn more AWS Network Firewall Deploy network security across your Amazon VPCs Learn more AWS Firewall Manager Centrally configure and manage firewall rules Learn more Solution areas Build strong network foundations Keep tabs on your complex network traffic with AWS network foundations. Simplify resource launch, network management, connectivity, and traffic monitoring with services including Amazon VPC, AWS Transit Gateway, AWS PrivateLink, Amazon VPC Flow Logs, and VPC Traffic Mirroring. Learn more Connect hybrid infrastructure Link your services running in AWS and your premises with secure and efficient network communication. AWS hybrid connectivity solutions provide an array of connection types and services for building hybrid networks that work seamlessly from cloud to on-premises to the network edge. Learn more Deliver faster, more secure applications with edge networking Deliver user applications and data with increased security and low-latency using edge networking. Move traffic off the internet and on to the world’s most secure, best performing cloud network. Amazon CloudFront, AWS Global Accelerator, and Amazon Route 53 securely deliver your data with low latency and high throughput. Learn more Streamline application networking Simplify and improve your application’s network architecture with AWS application networking. Elastic Load Balancing (ELB), AWS Global Accelerator (AGA), and AWS App Mesh work together to provide improved security, availability, performance, and streamlined monitoring capabilities. Learn more Featured Solutions on AWS Discover Purpose-Built Services, AWS Solutions, Partner Solutions, and Guidance to rapidly address your business and technical use cases. Network Orchestration for AWS Transit Gateway Automate the process of setting up and managing transit networks in distributed AWS environments. Visualize and monitor your global network from a single dashboard in the AWS Console so that you can control, audit, and approve (transit) network changes. Get Started Firewall Automation for Network Traffic on AWS Deploy a solution that automates the process of provisioning a centralized AWS Network Firewall to inspect traffic between your Amazon VPCs. Get Started AWS Summit Hamburg 2025: Experience tomorrow's cloud today Join industry pioneers and cloud experts for a day of hands-on learning and networking opportunities that will transform your business's cloud journey. Register now Create an AWS account Learn What Is AWS? What Is Cloud Computing? What Is Agentic AI? Cloud Computing Concepts Hub AWS Cloud Security What's New Blogs Press Releases Resources Getting Started Training AWS Trust Center AWS Solutions Library Architecture Center Product and Technical FAQs Analyst Reports AWS Partners Developers Builder Center SDKs & Tools .NET on AWS Python on AWS Java on AWS PHP on AWS JavaScript on AWS Help Contact Us File a Support Ticket AWS re:Post Knowledge Center AWS Support Overview Get Expert Help AWS Accessibility Legal English Back to top Amazon is an Equal Opportunity Employer: Minority / Women / Disability / Veteran / Gender Identity / Sexual Orientation / Age. x facebook linkedin instagram twitch youtube podcasts email Privacy Site terms Cookie Preferences © 2026, Amazon Web Services, Inc. or its affiliates. All rights reserved. | 2026-01-13T09:30:35 |
https://docs.aws.amazon.com/es_es/AmazonCloudFront/latest/DeveloperGuide/lambda-examples.html#lambda-examples-content-based-S3-origin-based-on-query | Funciones de ejemplo de Lambda@Edge - Amazon CloudFront Funciones de ejemplo de Lambda@Edge - Amazon CloudFront Documentación Amazon CloudFront Guía para desarrolladores Ejemplos generales Generación de respuestas: ejemplos Cadenas de consulta: ejemplos Personalización de contenido por encabezados de tipo de dispositivo o país: ejemplos Selección de origen dinámico basada en contenido: ejemplos Actualización de estados de error: ejemplos Acceso al cuerpo de la solicitud: ejemplos Funciones de ejemplo de Lambda@Edge Consulte los ejemplos siguientes para usar funciones de Lambda con Amazon CloudFront. nota Si elige el tiempo de ejecución Node.js 18 o una versión posterior para la función Lambda@Edge, se creará automáticamente un archivo index.mjs . Para usar los siguientes ejemplos de código, cambie el nombre del archivo index.mjs a index.js . Temas Ejemplos generales Generación de respuestas: ejemplos Cadenas de consulta: ejemplos Personalización de contenido por encabezados de tipo de dispositivo o país: ejemplos Selección de origen dinámico basada en contenido: ejemplos Actualización de estados de error: ejemplos Acceso al cuerpo de la solicitud: ejemplos Ejemplos generales Los ejemplos siguientes muestran formas habituales de usar Lambda@Edge en CloudFront. Temas Ejemplo: prueba A/B Ejemplo: Sobrescritura de un encabezado de respuesta Ejemplo: prueba A/B Puede utilizar el siguiente ejemplo para probar dos versiones diferentes de una imagen sin crear redirecciones ni cambiar la dirección URL. En este ejemplo se leen las cookies de la solicitud del lector y se modifica la URL de la solicitud en consecuencia. Si el espectador no envía una cookie con uno de los valores esperados, el ejemplo asigna aleatoriamente al espectador una de las URL. 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; } 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; } } 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" ''' experimentUri = "" 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 Ejemplo: Sobrescritura de un encabezado de respuesta En el ejemplo siguiente, se muestra cómo cambiar el valor de un encabezado de respuesta según el valor de otro encabezado. Node.js export const handler = async (event) => { 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()] = [ { key: headerNameDst, value: headers[headerNameSrc.toLowerCase()][0].value, }]; console.log(`Response header "$ { headerNameDst}" was set to ` + `"$ { headers[headerNameDst.toLowerCase()][0].value}"`); } return response; }; Python import json def lambda_handler(event, context): response = event['Records'][0]['cf']['response'] headers = response['headers'] header_name_src = 'X-Amz-Meta-Last-Modified' header_name_dst = 'Last-Modified' if headers.get(header_name_src.lower()): headers[header_name_dst.lower()] = [ { 'key': header_name_dst, 'value': headers[header_name_src.lower()][0]['value'] }] print(f'Response header " { header_name_dst}" was set to ' f'" { headers[header_name_dst.lower()][0]["value"]}"') return response Generación de respuestas: ejemplos En los ejemplos siguientes se muestra cómo puede usar Lambda@Edge para generar respuestas. Temas Ejemplo: Envío de contenido estático (respuesta generada) Ejemplo: Generación de un redireccionamiento HTTP (respuesta generada) Ejemplo: Envío de contenido estático (respuesta generada) En el siguiente ejemplo se muestra cómo utilizar una función de Lambda para enviar contenido de sitio web estático, lo que reduce la carga en el servidor de origen y la latencia total. nota Puede generar respuestas HTTP para los eventos de solicitud del espectador y al origen. Para obtener más información, consulte Generación de respuestas HTTP en los desencadenadores de solicitud . También puede sustituir o quitar el cuerpo de la respuesta HTTP en eventos de respuesta de origen. Para obtener más información, consulte Actualización de respuestas HTTP en desencadenadores de respuesta de origen . 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' }] }, 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 } return response Ejemplo: Generación de un redireccionamiento HTTP (respuesta generada) En el siguiente ejemplo se muestra cómo generar una redirección HTTP. nota Puede generar respuestas HTTP para los eventos de solicitud del espectador y al origen. Para obtener más información, consulte Generación de respuestas HTTP en los desencadenadores de solicitud . 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. response = { 'status': '302', 'statusDescription': 'Found', 'headers': { 'location': [ { 'key': 'Location', 'value': 'https://docs.aws.amazon.com/lambda/latest/dg/lambda-edge.html' }] } } return response Cadenas de consulta: ejemplos En los ejemplos siguientes se muestran formas de usar Lambda@Edge con cadenas de consulta. Temas Ejemplo: Adición de un encabezado en función de un parámetro de la cadena de consulta Ejemplo: Normalización de parámetros de cadenas de consulta para mejorar la tasa de aciertos de caché Ejemplo: Redireccionamiento de los usuarios no autenticados a una página de inicio de sesión Ejemplo: Adición de un encabezado en función de un parámetro de la cadena de consulta El siguiente ejemplo muestra cómo obtener el par clave-valor de un parámetro de la cadena de consulta y, a continuación, añadir un encabezado en función de dichos valores. 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. * 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 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'] # Update request querystring request['querystring'] = urlencode(params) return request Ejemplo: Normalización de parámetros de cadenas de consulta para mejorar la tasa de aciertos de caché El siguiente ejemplo muestra cómo mejorar la tasa de acceso a la caché haciendo los siguientes cambios en las cadenas de consulta antes de que CloudFront reenvíe las solicitudes a su origen: Alfabetizar los pares de clave-valor por el nombre del parámetro. Cambiar a minúsculas el modelo de mayúsculas y minúsculas de los pares de clave-valor. Para obtener más información, consulte Almacenamiento en caché de contenido en función de parámetros de cadenas de consulta . 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 */ 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 request['querystring'] = urlencode(sortedParams) return request Ejemplo: Redireccionamiento de los usuarios no autenticados a una página de inicio de sesión El siguiente ejemplo muestra cómo redirigir a los usuarios una página de inicio de sesión si no ha introducido sus credenciales. 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; } /* 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 params. ''' # Check for session-id in cookie, if present, then proceed with request parsedCookies = parseCookies(headers) 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 Personalización de contenido por encabezados de tipo de dispositivo o país: ejemplos En los ejemplos siguientes se muestra cómo puede usar Lambda@Edge para personalizar el comportamiento en función de la ubicación o el tipo de dispositivo que usa el lector. Temas Ejemplo: Redireccionamiento de solicitudes de espectadores a una URL específica de un país Ejemplo: Envío de distintas versiones de un objeto en función del dispositivo Ejemplo: Redireccionamiento de solicitudes de espectadores a una URL específica de un país El siguiente ejemplo muestra cómo generar una respuesta de redireccionamiento HTTP con una URL específica del país y devolver la respuesta al espectador. Esto resulta útil cuando se quiere proporcionar respuestas específicas del país. Por ejemplo: Si tiene subdominios específicos de un país, como us.ejemplo.com y tw.ejemplo.com, puede generar una respuesta de redireccionamiento cuando un espectador solicite ejemplo.com. Si está haciendo streaming de video, pero no tiene derechos para transmitir el contenido en un país determinado, puede redirigir a los usuarios de dicho país a una página en la que se explica por qué no pueden ver el video. Tenga en cuenta lo siguiente: Debe configurar la distribución para almacenar en la caché en función del encabezado CloudFront-Viewer-Country . Para obtener más información, consulte Caché en función de encabezados de solicitud seleccionados . CloudFront agrega el encabezado CloudFront-Viewer-Country después del evento de solicitud del lector. Para utilizar este ejemplo, debe crear un activador para el evento de solicitud al origen. 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 = { 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', 'statusDescription': 'Found', 'headers': { 'location': [ { 'key': 'Location', 'value': url }] } } return response Ejemplo: Envío de distintas versiones de un objeto en función del dispositivo El siguiente ejemplo muestra cómo ofrecer distintas versiones de un objeto en función del tipo de dispositivo que el usuario está utilizando; por ejemplo, un dispositivo móvil o una tablet. Tenga en cuenta lo siguiente: Debe configurar la distribución para almacenar en la caché en función de los encabezados CloudFront-Is-*-Viewer . Para obtener más información, consulte Caché en función de encabezados de solicitud seleccionados . CloudFront agrega los encabezados CloudFront-Is-*-Viewer después del evento de solicitud del lector. Para utilizar este ejemplo, debe crear un activador para el evento de solicitud al origen. 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 * 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. ''' desktopPath = '/desktop'; mobilePath = '/mobile'; tabletPath = '/tablet'; smarttvPath = '/smarttv'; 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 Selección de origen dinámico basada en contenido: ejemplos En los ejemplos siguientes se muestra cómo puede usar Lambda@Edge para el direccionamiento a diferentes orígenes en función de la información de la solicitud. Temas Ejemplo: Uso de un desencadenador de solicitud de origen para cambiar desde un origen personalizado a un origen de Amazon S3 Ejemplo: Uso de un desencadenador de solicitud de origen para cambiar la región de origen de Amazon S3 Ejemplo: Uso de un desencadenador de solicitud de origen para cambiar desde un origen de Amazon S3 a un origen personalizado Ejemplo: Uso de un desencadenador de solicitud al origen para transferir gradualmente el tráfico desde un bucket de Amazon S3 a otro Ejemplo: Uso de un desencadenador de solicitud de origen para cambiar el nombre del dominio de origen en función del encabezado de país Ejemplo: Uso de un desencadenador de solicitud de origen para cambiar desde un origen personalizado a un origen de Amazon S3 Esta función demuestra cómo utilizar un desencadenador de solicitud al origen para cambiar desde un origen personalizado a un origen de Amazon S3 desde el que recuperar el contenido, en función de las propiedades de la solicitud. 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: 'origin-access-identity', path: '', customHeaders: { } } }; request.headers['host'] = [ { key: 'host', value: s3DomainName}]; } } 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 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': 'origin-access-identity', 'path': '', 'customHeaders': { } } } request['headers']['host'] = [ { 'key': 'host', 'value': s3DomainName}] return request Ejemplo: Uso de un desencadenador de solicitud de origen para cambiar la región de origen de Amazon S3 Esta función demuestra cómo utilizar un desencadenador de solicitud al origen para cambiar el origen de Amazon S3 desde el que se recupera el contenido, en función de las propiedades de la solicitud. En este ejemplo, utilizamos el valor del encabezado CloudFront-Viewer-Country para actualizar el nombre de dominio del bucket de S3 por un bucket de una región que está más cerca del lector. Esto puede resultar útil de varias maneras: Reduce las latencias cuando la región especificada está más cerca del país del lector. Proporciona soberanía de los datos, al asegurarse de que los datos se distribuyen desde un origen que está en el país del que provino la solicitud. Para utilizar este ejemplo, debe hacer lo siguiente: Configure la distribución para almacenar en la caché en función del encabezado CloudFront-Viewer-Country . Para obtener más información, consulte Caché en función de encabezados de solicitud seleccionados . Crear un disparador para esta función en el evento de solicitud al origen. CloudFront agrega el encabezado CloudFront-Viewer-Country después del evento de solicitud del lector; por lo tanto, para utilizar este ejemplo, debe asegurarse de que la función ejecuta una solicitud de origen. nota El siguiente código de ejemplo usa la misma identidad de acceso de origen (OAI) para todos los buckets de S3 que usa para el origen. Para obtener más información, consulte Identidad de acceso de origen . 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 * 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); }; Python 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: 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: ''' 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 Ejemplo: Uso de un desencadenador de solicitud de origen para cambiar desde un origen de Amazon S3 a un origen personalizado Esta función demuestra cómo utilizar un disparador de solicitud al origen para cambiar el origen personalizado desde el que se recupera el contenido, en función de las propiedades de la solicitud. 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: { 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': { } } } request['headers']['host'] = [ { 'key': 'host', 'value': 'www.example.com'}] return request Ejemplo: Uso de un desencadenador de solicitud al origen para transferir gradualmente el tráfico desde un bucket de Amazon S3 a otro Esta función demuestra cómo transferir gradualmente el tráfico desde un bucket de Amazon S3 a otro de forma controlada. 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}]; } 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 Ejemplo: Uso de un desencadenador de solicitud de origen para cambiar el nombre del dominio de origen en función del encabezado de país Esta función demuestra cómo cambiar el nombre del dominio de origen en función del encabezado CloudFront-Viewer-Country , de forma que el contenido se distribuya desde un origen más cercano al país del lector. La implementación de esta funcionalidad para su distribución puede tener ventajas como las siguientes: Reducir las latencias cuando la región especificada está más cerca del país del lector Proporcionar soberanía de los datos, al asegurarse de que los datos se distribuyen desde un origen que está en el país del que provino la solicitud Tenga en cuenta que para habilitar esta funcionalidad, debe configurar su distribución para almacenar en la caché en función del encabezado CloudFront-Viewer-Country . Para obtener más información, consulte Caché en función de encabezados de solicitud seleccionados . 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 request['headers']['host'] = [ { 'key': 'host', 'value': domainName}] return request Actualización de estados de error: ejemplos En los ejemplos siguientes se proporciona orientación acerca de cómo puede usar Lambda@Edge para cambiar el estado de error que se devuelve a los usuarios. Temas Ejemplo: Uso de un desencadenador de respuesta de origen para actualizar el código de estado de error a 200 Ejemplo: Uso de un desencadenador de respuesta de origen para actualizar el código de estado de error a 302 Ejemplo: Uso de un desencadenador de respuesta de origen para actualizar el código de estado de error a 200 Esta función demuestra cómo actualizar el estado de la respuesta a 200 y generar un cuerpo con contenido estático para devolverlo al espectador en la siguiente situación: La función se desencadena en una respuesta del origen. El estado de la respuesta del servidor de origen es un código de estado de error (4xx o 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'; } callback(null, response); }; Python 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 Ejemplo: Uso de un desencadenador de respuesta de origen para actualizar el código de estado de error a 302 Esta función demuestra cómo actualizar el código de estado HTTP a 302 para la redirección a otra ruta (comportamiento de la caché) en la que se ha configurado un origen diferente. Tenga en cuenta lo siguiente: La función se desencadena en una respuesta del origen. El estado de la respuesta del servidor de origen es un código de estado de error (4xx o 5xx). Node.js 'use strict'; exports.handler = (event, context, callback) => { const response = event.Records[0].cf.response; const 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 (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 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 Acceso al cuerpo de la solicitud: ejemplos En los ejemplos siguientes se muestra cómo puede usar Lambda@Edge para trabajar con las solicitudes POST. nota Para utilizar estos ejemplos, debe habilitar la opción incluir cuerpo en la asociación de funciones Lambda de la distribución. No está habilitada de forma predeterminada. Para habilitar esta configuración en la consola de CloudFront, seleccione la casilla de verificación Incluir cuerpo en la Asociación de funciones Lambda . Para habilitar esta configuración en la API de CloudFront o con CloudFormation, establezca el campo IncludeBody en true en LambdaFunctionAssociation . Temas Ejemplo: Uso de un desencadenador de solicitud para leer un formulario HTML Ejemplo: Uso de un desencadenador de solicitud para modificar un formulario HTML Ejemplo: Uso de un desencadenador de solicitud para leer un formulario HTML Esta función ilustra cómo puede procesar el cuerpo de una solicitud POST generada por un formulario HTML (formulario web), como por ejemplo un formulario tipo "póngase en contacto con nosotros". Por ejemplo, es posible que tenga un formulario HTML como el siguiente: <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> Para la función de ejemplo que se indica a continuación, la función se debe desencadenar en una solicitud al origen o del lector de CloudFront. 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 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 Ejemplo: Uso de un desencadenador de solicitud para modificar un formulario HTML Esta función ilustra cómo puede modificar el cuerpo de una solicitud POST generada por un formulario HTML (formulario web). La función se activa en una solicitud al origen o del lector de CloudFront. 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. * * 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'] | 2026-01-13T09:30:35 |
https://aws.amazon.com/solutions/implementations/network-orchestration-aws-transit-gateway/ | Network Orchestration for AWS Transit Gateway | AWS Solutions Skip to main content Filter: All English Contact us AWS Marketplace Support My account Search Filter: All Sign in to console Create account AWS Solutions Library Industry Cross-Industry Technology Organization Type Browse By More AWS Solutions Library › Network Orchestration for AWS Transit Gateway Network Orchestration for AWS Transit Gateway Automate setting up and managing your transit networks with AWS Transit Gateway Open guide Go to source code Overview The Network Orchestration for AWS Transit Gateway solution automates the process of setting up and managing transit networks in distributed AWS environments. This solution allows customers to visualize and monitor their global network from a single dashboard rather than toggling between Regions from the AWS Console. It creates a web interface to help control, audit, and approve transit network changes. Benefits Cross-account and cross-Region capability Automate the process of setting up and managing transit networks in multi-account AWS environments. Change management Use the web user interface to either accept or reject connectivity requests when manual approval is required. Web user interface Deploy a web user interface to control, audit, and approve transit network changes. Compliance Use rules to automatically accept or reject network changes based on the Organization Unit (OU). How it works You can automatically deploy this architecture using the implementation guide and the accompanying AWS CloudFormation templates. View implementation guide About this deployment Version: 3.3.21 Released: 12/2025 Author: AWS Est. deployment time: 25 mins Estimated cost: See details Deploy with confidence Everything you need to launch this AWS Solution in your account is right here We'll walk you through it Get started fast. Read the implementation guide for deployment steps, architecture details, cost information, and customization options. Open guide Let's make it happen Ready to deploy? Open the CloudFormation template in the AWS Console to begin setting up the infrastructure you need. You'll be prompted to access your AWS account if you haven't yet logged in. Launch in the AWS Console Deployment options Download implementation guide Learn more Source code Learn more CloudFormation templates Learn more Australia Post "Australia Post is a self-funded postal service business with both commercial and community service obligations, serving 12.3 million delivery points across Australia. Our organization is made up of 35,000 employees so when we needed to expand our cloud technologies to scale our network across our growing cloud infrastructure with siloed VPCs and on-premises data centers, we experienced significant latency issues. The Network Orchestration for AWS Transit Gateway solution allowed us to automate our configuration and customize our network setup based on our needs with AWS Transit Gateway, reducing our network setup time from weeks to minutes, resulting on the final solution reaching 13X improved network traffic speeds between accounts." Jason Gorringe, Cloud Services Manager Australia Post Related content Getting into the Serverless Mindset Learn how to move forward without provisioning, scaling, or managing servers. Enroll now Subnets, Gateways, and Route Tables Explained In this course, we will use sample three-tiered architecture to better understand how certain network components can help you effectively network your application. We review the differences between public and private subnets and discuss how gateways and route tables can be used for network routing. Enroll now Solving with AWS Solutions: Network Orchestration for AWS Transit Gateway Watch the video Did you find what you were looking for today? Let us know so we can improve the quality of the content on our pages Yes No Create an AWS account Learn What Is AWS? What Is Cloud Computing? What Is Agentic AI? Cloud Computing Concepts Hub AWS Cloud Security What's New Blogs Press Releases Resources Getting Started Training AWS Trust Center AWS Solutions Library Architecture Center Product and Technical FAQs Analyst Reports AWS Partners Developers Builder Center SDKs & Tools .NET on AWS Python on AWS Java on AWS PHP on AWS JavaScript on AWS Help Contact Us File a Support Ticket AWS re:Post Knowledge Center AWS Support Overview Get Expert Help AWS Accessibility Legal English Back to top Amazon is an Equal Opportunity Employer: Minority / Women / Disability / Veteran / Gender Identity / Sexual Orientation / Age. x facebook linkedin instagram twitch youtube podcasts email Privacy Site terms Cookie Preferences © 2026, Amazon Web Services, Inc. or its affiliates. All rights reserved. | 2026-01-13T09:30:35 |
https://docs.aws.amazon.com/zh_cn/lambda/latest/dg/invocation-async.html | 异步调用 Lambda 函数 - AWS Lambda 异步调用 Lambda 函数 - AWS Lambda 文档 AWS Lambda 开发人员指南 异步调用 Lambda 函数 多个 AWS 服务(如 Amazon Simple Storage Service(Amazon S3)和 Amazon Simple Notification Service(Amazon SNS)将异步调用函数以处理事件。您也可以使用 AWS Command Line Interface(AWS CLI)或一种 AWS SDK 来异步调用 Lambda 函数。在异步调用函数时,您不会等待函数代码的响应。您将事件交给 Lambda,Lambda 处理其余部分。您可以配置 Lambda 处理错误的方式,并将调用记录发送到下游资源,例如 Amazon Simple Queue Service(Amazon SQS)或 Amazon EventBridge(EventBridge),以将应用程序的组件链接在一起。 下图显示了异步调用 Lambda 函数的客户端。Lambda 在将事件发送到函数之前对事件排队。 对于异步调用,Lambda 将事件置于队列中并返回成功响应,而不返回其他信息。一个单独的进程会从队列中读取事件并将其发送到函数。 要使用 AWS Command Line Interface(AWS CLI)或一种 AWS SDK 来异步调用 Lambda 函数,请将 InvocationType 参数设置为 Event 。以下示例显示了调用函数的 AWS CLI 命令。 aws lambda invoke \ --function-name my-function \ --invocation-type Event \ --cli-binary-format raw-in-base64-out \ --payload ' { "key": "value" }' response.json 您应看到以下输出: { "StatusCode": 202 } 如果使用 cli-binary-format 版本 2,则 AWS CLI 选项是必需的。要将其设为默认设置,请运行 aws configure set cli-binary-format raw-in-base64-out 。有关更多信息,请参阅 版本 2 的 AWS Command Line Interface 用户指南 中的 AWS CLI 支持的全局命令行选项 。 输出文件 ( response.json ) 不包含任何信息,但运行此命令时仍会创建该文件。如果 Lambda 无法将事件添加到队列,则命令输出中将显示错误消息。 Javascript 在您的浏览器中被禁用或不可用。 要使用 Amazon Web Services 文档,必须启用 Javascript。请参阅浏览器的帮助页面以了解相关说明。 文档惯例 同步调用函数 错误处理 此页面对您有帮助吗?- 是 感谢您对我们工作的肯定! 如果不耽误您的时间,请告诉我们做得好的地方,让我们做得更好。 此页面对您有帮助吗?- 否 感谢您告诉我们本页内容还需要完善。很抱歉让您失望了。 如果不耽误您的时间,请告诉我们如何改进文档。 | 2026-01-13T09:30:35 |
https://phproundtable.com/show/security-encryption-hashing-and-php | PHPRoundtable PHPRoundtable The PHP podcast where everyone has a seat. Guests Library Sponsors About Us 54: Security: Encryption, Hashing and PHP Panelists: Scott Arciszewski Chris Riley Chris Cornutt October 25 2016 We chat about security in the the PHP community, encryption & hashing in PHP and a new-hotness crypto library called libsodium . PSR-9 and PSR-10 PSR-9 deals with the process by which security issues are submitted or reported to project maintainers. [PSR-10]( https://github.c About Us Sponsors © 2026 PHPRoundtable Proud member of the php[architect] family | 2026-01-13T09:30:35 |
https://phproundtable.com/show/character-encoding-and-utf-8-in-php | PHPRoundtable PHPRoundtable The PHP podcast where everyone has a seat. Guests Library Sponsors About Us 46: Character Encoding and UTF-8 in PHP Panelists: Andreas Heigl Evert Pot May 30 2016 If you've ever gotten a number of weird looking characters in your database or on your website like, " � " and didn't know why, then this episode is for you. Those bizarre chara What are character encodings? Comparison of number systems (base-10, binary, hexadecimal) Historical development of character maps and encodings (telegram, ASCII, ISO-8859-1...) Unicode and its implementations (UTF-8, UTF-16, UTF-32) UT About Us Sponsors © 2026 PHPRoundtable Proud member of the php[architect] family | 2026-01-13T09:30:35 |
https://phproundtable.com/show/documentation-and-developer-experience | PHPRoundtable PHPRoundtable The PHP podcast where everyone has a seat. Guests Library Sponsors About Us 26: Documentation and Developer Experience Panelists: Ryan Weaver Taylor Otwell Frank de Jonge August 4 2015 Documentation can make or break a project but it's often completely overlooked until the very end. And if we don't think about how developers will interact with our project before writing our opening <?php tag, we could end up with a very ugly API. W About Us Sponsors © 2026 PHPRoundtable Proud member of the php[architect] family | 2026-01-13T09:30:35 |
https://docs.aws.amazon.com/zh_cn/lambda/latest/dg/configuration-versions.html#versioning-versions-using | 管理 Lambda 函数版本 - AWS Lambda 管理 Lambda 函数版本 - AWS Lambda 文档 AWS Lambda 开发人员指南 创建函数版本 使用版本 授予权限 管理 Lambda 函数版本 您可以使用版本来管理函数的部署。例如,您可以发布函数的新版本用于测试版测试,而不会影响稳定的生产版本的用户。您每次发布函数时,Lambda 都会为函数创建一个新版本。新版本是函数的未发布版本的副本。未发布版本的名为 $LATEST 。 重要的是,每当您部署函数代码时,都会覆盖 $LATEST 中的当前代码。要保存 $LATEST 的当前迭代,请创建一个新的函数版本。如果 $LATEST 与之前发布的版本相同,则在将更改部署到 $LATEST 之前,您无法创建新版本。这些更改可能会包括更新代码或修改函数配置设置。 发布函数版本后,其代码、运行时、架构、内存、层和大多数其他配置设置都不可变。这意味着,如果不从 $LATEST 发布新版本,则无法更改这些设置。您可以为已发布函数版本配置以下项目: 触发 目标 预配置并发 异步调用 数据库连接和代理 注意 在 自动 模式下使用 运行时管理控件 时,此函数版本使用的运行时版本会自动更新。使用 Function update (函数更新)或 Manual (手动)模式时,不会更新运行时版本。有关更多信息,请参阅 了解 Lambda 如何管理运行时版本更新 。 Sections 创建函数版本 使用版本 授予权限 创建函数版本 只能在函数的未发布版本上更改函数代码和设置。在您发布版本时,Lambda 会锁定代码和大多数设置,以便为该版本的用户维持一致的体验。 您可以使用 Lambda 控制台创建函数版本。 创建新函数版本 打开 Lamba 控制台的 函数页面 。 选择一个函数,然后选择 版本 选项卡。 在版本配置页面上,选择 Publish new version(发布新版本) 。 (可选)输入版本说明。 选择 发布 。 或者,您可以使用 PublishVersion API 操作发布函数版本。 以下 AWS CLI 命令发布函数的新版本。响应返回有关新版本的配置信息,包括版本号和具有版本后缀的函数 ARN。 aws lambda publish-version --function-name my-function 您应看到以下输出: { "FunctionName": "my-function", "FunctionArn": "arn:aws:lambda:us-east-2:123456789012:function:my-function:1", "Version": "1", "Role": "arn:aws:iam::123456789012:role/lambda-role", "Handler": "function.handler", "Runtime": "nodejs22.x", ... } 注意 Lambda 会分配单调递增的序列号,以便进行版本控制。Lambda 不会重复使用版本号,即使是删除并重新创建函数之后也是如此。 使用版本 您可以使用限定的 ARN 或非限定的 ARN 来引用您的 Lambda 函数。 限定的 ARN – 具有版本后缀的函数 ARN。以下示例引用 helloworld 函数的版本 42。 arn:aws:lambda:aws-region:acct-id:function:helloworld:42 非限定的 ARN – 不具有版本后缀的函数 ARN。 arn:aws:lambda:aws-region:acct-id:function:helloworld 您可以在所有相关 API 操作中使用限定或非非限定的 ARN。但是,不能使用非限定 ARN 来创建别名。 如果您决定不发布函数版本,可以使用 事件源映射 中的限定或非限定 ARN 来调用函数。当您使用非限定 ARN 调用函数时,Lambda 会隐式调用 $LATEST 。 每个 Lambda 函数版本的限定 ARN 都是唯一的。发布版本后,您无法更改 ARN 或函数代码。 Lambda 仅在代码从未发布过或自上次发布版本后已发生更改时,才会发布新函数版本。如果没有任何更改,函数版本将保持为上次发布的版本。 当您发布版本时,Lambda 会创建函数代码和配置的不可变快照。并非所有配置更改都会触发新版本的发布。以下配置更改使函数有资格发布版本: 函数代码 环境变量 运行时 处理程序 图层 内存大小 超时 VPC 配置 死信队列 (DLQ) 配置 IAM 角色 描述 架构(x86_64 或 arm64) 临时存储大小 包类型 日志记录配置 文件系统配置 SnapStart 跟踪配置 预留并发 等操作设置在更改时不会触发新版本的发布。 授予权限 您可以使用基于 资源的策略 或 基于身份的策略 授予对函数的访问权限。权限的范围取决于您要将策略应用于整个函数还是函数的某个版本。有关策略中的函数资源名称的更多信息,请参阅 微调策略的“资源和条件”部分 。 您可以使用函数别名,简化事件源和 AWS Identity and Access Management (IAM) 策略的管理。有关更多信息,请参阅 为 Lambda 函数创建别名 。 Javascript 在您的浏览器中被禁用或不可用。 要使用 Amazon Web Services 文档,必须启用 Javascript。请参阅浏览器的帮助页面以了解相关说明。 文档惯例 加权别名 标签 此页面对您有帮助吗?- 是 感谢您对我们工作的肯定! 如果不耽误您的时间,请告诉我们做得好的地方,让我们做得更好。 此页面对您有帮助吗?- 否 感谢您告诉我们本页内容还需要完善。很抱歉让您失望了。 如果不耽误您的时间,请告诉我们如何改进文档。 | 2026-01-13T09:30:35 |
https://docs.aws.amazon.com/id_id/AmazonCloudFront/latest/DeveloperGuide/GettingStarted.html | Memulai dengan CloudFront - Amazon CloudFront Memulai dengan CloudFront - Amazon CloudFront Dokumentasi Amazon CloudFront Panduan Developerr Terjemahan disediakan oleh mesin penerjemah. Jika konten terjemahan yang diberikan bertentangan dengan versi bahasa Inggris aslinya, utamakan versi bahasa Inggris. Memulai dengan CloudFront Topik di bagian ini menunjukkan cara memulai mengirimkan konten Anda dengan Amazon CloudFront. Siapkan Akun AWS Topik ini menjelaskan prasyarat untuk tutorial berikut, seperti membuat Akun AWS dan membuat pengguna dengan akses administratif. Tutorial distribusi dasar menunjukkan cara mengatur kontrol akses asal (OAC) untuk mengirim permintaan yang diautentikasi ke asal Amazon S3. Tutorial situs web statis aman menunjukkan kepada Anda cara membuat situs web statis yang aman untuk nama domain Anda menggunakan OAC dengan asal Amazon S3. Tutorial menggunakan template Amazon CloudFront (CloudFront) untuk konfigurasi dan penyebaran. Topik Siapkan Akun AWS Memulai dengan distribusi CloudFront standar Memulai dengan distribusi standar (AWS CLI) Memulai dengan situs web statis yang aman Javascript dinonaktifkan atau tidak tersedia di browser Anda. Untuk menggunakan Dokumentasi AWS, Javascript harus diaktifkan. Lihat halaman Bantuan browser Anda untuk petunjuk. Konvensi Dokumen Bekerja dengan AWS SDKs Siapkan Akun AWS Apakah halaman ini membantu Anda? - Ya Terima kasih telah memberitahukan bahwa hasil pekerjaan kami sudah baik. Jika Anda memiliki waktu luang, beri tahu kami aspek apa saja yang sudah bagus, agar kami dapat menerapkannya secara lebih luas. Apakah halaman ini membantu Anda? - Tidak Terima kasih telah memberi tahu kami bahwa halaman ini perlu ditingkatkan. Maaf karena telah mengecewakan Anda. Jika Anda memiliki waktu luang, beri tahu kami bagaimana dokumentasi ini dapat ditingkatkan. | 2026-01-13T09:30:35 |
https://docs.aws.amazon.com/lambda/latest/dg/access-control-resource-based.html | Viewing resource-based IAM policies in Lambda - AWS Lambda Viewing resource-based IAM policies in Lambda - AWS Lambda Documentation AWS Lambda Developer Guide Supported API actions Viewing resource-based IAM policies in Lambda Lambda supports resource-based permissions policies for Lambda functions and layers. You can use resource-based policies to grant access to other AWS accounts , organizations , or services . Resource-based policies apply to a single function, version, alias, or layer version. Console To view a function's resource-based policy Open the Functions page of the Lambda console. Choose a function. Choose Configuration and then choose Permissions . Scroll down to Resource-based policy and then choose View policy document . The resource-based policy shows the permissions that are applied when another account or AWS service attempts to access the function. The following example shows a statement that allows Amazon S3 to invoke a function named my-function for a bucket named amzn-s3-demo-bucket in account 123456789012 . Example resource-based policy { "Version":"2012-10-17", "Id": "default", "Statement": [ { "Sid": "lambda-allow-s3-my-function", "Effect": "Allow", "Principal": { "Service": "s3.amazonaws.com" }, "Action": "lambda:InvokeFunction", "Resource": "arn:aws:lambda:us-east-2:123456789012:function:my-function", "Condition": { "StringEquals": { "AWS:SourceAccount": "123456789012" }, "ArnLike": { "AWS:SourceArn": "arn:aws:s3:::amzn-s3-demo-bucket" } } } ] } AWS CLI To view a function's resource-based policy, use the get-policy command. aws lambda get-policy \ --function-name my-function \ --output text You should see the following output: { "Version":"2012-10-17", "Id":"default","Statement":[ { "Sid":"sns","Effect":"Allow","Principal": { "Service":"s3.amazonaws.com"},"Action":"lambda:InvokeFunction","Resource":"arn:aws:lambda:us-east-2:123456789012:function:my-function","Condition": { "ArnLike": { "AWS:SourceArn":"arn:aws:sns:us-east-2:123456789012:lambda*"}}}]} For versions and aliases, append the version number or alias to the function name. aws lambda get-policy --function-name my-function:PROD To remove permissions from your function, use remove-permission . aws lambda remove-permission \ --function-name example \ --statement-id sns Use the get-layer-version-policy command to view the permissions on a layer. aws lambda get-layer-version-policy \ --layer-name my-layer \ --version-number 3 \ --output text You should see the following output: b0cd9796-d4eb-4564-939f-de7fe0b42236 { "Sid":"engineering-org","Effect":"Allow","Principal":"*","Action":"lambda:GetLayerVersion","Resource":"arn:aws:lambda:us-west-2:123456789012:layer:my-layer:3","Condition": { "StringEquals": { "aws:PrincipalOrgID":"o-t194hfs8cz"}}}" Use remove-layer-version-permission to remove statements from the policy. aws lambda remove-layer-version-permission --layer-name my-layer --version-number 3 --statement-id engineering-org Supported API actions The following Lambda API actions support resource-based policies: CreateAlias DeleteAlias DeleteFunction DeleteFunctionConcurrency DeleteFunctionEventInvokeConfig DeleteProvisionedConcurrencyConfig GetAlias GetFunction GetFunctionConcurrency GetFunctionConfiguration GetFunctionEventInvokeConfig GetPolicy GetProvisionedConcurrencyConfig Invoke InvokeFunctionUrl (permission only) ListAliases ListFunctionEventInvokeConfigs ListProvisionedConcurrencyConfigs ListTags ListVersionsByFunction PublishVersion PutFunctionConcurrency PutFunctionEventInvokeConfig PutProvisionedConcurrencyConfig TagResource UntagResource UpdateAlias UpdateFunctionCode UpdateFunctionEventInvokeConfig Javascript is disabled or is unavailable in your browser. To use the Amazon Web Services Documentation, Javascript must be enabled. Please refer to your browser's Help pages for instructions. Document Conventions Layer access Function access for AWS services Did this page help you? - Yes Thanks for letting us know we're doing a good job! If you've got a moment, please tell us what we did right so we can do more of it. Did this page help you? - No Thanks for letting us know this page needs work. We're sorry we let you down. If you've got a moment, please tell us how we can make the documentation better. | 2026-01-13T09:30:35 |
https://docs.aws.amazon.com/lambda/latest/dg/lambda-intro-execution-role.html | Defining Lambda function permissions with an execution role - AWS Lambda Defining Lambda function permissions with an execution role - AWS Lambda Documentation AWS Lambda Developer Guide Creating an execution role in the IAM console Creating and managing roles with the AWS CLI Grant least privilege access to your Lambda execution role Defining Lambda function permissions with an execution role A Lambda function's execution role is an AWS Identity and Access Management (IAM) role that grants the function permission to access AWS services and resources. For example, you might create an execution role that has permission to send logs to Amazon CloudWatch and upload trace data to AWS X-Ray. This page provides information on how to create, view, and manage a Lambda function's execution role. Lambda automatically assumes your execution role when you invoke your function. You should avoid manually calling sts:AssumeRole to assume the execution role in your function code. If your use case requires that the role assumes itself, you must include the role itself as a trusted principal in your role's trust policy. For more information on how to modify a role trust policy, see Modifying a role trust policy (console) in the IAM User Guide. In order for Lambda to properly assume your execution role, the role's trust policy must specify the Lambda service principal ( lambda.amazonaws.com ) as a trusted service. Topics Creating an execution role in the IAM console Creating and managing roles with the AWS CLI Grant least privilege access to your Lambda execution role Viewing and updating permissions in the execution role Working with AWS managed policies in the execution role Using source function ARN to control function access behavior Creating an execution role in the IAM console By default, Lambda creates an execution role with minimal permissions when you create a function in the Lambda console . Specifically, this execution role includes the AWSLambdaBasicExecutionRole managed policy , which gives your function basic permissions to log events to Amazon CloudWatch Logs. Your functions typically need additional permissions to perform more meaningful tasks. For example, you might have a Lambda function that responds to an event by updating entries in an Amazon DynamoDB database. You can create an execution role with the necessary permissions using the IAM console. To create an execution role in the IAM console Open the Roles page in the IAM console. Choose Create role . Under Trusted entity type , choose AWS service . Under Use case , choose Lambda . Choose Next . Select the AWS managed policies that you want to attach to your role. For example, if your function needs to access DynamoDB, select the AWSLambdaDynamoDBExecutionRole managed policy. Choose Next . Enter a Role name and then choose Create role . For detailed instructions, see Creating a role for an AWS service (console) in the IAM User Guide . After you create your execution role, attach it to your function. When you create a function in the Lambda console , you can attach any execution role that you previously created to the function. If you want to attach a new execution role to an existing function, follow the steps in Updating a function's execution role . Creating and managing roles with the AWS CLI To create an execution role with the AWS Command Line Interface (AWS CLI), use the create-role command. When using this command, you can specify the trust policy inline. A role's trust policy gives the specified principals permission to assume the role. In the following example, you grant the Lambda service principal permission to assume your role. Note that requirements for escaping quotes in the JSON string may vary depending on your shell. aws iam create-role \ --role-name lambda-ex \ --assume-role-policy-document ' { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": { "Service": "lambda.amazonaws.com"}, "Action": "sts:AssumeRole"}]}' You can also define the trust policy for the role using a separate JSON file. In the following example, trust-policy.json is a file in the current directory. Example trust-policy.json JSON { "Version":"2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": { "Service": "lambda.amazonaws.com" }, "Action": "sts:AssumeRole" } ] } aws iam create-role \ --role-name lambda-ex \ --assume-role-policy-document file://trust-policy.json To add permissions to the role, use the attach-policy-to-role command. The following command adds the AWSLambdaBasicExecutionRole managed policy to the lambda-ex execution role. aws iam attach-role-policy --role-name lambda-ex --policy-arn arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole After you create your execution role, attach it to your function. When you create a function in the Lambda console , you can attach any execution role that you previously created to the function. If you want to attach a new execution role to an existing function, follow the steps in Updating a function's execution role . Grant least privilege access to your Lambda execution role When you first create an IAM role for your Lambda function during the development phase, you might sometimes grant permissions beyond what is required. Before publishing your function in the production environment, as a best practice, adjust the policy to include only the required permissions. For more information, see Apply least-privilege permissions in the IAM User Guide . Use IAM Access Analyzer to help identify the required permissions for the IAM execution role policy. IAM Access Analyzer reviews your AWS CloudTrail logs over the date range that you specify and generates a policy template with only the permissions that the function used during that time. You can use the template to create a managed policy with fine-grained permissions, and then attach it to the IAM role. That way, you grant only the permissions that the role needs to interact with AWS resources for your specific use case. For more information, see Generate policies based on access activity in the IAM User Guide . Javascript is disabled or is unavailable in your browser. To use the Amazon Web Services Documentation, Javascript must be enabled. Please refer to your browser's Help pages for instructions. Document Conventions Lambda permissions Update execution role Did this page help you? - Yes Thanks for letting us know we're doing a good job! If you've got a moment, please tell us what we did right so we can do more of it. Did this page help you? - No Thanks for letting us know this page needs work. We're sorry we let you down. If you've got a moment, please tell us how we can make the documentation better. | 2026-01-13T09:30:35 |
https://docs.aws.amazon.com/zh_cn/lambda/latest/dg/invocation-eventsourcemapping.html | Lambda 如何处理来自基于流和队列的事件源的记录 - AWS Lambda Lambda 如何处理来自基于流和队列的事件源的记录 - AWS Lambda 文档 AWS Lambda 开发人员指南 事件源映射和触发器 批处理行为 预置模式 事件源映射 API Lambda 如何处理来自基于流和队列的事件源的记录 事件源映射 是一种 Lambda 资源,它从流或基于队列的服务中读取项目并调用包含批次记录的函数。在事件源映射内,称为 事件轮询器 的资源会主动轮询新消息并调用函数。默认情况下,Lambda 会自动扩展事件轮询器,但对于某些事件源类型,您可以使用 预调配模式 来控制专用于事件源映射的事件轮询器的最小和最大数量。 以下服务使用事件源映射调用 Lambda 函数: Amazon DocumentDB(与 MongoDB 兼容)(Amazon DocumentDB) Amazon DynamoDB Amazon Kinesis Amazon MQ Amazon Managed Streaming for Apache Kafka (Amazon MSK) 自行管理的 Apache Kafka Amazon Simple Queue Service (Amazon SQS) 警告 Lambda 事件源映射至少处理每个事件一次,有可能出现重复处理记录的情况。为避免与重复事件相关的潜在问题,我们强烈建议您将函数代码设为幂等性。要了解更多信息,请参阅 AWS 知识中心的 如何让我的 Lambda 函数保持幂等性 。 事件源映射与直接触发器的区别 某些 AWS 服务可以使用 触发器 直接调用 Lambda 函数。这些服务将事件推送到 Lambda,并在指定事件发生时立即调用该函数。触发器适用于离散事件和实时处理。当您 使用 Lambda 控制台创建触发器 时,控制台会与相应的 AWS 服务交互以配置该服务的事件通知。触发器实际上由生成事件的服务而不是 Lambda 存储和管理。以下是一些使用触发器调用 Lambda 函数的服务示例: Amazon Simple Storage Service(Amazon S3): 当在存储桶中创建、删除或修改对象时调用函数。有关更多信息,请参阅 教程:使用 Amazon S3 触发器调用 Lambda 函数 。 Amazon Simple Notification Service(Amazon SNS): 将消息发布到 SNS 主题时调用函数。有关更多信息,请参阅 教程:将 AWS Lambda 与 Amazon Simple Notification Service 结合使用 。 Amazon API Gateway: 在向特定端点发出 API 请求时调用函数。有关更多信息,请参阅 使用 Amazon API Gateway 端点调用 Lambda 函数 。 事件源映射是在 Lambda 服务中创建和管理的 Lambda 资源。事件源映射旨在处理来自队列的大量流数据或消息。分批处理来自流或队列的记录比单独处理记录更高效。 批处理行为 预设情况下,事件源映射会将记录合并为单个有效负载进行批处理,并由 Lambda 将其发送到您的函数。要微调批处理行为,您可以配置批处理时段( MaximumBatchingWindowInSeconds )和批处理大小( BatchSize )。批处理时段是将记录收集到单个有效负载中的最长时间。批处理大小是单个批处理中的最大记录数。满足以下三个条件中的任意一个时,Lambda 会调用您的函数: 批处理时段达到其最大值。 默认的批处理时段行为因特定的事件源而异。 对于 Kinesis、DynamoDB 和 Amazon SQS 事件源: 原定设置的批处理时段是 0 秒。这意味着,一旦记录可用,Lambda 就会调用您的函数。要设置批处理时段,请配置 MaximumBatchingWindowInSeconds 。您可以将此参数设置为介于 0 秒到 300 秒之间的任意值,以 1 秒为增量。如果您配置了批处理时段,则下一个时段将在上一个函数调用完成后立即开始计算。 对于 Amazon MSK、自托管式 Apache Kafka、Amazon MQ 和 Amazon DocumentDB 事件源: 默认批处理时段为 500 毫秒。您可以将 MaximumBatchingWindowInSeconds 配置为介于 0 秒到 300 秒之间的任意值,以秒的整数倍调整。在 Kafka 事件源映射的预置模式中,如果您配置了批处理时段,则下一个时段将在上一批处理完成后立即开始计算。在非预置 Kafka 事件源映射中,如果您配置了批处理时段,则下一个时段将在上一个函数调用完成后立即开始计算。要最大限度地减小在预置模式下使用 Kafka 事件源映射的延迟,请将 MaximumBatchingWindowInSeconds 设置为 0。此设置可确保 Lambda 在完成当前函数调用后立即开始处理下一个批次。有关低延迟处理的更多信息,请参阅 低延迟 Apache Kafka 。 对于 Amazon MQ 和 Amazon DocumentDB 事件源: 默认批处理时段为 500 毫秒。您可以将 MaximumBatchingWindowInSeconds 配置为介于 0 秒到 300 秒之间的任意值,以秒的整数倍调整。第一条记录到达后,批处理时段将立即开始计算。 注意 由于您只能以秒的整数倍调整 MaximumBatchingWindowInSeconds ,因此无法在更改该值后恢复到 500 毫秒的默认批处理时段。要恢复原定设置的批处理时段,必须创建新的事件源映射。 达到批处理大小。 最小批处理大小为 1。原定设置和最大批处理大小取决于事件源。有关这些值的详细信息,请参阅 CreateEventSourceMapping API 操作的 BatchSize 规范。 有效负载大小达到 6MB 。 您不能修改此限制。 下图演示了这三个条件。假设批处理时段从 t = 7 秒开始。在第一种场景中,批处理时段累积 5 条记录后在 t = 47 秒达到 40 秒的最大值。在第二种场景中,批处理大小在批处理时段到期之前达到 10,因此批处理时段会提前结束。在第三种场景中,在批处理时段到期之前达到最大有效负载大小,因此批处理时段会提前结束。 建议您测试不同批处理和记录的大小,这样每个事件源的轮询频率都会根据函数完成任务的速度进行调整。 CreateEventSourceMapping BatchSize 参数控制每次调用可向您的函数发送记录的最大数量。批处理大小如果较大,通常可以更有效地吸收大量记录的调用开销,从而增加吞吐量。 Lambda 在发送下次批处理之前不会等待任何配置的 扩展 完成。换句话说,扩展可能会在 Lambda 处理下一批记录时继续运行。如果您违反了账户的任何 并发 设置或限制,可能会导致节流问题。要检测这是否是潜在问题,请监控函数并检查所显示的 并发指标 是否高于事件源映射的预期。由于调用间隔时间较短,Lambda 可能会短暂报告高于分片数量的并发使用量。即使对于没有扩展名的 Lambda 函数也是如此。 预设情况下,如果函数返回错误,事件源映射会重新处理整个批处理,直到函数成功,或直到批处理中的项目到期。为确保按顺序处理,在错误得到解决之前,事件源映射会暂停处理受影响的分片。对于流源(DynamoDB 和 Kinesis),可以配置 Lambda 在函数返回错误时重试的最大次数。批次未到达您的函数时出现的服务错误或节流,不计入重试次数。您还可以配置事件源映射,以便在丢弃事件批处理时将调用记录发送到 目标 。 预置模式 Lambda 事件源映射使用事件轮询器对您的事件源进行轮询,以获取新消息。默认情况下,Lambda 根据消息量管理这些轮询器的自动扩缩。当消息流量增加时,Lambda 会自动增加用于处理负载的事件轮询器数量,并在流量减少时减少事件轮询器数量。 在预调配模式下,您可以通过定义预调配事件轮询器数量的最小和最大限制来微调事件源映射的吞吐量。然后,Lambda 会以响应式方式在事件轮询器的最小和最大数量之间扩展事件源映射。这些预调配事件轮询器专用于事件源映射,增强了您处理不可预测的事件激增的能力。 在 Lambda 中,事件轮询器是一种能够处理高达 5 Mbps 吞吐量的计算单位。作为参考,假设您的事件源产生的平均有效载荷为 1 MB,并且平均函数持续时间为 1 秒。如果有效载荷未进行任何转换(例如筛选),则单个轮询器可以支持 5 Mbps 的吞吐量和 5 次并发 Lambda 调用。使用预调配模式会产生额外成本。有关定价估算,请参阅 AWS Lambda 定价 。 仅 Amazon MSK 和自行管理 Apache Kafka 事件源支持预调配模式。虽然并发设置允许您控制函数的扩展,但预调配模式允许您控制事件源映射的吞吐量。为了确保最佳性能,您可能需要分别调整这两个设置。有关配置预调配模式的详细信息,请参阅以下各部分: 为 Amazon MSK 事件源映射配置预调配模式 为自行管理 Apache Kafka 事件源映射配置预调配模式 要最大限度地减小在预置模式下使用 Kafka 事件源映射的延迟,请将 MaximumBatchingWindowInSeconds 设置为 0。此设置可确保 Lambda 在完成当前函数调用后立即开始处理下一个批次。有关低延迟处理的更多信息,请参阅 低延迟 Apache Kafka 。 配置预调配模式后,您可以通过监控 ProvisionedPollers 指标来观测事件轮询器对您的工作负载的使用情况。有关更多信息,请参阅 事件源映射指标 。 事件源映射 API 要使用 AWS Command Line Interface(AWS CLI) 或 AWS SDK 来管理事件源,可以使用以下 API 操作: CreateEventSourceMapping ListEventSourceMappings GetEventSourceMapping UpdateEventSourceMapping DeleteEventSourceMapping Javascript 在您的浏览器中被禁用或不可用。 要使用 Amazon Web Services 文档,必须启用 Javascript。请参阅浏览器的帮助页面以了解相关说明。 文档惯例 保留记录 事件源映射标签 此页面对您有帮助吗?- 是 感谢您对我们工作的肯定! 如果不耽误您的时间,请告诉我们做得好的地方,让我们做得更好。 此页面对您有帮助吗?- 否 感谢您告诉我们本页内容还需要完善。很抱歉让您失望了。 如果不耽误您的时间,请告诉我们如何改进文档。 | 2026-01-13T09:30:35 |
https://docs.aws.amazon.com/zh_cn/lambda/latest/dg/access-control-identity-based.html | Lambda 的基于身份的 IAM policy - AWS Lambda Lambda 的基于身份的 IAM policy - AWS Lambda 文档 AWS Lambda 开发人员指南 Lambda 的基于身份的 IAM policy 您可以使用 AWS Identity and Access Management (IAM) 中基于身份的策略授予您账户中的用户访问 Lambda 的权限。基于身份的策略可以应用于用户、用户组或角色。您也可以授予另一个账户中的用户在您的账户中代入角色和访问您的 Lambda 资源的权限。 Lambda 提供AWS托管策略,授予对 Lambda API 操作的访问权限,在某些情况下还可以访问其他AWS服务,用于开发和管理 Lambda 资源。Lambda 根据需要更新这些托管策略,确保您的用户有权在新功能发布时进行访问。 AWSLambda_FullAccess - 授予对 Lambda 操作和其他用于开发和维护 Lambda 资源的 AWS 服务的完全访问权。 AWSLambda_ReadOnlyAccess – 授予对 Lambda 资源的只读访问权限。 AWSLambdaRole – 授予调用 Lambda 函数的权限。 AWS 托管策略授予 API 操作的权限,而不限制用户可以修改的 Lambda 函数或层。要进行更精细的控制,您可以创建自己的策略来限制用户权限的范围。 主题 授予用户对 Lambda 函数的访问权限 授予用户对 Lambda 层的访问权限 Javascript 在您的浏览器中被禁用或不可用。 要使用 Amazon Web Services 文档,必须启用 Javascript。请参阅浏览器的帮助页面以了解相关说明。 文档惯例 访问权限(其他实体访问您的函数的权限) 函数访问 此页面对您有帮助吗?- 是 感谢您对我们工作的肯定! 如果不耽误您的时间,请告诉我们做得好的地方,让我们做得更好。 此页面对您有帮助吗?- 否 感谢您告诉我们本页内容还需要完善。很抱歉让您失望了。 如果不耽误您的时间,请告诉我们如何改进文档。 | 2026-01-13T09:30:35 |
https://docs.aws.amazon.com/zh_cn/lambda/latest/dg/access-control-resource-based.html | 在 Lambda 中查看基于资源的 IAM 策略 - AWS Lambda 在 Lambda 中查看基于资源的 IAM 策略 - AWS Lambda 文档 AWS Lambda 开发人员指南 支持的 API 操作 在 Lambda 中查看基于资源的 IAM 策略 Lambda 支持将基于资源的权限策略用于 Lambda 函数和层。您可以使用基于资源的策略向其他 AWS 账户 、 组织 或 服务 授予访问权限。基于资源的策略应用于单个函数、版本、别名或层版本。 Console 查看函数的基于资源的策略 打开 Lamba 控制台的 函数 页面。 选择函数。 选择 Configuration (配置) ,然后选择 Permissions (权限) 。 向下滚动到 Resource-based policy (基于资源的策略) ,然后选择 View policy document (查看策略文档) 。基于资源的策略显示了在其他账户或 AWS 服务尝试访问该函数时应用的权限。以下示例显示了一个语句,该语句允许 Amazon S3 调用为账户 123456789012 中名为 amzn-s3-demo-bucket 的存储桶调用名为 my-function 的函数。 例 基于资源的策略 { "Version":"2012-10-17", "Id": "default", "Statement": [ { "Sid": "lambda-allow-s3-my-function", "Effect": "Allow", "Principal": { "Service": "s3.amazonaws.com" }, "Action": "lambda:InvokeFunction", "Resource": "arn:aws:lambda:us-east-2:123456789012:function:my-function", "Condition": { "StringEquals": { "AWS:SourceAccount": "123456789012" }, "ArnLike": { "AWS:SourceArn": "arn:aws:s3:::amzn-s3-demo-bucket" } } } ] } AWS CLI 要查看函数的基于资源的策略,请使用 get-policy 命令。 aws lambda get-policy \ --function-name my-function \ --output text 您应看到以下输出: { "Version":"2012-10-17", "Id":"default","Statement":[ { "Sid":"sns","Effect":"Allow","Principal": { "Service":"s3.amazonaws.com"},"Action":"lambda:InvokeFunction","Resource":"arn:aws:lambda:us-east-2:123456789012:function:my-function","Condition": { "ArnLike": { "AWS:SourceArn":"arn:aws:sns:us-east-2:123456789012:lambda*"}}}]} 对于版本和别名,请在函数名后面附加版本号或别名。 aws lambda get-policy --function-name my-function:PROD 要从函数中删除权限,请使用 remove-permission 。 aws lambda remove-permission \ --function-name example \ --statement-id sns 使用 get-layer-version-policy 命令可查看层上的权限。 aws lambda get-layer-version-policy \ --layer-name my-layer \ --version-number 3 \ --output text 您应看到以下输出: b0cd9796-d4eb-4564-939f-de7fe0b42236 { "Sid":"engineering-org","Effect":"Allow","Principal":"*","Action":"lambda:GetLayerVersion","Resource":"arn:aws:lambda:us-west-2:123456789012:layer:my-layer:3","Condition": { "StringEquals": { "aws:PrincipalOrgID":"o-t194hfs8cz"}}}" 使用 remove-layer-version-permission 可从策略中删除语句。 aws lambda remove-layer-version-permission --layer-name my-layer --version-number 3 --statement-id engineering-org 支持的 API 操作 以下 Lambda API 操作支持基于资源的策略: CreateAlias DeleteAlias DeleteFunction DeleteFunctionConcurrency DeleteFunctionEventInvokeConfig DeleteProvisionedConcurrencyConfig GetAlias GetFunction GetFunctionConcurrency GetFunctionConfiguration GetFunctionEventInvokeConfig GetPolicy GetProvisionedConcurrencyConfig 调用 InvokeFunctionUrl (仅权限) ListAliases ListFunctionEventInvokeConfigs ListProvisionedConcurrencyConfigs ListTags ListVersionsByFunction PublishVersion PutFunctionConcurrency PutFunctionEventInvokeConfig PutProvisionedConcurrencyConfig TagResource UntagResource UpdateAlias UpdateFunctionCode UpdateFunctionEventInvokeConfig Javascript 在您的浏览器中被禁用或不可用。 要使用 Amazon Web Services 文档,必须启用 Javascript。请参阅浏览器的帮助页面以了解相关说明。 文档惯例 层访问 AWS 服务 的函数访问权限 此页面对您有帮助吗?- 是 感谢您对我们工作的肯定! 如果不耽误您的时间,请告诉我们做得好的地方,让我们做得更好。 此页面对您有帮助吗?- 否 感谢您告诉我们本页内容还需要完善。很抱歉让您失望了。 如果不耽误您的时间,请告诉我们如何改进文档。 | 2026-01-13T09:30:35 |
https://phproundtable.com/show/hourly-vs-value-based-pricing | PHPRoundtable PHPRoundtable The PHP podcast where everyone has a seat. Guests Library Sponsors About Us 56: Hourly vs Value-Based Pricing Panelists: Keith Casey Jr Tim Lytle Mike McDerment November 7 2016 There are two seemingly contradicting philosophies about how to charge clients for programming work. The hourly camp suggests that the client is paying for your skill and hiring you for your time. The value-based pricing camp suggests that the programmer Time-based pricing Resolution could be hourly or daily Allows flexibility: bill your client for the hours you work Requires you to keep track of your time Was that 10 hours of actual development, or 10 hours of replying to emails? As you About Us Sponsors © 2026 PHPRoundtable Proud member of the php[architect] family | 2026-01-13T09:30:35 |
https://docs.aws.amazon.com/zh_cn/lambda/latest/dg/provisioned-concurrency.html | 为函数配置预置并发 - AWS Lambda 为函数配置预置并发 - AWS Lambda 文档 AWS Lambda 开发人员指南 配置预配置并发 准确估计函数所需的预置并发 使用预置并发时优化函数代码 使用环境变量查看和控制预置并发行为 了解使用预置并发的日志记录和计费行为 使用 Application Auto Scaling 自动执行预置并发管理 为函数配置预置并发 在 Lambda 中, 并发 指您的函数当前正在进行的请求数。有两种类型的并发控件可用: 预留并发 – 这将设置分配给您的函数的最大和最小并发实例数。当一个函数有预留并发时,任何其他函数都不可以使用该并发。对于确保最关键的函数始终具有足够的并发性来处理传入请求,预留并发非常有用。此外,预留并发可用于限制并发,以防止下游资源(如数据库连接)不堪重负。预留并发既充当下限,也充当上限,它专门为您的函数预留指定的容量,同时也防止其超出该限制扩展。为函数配置预留并发不产生任何额外费用。 预置并发 – 指分配给函数的预初始化执行环境的数量。这些执行环境已准备就绪,可以立即响应传入的函数请求。预置并发有助于减少函数的冷启动延迟,旨在使函数具有两位数毫秒的响应时间。通常,交互式工作负载从该功能中获益最大。这些是用户发起请求的应用程序(例如 Web 和移动应用程序),并且对延迟最敏感。异步工作负载(例如数据处理管线)经常对延迟不太敏感,因此通常不需要预置并发。配置预置并发会让您的 AWS 账户 产生额外费用。 本主题详细介绍了如何管理和配置预置并发。有关这两种并发控制的概念概述,请参阅 预留并发和预置并发 。有关配置预留并发的更多信息,请参阅 为函数配置预留并发 。 注意 关联到 Amazon MQ 事件源映射的 Lambda 函数具有默认的最大并发数。对于 Apache Active MQ,最大并发实例数为 5。对于 Rabbit MQ,最大并发实例数为 1。为函数设置预留或预调配的并发不会更改这些限制。要在使用 Amazon MQ 时请求增加默认的最大并发数,请联系 支持。 Sections 配置预配置并发 准确估计函数所需的预置并发 使用预置并发时优化函数代码 使用环境变量查看和控制预置并发行为 了解使用预置并发的日志记录和计费行为 使用 Application Auto Scaling 自动执行预置并发管理 配置预配置并发 您可以使用 Lambda 控制台或 Lambda API 为函数配置预置并发设置。 要为函数分配预置并发(控制台) 打开 Lamba 控制台的 函数页面 。 选择要为其分配预置并发的函数。 选择 Configuration (配置),然后选择 Concurrency (并发)。 在 Provisioned concurrency configurations(预配置并发配置) 下,选择 Add configuration(添加配置) 。 选择限定符类型以及别名或版本。 注意 您不能将预置并发与任何函数的 $LATEST 版本一起使用。 如果函数具有事件源,请确保该事件源指向正确的函数别名或版本。否则,您的函数将不会使用预置并发环境。 在 预置并发 下输入一个数字。 选择 保存 。 您最多可以在账户中配置的单位数量为 非预留账户并发 减去 100。剩余 100 个单位的并发可用于不会使用预留并发的函数。例如,如果您的账户的并发限制为 1000,并且您没有为任何其他函数分配任何预留或预置并发,则可以为单个函数配置最多 900 个单位的预置并发。 为函数配置预置并发会影响可用于其他函数的并发池。例如,如果您为 function-a 配置 100 个单位的预置并发,则您账户中的其他函数必须共享剩余的 900 个单位的并发。即使 function-a 不使用所有 100 个单位的预置并发也是如此。 可以为同一函数同时分配预留并发和预置并发。在这种情况下,预置并发数不能超过预留并发数。 此限制也适用于函数版本。您可以分配给特定函数版本的最大预置并发数等于该函数的预留并发减去其他函数版本上配置的预置并发。 要使用 Lambda API 配置预置并发,请使用以下 API 操作: PutProvisionedConcurrencyConfig GetProvisionedConcurrencyConfig ListProvisionedConcurrencyConfigs DeleteProvisionedConcurrencyConfig 例如,要使用 AWS Command Line Interface(CLI)配置预置并发,请使用 put-provisioned-concurrency-config 命令。以下命令将为名为 my-function 的 BLUE 别名分配 100 个单位的预置并发: aws lambda put-provisioned-concurrency-config --function-name my-function \ --qualifier BLUE \ --provisioned-concurrent-executions 100 您应该会看到类似如下输出: { "Requested ProvisionedConcurrentExecutions": 100, "Allocated ProvisionedConcurrentExecutions": 0, "Status": "IN_PROGRESS", "LastModified": "2023-01-21T11:30:00+0000" } 准确估计函数所需的预置并发 您可以使用 CloudWatch 指标 查看任何活动函数的并发指标。具体而言, ConcurrentExecutions 指标显示了您账户中函数的并发调用数。 前面的图表显示,在给定的任何时间,此函数平均处理 5 到 10 个并发请求,峰值为 20 个请求。假设您的账户中还有许多其他函数。 如果此函数对您的应用程序至关重要,并且您的每次调用都需要低延迟响应 ,请配置至少 20 个单位的预置并发。 请注意,您也可以使用以下公式 计算并发数 : Concurrency = (average requests per second) * (average request duration in seconds) 要估计您需要的并发数,请将每秒的平均请求数与平均请求持续时间(以秒为单位)相乘。您可以使用 Invocation 指标估算每秒的平均请求数,并使用 Duration 指标估计平均请求持续时间(以秒为单位)。 对于配置预置并发,Lambda 建议在函数通常需要的并发的基础上添加 10% 的浮动。例如,如果函数通常在出现 200 个并发请求时达到峰值,请将预置并发设置为 220(200 个并发请求 + 10% = 220 个预置并发)。 使用预置并发时优化函数代码 如果您使用预置并发,则请考虑重构函数代码以优化实现低延迟。对于使用预置并发的函数,Lambda 会在分配期间运行任何初始化代码(例如加载库和实例化客户端)。因此,建议将尽可能多的初始化放在主函数处理程序之外,以避免影响实际函数调用期间的延迟。相比之下,如果您在主处理程序代码中初始化库或实例化客户端,则意味着您的函数必须在每次调用时运行该代码(无论您是否使用预置并发,都会发生这种情况)。 对于按需调用,每次函数出现冷启动时,Lambda 可能需要重新运行您的初始化代码。对于此类函数,您可以选择将特定功能的初始化推迟到函数需要该功能的时候。例如,请为 Lambda 处理程序考虑以下控制流: def handler(event, context): ... if ( some_condition ): // Initialize CLIENT_A to perform a task else: // Do nothing 在前面的示例中,开发人员没有在主处理程序之外初始化 CLIENT_A ,而是在 if 语句中对其进行初始化。这样一来,Lambda 只有在 some_condition 得到满足时才会运行此代码。如果您在主处理程序之外初始化 CLIENT_A ,Lambda 会在每次冷启动时运行该代码。这可能会增加总体延迟。 您可以通过向函数添加 X-Ray 监控,来测量随着 Lambda 纵向扩展的冷启动。使用预置并发的函数不会表现出冷启动行为,因为执行环境是在调用之前准备好的。但是,预置并发必须应用于函数的 特定版本或别名 ,而不是 $LATEST 版本。如果继续看到冷启动行为,则请确保您调用的是配置了预置并发的别名版本。 使用环境变量查看和控制预置并发行为 函数可能会用尽其所有预置并发。Lambda 使用按需实例来处理任何过多流量。为了确定 Lambda 将哪种类型的初始化用于特定环境,请检查 AWS_LAMBDA_INITIALIZATION_TYPE 环境变量的值。此变量可能有两个值: provisioned-concurrency 和 on-demand 。 AWS_LAMBDA_INITIALIZATION_TYPE 的值是不可变的,并且在环境的整个生命周期中保持不变。要查看函数代码中环境变量的值,请参阅 检索 Lambda 环境变量 。 如果使用的是 .NET 8 运行时系统,则可以配置 AWS_LAMBDA_DOTNET_PREJIT 环境变量以改善函数的延迟,即使函数不使用预置并发。.NET 运行时系统会延时编译和初始化代码首次调用的每个库。因此,首次调用 Lambda 函数的时间可能比后续调用的时间更长。要缓解此问题,可以为 AWS_LAMBDA_DOTNET_PREJIT 从以下三个值中任选一个: ProvisionedConcurrency :Lambda 会使用预置并发为所有环境执行提前 JIT 编译。这是默认值。 Always :Lambda 会为每个环境执行提前 JIT 编译,即使函数不使用预置并发也是如此。 Never :Lambda 会为所有环境禁用提前 JIT 编译。 了解使用预置并发的日志记录和计费行为 对于预置并发环境,函数的初始化代码在分配期间定期运行一次,因为 Lambda 会回收环境实例。即使环境实例从未处理过请求,Lambda 也会对初始化进行计费。预配置并发连续运行,并且与初始化和调用成本分开计费。有关更多详细信息,请参阅 AWS Lambda 定价 。 当您配置具有预置并发的 Lambda 函数时,Lambda 会预先初始化该执行环境,使其在调用请求之前可用。每次初始化环境时,Lambda 都会以 JSON 日志记录格式将函数的 初始化持续时间字段 记录在 platform-initReport 日志事件中。要查看此日志事件,请将您的 JSON 日志级别 至少配置为 INFO 。您还可以使用 遥测 API 来使用报告“初始化持续时间”字段的平台事件。 使用 Application Auto Scaling 自动执行预置并发管理 您可以使用 Application Auto Scaling 根据计划或基于利用率管理预置并发。如果函数的流量模式是可预测的,请使用计划扩展。如果您希望函数保持特定利用率,请使用目标跟踪扩展策略。 注意 如果您使用 Application Auto Scaling 来管理函数的预调配并发,请确保先 配置初始预调配并发值 。如果您的函数没有初始预调配并发值,则 Application Auto Scaling 可能无法正确处理函数扩展。 计划扩展 借助 Application Auto Scaling,您可以按照可预测的负载变化来设置自己的扩展计划。有关更多信息和示例,请参阅《Application Auto Scaling 用户指南》中的 Application Auto Scaling 的计划扩展 ,以及在 AWS 计算博客上的 为经常出现的峰值使用情况计划 AWS Lambda 预置并发 。 目标跟踪 借助目标跟踪,Application Auto Scaling 可根据您定义扩展策略的方式创建和管理一组 CloudWatch 警报。当这些警报激活时,Application Auto Scaling 会使用预置并发自动调整分配的环境数量。针对流量模式不可预测的应用程序,使用目标跟踪。 要使用目标跟踪扩展预置并发,请使用 RegisterScalableTarget 和 PutScalingPolicy Application Auto Scaling API 操作。例如,如果您使用的是 AWS Command Line Interface(CLI),请按照以下步骤操作: 将函数的别名注册为扩展目标。以下示例注册名为 my-function 的函数的 BLUE 别名: aws application-autoscaling register-scalable-target --service-namespace lambda \ --resource-id function:my-function:BLUE --min-capacity 1 --max-capacity 100 \ --scalable-dimension lambda:function:ProvisionedConcurrency 将扩展策略应用于目标。以下示例配置 Application Auto Scaling,用于调节别名的预置并发配置,让利用率接近 70%,但也可以应用 10% 到 90% 之间的任意值。 aws application-autoscaling put-scaling-policy \ --service-namespace lambda \ --scalable-dimension lambda:function:ProvisionedConcurrency \ --resource-id function:my-function:BLUE \ --policy-name my-policy \ --policy-type TargetTrackingScaling \ --target-tracking-scaling-policy-configuration ' { "TargetValue": 0.7, "PredefinedMetricSpecification": { "PredefinedMetricType": "LambdaProvisionedConcurrencyUtilization" }}' 应看到类似如下内容的输出: { "PolicyARN": "arn:aws:autoscaling:us-east-2:123456789012:scalingPolicy:12266dbb-1524-xmpl-a64e-9a0a34b996fa:resource/lambda/function:my-function:BLUE:policyName/my-policy", "Alarms": [ { "AlarmName": "TargetTracking-function:my-function:BLUE-AlarmHigh-aed0e274-xmpl-40fe-8cba-2e78f000c0a7", "AlarmARN": "arn:aws:cloudwatch:us-east-2:123456789012:alarm:TargetTracking-function:my-function:BLUE-AlarmHigh-aed0e274-xmpl-40fe-8cba-2e78f000c0a7" }, { "AlarmName": "TargetTracking-function:my-function:BLUE-AlarmLow-7e1a928e-xmpl-4d2b-8c01-782321bc6f66", "AlarmARN": "arn:aws:cloudwatch:us-east-2:123456789012:alarm:TargetTracking-function:my-function:BLUE-AlarmLow-7e1a928e-xmpl-4d2b-8c01-782321bc6f66" } ] } Application Auto Scaling 会在 CloudWatch 中创建两个警报。当预置并发的利用率持续超过 70% 时,第一个警报会触发。发生这种情况时,Application Auto Scaling 会分配更多的预配置并发以降低利用率。当利用率持续低于 63%(70% 目标的 90%)时,第二个警报会触发。发生这种情况时,Application Auto Scaling 会减少别名的预配置并发。 注意 如果您的函数处于活跃状态并且正在接收请求,则 Lambda 会发出 ProvisionedConcurrencyUtilization 指标。在不活动期间,不会发出任何指标,并且您的自动扩缩警报将进入 INSUFFICIENT_DATA 状态。因此,Application Auto Scaling 将无法调整函数的预置并发。这可能会导致意外计费。 在以下示例中,函数会根据利用率在最小和最大预置并发量之间进行扩缩。 图例 函数实例 打开请求 预配置并发 标准并发 打开的请求数量增加时,Application Auto Scaling 会大幅度增加预置并发,直到达到配置的最大值。达到最大值后,如果账户尚未达到账户并发数限制,则函数可能会在标准的非预留并发上继续扩展。利用率下降并保持较低时,Application Auto Scaling 会以较短周期逐步减少预置并发。 默认情况下,Application Auto Scaling 的两个警报都使用平均统计数据。具有快速突发流量的函数可能不会触发这些警报。例如,假设 Lambda 函数执行速度很快(如 20-100 毫秒),并且您的流量出现快速突发。在这种情况下,请求数超过了在突发期间分配的预置并发数。但是,突发负载需要维持至少 3 分钟,Application Auto Scaling 才能预置更多环境。此外,两个 CloudWatch 警报都需要获得 3 个达到目标平均水平的数据点,然后才能激活自动扩缩策略。 如果函数遭遇快速的流量爆发,使用 Maximum 统计数据而非 Average 统计数据可以更有效地扩展预置并发数,从而最大限度地减少冷启动。 有关目标跟踪扩展策略的更多信息,请参阅 适用于 Application Auto Scaling 的目标跟踪扩展策略 。 Javascript 在您的浏览器中被禁用或不可用。 要使用 Amazon Web Services 文档,必须启用 Javascript。请参阅浏览器的帮助页面以了解相关说明。 文档惯例 配置预留并发 扩展行为 此页面对您有帮助吗?- 是 感谢您对我们工作的肯定! 如果不耽误您的时间,请告诉我们做得好的地方,让我们做得更好。 此页面对您有帮助吗?- 否 感谢您告诉我们本页内容还需要完善。很抱歉让您失望了。 如果不耽误您的时间,请告诉我们如何改进文档。 | 2026-01-13T09:30:35 |
https://docs.aws.amazon.com/zh_cn/lambda/latest/dg/configuration-versions.html#versioning-permissions | 管理 Lambda 函数版本 - AWS Lambda 管理 Lambda 函数版本 - AWS Lambda 文档 AWS Lambda 开发人员指南 创建函数版本 使用版本 授予权限 管理 Lambda 函数版本 您可以使用版本来管理函数的部署。例如,您可以发布函数的新版本用于测试版测试,而不会影响稳定的生产版本的用户。您每次发布函数时,Lambda 都会为函数创建一个新版本。新版本是函数的未发布版本的副本。未发布版本的名为 $LATEST 。 重要的是,每当您部署函数代码时,都会覆盖 $LATEST 中的当前代码。要保存 $LATEST 的当前迭代,请创建一个新的函数版本。如果 $LATEST 与之前发布的版本相同,则在将更改部署到 $LATEST 之前,您无法创建新版本。这些更改可能会包括更新代码或修改函数配置设置。 发布函数版本后,其代码、运行时、架构、内存、层和大多数其他配置设置都不可变。这意味着,如果不从 $LATEST 发布新版本,则无法更改这些设置。您可以为已发布函数版本配置以下项目: 触发 目标 预配置并发 异步调用 数据库连接和代理 注意 在 自动 模式下使用 运行时管理控件 时,此函数版本使用的运行时版本会自动更新。使用 Function update (函数更新)或 Manual (手动)模式时,不会更新运行时版本。有关更多信息,请参阅 了解 Lambda 如何管理运行时版本更新 。 Sections 创建函数版本 使用版本 授予权限 创建函数版本 只能在函数的未发布版本上更改函数代码和设置。在您发布版本时,Lambda 会锁定代码和大多数设置,以便为该版本的用户维持一致的体验。 您可以使用 Lambda 控制台创建函数版本。 创建新函数版本 打开 Lamba 控制台的 函数页面 。 选择一个函数,然后选择 版本 选项卡。 在版本配置页面上,选择 Publish new version(发布新版本) 。 (可选)输入版本说明。 选择 发布 。 或者,您可以使用 PublishVersion API 操作发布函数版本。 以下 AWS CLI 命令发布函数的新版本。响应返回有关新版本的配置信息,包括版本号和具有版本后缀的函数 ARN。 aws lambda publish-version --function-name my-function 您应看到以下输出: { "FunctionName": "my-function", "FunctionArn": "arn:aws:lambda:us-east-2:123456789012:function:my-function:1", "Version": "1", "Role": "arn:aws:iam::123456789012:role/lambda-role", "Handler": "function.handler", "Runtime": "nodejs22.x", ... } 注意 Lambda 会分配单调递增的序列号,以便进行版本控制。Lambda 不会重复使用版本号,即使是删除并重新创建函数之后也是如此。 使用版本 您可以使用限定的 ARN 或非限定的 ARN 来引用您的 Lambda 函数。 限定的 ARN – 具有版本后缀的函数 ARN。以下示例引用 helloworld 函数的版本 42。 arn:aws:lambda:aws-region:acct-id:function:helloworld:42 非限定的 ARN – 不具有版本后缀的函数 ARN。 arn:aws:lambda:aws-region:acct-id:function:helloworld 您可以在所有相关 API 操作中使用限定或非非限定的 ARN。但是,不能使用非限定 ARN 来创建别名。 如果您决定不发布函数版本,可以使用 事件源映射 中的限定或非限定 ARN 来调用函数。当您使用非限定 ARN 调用函数时,Lambda 会隐式调用 $LATEST 。 每个 Lambda 函数版本的限定 ARN 都是唯一的。发布版本后,您无法更改 ARN 或函数代码。 Lambda 仅在代码从未发布过或自上次发布版本后已发生更改时,才会发布新函数版本。如果没有任何更改,函数版本将保持为上次发布的版本。 当您发布版本时,Lambda 会创建函数代码和配置的不可变快照。并非所有配置更改都会触发新版本的发布。以下配置更改使函数有资格发布版本: 函数代码 环境变量 运行时 处理程序 图层 内存大小 超时 VPC 配置 死信队列 (DLQ) 配置 IAM 角色 描述 架构(x86_64 或 arm64) 临时存储大小 包类型 日志记录配置 文件系统配置 SnapStart 跟踪配置 预留并发 等操作设置在更改时不会触发新版本的发布。 授予权限 您可以使用基于 资源的策略 或 基于身份的策略 授予对函数的访问权限。权限的范围取决于您要将策略应用于整个函数还是函数的某个版本。有关策略中的函数资源名称的更多信息,请参阅 微调策略的“资源和条件”部分 。 您可以使用函数别名,简化事件源和 AWS Identity and Access Management (IAM) 策略的管理。有关更多信息,请参阅 为 Lambda 函数创建别名 。 Javascript 在您的浏览器中被禁用或不可用。 要使用 Amazon Web Services 文档,必须启用 Javascript。请参阅浏览器的帮助页面以了解相关说明。 文档惯例 加权别名 标签 此页面对您有帮助吗?- 是 感谢您对我们工作的肯定! 如果不耽误您的时间,请告诉我们做得好的地方,让我们做得更好。 此页面对您有帮助吗?- 否 感谢您告诉我们本页内容还需要完善。很抱歉让您失望了。 如果不耽误您的时间,请告诉我们如何改进文档。 | 2026-01-13T09:30:35 |
https://docs.aws.amazon.com/zh_cn/lambda/latest/dg/configuration-aliases.html | 为 Lambda 函数创建别名 - AWS Lambda 为 Lambda 函数创建别名 - AWS Lambda 文档 AWS Lambda 开发人员指南 为 Lambda 函数创建别名 您可以为 Lambda 函数创建别名。Lambda 别名是您可以更新的指向函数版本的指针。函数的用户可以使用别名 Amazon 资源名称(ARN)访问函数版本。部署新版本时,您可以更新别名以使用新版本,或者在两个版本之间拆分流量。 Console 使用控制台创建别名 打开 Lamba 控制台的 Functions (函数)页面。 选择函数。 选择 Aliases (别名),然后选择 Create alias (创建别名)。 在 创建别名 页面上,执行以下操作: 输入别名的 名称 。 (可选)输入别名的 描述 。 对于 版本 ,选择希望别名指向的函数版本。 (可选)要在别名上配置路由,请展开 加权别名 。有关更多信息,请参阅 使用加权别名实施 Lambda 金丝雀部署 。 选择 保存 。 AWS CLI 要使用 AWS Command Line Interface(AWS CLI)创建别名,请使用 create-alias 命令。 aws lambda create-alias \ --function-name my-function \ --name alias-name \ --function-version version-number \ --description " " 要更改别名以便指向函数的新版本,请使用 update-alias 命令。 aws lambda update-alias \ --function-name my-function \ --name alias-name \ --function-version version-number 要删除别名,请使用 delete-alias 命令。 aws lambda delete-alias \ --function-name my-function \ --name alias-name 以上步骤中的 AWS CLI 命令对应于以下 Lambda API 操作: CreateAlias UpdateAlias DeleteAlias Javascript 在您的浏览器中被禁用或不可用。 要使用 Amazon Web Services 文档,必须启用 Javascript。请参阅浏览器的帮助页面以了解相关说明。 文档惯例 文件系统 使用别名 此页面对您有帮助吗?- 是 感谢您对我们工作的肯定! 如果不耽误您的时间,请告诉我们做得好的地方,让我们做得更好。 此页面对您有帮助吗?- 否 感谢您告诉我们本页内容还需要完善。很抱歉让您失望了。 如果不耽误您的时间,请告诉我们如何改进文档。 | 2026-01-13T09:30:35 |
https://docs.aws.amazon.com/zh_cn/lambda/latest/dg/configuration-versions.html#configuration-versions-config | 管理 Lambda 函数版本 - AWS Lambda 管理 Lambda 函数版本 - AWS Lambda 文档 AWS Lambda 开发人员指南 创建函数版本 使用版本 授予权限 管理 Lambda 函数版本 您可以使用版本来管理函数的部署。例如,您可以发布函数的新版本用于测试版测试,而不会影响稳定的生产版本的用户。您每次发布函数时,Lambda 都会为函数创建一个新版本。新版本是函数的未发布版本的副本。未发布版本的名为 $LATEST 。 重要的是,每当您部署函数代码时,都会覆盖 $LATEST 中的当前代码。要保存 $LATEST 的当前迭代,请创建一个新的函数版本。如果 $LATEST 与之前发布的版本相同,则在将更改部署到 $LATEST 之前,您无法创建新版本。这些更改可能会包括更新代码或修改函数配置设置。 发布函数版本后,其代码、运行时、架构、内存、层和大多数其他配置设置都不可变。这意味着,如果不从 $LATEST 发布新版本,则无法更改这些设置。您可以为已发布函数版本配置以下项目: 触发 目标 预配置并发 异步调用 数据库连接和代理 注意 在 自动 模式下使用 运行时管理控件 时,此函数版本使用的运行时版本会自动更新。使用 Function update (函数更新)或 Manual (手动)模式时,不会更新运行时版本。有关更多信息,请参阅 了解 Lambda 如何管理运行时版本更新 。 Sections 创建函数版本 使用版本 授予权限 创建函数版本 只能在函数的未发布版本上更改函数代码和设置。在您发布版本时,Lambda 会锁定代码和大多数设置,以便为该版本的用户维持一致的体验。 您可以使用 Lambda 控制台创建函数版本。 创建新函数版本 打开 Lamba 控制台的 函数页面 。 选择一个函数,然后选择 版本 选项卡。 在版本配置页面上,选择 Publish new version(发布新版本) 。 (可选)输入版本说明。 选择 发布 。 或者,您可以使用 PublishVersion API 操作发布函数版本。 以下 AWS CLI 命令发布函数的新版本。响应返回有关新版本的配置信息,包括版本号和具有版本后缀的函数 ARN。 aws lambda publish-version --function-name my-function 您应看到以下输出: { "FunctionName": "my-function", "FunctionArn": "arn:aws:lambda:us-east-2:123456789012:function:my-function:1", "Version": "1", "Role": "arn:aws:iam::123456789012:role/lambda-role", "Handler": "function.handler", "Runtime": "nodejs22.x", ... } 注意 Lambda 会分配单调递增的序列号,以便进行版本控制。Lambda 不会重复使用版本号,即使是删除并重新创建函数之后也是如此。 使用版本 您可以使用限定的 ARN 或非限定的 ARN 来引用您的 Lambda 函数。 限定的 ARN – 具有版本后缀的函数 ARN。以下示例引用 helloworld 函数的版本 42。 arn:aws:lambda:aws-region:acct-id:function:helloworld:42 非限定的 ARN – 不具有版本后缀的函数 ARN。 arn:aws:lambda:aws-region:acct-id:function:helloworld 您可以在所有相关 API 操作中使用限定或非非限定的 ARN。但是,不能使用非限定 ARN 来创建别名。 如果您决定不发布函数版本,可以使用 事件源映射 中的限定或非限定 ARN 来调用函数。当您使用非限定 ARN 调用函数时,Lambda 会隐式调用 $LATEST 。 每个 Lambda 函数版本的限定 ARN 都是唯一的。发布版本后,您无法更改 ARN 或函数代码。 Lambda 仅在代码从未发布过或自上次发布版本后已发生更改时,才会发布新函数版本。如果没有任何更改,函数版本将保持为上次发布的版本。 当您发布版本时,Lambda 会创建函数代码和配置的不可变快照。并非所有配置更改都会触发新版本的发布。以下配置更改使函数有资格发布版本: 函数代码 环境变量 运行时 处理程序 图层 内存大小 超时 VPC 配置 死信队列 (DLQ) 配置 IAM 角色 描述 架构(x86_64 或 arm64) 临时存储大小 包类型 日志记录配置 文件系统配置 SnapStart 跟踪配置 预留并发 等操作设置在更改时不会触发新版本的发布。 授予权限 您可以使用基于 资源的策略 或 基于身份的策略 授予对函数的访问权限。权限的范围取决于您要将策略应用于整个函数还是函数的某个版本。有关策略中的函数资源名称的更多信息,请参阅 微调策略的“资源和条件”部分 。 您可以使用函数别名,简化事件源和 AWS Identity and Access Management (IAM) 策略的管理。有关更多信息,请参阅 为 Lambda 函数创建别名 。 Javascript 在您的浏览器中被禁用或不可用。 要使用 Amazon Web Services 文档,必须启用 Javascript。请参阅浏览器的帮助页面以了解相关说明。 文档惯例 加权别名 标签 此页面对您有帮助吗?- 是 感谢您对我们工作的肯定! 如果不耽误您的时间,请告诉我们做得好的地方,让我们做得更好。 此页面对您有帮助吗?- 否 感谢您告诉我们本页内容还需要完善。很抱歉让您失望了。 如果不耽误您的时间,请告诉我们如何改进文档。 | 2026-01-13T09:30:35 |
https://docs.aws.amazon.com/zh_cn/lambda/latest/dg/invocation-async-retain-records.html#create-destination | 获取 Lambda 异步调用记录 - AWS Lambda 获取 Lambda 异步调用记录 - AWS Lambda 文档 AWS Lambda 开发人员指南 目标 死信队列 获取 Lambda 异步调用记录 Lambda 可以将异步调用记录发送给以下某个 AWS 服务。 Amazon SQS – 标准 SQS 队列 Amazon SNS – 标准 SNS 主题 Amazon S3 – Amazon S3 存储桶(仅限失败时) AWS Lambda – Lambda 函数 Amazon EventBridge – EventBridge 事件总线 调用记录包含有关 JSON 格式的请求和响应的详细信息。您可为成功处理的事件以及处理尝试失败的事件配置单独的目标。或者,您可以将标准 Amazon SQS 队列或标准 Amazon SNS 主题配置为丢弃事件的死信队列。对于死信队列,Lambda 只发送事件的内容,不包含有关响应的详细信息。 如果 Lambda 无法向您配置的目的地发送记录,它会向 Amazon CloudWatch 发送 DestinationDeliveryFailures 指标。如果您的配置包含不支持的目标类型,例如 Amazon SQS FIFO 队列或 Amazon SNS FIFO 主题,则可能会发生这种情况。权限误配和大小限制可能会导致发生传输错误。有关 Lambda 调用指标的更多信息,请参阅 调用指标 。 注意 要防止触发函数,可以将函数的预留并发设置为零。当您将异步调用函数的预留并发设置为零时,Lambda 会开始将新事件发送到已配置的 死信队列 或失败时的 事件目标 ,且不会做出任何重试。要处理在预留并发设置为零时发送的事件,您必须使用死信队列或失败时事件目标中的事件。 添加目标 要保留异步调用的记录,请向函数添加目标。您可以选择将成功或失败的调用发送到目标。每个函数可以有多个目标,因此您可以为成功和失败的事件配置不同的目标。发送到目标的每条记录都是一个 JSON 文档,其中包含有关调用的详细信息。与错误处理设置一样,您可以在函数版本或别名上配置目标。 提示 您还可以保留以下事件源映射类型的失败调用记录: Amazon Kinesis 、 Amazon DynamoDB 、 Kafka(Amazon MSK 和自托管式 Apache Kafka) 。 下表列出了 Lambda 支持的异步调用记录目标。要让 Lambda 成功将记录发送到您选择的目标,请确保函数的 执行角色 也包含相关权限。该表还描述了每种目标类型如何接收 JSON 调用记录。 目标类型 所需的权限 特定于目标的 JSON 格式 Amazon SQS 队列 sqs:SendMessage Lambda 将调用记录作为 Message 传递到目标。 Amazon SNS 主题 sns:Publish Lambda 将调用记录作为 Message 传递到目标。 Amazon S3 存储桶(仅限失败时) s3:PutObject s3:ListBucket Lambda 将调用记录作为 JSON 对象存储于目标存储桶中。 S3 对象名称使用以下命名约定: aws/lambda/async/<function-name>/YYYY/MM/DD/YYYY-MM-DDTHH.MM.SS-<Random UUID> Lambda 函数 lambda:InvokeFunction Lambda 将调用记录作为有效负载传递给函数。 EventBridge events:PutEvents Lambda 将调用记录作为 detail 在 PutEvents 调用中传递。 source 事件字段的值为 aws.lambda 。 detail-type 事件字段的值为“Lambda Function Invocation Result – Success”(Lambda 函数调用结果 – 成功)或“Lambda Function Invocation Result – Failure”(Lambda 函数调用结果 – 失败)。 resource 事件字段包含函数和目标的 Amazon 资源名称(ARN)。 对于其他事件字段,请参阅 Amazon EventBridge 事件 。 注意 对于 Amazon S3 目标,如果您已使用 KMS 密钥对存储桶启用加密,则您的函数还需要 kms:GenerateDataKey 权限。 重要 使用 Amazon SNS 作为目的地时,请注意,Amazon SNS 的最大消息大小限为 256 KB。如果异步调用有效载荷接近 1 MB,则调用记录(包括原始有效载荷加上其他元数据)可能会超过 Amazon SNS 限制并导致传输失败。对于较大的有效载荷,可考虑使用 Amazon SQS 或 Amazon S3 目的地。 以下步骤介绍如何使用 Lambda 控制台和 AWS CLI 配置函数的目标。 Console 打开 Lamba 控制台的 函数 页面。 选择函数。 在 Function overview (函数概览) 下,选择 Add destination (添加目标) 。 对于 Source (源) ,选择 Asynchronous invocation (异步调用) 。 对于 Condition (条件) ,请从以下选项中选择: On failure (失败时)– 当事件的所有处理尝试均失败或超过最长期限时发送记录。 On success (成功时)– 函数成功处理异步调用时发送记录。 对于 Destination type (目标类型) ,请选择接收调用记录的资源类型。 对于 Destination (目标) ,请选择一个资源。 选择 保存 。 AWS CLI 要使用 AWS CLI 配置目标,请运行 update-function-event-invoke-config 命令。以下示例配置 Lambda,以便在无法处理事件时将记录发送到名为 destination 的标准 SQS 队列。 aws lambda update-function-event-invoke-config \ --function-name my-function \ --destination-config ' { "OnFailure": { "Destination": " arn:aws:sqs:us-east-1:123456789012: destination "}}' Amazon S3 目标的安全最佳实践 如果删除配置为目标的 S3 存储桶而不将目标从函数配置中删除,则可能会造成安全风险。如果其他用户知道您的目标存储桶的名称,则他们可以在其 AWS 账户中重新创建存储桶。调用失败的记录将发送到存储桶,这可能会暴露您函数中的数据。 警告 为确保您的函数中的调用记录不会发送到另一个 AWS 账户中的 S3 存储桶,请向函数的执行角色添加条件,以将 s3:PutObject 权限限制为您账户中的存储桶。 以下示例显示了一个 IAM 策略,该策略将您函数的 s3:PutObject 权限限制为您账户中的存储桶。该策略还为 Lambda 提供了使用 S3 存储桶作为目标所需的 s3:ListBucket 权限。 { "Version": "2012-10-17", "Statement": [ { "Sid": "S3BucketResourceAccountWrite", "Effect": "Allow", "Action": [ "s3:PutObject", "s3:ListBucket" ], "Resource": [ "arn:aws:s3:::*/*", "arn:aws:s3:::*" ], "Condition": { "StringEquals": { "s3:ResourceAccount": "111122223333" } } } ] } 要使用 AWS 管理控制台 或 AWS CLI 向函数的执行角色添加权限策略,请参阅以下程序中的说明: Console 向函数的执行角色添加权限策略(控制台) 打开 Lamba 控制台的 函数 页面。 选择想要修改其执行角色的 Lambda 函数。 在 配置 选项卡中,选择 权限 。 在 执行角色 选项卡中,选择您的函数的 角色名称 ,以打开该角色的 IAM 控制台页面。 通过执行以下操作,向角色添加权限策略: 在 权限策略 窗格中,选择 添加权限 ,然后选择 创建内联策略 。 在 策略编辑器 中,选择 JSON 。 将要添加的策略粘贴到编辑器中(替换现有 JSON),然后选择 下一步 。 在 策略详细信息 下,输入 策略名称 。 选择 创建策略 。 AWS CLI 向函数的执行角色添加权限策略(CLI) 创建具有所需权限的 JSON 策略文档并将其保存在本地目录中。 使用 IAM put-role-policy CLI 命令向您函数的执行角色添加权限。在您保存 JSON 策略文档的目录中运行以下命令,并用您自己的值替换角色名称、策略名称和策略文档。 aws iam put-role-policy \ --role-name my_lambda_role \ --policy-name LambdaS3DestinationPolicy \ --policy-document file:// my_policy.json 调用记录的示例 当调用与条件匹配时,Lambda 会向目标发送包含调用详细信息的 JSON 文档 。以下示例显示了由于函数错误而导致三次处理尝试失败的事件的调用记录。 { "version": "1.0", "timestamp": "2019-11-14T18:16:05.568Z", "requestContext": { "requestId": "e4b46cbf-b738-xmpl-8880-a18cdf61200e", "functionArn": "arn:aws:lambda:us-east-1:123456789012:function:my-function:$LATEST", "condition": "RetriesExhausted", "approximateInvokeCount": 3 }, "requestPayload": { "ORDER_IDS": [ "9e07af03-ce31-4ff3-xmpl-36dce652cb4f", "637de236-e7b2-464e-xmpl-baf57f86bb53", "a81ddca6-2c35-45c7-xmpl-c3a03a31ed15" ] }, "responseContext": { "statusCode": 200, "executedVersion": "$LATEST", "functionError": "Unhandled" }, "responsePayload": { "errorMessage": "RequestId: e4b46cbf-b738-xmpl-8880-a18cdf61200e Process exited before completing request" } } 调用记录包含有关事件、响应和记录发送原因的详细信息。 追踪发往目的地的请求 在每个请求排队、由 Lambda 函数处理并传递到目标服务时,您可以使用 AWS X-Ray 查看每个请求的连接视图。当您为调用函数的函数或服务激活 X-Ray 跟踪时,Lambda 会向请求添加 X-Ray 标头并将标头传递给目标服务。来自上游服务的跟踪会自动链接到下游 Lambda 函数的跟踪,从而创建整个应用程序的端到端视图。有关跟踪的更多信息,请参阅 使用 AWS X-Ray 可视化 Lambda 函数调用 。 添加死信队列 作为 失败时的目标 的替代,您可以使用死信队列配置函数,以保存丢弃的事件供进一步处理。死信队列的作用与失败时的目标相同,在某个事件的所有处理尝试都失败或者已过期而未处理时使用。但是,您只能在函数级别添加或删除死信队列。函数版本使用与未发布的版本($LATEST)相同的死信队列设置。失败时的目标还支持其他目标,并在调用记录中包含有关函数响应的详细信息。 要重新处理死信队列中的事件,您可以将其设置为 Lambda 函数的 事件源 。或者,您也可以手动检索事件。 您可以为死信队列选择 Amazon SQS 标准队列或 Amazon SNS 标准主题。不支持 FIFO 队列和 Amazon SNS FIFO 主题。 Amazon SQS 队列 – 队列会保存失败的事件,直到检索这些事件为止。如果您希望单个实体(例如 Lambda 函数或 CloudWatch 告警)来处理失败事件,请选择 Amazon SQS 标准队列。有关更多信息,请参阅 将 Lambda 与 Amazon SQS 结合使用 。 Amazon SNS 主题 – 主题将失败的事件中继到一个或多个目标。如果您希望多个实体对失败事件采取行动,请选择 Amazon SNS 标准主题。例如,您可以配置主题以将事件发送到电子邮件地址、Lambda 函数或 HTTP 端点。有关更多信息,请参阅 使用 Amazon SNS 通知调用 Lambda 函数 。 要将事件发送到队列或主题,您的函数需要其他权限。添加具有函数 执行角色 所需权限 的策略。如果已使用客户自主管理型 AWS KMS 密钥加密目标队列或主题,则请确保您的函数的执行角色和密钥 基于资源的策略 都包含相关权限。 创建目标并更新函数的执行角色后,将死信队列添加到函数中。您可以配置多个函数,以便将事件发送到同一目标。 Console 打开 Lamba 控制台的 函数 页面。 选择函数。 选择 Configuration(配置) ,然后选择 Asynchronous invocation(异步调用) 。 在 Asynchronous invocation (异步调用) 下,选择 Edit (编辑) 。 将 死信队列服务 设置为 Amazon SQS 或 Amazon SNS 。 选择目标队列或主题。 选择 保存 。 AWS CLI 要通过 AWS CLI 配置死信队列,请使用 update-function-configuration 命令。 aws lambda update-function-configuration \ --function-name my-function \ --dead-letter-config TargetArn= arn:aws:sns:us-east-1:123456789012:my-topic Lambda 按原样将事件发送到死信队列,并在属性中包含其他信息。您可以使用此信息来标识函数返回的错误,或者将事件与日志或 AWS X-Ray 跟踪相关联。 死信队列消息属性 RequestID (字符串)– 调用请求的 ID。请求 ID 显示在函数日志中。您还可以使用 X-Ray 开发工具包,在跟踪中的属性上记录请求 ID。然后,可以在 X-Ray 控制台中按请求 ID 搜索跟踪。 ErrorCode (数字)– HTTP 状态代码。 ErrorMessage (字符串)– 错误消息的第一个 1 KB 文本块。 如果 Lambda 无法向死信队列发送消息,则会删除该事件并发出 DeadLetterErrors 指标。之所以发生这种情况,可能是由于缺少权限,或者消息的总大小超过目标队列或主题的限制。例如,假设正文大小接近 1 MB 的 Amazon SNS 通知触发了一个导致错误的函数。在这种情况下,Amazon SNS 添加的事件数据加上 Lambda 添加的属性,可能会导致消息超过死信队列中允许的最大大小。 如果您正在使用 Amazon SQS 作为事件源,请在 Amazon SQS 队列本身而不是 Lambda 函数上配置死信队列。有关更多信息,请参阅 将 Lambda 与 Amazon SQS 结合使用 。 Javascript 在您的浏览器中被禁用或不可用。 要使用 Amazon Web Services 文档,必须启用 Javascript。请参阅浏览器的帮助页面以了解相关说明。 文档惯例 配置 事件源映射 此页面对您有帮助吗?- 是 感谢您对我们工作的肯定! 如果不耽误您的时间,请告诉我们做得好的地方,让我们做得更好。 此页面对您有帮助吗?- 否 感谢您告诉我们本页内容还需要完善。很抱歉让您失望了。 如果不耽误您的时间,请告诉我们如何改进文档。 | 2026-01-13T09:30:35 |
https://docs.aws.amazon.com/zh_cn/lambda/latest/dg/lambda-services.html#lambda-invocation-trigger | 使用来自其 AWS 他服务的事件调用 Lambda - AWS Lambda 使用来自其 AWS 他服务的事件调用 Lambda - AWS Lambda 文档 AWS Lambda 开发人员指南 创建触发器 服务列表 使用来自其 AWS 他服务的事件调用 Lambda 某些 AWS 服务可以使用 触发器 直接调用 Lambda 函数。这些服务将事件推送到 Lambda,并在指定事件发生时立即调用该函数。触发器适用于离散事件和实时处理。当您 使用 Lambda 控制台创建触发器 时,控制台会与相应的 AWS 服务交互以配置该服务的事件通知。触发器实际上由生成事件的服务而不是 Lambda 存储和管理。 事件使用 JSON 格式的数据结构。JSON 结构因生成它的服务和事件类型而异,但它们都包含函数处理事件所需的数据。 一个函数可具有多个触发器。每个触发器都可以作为一个客户端独立调用您的函数,Lambda 传递到您的函数的每个事件仅具有一个触发器的数据。Lambda 将事件文档转换为一个对象,并将该对象传递给函数处理程序。 取决于服务,事件驱动调用可以是 同步的 ,也可以是 异步的 。 对于同步调用,生成事件的服务服务等待来自您的函数的响应。该服务定义函数需要在响应中返回的数据。该服务控制错误策略,例如是否重试错误。 对于异步调用,Lambda 先将事件排队,然后再将事件传递给您的函数。当 Lambda 将事件排队时,它会立即向生成事件的服务发送成功响应。函数处理事件后,Lambda 不会返回事件生成服务的响应。 创建触发器 创建触发器最简单的方法是使用 Lambda 控制台。使用控制台创建触发器时,Lambda 会自动将所需的权限添加到函数 基于资源的策略 。 要使用 Lambda 控制台创建触发器 打开 Lamba 控制台的 函数 页面。 选择要为其创建触发器的函数。 在 函数概述 窗格中,选择 添加触发器 。 选择要调用函数的 AWS 服务。 填写 触发器配置 窗格中的选项,然后选择 添加 。根据您选择调用函数的 AWS 服务,触发器配置选项会有所不同。 可以调用 Lambda 函数的服务 下表列出了可以调用 Lambda 函数的服务。 服务 调用方法 Amazon Managed Streaming for Apache Kafka 事件源映射 自行管理的 Apache Kafka 事件源映射 Amazon API Gateway 事件驱动;同步调用 AWS CloudFormation 事件驱动;异步调用 Amazon CloudWatch Logs () 事件驱动;异步调用 AWS CodeCommit 事件驱动;异步调用 AWS CodePipeline 事件驱动;异步调用 Amazon Cognito 。 事件驱动;同步调用 AWS Config 事件驱动;异步调用 Amazon Connect : 事件驱动;同步调用 :Amazon DocumentDB 事件源映射 Amazon DynamoDB 事件源映射 Elastic Load Balancing(应用程序负载均衡器) 事件驱动;同步调用 Amazon EventBridge (CloudWatch Events) 事件驱动;异步调用(事件总线)、同步或异步调用(管道和计划) AWS IoT 事件驱动;异步调用 Amazon Kinesis 事件源映射 Amazon Data Firehose 事件驱动;同步调用 Amazon Lex 事件驱动;同步调用 Amazon MQ 事件源映射 Amazon Simple Email Service 事件驱动;异步调用 Amazon Simple Notification Service 事件驱动;异步调用 Amazon Simple Queue Service () 事件源映射 Amazon Simple Storage Service(Amazon S3) 事件驱动;异步调用 Amazon Simple Storage Service 批处理 事件驱动;同步调用 Secrets Manager 密钥轮换 AWS Step Functions 事件驱动;同步或异步调用 Amazon VPC Lattice 事件驱动;同步调用 Javascript 在您的浏览器中被禁用或不可用。 要使用 Amazon Web Services 文档,必须启用 Javascript。请参阅浏览器的帮助页面以了解相关说明。 文档惯例 故障排除 Apache Kafka 此页面对您有帮助吗?- 是 感谢您对我们工作的肯定! 如果不耽误您的时间,请告诉我们做得好的地方,让我们做得更好。 此页面对您有帮助吗?- 否 感谢您告诉我们本页内容还需要完善。很抱歉让您失望了。 如果不耽误您的时间,请告诉我们如何改进文档。 | 2026-01-13T09:30:35 |
https://docs.aws.amazon.com/lambda/latest/dg/python-package.html#python-package-dependencies | Working with .zip file archives for Python Lambda functions - AWS Lambda Working with .zip file archives for Python Lambda functions - AWS Lambda Documentation AWS Lambda Developer Guide Runtime dependencies in Python Creating a .zip deployment package with no dependencies Creating a .zip deployment package with dependencies Dependency search path and runtime-included libraries Using __pycache__ folders Creating .zip deployment packages with native libraries Creating and updating Python Lambda functions using .zip files Working with .zip file archives for Python Lambda functions Your AWS Lambda function’s code comprises a .py file containing your function’s handler code, together with any additional packages and modules your code depends on. To deploy this function code to Lambda, you use a deployment package . This package may either be a .zip file archive or a container image. For more information about using container images with Python, see Deploy Python Lambda functions with container images . To create your deployment package as .zip file archive, you can use your command-line tool’s built-in .zip file archive utility, or any other .zip file utility such as 7zip . The examples shown in the following sections assume you’re using a command-line zip tool in a Linux or MacOS environment. To use the same commands in Windows, you can install the Windows Subsystem for Linux to get a Windows-integrated version of Ubuntu and Bash. Note that Lambda uses POSIX file permissions, so you may need to set permissions for the deployment package folder before you create the .zip file archive. Topics Runtime dependencies in Python Creating a .zip deployment package with no dependencies Creating a .zip deployment package with dependencies Dependency search path and runtime-included libraries Using __pycache__ folders Creating .zip deployment packages with native libraries Creating and updating Python Lambda functions using .zip files Runtime dependencies in Python For Lambda functions that use the Python runtime, a dependency can be any Python package or module. When you deploy your function using a .zip archive, you can either add these dependencies to your .zip file with your function code or use a Lambda layer . A layer is a separate .zip file that can contain additional code and other content. To learn more about using Lambda layers in Python, see Working with layers for Python Lambda functions . The Lambda Python runtimes include the AWS SDK for Python (Boto3) and its dependencies. Lambda provides the SDK in the runtime for deployment scenarios where you are unable to add your own dependencies. These scenarios include creating functions in the console using the built-in code editor or using inline functions in AWS Serverless Application Model (AWS SAM) or CloudFormation templates. Lambda periodically updates the libraries in the Python runtime to include the latest updates and security patches. If your function uses the version of the Boto3 SDK included in the runtime but your deployment package includes SDK dependencies, this can cause version misalignment issues. For example, your deployment package could include the SDK dependency urllib3. When Lambda updates the SDK in the runtime, compatibility issues between the new version of the runtime and the version of urllib3 in your deployment package can cause your function to fail. Important To maintain full control over your dependencies and to avoid possible version misalignment issues, we recommend you add all of your function’s dependencies to your deployment package, even if versions of them are included in the Lambda runtime. This includes the Boto3 SDK. To find out which version of the SDK for Python (Boto3) is included in the runtime you're using, see Runtime-included SDK versions . Under the AWS shared responsibility model , you are responsible for the management of any dependencies in your functions' deployment packages. This includes applying updates and security patches. To update dependencies in your function's deployment package, first create a new .zip file and then upload it to Lambda. See Creating a .zip deployment package with dependencies and Creating and updating Python Lambda functions using .zip files for more information. Creating a .zip deployment package with no dependencies If your function code has no dependencies, your .zip file contains only the .py file with your function’s handler code. Use your preferred zip utility to create a .zip file with your .py file at the root. If the .py file is not at the root of your .zip file, Lambda won’t be able to run your code. To learn how to deploy your .zip file to create a new Lambda function or update an existing one, see Creating and updating Python Lambda functions using .zip files . Creating a .zip deployment package with dependencies If your function code depends on additional packages or modules, you can either add these dependencies to your .zip file with your function code or use a Lambda layer . The instructions in this section show you how to include your dependencies in your .zip deployment package. For Lambda to run your code, the .py file containing your handler code and all of your function's dependencies must be installed at the root of the .zip file. Suppose your function code is saved in a file named lambda_function.py . The following example CLI commands create a .zip file named my_deployment_package.zip containing your function code and its dependencies. You can either install your dependencies directly to a folder in your project directory or use a Python virtual environment. To create the deployment package (project directory) Navigate to the project directory containing your lambda_function.py source code file. In this example, the directory is named my_function . cd my_function Create a new directory named package into which you will install your dependencies. mkdir package Note that for a .zip deployment package, Lambda expects your source code and its dependencies all to be at the root of the .zip file. However, installing dependencies directly in your project directory can introduce a large number of new files and folders and make navigating around your IDE difficult. You create a separate package directory here to keep your dependencies separate from your source code. Install your dependencies in the package directory. The example below installs the Boto3 SDK from the Python Package Index using pip. If your function code uses Python packages you have created yourself, save them in the package directory. pip install --target ./package boto3 Create a .zip file with the installed libraries at the root. cd package zip -r ../my_deployment_package.zip . This generates a my_deployment_package.zip file in your project directory. Add the lambda_function.py file to the root of the .zip file cd .. zip my_deployment_package.zip lambda_function.py Your .zip file should have a flat directory structure, with your function's handler code and all your dependency folders installed at the root as follows. my_deployment_package.zip |- bin | |-jp.py |- boto3 | |-compat.py | |-data | |-docs ... |- lambda_function.py If the .py file containing your function’s handler code is not at the root of your .zip file, Lambda will not be able to run your code. To create the deployment package (virtual environment) Create and activate a virtual environment in your project directory. In this example the project directory is named my_function . ~$ cd my_function ~/my_function$ python3.14 -m venv my_virtual_env ~/my_function$ source ./my_virtual_env/bin/activate Install your required libraries using pip. The following example installs the Boto3 SDK (my_virtual_env) ~/my_function$ pip install boto3 Use pip show to find the location in your virtual environment where pip has installed your dependencies. (my_virtual_env) ~/my_function$ pip show <package_name> The folder in which pip installs your libraries may be named site-packages or dist-packages . This folder may be located in either the lib/python3.x or lib64/python3.x directory (where python3.x represents the version of Python you are using). Deactivate the virtual environment (my_virtual_env) ~/my_function$ deactivate Navigate into the directory containing the dependencies you installed with pip and create a .zip file in your project directory with the installed dependencies at the root. In this example, pip has installed your dependencies in the my_virtual_env/lib/python3.14/site-packages directory. ~/my_function$ cd my_virtual_env/lib/python3.14/site-packages ~/my_function/my_virtual_env/lib/python3.14/site-packages$ zip -r ../../../../my_deployment_package.zip . Navigate to the root of your project directory where the .py file containing your handler code is located and add that file to the root of your .zip package. In this example, your function code file is named lambda_function.py . ~/my_function/my_virtual_env/lib/python3.14/site-packages$ cd ../../../../ ~/my_function$ zip my_deployment_package.zip lambda_function.py Dependency search path and runtime-included libraries When you use an import statement in your code, the Python runtime searches the directories in its search path until it finds the module or package. By default, the first location the runtime searches is the directory into which your .zip deployment package is decompressed and mounted ( /var/task ). If you include a version of a runtime-included library in your deployment package, your version will take precedence over the version that's included in the runtime. Dependencies in your deployment package also have precedence over dependencies in layers. When you add a dependency to a layer, Lambda extracts this to /opt/python/lib/python3.x/site-packages (where python3.x represents the version of the runtime you're using) or /opt/python . In the search path, these directories have precedence over the directories containing the runtime-included libraries and pip-installed libraries ( /var/runtime and /var/lang/lib/python3.x/site-packages ). Libraries in function layers therefore have precedence over versions included in the runtime. Note In the Python 3.11 managed runtime and base image, the AWS SDK and its dependencies are installed in the /var/lang/lib/python3.11/site-packages directory. You can see the full search path for your Lambda function by adding the following code snippet. import sys search_path = sys.path print(search_path) Note Because dependencies in your deployment package or layers take precedence over runtime-included libraries, this can cause version misalignment problems if you include an SDK dependency such as urllib3 in your package without including the SDK as well. If you deploy your own version of a Boto3 dependency, you must also deploy Boto3 as a dependency in your deployment package. We recommend that you package all of your function’s dependencies, even if versions of them are included in the runtime. You can also add dependencies in a separate folder inside your .zip package. For example, you might add a version of the Boto3 SDK to a folder in your .zip package called common . When your .zip package is decompressed and mounted, this folder is placed inside the /var/task directory. To use a dependency from a folder in your .zip deployment package in your code, use an import from statement. For example, to use a version of Boto3 from a folder named common in your .zip package, use the following statement. from common import boto3 Using __pycache__ folders We recommend that you don't include __pycache__ folders in your function's deployment package. Python bytecode that's compiled on a build machine with a different architecture or operating system might not be compatible with the Lambda execution environment. Creating .zip deployment packages with native libraries If your function uses only pure Python packages and modules, you can use the pip install command to install your dependencies on any local build machine and create your .zip file. Many popular Python libraries, including NumPy and Pandas, are not pure Python and contain code written in C or C++. When you add libraries containing C/C++ code to your deployment package, you must build your package correctly to ensure that it’s compatible with the Lambda execution environment. Most packages available on the Python Package Index ( PyPI ) are available as “wheels” (.whl files). A .whl file is a type of ZIP file which contains a built distribution with pre-compiled binaries for a particular operating system and instruction set architecture. To make your deployment package compatible with Lambda, you install the wheel for Linux operating systems and your function’s instruction set architecture. Some packages may only be available as source distributions. For these packages, you need to compile and build the C/C++ components yourself. To see what distributions are available for your required package, do the following: Search for the name of the package on the Python Package Index main page . Choose the version of the package you want to use. Choose Download files . Working with built distributions (wheels) To download a wheel that’s compatible with Lambda, you use the pip --platform option. If your Lambda function uses the x86_64 instruction set architecture, run the following pip install command to install a compatible wheel in your package directory. Replace --python 3.x with the version of the Python runtime you are using. pip install \ --platform manylinux2014_x86_64 \ --target=package \ --implementation cp \ --python-version 3.x \ --only-binary=:all: --upgrade \ <package_name> If your function uses the arm64 instruction set architecture, run the following command. Replace --python 3.x with the version of the Python runtime you are using. pip install \ --platform manylinux2014_aarch64 \ --target=package \ --implementation cp \ --python-version 3.x \ --only-binary=:all: --upgrade \ <package_name> Working with source distributions If your package is only available as a source distribution, you need to build the C/C++ libraries yourself. To make your package compatible with the Lambda execution environment, you need to build it in an environment that uses the same Amazon Linux operating system. You can do this by building your package in an Amazon Elastic Compute Cloud (Amazon EC2) Linux instance. To learn how to launch and connect to an Amazon EC2 Linux instance, see Get started with Amazon EC2 in the Amazon EC2 User Guide . Creating and updating Python Lambda functions using .zip files After you have created your .zip deployment package, you can use it to create a new Lambda function or update an existing one. You can deploy your .zip package using the Lambda console, the AWS Command Line Interface, and the Lambda API. You can also create and update Lambda functions using AWS Serverless Application Model (AWS SAM) and CloudFormation. The maximum size for a .zip deployment package for Lambda is 250 MB (unzipped). Note that this limit applies to the combined size of all the files you upload, including any Lambda layers. The Lambda runtime needs permission to read the files in your deployment package. In Linux permissions octal notation, Lambda needs 644 permissions for non-executable files (rw-r--r--) and 755 permissions (rwxr-xr-x) for directories and executable files. In Linux and MacOS, use the chmod command to change file permissions on files and directories in your deployment package. For example, to give a non-executable file the correct permissions, run the following command. chmod 644 <filepath> To change file permissions in Windows, see Set, View, Change, or Remove Permissions on an Object in the Microsoft Windows documentation. Note If you don't grant Lambda the permissions it needs to access directories in your deployment package, Lambda sets the permissions for those directories to 755 (rwxr-xr-x). Creating and updating functions with .zip files using the console To create a new function, you must first create the function in the console, then upload your .zip archive. To update an existing function, open the page for your function, then follow the same procedure to add your updated .zip file. If your .zip file is less than 50MB, you can create or update a function by uploading the file directly from your local machine. For .zip files greater than 50MB, you must upload your package to an Amazon S3 bucket first. For instructions on how to upload a file to an Amazon S3 bucket using the AWS Management Console, see Getting started with Amazon S3 . To upload files using the AWS CLI, see Move objects in the AWS CLI User Guide . Note You cannot change the deployment package type (.zip or container image) for an existing function. For example, you cannot convert a container image function to use a .zip file archive. You must create a new function. To create a new function (console) Open the Functions page of the Lambda console and choose Create Function . Choose Author from scratch . Under Basic information , do the following: For Function name , enter the name for your function. For Runtime , select the runtime you want to use. (Optional) For Architecture , choose the instruction set architecture for your function. The default architecture is x86_64. Ensure that the .zip deployment package for your function is compatible with the instruction set architecture you select. (Optional) Under Permissions , expand Change default execution role . You can create a new Execution role or use an existing one. Choose Create function . Lambda creates a basic 'Hello world' function using your chosen runtime. To upload a .zip archive from your local machine (console) In the Functions page of the Lambda console, choose the function you want to upload the .zip file for. Select the Code tab. In the Code source pane, choose Upload from . Choose .zip file . To upload the .zip file, do the following: Select Upload , then select your .zip file in the file chooser. Choose Open . Choose Save . To upload a .zip archive from an Amazon S3 bucket (console) In the Functions page of the Lambda console, choose the function you want to upload a new .zip file for. Select the Code tab. In the Code source pane, choose Upload from . Choose Amazon S3 location . Paste the Amazon S3 link URL of your .zip file and choose Save . Updating .zip file functions using the console code editor For some functions with .zip deployment packages, you can use the Lambda console’s built-in code editor to update your function code directly. To use this feature, your function must meet the following criteria: Your function must use one of the interpreted language runtimes (Python, Node.js, or Ruby) Your function’s deployment package must be smaller than 50 MB (unzipped). Function code for functions with container image deployment packages cannot be edited directly in the console. To update function code using the console code editor Open the Functions page of the Lambda console and select your function. Select the Code tab. In the Code source pane, select your source code file and edit it in the integrated code editor. In the DEPLOY section, choose Deploy to update your function's code: Creating and updating functions with .zip files using the AWS CLI You can can use the AWS CLI to create a new function or to update an existing one using a .zip file. Use the create-function and update-function-code commands to deploy your .zip package. If your .zip file is smaller than 50MB, you can upload the .zip package from a file location on your local build machine. For larger files, you must upload your .zip package from an Amazon S3 bucket. For instructions on how to upload a file to an Amazon S3 bucket using the AWS CLI, see Move objects in the AWS CLI User Guide . Note If you upload your .zip file from an Amazon S3 bucket using the AWS CLI, the bucket must be located in the same AWS Region as your function. To create a new function using a .zip file with the AWS CLI, you must specify the following: The name of your function ( --function-name ) Your function’s runtime ( --runtime ) The Amazon Resource Name (ARN) of your function’s execution role ( --role ) The name of the handler method in your function code ( --handler ) You must also specify the location of your .zip file. If your .zip file is located in a folder on your local build machine, use the --zip-file option to specify the file path, as shown in the following example command. aws lambda create-function --function-name myFunction \ --runtime python3.14 --handler lambda_function.lambda_handler \ --role arn:aws:iam::111122223333:role/service-role/my-lambda-role \ --zip-file fileb://myFunction.zip To specify the location of .zip file in an Amazon S3 bucket, use the --code option as shown in the following example command. You only need to use the S3ObjectVersion parameter for versioned objects. aws lambda create-function --function-name myFunction \ --runtime python3.14 --handler lambda_function.lambda_handler \ --role arn:aws:iam::111122223333:role/service-role/my-lambda-role \ --code S3Bucket=amzn-s3-demo-bucket,S3Key=myFileName.zip,S3ObjectVersion=myObjectVersion To update an existing function using the CLI, you specify the the name of your function using the --function-name parameter. You must also specify the location of the .zip file you want to use to update your function code. If your .zip file is located in a folder on your local build machine, use the --zip-file option to specify the file path, as shown in the following example command. aws lambda update-function-code --function-name myFunction \ --zip-file fileb://myFunction.zip To specify the location of .zip file in an Amazon S3 bucket, use the --s3-bucket and --s3-key options as shown in the following example command. You only need to use the --s3-object-version parameter for versioned objects. aws lambda update-function-code --function-name myFunction \ --s3-bucket amzn-s3-demo-bucket --s3-key myFileName.zip --s3-object-version myObject Version Creating and updating functions with .zip files using the Lambda API To create and update functions using a .zip file archive, use the following API operations: CreateFunction UpdateFunctionCode Creating and updating functions with .zip files using AWS SAM The AWS Serverless Application Model (AWS SAM) is a toolkit that helps streamline the process of building and running serverless applications on AWS. You define the resources for your application in a YAML or JSON template and use the AWS SAM command line interface (AWS SAM CLI) to build, package, and deploy your applications. When you build a Lambda function from an AWS SAM template, AWS SAM automatically creates a .zip deployment package or container image with your function code and any dependencies you specify. To learn more about using AWS SAM to build and deploy Lambda functions, see Getting started with AWS SAM in the AWS Serverless Application Model Developer Guide . You can also use AWS SAM to create a Lambda function using an existing .zip file archive. To create a Lambda function using AWS SAM, you can save your .zip file in an Amazon S3 bucket or in a local folder on your build machine. For instructions on how to upload a file to an Amazon S3 bucket using the AWS CLI, see Move objects in the AWS CLI User Guide . In your AWS SAM template, the AWS::Serverless::Function resource specifies your Lambda function. In this resource, set the following properties to create a function using a .zip file archive: PackageType - set to Zip CodeUri - set to the function code's Amazon S3 URI, path to local folder, or FunctionCode object Runtime - Set to your chosen runtime With AWS SAM, if your .zip file is larger than 50MB, you don’t need to upload it to an Amazon S3 bucket first. AWS SAM can upload .zip packages up to the maximum allowed size of 250MB (unzipped) from a location on your local build machine. To learn more about deploying functions using .zip file in AWS SAM, see AWS::Serverless::Function in the AWS SAM Developer Guide . Creating and updating functions with .zip files using CloudFormation You can use CloudFormation to create a Lambda function using a .zip file archive. To create a Lambda function from a .zip file, you must first upload your file to an Amazon S3 bucket. For instructions on how to upload a file to an Amazon S3 bucket using the AWS CLI, see Move objects in the AWS CLI User Guide. For Node.js and Python runtimes, you can also provide inline source code in your CloudFormation template. CloudFormation then creates a .zip file containing your code when you build your function. Using an existing .zip file In your CloudFormation template, the AWS::Lambda::Function resource specifies your Lambda function. In this resource, set the following properties to create a function using a .zip file archive: PackageType - Set to Zip Code - Enter the Amazon S3 bucket name and the .zip file name in the S3Bucket and S3Key fields Runtime - Set to your chosen runtime Creating a .zip file from inline code You can declare simple functions written in Python or Node.js inline in an CloudFormation template. Because the code is embedded in YAML or JSON, you can't add any external dependenices to your deployment package. This means your function has to use the version of the AWS SDK that's included in the runtime. The requirements of the template, such as having to escape certain characters, also make it harder to use your IDE's syntax checking and code completion features. This means that your template might require additional testing. Because of these limitations, declaring functions inline is best suited for very simple code that does not change frequently. To create a .zip file from inline code for Node.js and Python runtimes, set the following properties in your template’s AWS::Lambda::Function resource: PackageType - Set to Zip Code - Enter your function code in the ZipFile field Runtime - Set to your chosen runtime The .zip file that CloudFormation generates cannot exceed 4MB. To learn more about deploying functions using .zip file in CloudFormation, see AWS::Lambda::Function in the CloudFormation User Guide . Javascript is disabled or is unavailable in your browser. To use the Amazon Web Services Documentation, Javascript must be enabled. Please refer to your browser's Help pages for instructions. Document Conventions Handler Deploy container images Did this page help you? - Yes Thanks for letting us know we're doing a good job! If you've got a moment, please tell us what we did right so we can do more of it. Did this page help you? - No Thanks for letting us know this page needs work. We're sorry we let you down. If you've got a moment, please tell us how we can make the documentation better. | 2026-01-13T09:30:35 |
https://www.php.net/x-myracloud-5958a2bbbed300a9b9ac631223924e0b/1768296244.918 | PHP update page now Downloads Documentation Get Involved Help Search docs Getting Started Introduction A simple tutorial Language Reference Basic syntax Types Variables Constants Expressions Operators Control Structures Functions Classes and Objects Namespaces Enumerations Errors Exceptions Fibers Generators Attributes References Explained Predefined Variables Predefined Exceptions Predefined Interfaces and Classes Predefined Attributes Context options and parameters Supported Protocols and Wrappers Security Introduction General considerations Installed as CGI binary Installed as an Apache module Session Security Filesystem Security Database Security Error Reporting User Submitted Data Hiding PHP Keeping Current Features HTTP authentication with PHP Cookies Sessions Handling file uploads Using remote files Connection handling Persistent Database Connections Command line usage Garbage Collection DTrace Dynamic Tracing Function Reference Affecting PHP's Behaviour Audio Formats Manipulation Authentication Services Command Line Specific Extensions Compression and Archive Extensions Cryptography Extensions Database Extensions Date and Time Related Extensions File System Related Extensions Human Language and Character Encoding Support Image Processing and Generation Mail Related Extensions Mathematical Extensions Non-Text MIME Output Process Control Extensions Other Basic Extensions Other Services Search Engine Extensions Server Specific Extensions Session Extensions Text Processing Variable and Type Related Extensions Web Services Windows Only Extensions XML Manipulation GUI Extensions Keyboard Shortcuts ? This help j Next menu item k Previous menu item g p Previous man page g n Next man page G Scroll to bottom g g Scroll to top g h Goto homepage g s Goto search (current page) / Focus search box A popular general-purpose scripting language that is especially suited to web development. Fast, flexible and pragmatic, PHP powers everything from your blog to the most popular websites in the world. What's new in 8.5 Download 8.5.1 · Changelog · Upgrading 8.4.16 · Changelog · Upgrading 8.3.29 · Changelog · Upgrading 8.2.30 · Changelog · Upgrading 18 Dec 2025 PHP 8.1.34 Released! The PHP development team announces the immediate availability of PHP 8.1.34. This is a security release. All PHP 8.1 users are encouraged to upgrade to this version. For source downloads of PHP 8.1.34 please visit our downloads page , Windows source and binaries can also be found there . The list of changes is recorded in the ChangeLog . 18 Dec 2025 PHP 8.4.16 Released! The PHP development team announces the immediate availability of PHP 8.4.16. This is a security release. All PHP 8.4 users are encouraged to upgrade to this version. For source downloads of PHP 8.4.16 please visit our downloads page , Windows source and binaries can also be found there . The list of changes is recorded in the ChangeLog . 18 Dec 2025 PHP 8.2.30 Released! The PHP development team announces the immediate availability of PHP 8.2.30. This is a security release. All PHP 8.2 users are encouraged to upgrade to this version. For source downloads of PHP 8.2.30 please visit our downloads page , Windows source and binaries can also be found there . The list of changes is recorded in the ChangeLog . 18 Dec 2025 PHP 8.3.29 Released! The PHP development team announces the immediate availability of PHP 8.3.29. This is a security release. All PHP 8.3 users are encouraged to upgrade to this version. For source downloads of PHP 8.3.29 please visit our downloads page , Windows source and binaries can also be found there . The list of changes is recorded in the ChangeLog . 18 Dec 2025 PHP 8.5.1 Released! The PHP development team announces the immediate availability of PHP 8.5.1. This is a security release. All PHP 8.5 users are encouraged to upgrade to this version. For source downloads of PHP 8.5.1 please visit our downloads page , Windows source and binaries can also be found there . The list of changes is recorded in the ChangeLog . 20 Nov 2025 PHP 8.5.0 Released! The PHP development team announces the immediate availability of PHP 8.5.0. This release marks the latest minor release of the PHP language. PHP 8.5 comes with numerous improvements and new features such as: New "URI" extension New pipe operator (|>) Clone With New #[\NoDiscard] attribute Support for closures, casts, and first class callables in constant expressions And much much more... For source downloads of PHP 8.5.0 please visit our downloads page , Windows source and binaries can also be found there . The list of changes is recorded in the ChangeLog . The migration guide is available in the PHP Manual. Please consult it for the detailed list of new features and backward incompatible changes. Kudos to all the contributors and supporters! 20 Nov 2025 PHP 8.4.15 Released! The PHP development team announces the immediate availability of PHP 8.4.15. This is a bug fix release. All PHP 8.4 users are encouraged to upgrade to this version. For source downloads of PHP 8.4.15 please visit our downloads page , Windows source and binaries can also be found there . The list of changes is recorded in the ChangeLog . 20 Nov 2025 PHP 8.3.28 Released! The PHP development team announces the immediate availability of PHP 8.3.28. This is a bug fix release. All PHP 8.3 users are encouraged to upgrade to this version. For source downloads of PHP 8.3.28 please visit our downloads page , Windows source and binaries can also be found there . The list of changes is recorded in the ChangeLog . 13 Nov 2025 PHP 8.5.0 RC 5 available for testing The PHP team is pleased to announce the fifth release candidate of PHP 8.5.0, RC 5. This continues the PHP 8.5 release cycle, the rough outline of which is specified in the PHP Wiki . For source downloads of PHP 8.5.0 RC5, please visit the download page . Please carefully test this version and report any issues found on GitHub . Please DO NOT use this version in production, it is a test version. For more information on the new features and other changes, you can read the NEWS file, or the UPGRADING file for a complete list of upgrading notes. These files can also be found in the release archive. The next release will be the GA release of PHP 8.5.0, planned for 20 Nov 2025. The signatures for the release can be found in the manifest or on the Release Candidates page . Thank you for helping us make PHP better. 06 Nov 2025 PHP 8.5.0 RC4 available for testing The PHP team is pleased to announce the final planned release candidate of PHP 8.5.0, RC 4. This continues the PHP 8.5 release cycle, the rough outline of which is specified in the PHP Wiki . For source downloads of PHP 8.5.0 RC4, please visit the download page . Please carefully test this version and report any issues found on GitHub . Please DO NOT use this version in production, it is a test version. For more information on the new features and other changes, you can read the NEWS file, or the UPGRADING file for a complete list of upgrading notes. These files can also be found in the release archive. The next release will be the GA release of PHP 8.5.0, planned for 20 Nov 2025. The signatures for the release can be found in the manifest or on the Release Candidates page . Thank you for helping us make PHP better. 23 Oct 2025 PHP 8.3.27 Released! The PHP development team announces the immediate availability of PHP 8.3.27. This is a bug fix release. All PHP 8.3 users are encouraged to upgrade to this version. For source downloads of PHP 8.3.27 please visit our downloads page , Windows source and binaries can be found on windows.php.net/download/ . The list of changes is recorded in the ChangeLog . 23 Oct 2025 PHP 8.4.14 Released! The PHP development team announces the immediate availability of PHP 8.4.14. This is a bug fix release. All PHP 8.4 users are encouraged to upgrade to this version. For source downloads of PHP 8.4.14 please visit our downloads page , Windows source and binaries can be found on windows.php.net/download/ . The list of changes is recorded in the ChangeLog . 23 Oct 2025 PHP 8.5.0 RC 3 available for testing The PHP team is pleased to announce the third release candidate of PHP 8.5.0, RC 3. This continues the PHP 8.5 release cycle, the rough outline of which is specified in the PHP Wiki . For source downloads of PHP 8.5.0 RC3, please visit the download page . Please carefully test this version and report any issues found on GitHub . Please DO NOT use this version in production, it is an early test version. For more information on the new features and other changes, you can read the NEWS file, or the UPGRADING file for a complete list of upgrading notes. These files can also be found in the release archive. The next release will be RC4, planned for 6 Nov 2025. The signatures for the release can be found in the manifest or on the Release Candidates page . Thank you for helping us make PHP better. 09 Oct 2025 PHP 8.5.0 RC 2 available for testing The PHP team is pleased to announce the second release candidate of PHP 8.5.0, RC 2. This continues the PHP 8.5 release cycle, the rough outline of which is specified in the PHP Wiki . For source downloads of PHP 8.5.0 RC2, please visit the download page . Please carefully test this version and report any issues found on GitHub . Please DO NOT use this version in production, it is an early test version. For more information on the new features and other changes, you can read the NEWS file, or the UPGRADING file for a complete list of upgrading notes. These files can also be found in the release archive. The next release will be RC3, planned for 23 Oct 2025. The signatures for the release can be found in the manifest or on the Release Candidates page . Thank you for helping us make PHP better. 25 Sep 2025 PHP 8.5.0 RC 1 available for testing The PHP team is pleased to announce the first release candidate of PHP 8.5.0, RC 1. This continues the PHP 8.5 release cycle, the rough outline of which is specified in the PHP Wiki . For source downloads of PHP 8.5.0 RC1, please visit the download page . Please carefully test this version and report any issues found on GitHub . Please DO NOT use this version in production, it is an early test version. For more information on the new features and other changes, you can read the NEWS file, or the UPGRADING file for a complete list of upgrading notes. These files can also be found in the release archive. The next release will be RC2, planned for 9 Oct 2025. The signatures for the release can be found in the manifest or on the Release Candidates page . Thank you for helping us make PHP better. 25 Sep 2025 PHP 8.3.26 Released! The PHP development team announces the immediate availability of PHP 8.3.26. This is a bug fix release. All PHP 8.3 users are encouraged to upgrade to this version. For source downloads of PHP 8.3.26 please visit our downloads page , Windows source and binaries can be found on windows.php.net/download/ . The list of changes is recorded in the ChangeLog . 25 Sep 2025 PHP 8.4.13 Released! The PHP development team announces the immediate availability of PHP 8.4.13. This is a bug fix release. All PHP 8.4 users are encouraged to upgrade to this version. For source downloads of PHP 8.4.13 please visit our downloads page , Windows source and binaries can be found on windows.php.net/download/ . The list of changes is recorded in the ChangeLog . 11 Sep 2025 PHP 8.5.0 Beta 3 available for testing The PHP team is pleased to announce the third beta release of PHP 8.5.0, Beta 3. This continues the PHP 8.5 release cycle, the rough outline of which is specified in the PHP Wiki . For source downloads of PHP 8.5.0 Beta 3, please visit the download page . Please carefully test this version and report any issues found on GitHub . Please DO NOT use this version in production, it is an early test version. For more information on the new features and other changes, you can read the NEWS file, or the UPGRADING file for a complete list of upgrading notes. These files can also be found in the release archive. The next release will be RC1, planned for 25 Sep 2025. The signatures for the release can be found in the manifest or on the Release Candidates page . Thank you for helping us make PHP better. 28 Aug 2025 PHP 8.5.0 Beta 2 available for testing The PHP team is pleased to announce the second beta release of PHP 8.5.0, Beta 2. This continues the PHP 8.5 release cycle, the rough outline of which is specified in the PHP Wiki . For source downloads of PHP 8.5.0 Beta 2 please visit the download page . Please carefully test this version and report any issues found on GitHub . Please DO NOT use this version in production, it is an early test version. For more information on the new features and other changes, you can read the NEWS file, or the UPGRADING file for a complete list of upgrading notes. These files can also be found in the release archive. The next release will be Beta 3, planned for 11 Sep 2025. The signatures for the release can be found in the manifest or on the Release Candidates page . Thank you for helping us make PHP better. 28 Aug 2025 PHP 8.3.25 Released! The PHP development team announces the immediate availability of PHP 8.3.25. This is a bug fix release. All PHP 8.3 users are encouraged to upgrade to this version. For source downloads of PHP 8.3.25 please visit our downloads page , Windows source and binaries can be found on windows.php.net/download/ . The list of changes is recorded in the ChangeLog . 28 Aug 2025 PHP 8.4.12 Released! The PHP development team announces the immediate availability of PHP 8.4.12. This is a bug fix release. All PHP 8.4 users are encouraged to upgrade to this version. For source downloads of PHP 8.4.12 please visit our downloads page , Windows source and binaries can be found on windows.php.net/download/ . The list of changes is recorded in the ChangeLog . 14 Aug 2025 PHP 8.5.0 Beta 1 available for testing The PHP team is pleased to announce the first beta release of PHP 8.5.0, Beta 1. This continues the PHP 8.5 release cycle, the rough outline of which is specified in the PHP Wiki . For source downloads of PHP 8.5.0 Beta 1 please visit the download page . Please carefully test this version and report any issues found on GitHub . Please DO NOT use this version in production, it is an early test version. For more information on the new features and other changes, you can read the NEWS file, or the UPGRADING file for a complete list of upgrading notes. These files can also be found in the release archive. The next release will be Beta 2, planned for 28 Aug 2025. The signatures for the release can be found in the manifest or on the Release Candidates page . Thank you for helping us make PHP better. 01 Aug 2025 PHP 8.5.0 Alpha 4 available for testing The PHP team is pleased to announce the third testing release of PHP 8.5.0, Alpha 4. This continues the PHP 8.5 release cycle, the rough outline of which is specified in the PHP Wiki . For source downloads of PHP 8.5.0 Alpha 4 please visit the download page . Please carefully test this version and report any issues found on GitHub . Please DO NOT use this version in production, it is an early test version. For more information on the new features and other changes, you can read the NEWS file, or the UPGRADING file for a complete list of upgrading notes. These files can also be found in the release archive. The next release will be Beta 1, planned for 14 Aug 2025. The signatures for the release can be found in the manifest or on the Release Candidates page . Thank you for helping us make PHP better. 31 Jul 2025 PHP 8.4.11 Released! The PHP development team announces the immediate availability of PHP 8.4.11. This is a bug fix release. All PHP 8.4 users are encouraged to upgrade to this version. For source downloads of PHP 8.4.11 please visit our downloads page , Windows source and binaries can be found on windows.php.net/download/ . The list of changes is recorded in the ChangeLog . 31 Jul 2025 PHP 8.3.24 Released! The PHP development team announces the immediate availability of PHP 8.3.24. This is a bug fix release. All PHP 8.3 users are encouraged to upgrade to this version. For source downloads of PHP 8.3.24 please visit our downloads page , Windows source and binaries can be found on windows.php.net/download/ . The list of changes is recorded in the ChangeLog . Older News Entries The PHP Foundation The PHP Foundation is a collective of people and organizations, united in the mission to ensure the long-term prosperity of the PHP language. Donate Upcoming conferences International PHP Conference Berlin 2026 Laravel Live Japan Conferences calling for papers Dutch PHP Conference 2026 User Group Events Special Thanks Social media @official_php @php@fosstodon.org @phpnet Copyright © 2001-2026 The PHP Group My PHP.net Contact Other PHP.net sites Privacy policy View Source ↑ and ↓ to navigate • Enter to select • Esc to close • / to open Press Enter without selection to search using Google | 2026-01-13T09:30:35 |
https://support.microsoft.com/et-ee/windows/windowsi-uuesti-installimine-installikandja-abil-d8369486-3e33-7d9c-dccc-859e2b022fc7 | Windowsi uuesti installimine installikandja abil - Microsofti tugiteenus Seotud teemad × Windowsi turve, ohutus ja privaatsus Overview Turbe, ohutuse ja privaatsuse ülevaade Windowsi turve Windowsi turbe kasutajaabi Windowsi turve tagab kaitse Enne Xboxi või Windowsi arvuti müümist, kinkimist või taaskasutusse andmist Ründevara eemaldamine Windowsi arvutist Windowsi ohutus Windowsi ohutuse kasutajaabi Brauseriajaloo kuvamine ja kustutamine Microsoft Edge’is Küpsiste kustutamine ja haldamine Windowsi uuesti installimisel saate väärtusliku sisu ohutult eemaldada Kaotsiläinud Windowsi seadme leidmine ja lukustamine Windowsi privaatsus Windowsi privaatsuse kasutajaabi Rakenduste kasutatavad Windowsi privaatsussätted Andmete vaatamine privaatsussätete armatuurlaual Põhisisu juurde Microsoft Tugi Tugi Tugi Avaleht Microsoft 365 Office Tooted Microsoft 365 Outlook Microsoft Teams OneDrive Microsoft Copilot OneNote Windows rohkem… Seadmed Surface Arvuti tarvikud Xbox Arvutimängud HoloLens Surface Hub Riistvara garantiid Konto ja arveldamine konto Microsoft Store ja arveldamine Ressursid Mis on uut? Kogukonnafoorumid Microsoft 365 administraatorid Väikeettevõtete portaal Arendaja Haridus Teatage tehnilise toega seotud pettusest Tooteohutus Rohkem Osta Microsoft 365 Kogu Microsoft Global Microsoft 365 Teams Copilot Windows Surface Xbox Tugi Tarkvara Tarkvara Windowsi rakendused AI OneDrive Outlook Üleminek Skype'ilt Teamsile OneNote Microsoft Teams Arvutid ja seadmed Arvutid ja seadmed Accessories Meelelahutus Meelelahutus PC-mängud Äri Äri Microsofti turve Azure Dynamics 365 Microsoft 365 ettevõtteversioon Microsoft Industry Microsoft Power Platform Windows 365 Arendaja ja IT Arendaja ja IT Microsofti arendaja Microsoft Learn Tehisintellekti-turuplatsi rakenduste tugi Microsofti tehnoloogiakogukond Microsoft Marketplace Visual Studio Marketplace Rewards Muud Muud Tasuta allalaadimised ja turve Kuva saidikaart Otsing Spikri otsing Tulemid puuduvad Loobu Logi sisse Logige sisse Microsofti kontoga Logige sisse või looge konto. Tere! Valige mõni muu konto. Teil on mitu kontot Valige konto, millega soovite sisse logida. Seotud teemad Windowsi turve, ohutus ja privaatsus Overview Turbe, ohutuse ja privaatsuse ülevaade Windowsi turve Windowsi turbe kasutajaabi Windowsi turve tagab kaitse Enne Xboxi või Windowsi arvuti müümist, kinkimist või taaskasutusse andmist Ründevara eemaldamine Windowsi arvutist Windowsi ohutus Windowsi ohutuse kasutajaabi Brauseriajaloo kuvamine ja kustutamine Microsoft Edge’is Küpsiste kustutamine ja haldamine Windowsi uuesti installimisel saate väärtusliku sisu ohutult eemaldada Kaotsiläinud Windowsi seadme leidmine ja lukustamine Windowsi privaatsus Windowsi privaatsuse kasutajaabi Rakenduste kasutatavad Windowsi privaatsussätted Andmete vaatamine privaatsussätete armatuurlaual Windowsi uuesti installimine installikandja abil Rakenduskoht Windows 11 Windows 10 Windowsi installikandja on mitmekülgne tööriist, millel on mitu otstarvet, sealhulgas kohapealsed taasteinstallid ja uued installid. Tavaliselt USB-draivile või DVD-le loodud andmekandja sisaldab kõiki vajalikke faile Windowsi installimiseks või uuesti installimiseks teie seadmesse. See on eriti kasulik juhul, kui teie süsteemil esineb olulisi probleeme (nt tarkvara rike või riistvaratõrge), mis takistavad süsteemi algkäivitamist või õigesti toimimist. Taastamiseks võimaldab installikandja teil teha kohapealse installi, mis sisuliselt installib Windowsi uuesti, mõjutamata teie isiklikke faile, sätteid või installitud rakendusi. See meetod sobib suurepäraselt süsteemiprobleemide lahendamiseks, säilitades samal ajal teie andmed ja konfiguratsioonid. Kui käivitate installikandjalt ja valite sobivad taastesuvandid, saate taastada süsteemi stabiilsesse olekusse ilma täieliku tühjendamiseta. Kui on vaja uut algust, saab windowsi uueks installimiseks kasutada installikandjat. See protsess hõlmab olemasolevate andmete täielikku kustutamist teie seadmes ja Windowsi puhta versiooni installimist. See on sobiv valik, kui soovite eemaldada kõik varasemad andmed, sätted ja rakendused või kui häälestate uue seadme. Alternatiivsed lahendused meediumi uuesti installimisele Enne Windowsi uuesti installimist installikandja abil lugege artiklit Windowsi taastesuvandid , mis annavad ülevaate Windowsi taastamise erinevatest lahendustest. Enne uuesti installimise alustamist Kettaruumi kontrollimine Kui seade ei tööta ootuspäraselt või Windowsiga on probleeme, võib põhjus olla väheses kettaruumis. Enne Windowsi uuesti installimist proovige kettaruumi vabastada, et näha, kas see lahendab probleemid. Lisateavet leiate teemast Kettaruumi vabastamine Windowsis . Andmete varundamine Kui isikuandmed ja failid tuleb enne Windowsi uuesti installimist salvestada, varundage need enne uuesti installimist. Isikuandmeid ja faile saab varundada välisele kõvakettale, USB-mäluseadmele või pilveasukohta (nt OneDrive'i). Veenduge, et Windows oleks aktiveeritud Windows tuleb pärast uuesti installimist aktiveerida. Tavaliselt toimub aktiveerimine automaatselt pärast võrguühenduse avamist. Lisateavet leiate teemast Aktiveerimine pärast Windowsi uuesti installimist . Digitaallitsentsi linkimine Microsofti kontoga Enne Windowsi uuesti aktiveerimist pärast Windowsi uuesti installimist peab teie Microsofti konto olema seadmes seotud Windowsi digitaallitsentsiga. Lisateavet leiate teemast Windowsi digitaallitsentsi linkimine Microsofti kontoga . Windows tuleb uuesti aktiveerida, kui seadmes on tehtud oluline riistvaramuudatus Kui Windows installitakse pärast seadmes olulise riistvaramuudatuse tegemist (nt emaplaadi välja vahetamist) uuesti, ei pruugi see enam aktiveeritud olla. Aktiveerimise tõrkeotsijat saab kasutada Windowsi uuesti aktiveerimiseks. Lisateavet leiate teemast Aktiveerimise tõrkeotsija kasutamine . Uuesti installitav Windowsi väljaanne peab vastama teie litsentsile Windowsi uuesti installimisel valige Windowsi väljaanne, mis vastab teie digitaallitsentsile. Näiteks kui praegune Windowsi väljaanne on Home , tuleb Windows Home uuesti installida. Praegu töötava Windowsi väljaande kontrollimiseks tehke järgmist. Paremklõpsake menüüd Start ja valige Sätted > Süsteem > Teave Või Valige järgmine teave otsetee kohta: Teave Avanevas aknas System > About (Teave) kuvatakse Windowsi väljaanne jaotises Windowsi tehnilised andmed väljaande väljaande kõrval Juhised Windowsi uuesti installimiseks meediumiga Windowsi saate uuesti installida, kui olete Windowsisse sisse logitud (kohapealne versioonitäiendus) või Windowsi taastekeskkonnas (puhas install). Valige enda vajadustele kõige paremini vastav suvand. Kohapealne versiooniuuendus Märkus.: Kui kahtlustate, et teie seade on nakatunud, veenduge, et teie viirusetõrjetarkvara oleks ajakohane. Kas teil on video esitamisega probleeme? Vaadake seda YouTube'is . Windowsi installikandja loomine Loodud installikandja ühendamine arvutiga Avage File Explorer ja valige installikandjaga draiv Avage draivi juurkataloogis fail setup.exe ja kui teilt küsitakse, kas soovite lubada rakendusel oma seadmes muudatusi teha, valige Jah . Valige Muuda säilitatava sisu Valige üks järgmistest suvanditest ja seejärel valige Edasi : Säilita isiklikud failid ja rakendused – see säilitab teie isikuandmed, rakendused ja sätted Säilita ainult isiklikud failid – see säilitab teie isikuandmed ja sätted, kuid kõik teie rakendused eemaldatakse Ära säilita midagi – see eemaldab kõik isikuandmed, sätted ja rakendused Lõpetamiseks valige Installi , et alustada Windowsi uuesti installimist oma arvutisse Arvuti võib uuesti installimise ajal mitu korda taaskäivituda. Puhasta install Kui teie arvuti ei käivitu ja teil pole taasteketast või parandusketast, saate Windowsi jaoks installikandja loomiseks kasutada installikandja loomise tööriista . Seda tööriista saab kasutada Windowsi uusima versiooni allalaadimiseks ja algkäivitatava USB-draivi või DVD loomiseks, mida saab seejärel kasutada Windowsi puhta installi tegemiseks. Hoiatus.: Puhas install on täiustatud võimalus, mis aitab seadmes uut seadet alustada. Microsoft soovitab järgida alltoodud juhiseid ainult juhul, kui olete nende muudatuste tegemises kindel. Lisateabe saamiseks pöörduge klienditoe poole. Puhas install eemaldab kõik järgmised üksused. Isiklikud failid Rakendused Seadme tootja kohandused Sätetes tehtud muudatused Looge töötavas arvutis Windowsi installikandja Ühendage loodud installikandja mittetöötava arvutiga. Arvuti käivitamine installikandja abil Märkus.: Uurige arvuti tootjalt, kuidas käivitada arvuti kandja abil. Windows 11 häälestamine käivitub pärast seda, kui seade Windowsi installikandjalt käivitub. Kui te seadistuskuva ei näe, pole teie arvuti seadistuses algkäivitus väliselt andmekandjalt lubatud. Vaadake arvutitootja veebisaiti, et saada teavet selle kohta, kuidas arvuti algkäivitusjärjestust muuta, ja proovige siis uuesti. Valige aknas Keelesätete valimine keele- ja lokaliseerimissätted ning seejärel valige Edasi Valige aknas Klaviatuurisätete valimine klaviatuurisätted ja seejärel valige Edasi . Valige aknas Häälestuse valimine käsk Installi Windows 11 , valige Nõustun, et kõik kustutatakse (sh failid, rakendused ja sätted) ning seejärel valige Edasi Kui kuvatakse aken Tootevõti , tehke järgmist. Valige Mul pole tootevõtit Valige kuvatavas aknas Pildi valimine seadmesse installitud Windowsi väljaanne, nagu on määratletud jaotises Uuesti installitav Windowsi väljaanne peab vastama teie litsentsile . Kui õige Windowsi väljaanne on valitud, valige Edasi . Kui Windows on uuesti installitud, rakendab Windows tootevõtme automaatselt, võttes aluseks teie Microsofti kontoga lingitud tootevõtme. Hoiatus.: Kui teil pole tootevõtit ja teie tootevõti pole teie Microsofti kontoga seotud, ärge jätkake edasi. Selle asemel tühistage Windowsi installiprogramm, sulgedes akna ja seejärel järgige juhiseid jaotises Digitaallitsentsi linkimine Oma Microsofti kontoga enne Windowsi uuesti installimist . Märkus.: Tootevõtme akent ei pruugita kuvada. Näiteks kui Windowsi installiprogramm leiab seadme püsivarast talletatud tootevõtme, rakendatakse see tootevõti automaatselt ja akent Tootevõti ei kuvata. Valige aknas Kohaldatavad teated ja litsentsitingimused nupp Aktsepteeri Tehke aknas Windows 11 installitava asukoha valimine järgmist. Kustutage kõik ketta 0 sektsioonid, mida pole loetletud kui Jaotamata ruum . Sektsioonid kustutatakse, kui valite ja tõstate iga partitsiooni eraldi esile ning seejärel valite ❌Kustuta sektsioon Hoiatus.: Kui seadmel on rohkem kui üks ketas, võib loendis olla ka rohkem kettaid, näiteks Ketas 1 . Ärge muutke ega kustutage sektsioone muudel ketastel peale ketta 0 . Kui kõik ketta 0 sektsioonid on kustutatud, peaks alles olema ainult üks üksus nimega Disk 0 Jaotamata ruum . Veenduge, et ketta 0 jaotamata ruum oleks valitud ja esile tõstetud, ning seejärel valige Edasi Aknas Installimiseks valmis valige Installi Algab Windowsi uuesti installimine. Seade taaskäivitub uuesti installimise ajal mitu korda Kui Windows on uuesti installimise lõpetanud, järgige Windowsi konfigureerimisviisardi juhiseid ja konfigureerige sätted vastavalt soovile. Looge kindlasti ühendus Microsofti kontoga ja logige sisse, et teie Microsofti kontole salvestatud digitaallitsents ja tootevõti rakendataks Windowsis õigesti TELLIGE RSS-KANALID Kas vajate veel abi? Kas soovite rohkem valikuvariante? Tutvustus Kogukonnafoorum Siin saate tutvuda tellimusega kaasnevate eelistega, sirvida koolituskursusi, õppida seadet kaitsma ja teha veel palju muud. Microsoft 365 tellimuse eelised Microsoft 365 koolitus Microsofti turbeteenus Hõlbustuskeskus Kogukonnad aitavad teil küsimusi esitada ja neile vastuseid saada, anda tagasisidet ja saada nõu rikkalike teadmistega asjatundjatelt. Nõu küsimine Microsofti kogukonnafoorumis Microsofti spetsialistide kogukonnafoorum Windows Insideri programmis osalejad Microsoft 365 Insideri programmis osalejad Kas sellest teabest oli abi? Jah Ei Aitäh! Veel tagasisidet Microsoftile? Kas saaksite aidata meil teenust paremaks muuta? (Saatke Microsoftile tagasisidet, et saaksime aidata.) Kui rahul te keelekvaliteediga olete? Mis mõjutas teie hinnangut? Leidsin oma probleemile lahenduse Juhised olid selged Tekstist oli lihtne aru saada Tekstis pole žargooni Piltidest oli abi Tõlkekvaliteet Tekst ei vastanud minu ekraanipildile Valed juhised Liiga tehniline Pole piisavalt teavet Pole piisavalt pilte Tõlkekvaliteet Kas soovite anda veel tagasisidet? (Valikuline) Saada tagasiside Kui klõpsate nuppu Edasta, kasutatakse teie tagasisidet Microsofti toodete ja teenuste täiustamiseks. IT-administraator saab neid andmeid koguda. Privaatsusavaldus. Täname tagasiside eest! × Mis on uut? Copilot organisatsioonidele Copilot isiklikuks kasutuseks Microsoft 365 Windows 11 rakendused Microsoft Store Konto profiil Allalaadimiskeskus Tagastused Tellimuse jälgimine Ringlussevõtt Commercial Warranties Haridus Microsoft Education Haridusseadmed Microsoft Teams haridusasutustele Microsoft 365 Education Office Education Haridustöötajate koolitus ja arendus Pakkumised õpilastele ja vanematele Azure õpilastele Äri Microsofti turve Azure Dynamics 365 Microsoft 365 Microsoft Advertising Microsoft 365 Copilot Microsoft Teamsi jaoks Arendaja ja IT Microsofti arendaja Microsoft Learn Tehisintellekti-turuplatsi rakenduste tugi Microsofti tehnoloogiakogukond Microsoft Marketplace Microsoft Power Platform Marketplace Rewards Visual Studio Ettevõte Töökohad Teave Microsofti kohta Privaatsus Microsoftis Investorid Jätkusuutlikkus Eesti (Eesti) Teie privaatsusvalikutest loobumise ikoon Teie privaatsusvalikud Teie privaatsusvalikutest loobumise ikoon Teie privaatsusvalikud Tarbijaseisundi privaatsus Võtke Microsoftiga ühendust Privaatsus Halda küpsiseid Kasutustingimused Kaubamärgid Reklaamide kohta EU Compliance DoCs © Microsoft 2026 | 2026-01-13T09:30:35 |
https://www.blogger.com/post-edit.g?blogID=1448865833015557942&postID=1092964057029657014&from=pencil | :root{--gm3-sys-color-on-surface-rgb:31,31,31}@media screen and (prefers-color-scheme:dark){:root{--gm3-sys-color-on-surface-rgb:227,227,227}}:root{--wf-harmonize-filter-light:none;--wf-harmonize-filter-dark:none}.q4Wquf,.nfoC7c{display:block;height:25vh;position:relative}@media (min-width:600px){.q4Wquf,.nfoC7c{height:150px}}.q4Wquf.Irjbwb{height:auto}@media screen and (prefers-color-scheme:dark){.q4Wquf:not(.GtvzYd){display:none}}.nfoC7c{margin:0;overflow:hidden}.PwpMUe,.lVUmD{display:block;height:100%;margin:0 auto;width:100%}.St9mde{display:block;-webkit-filter:var(--wf-harmonize-filter-light);filter:var(--wf-harmonize-filter-light);height:100%;max-width:100%;min-height:110px;position:relative;-webkit-transform:translate(-43%,-3%);-ms-transform:translate(-43%,-3%);transform:translate(-43%,-3%);width:auto;z-index:3}@media screen and (prefers-color-scheme:dark){.St9mde{-webkit-filter:var(--wf-harmonize-filter-dark);filter:var(--wf-harmonize-filter-dark)}}.PwpMUe,.lVUmD,.St9mde{-o-object-fit:contain;object-fit:contain}.wsArZ[data-ss-mode="1"] .q4Wquf,.wsArZ[data-ss-mode="1"] .St9mde{height:auto;width:100%}.wsArZ[data-ss-mode="1"] .St9mde{max-width:400px}@media (min-width:600px) and (orientation:landscape),all and (min-width:1600px){.NQ5OL .q4Wquf,.NQ5OL .St9mde{height:auto;width:100%}.NQ5OL .St9mde{max-width:400px}}.q4Wquf.NWba7e,.q4Wquf.NWba7e .St9mde{height:auto}.q4Wquf.NWba7e .St9mde{height:auto;max-width:312px;width:100%}.q4Wquf.NWba7e.zpCp3 .St9mde{max-width:unset}.q4Wquf.IiQozc .St9mde{margin:0 auto;-webkit-transform:none;-ms-transform:none;transform:none}.q4Wquf.Irjbwb .St9mde{height:auto;width:100%}.q4Wquf.EEeaqf .St9mde{max-height:144px;max-width:144px}.SnAaEd{background-image:-webkit-gradient(linear,left top,left bottom,from(rgba(233,233,233,0)),color-stop(62.22%,rgba(233,233,233,0)),color-stop(40.22%,rgb(233,233,233)),to(rgba(233,233,233,0)));background-image:-webkit-linear-gradient(top,rgba(233,233,233,0) 0,rgba(233,233,233,0) 62.22%,rgb(233,233,233) 40.22%,rgba(233,233,233,0) 100%);background-image:linear-gradient(to bottom,rgba(233,233,233,0) 0,rgba(233,233,233,0) 62.22%,rgb(233,233,233) 40.22%,rgba(233,233,233,0) 100%);height:100%;left:0;overflow:hidden;position:absolute;right:0;top:0;z-index:2}@media screen and (prefers-color-scheme:dark){.SnAaEd{display:none}}.SnAaEd::after,.SnAaEd::before{content:"";display:block;height:100%;min-width:110px;position:absolute;right:-10%;-webkit-transform:rotate(-104deg);-ms-transform:rotate(-104deg);transform:rotate(-104deg);width:25vh;z-index:2}@media (min-width:600px){.SnAaEd::after,.SnAaEd::before{width:150px}}.SnAaEd::before{background-image:-webkit-gradient(linear,left top,left bottom,from(rgba(243,243,243,0)),to(rgba(243,243,243,.9)));background-image:-webkit-linear-gradient(top,rgba(243,243,243,0) 0,rgba(243,243,243,.9) 100%);background-image:linear-gradient(to bottom,rgba(243,243,243,0) 0,rgba(243,243,243,.9) 100%);bottom:-10%}.SnAaEd::after{background-image:-webkit-gradient(linear,left top,left bottom,from(rgba(255,255,255,0)),to(rgba(255,255,255,.9)));background-image:-webkit-linear-gradient(top,rgba(255,255,255,0) 0,rgba(255,255,255,.9) 100%);background-image:linear-gradient(to bottom,rgba(255,255,255,0) 0,rgba(255,255,255,.9) 100%);bottom:-80%}.wsArZ[data-ss-mode="1"] .SnAaEd~.St9mde{width:auto}@media (min-width:600px) and (orientation:landscape),all and (min-width:1600px){.NQ5OL .SnAaEd~.St9mde{width:auto}}.RHNWk .St9mde{height:auto}@media (min-width:600px) and (orientation:landscape),all and (min-width:1600px){.NQ5OL .RHNWk .St9mde{width:115px}}.cf660d .St9mde{-webkit-transform:translate(-9%,-3%);-ms-transform:translate(-9%,-3%);transform:translate(-9%,-3%)}.tUhwwc .St9mde{margin:auto;max-height:230px;right:0;top:-3%;-webkit-transform:none;-ms-transform:none;transform:none}.Jkvqxd .St9mde{-webkit-transform:translate(9%,-3%);-ms-transform:translate(9%,-3%);transform:translate(9%,-3%)}.onc8Ic .St9mde{-webkit-transform:translate(var( --c-ps-s,24px ),0);-ms-transform:translate(var( --c-ps-s,24px ),0);transform:translate(var( --c-ps-s,24px ),0)}.WA89Yb .St9mde{-webkit-transform:translate(0,0);-ms-transform:translate(0,0);transform:translate(0,0)}.wsArZ[data-ss-mode="1"] .XEN8Yb .St9mde{max-width:115px}@media (min-width:600px) and (orientation:landscape),all and (min-width:1600px){.NQ5OL .XEN8Yb .St9mde{max-width:115px}}@media (min-width:1240px) and (orientation:landscape),all and (min-width:1600px){.KyPKed .NQ5OL .XEN8Yb .St9mde{max-width:115px}}.IsSr6b .St9mde{max-width:300px}.mmskdd .St9mde{-webkit-transform:none;-ms-transform:none;transform:none}@-webkit-keyframes quantumWizBoxInkSpread{0%{-webkit-transform:translate(-50%,-50%) scale(.2);transform:translate(-50%,-50%) scale(.2)}100%{-webkit-transform:translate(-50%,-50%) scale(2.2);transform:translate(-50%,-50%) scale(2.2)}}@keyframes quantumWizBoxInkSpread{0%{-webkit-transform:translate(-50%,-50%) scale(.2);transform:translate(-50%,-50%) scale(.2)}100%{-webkit-transform:translate(-50%,-50%) scale(2.2);transform:translate(-50%,-50%) scale(2.2)}}@-webkit-keyframes quantumWizIconFocusPulse{0%{-webkit-transform:translate(-50%,-50%) scale(1.5);transform:translate(-50%,-50%) scale(1.5);opacity:0}100%{-webkit-transform:translate(-50%,-50%) scale(2);transform:translate(-50%,-50%) scale(2);opacity:1}}@keyframes quantumWizIconFocusPulse{0%{-webkit-transform:translate(-50%,-50%) scale(1.5);transform:translate(-50%,-50%) scale(1.5);opacity:0}100%{-webkit-transform:translate(-50%,-50%) scale(2);transform:translate(-50%,-50%) scale(2);opacity:1}}@-webkit-keyframes quantumWizRadialInkSpread{0%{-webkit-transform:scale(1.5);transform:scale(1.5);opacity:0}100%{-webkit-transform:scale(2.5);transform:scale(2.5);opacity:1}}@keyframes quantumWizRadialInkSpread{0%{-webkit-transform:scale(1.5);transform:scale(1.5);opacity:0}100%{-webkit-transform:scale(2.5);transform:scale(2.5);opacity:1}}@-webkit-keyframes quantumWizRadialInkFocusPulse{0%{-webkit-transform:scale(2);transform:scale(2);opacity:0}100%{-webkit-transform:scale(2.5);transform:scale(2.5);opacity:1}}@keyframes quantumWizRadialInkFocusPulse{0%{-webkit-transform:scale(2);transform:scale(2);opacity:0}100%{-webkit-transform:scale(2.5);transform:scale(2.5);opacity:1}}:root{--wf-tfs:calc(var(--c-tfs,32)/16*1rem);--wf-tfs-bp2:calc(var(--c-tfs,36)/16*1rem);--wf-tfs-bp3:calc(var(--c-tfs,36)/16*1rem);--wf-tfs-bp5:calc(var(--c-tfs,44)/16*1rem);--wf-stfs:calc(var(--c-stfs,16)/16*1rem);--wf-stfs-bp5:calc(var(--c-stfs,16)/16*1rem)}:root{--wf-harmonize-filter-light:none;--wf-harmonize-filter-dark:none}.Dzz9Db,.GpMPBe{display:block;height:25vh;position:relative}@media (min-width:600px){.Dzz9Db,.GpMPBe{height:150px}}@media screen and (prefers-color-scheme:dark){.Dzz9Db:not(.GtvzYd){display:none}}.Dzz9Db.Irjbwb{height:auto}.GpMPBe{margin:0;overflow:hidden}.UFQPDd,.JNOvdd{display:block;height:100%;margin:0 auto;-o-object-fit:contain;object-fit:contain;width:100%}.f4ZpM{display:block;-webkit-filter:var(--wf-harmonize-filter-light);filter:var(--wf-harmonize-filter-light);height:100%;max-width:100%;min-height:110px;position:relative;-webkit-transform:translate(-43%,-3%);-ms-transform:translate(-43%,-3%);transform:translate(-43%,-3%);width:auto;z-index:3}@media screen and (prefers-color-scheme:dark){.f4ZpM{-webkit-filter:var(--wf-harmonize-filter-dark);filter:var(--wf-harmonize-filter-dark)}}.wsArZ[data-ss-mode="1"] .Dzz9Db,.wsArZ[data-ss-mode="1"] .f4ZpM{height:auto;width:100%}.wsArZ[data-ss-mode="1"] .f4ZpM{max-width:400px}@media (min-width:600px) and (orientation:landscape),all and (min-width:1600px){.NQ5OL .Dzz9Db,.NQ5OL .f4ZpM{height:auto;width:100%}.NQ5OL .f4ZpM{max-width:400px}}.Dzz9Db.utFBGf,.Dzz9Db.utFBGf .f4ZpM{height:auto}.Dzz9Db.utFBGf .f4ZpM{height:auto;max-width:312px;width:100%}.Dzz9Db.utFBGf.zpCp3 .f4ZpM{max-width:unset}.Dzz9Db.IiQozc .f4ZpM{margin:0 auto;-webkit-transform:none;-ms-transform:none;transform:none}.Dzz9Db.Irjbwb .f4ZpM{height:auto;width:100%}.Dzz9Db.EEeaqf .f4ZpM{max-height:144px;max-width:144px}.nPt1pc{background-image:-webkit-gradient(linear,left top,left bottom,from(rgba(233,233,233,0)),color-stop(62.22%,rgba(233,233,233,0)),color-stop(40.22%,rgb(233,233,233)),to(rgba(233,233,233,0)));background-image:-webkit-linear-gradient(top,rgba(233,233,233,0) 0,rgba(233,233,233,0) 62.22%,rgb(233,233,233) 40.22%,rgba(233,233,233,0) 100%);background-image:linear-gradient(to bottom,rgba(233,233,233,0) 0,rgba(233,233,233,0) 62.22%,rgb(233,233,233) 40.22%,rgba(233,233,233,0) 100%);height:100%;left:0;overflow:hidden;position:absolute;right:0;top:0;z-index:2}@media screen and (prefers-color-scheme:dark){.nPt1pc{display:none}}.nPt1pc::after,.nPt1pc::before{content:"";display:block;height:100%;min-width:110px;position:absolute;right:-10%;-webkit-transform:rotate(-104deg);-ms-transform:rotate(-104deg);transform:rotate(-104deg);width:25vh;z-index:2}@media (min-width:600px){.nPt1pc::after,.nPt1pc::before{width:150px}}.nPt1pc::before{background-image:-webkit-gradient(linear,left top,left bottom,from(rgba(243,243,243,0)),to(rgba(243,243,243,.9)));background-image:-webkit-linear-gradient(top,rgba(243,243,243,0) 0,rgba(243,243,243,.9) 100%);background-image:linear-gradient(to bottom,rgba(243,243,243,0) 0,rgba(243,243,243,.9) 100%);bottom:-10%}.nPt1pc::after{background-image:-webkit-gradient(linear,left top,left bottom,from(rgba(255,255,255,0)),to(rgba(255,255,255,.9)));background-image:-webkit-linear-gradient(top,rgba(255,255,255,0) 0,rgba(255,255,255,.9) 100%);background-image:linear-gradient(to bottom,rgba(255,255,255,0) 0,rgba(255,255,255,.9) 100%);bottom:-80%}.wsArZ[data-ss-mode="1"] .nPt1pc~.f4ZpM{width:auto}@media (min-width:600px) and (orientation:landscape),all and (min-width:1600px){.NQ5OL .nPt1pc~.f4ZpM{width:auto}}.ZS7CGc .f4ZpM{height:auto}@media (min-width:600px) and (orientation:landscape),all and (min-width:1600px){.NQ5OL .ZS7CGc .f4ZpM{width:115px}}.qiRZ5e .f4ZpM{-webkit-transform:translate(-9%,-3%);-ms-transform:translate(-9%,-3%);transform:translate(-9%,-3%)}.vIv7Gf .f4ZpM{margin:auto;max-height:230px;right:0;top:-3%;-webkit-transform:none;-ms-transform:none;transform:none}.nvYXVd .f4ZpM{-webkit-transform:translate(9%,-3%);-ms-transform:translate(9%,-3%);transform:translate(9%,-3%)}.uOhnzd .f4ZpM{-webkit-transform:translate(24px,0);-ms-transform:translate(24px,0);transform:translate(24px,0)}.MsYMaf .f4ZpM{-webkit-transform:translate(0,0);-ms-transform:translate(0,0);transform:translate(0,0)}.wsArZ[data-ss-mode="1"] .YIi9qf .f4ZpM{max-width:115px}@media (min-width:600px) and (orientation:landscape),all and (min-width:1600px){.NQ5OL .YIi9qf .f4ZpM{max-width:115px}}.QG3Xbe .f4ZpM{max-width:300px}.F6gtje .f4ZpM{-webkit-transform:none;-ms-transform:none;transform:none}@-webkit-keyframes mdc-ripple-fg-radius-in{from{-webkit-animation-timing-function:cubic-bezier(.4,0,.2,1);animation-timing-function:cubic-bezier(.4,0,.2,1);-webkit-transform:translate(var(--mdc-ripple-fg-translate-start,0)) scale(1);transform:translate(var(--mdc-ripple-fg-translate-start,0)) scale(1)}to{-webkit-transform:translate(var(--mdc-ripple-fg-translate-end,0)) scale(var(--mdc-ripple-fg-scale,1));transform:translate(var(--mdc-ripple-fg-translate-end,0)) scale(var(--mdc-ripple-fg-scale,1))}}@keyframes mdc-ripple-fg-radius-in{from{-webkit-animation-timing-function:cubic-bezier(.4,0,.2,1);animation-timing-function:cubic-bezier(.4,0,.2,1);-webkit-transform:translate(var(--mdc-ripple-fg-translate-start,0)) scale(1);transform:translate(var(--mdc-ripple-fg-translate-start,0)) scale(1)}to{-webkit-transform:translate(var(--mdc-ripple-fg-translate-end,0)) scale(var(--mdc-ripple-fg-scale,1));transform:translate(var(--mdc-ripple-fg-translate-end,0)) scale(var(--mdc-ripple-fg-scale,1))}}@-webkit-keyframes mdc-ripple-fg-opacity-in{from{-webkit-animation-timing-function:linear;animation-timing-function:linear;opacity:0}to{opacity:var(--mdc-ripple-fg-opacity,0)}}@keyframes mdc-ripple-fg-opacity-in{from{-webkit-animation-timing-function:linear;animation-timing-function:linear;opacity:0}to{opacity:var(--mdc-ripple-fg-opacity,0)}}@-webkit-keyframes mdc-ripple-fg-opacity-out{from{-webkit-animation-timing-function:linear;animation-timing-function:linear;opacity:var(--mdc-ripple-fg-opacity,0)}to{opacity:0}}@keyframes mdc-ripple-fg-opacity-out{from{-webkit-animation-timing-function:linear;animation-timing-function:linear;opacity:var(--mdc-ripple-fg-opacity,0)}to{opacity:0}}.VfPpkd-ksKsZd-XxIAqe{--mdc-ripple-fg-size:0;--mdc-ripple-left:0;--mdc-ripple-top:0;--mdc-ripple-fg-scale:1;--mdc-ripple-fg-translate-end:0;--mdc-ripple-fg-translate-start:0;-webkit-tap-highlight-color:rgba(0,0,0,0);will-change:transform,opacity;position:relative;outline:none;overflow:hidden}.VfPpkd-ksKsZd-XxIAqe::before,.VfPpkd-ksKsZd-XxIAqe::after{position:absolute;border-radius:50%;opacity:0;pointer-events:none;content:""}.VfPpkd-ksKsZd-XxIAqe::before{-webkit-transition:opacity 15ms linear,background-color 15ms linear;transition:opacity 15ms linear,background-color 15ms linear;z-index:1;z-index:var(--mdc-ripple-z-index,1)}.VfPpkd-ksKsZd-XxIAqe::after{z-index:0;z-index:var(--mdc-ripple-z-index,0)}.VfPpkd-ksKsZd-XxIAqe.VfPpkd-ksKsZd-mWPk3d::before{-webkit-transform:scale(var(--mdc-ripple-fg-scale,1));-ms-transform:scale(var(--mdc-ripple-fg-scale,1));transform:scale(var(--mdc-ripple-fg-scale,1))}.VfPpkd-ksKsZd-XxIAqe.VfPpkd-ksKsZd-mWPk3d::after{top:0;left:0;-webkit-transform:scale(0);-ms-transform:scale(0);transform:scale(0);-webkit-transform-origin:center center;-ms-transform-origin:center center;transform-origin:center center}.VfPpkd-ksKsZd-XxIAqe.VfPpkd-ksKsZd-mWPk3d-OWXEXe-ZNMTqd::after{top:var(--mdc-ripple-top,0);left:var(--mdc-ripple-left,0)}.VfPpkd-ksKsZd-XxIAqe.VfPpkd-ksKsZd-mWPk3d-OWXEXe-Tv8l5d-lJfZMc::after{-webkit-animation:mdc-ripple-fg-radius-in 225ms forwards,mdc-ripple-fg-opacity-in 75ms forwards;animation:mdc-ripple-fg-radius-in 225ms forwards,mdc-ripple-fg-opacity-in 75ms forwards}.VfPpkd-ksKsZd-XxIAqe.VfPpkd-ksKsZd-mWPk3d-OWXEXe-Tv8l5d-OmS1vf::after{-webkit-animation:mdc-ripple-fg-opacity-out .15s;animation:mdc-ripple-fg-opacity-out .15s;-webkit-transform:translate(var(--mdc-ripple-fg-translate-end,0)) scale(var(--mdc-ripple-fg-scale,1));-ms-transform:translate(var(--mdc-ripple-fg-translate-end,0)) scale(var(--mdc-ripple-fg-scale,1));transform:translate(var(--mdc-ripple-fg-translate-end,0)) scale(var(--mdc-ripple-fg-scale,1))}.VfPpkd-ksKsZd-XxIAqe::before,.VfPpkd-ksKsZd-XxIAqe::after{top:-50%;left:-50%;width:200%;height:200%}.VfPpkd-ksKsZd-XxIAqe.VfPpkd-ksKsZd-mWPk3d::after{width:var(--mdc-ripple-fg-size,100%);height:var(--mdc-ripple-fg-size,100%)}.VfPpkd-ksKsZd-XxIAqe[data-mdc-ripple-is-unbounded],.VfPpkd-ksKsZd-mWPk3d-OWXEXe-ZNMTqd{overflow:visible}.VfPpkd-ksKsZd-XxIAqe[data-mdc-ripple-is-unbounded]::before,.VfPpkd-ksKsZd-XxIAqe[data-mdc-ripple-is-unbounded]::after,.VfPpkd-ksKsZd-mWPk3d-OWXEXe-ZNMTqd::before,.VfPpkd-ksKsZd-mWPk3d-OWXEXe-ZNMTqd::after{top:0;left:0;width:100%;height:100%}.VfPpkd-ksKsZd-XxIAqe[data-mdc-ripple-is-unbounded].VfPpkd-ksKsZd-mWPk3d::before,.VfPpkd-ksKsZd-XxIAqe[data-mdc-ripple-is-unbounded].VfPpkd-ksKsZd-mWPk3d::after,.VfPpkd-ksKsZd-mWPk3d-OWXEXe-ZNMTqd.VfPpkd-ksKsZd-mWPk3d::before,.VfPpkd-ksKsZd-mWPk3d-OWXEXe-ZNMTqd.VfPpkd-ksKsZd-mWPk3d::after{top:var(--mdc-ripple-top,0);left:var(--mdc-ripple-left,0);width:var(--mdc-ripple-fg-size,100%);height:var(--mdc-ripple-fg-size,100%)}.VfPpkd-ksKsZd-XxIAqe[data-mdc-ripple-is-unbounded].VfPpkd-ksKsZd-mWPk3d::after,.VfPpkd-ksKsZd-mWPk3d-OWXEXe-ZNMTqd.VfPpkd-ksKsZd-mWPk3d::after{width:var(--mdc-ripple-fg-size,100%);height:var(--mdc-ripple-fg-size,100%)}.VfPpkd-ksKsZd-XxIAqe::before,.VfPpkd-ksKsZd-XxIAqe::after{background-color:#000;background-color:var(--mdc-ripple-color,#000)}.VfPpkd-ksKsZd-XxIAqe:hover::before,.VfPpkd-ksKsZd-XxIAqe.VfPpkd-ksKsZd-XxIAqe-OWXEXe-ZmdkE::before{opacity:.04;opacity:var(--mdc-ripple-hover-opacity,.04)}.VfPpkd-ksKsZd-XxIAqe.VfPpkd-ksKsZd-mWPk3d-OWXEXe-AHe6Kc-XpnDCe::before,.VfPpkd-ksKsZd-XxIAqe:not(.VfPpkd-ksKsZd-mWPk3d):focus::before{-webkit-transition-duration:75ms;transition-duration:75ms;opacity:.12;opacity:var(--mdc-ripple-focus-opacity,.12)}.VfPpkd-ksKsZd-XxIAqe:not(.VfPpkd-ksKsZd-mWPk3d)::after{-webkit-transition:opacity .15s linear;transition:opacity .15s linear}.VfPpkd-ksKsZd-XxIAqe:not(.VfPpkd-ksKsZd-mWPk3d):active::after{-webkit-transition-duration:75ms;transition-duration:75ms;opacity:.12;opacity:var(--mdc-ripple-press-opacity,.12)}.VfPpkd-ksKsZd-XxIAqe.VfPpkd-ksKsZd-mWPk3d{--mdc-ripple-fg-opacity:var(--mdc-ripple-press-opacity,0.12)}.VfPpkd-Bz112c-LgbsSe{font-size:24px;width:48px;height:48px;padding:12px}.VfPpkd-Bz112c-LgbsSe.VfPpkd-Bz112c-LgbsSe-OWXEXe-e5LLRc-SxQuSe .VfPpkd-Bz112c-Jh9lGc{width:40px;height:40px;margin-top:4px;margin-bottom:4px;margin-right:4px;margin-left:4px}.VfPpkd-Bz112c-LgbsSe.VfPpkd-Bz112c-LgbsSe-OWXEXe-e5LLRc-SxQuSe .VfPpkd-Bz112c-J1Ukfc-LhBDec{max-height:40px;max-width:40px}.VfPpkd-Bz112c-LgbsSe:disabled{color:rgba(0,0,0,.38);color:var(--mdc-theme-text-disabled-on-light,rgba(0,0,0,.38))}.VfPpkd-Bz112c-LgbsSe svg,.VfPpkd-Bz112c-LgbsSe img{width:24px;height:24px}.VfPpkd-Bz112c-LgbsSe{display:inline-block;position:relative;-webkit-box-sizing:border-box;box-sizing:border-box;border:none;outline:none;background-color:transparent;fill:currentColor;color:inherit;text-decoration:none;cursor:pointer;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;z-index:0;overflow:visible}.VfPpkd-Bz112c-LgbsSe .VfPpkd-Bz112c-RLmnJb{position:absolute;top:50%;height:48px;left:50%;width:48px;-webkit-transform:translate(-50%,-50%);-ms-transform:translate(-50%,-50%);transform:translate(-50%,-50%)}@media screen and (forced-colors:active){.VfPpkd-Bz112c-LgbsSe.VfPpkd-ksKsZd-mWPk3d-OWXEXe-AHe6Kc-XpnDCe .VfPpkd-Bz112c-J1Ukfc-LhBDec,.VfPpkd-Bz112c-LgbsSe:not(.VfPpkd-ksKsZd-mWPk3d):focus .VfPpkd-Bz112c-J1Ukfc-LhBDec{display:block}}.VfPpkd-Bz112c-LgbsSe:disabled{cursor:default;pointer-events:none}.VfPpkd-Bz112c-LgbsSe[hidden]{display:none}.VfPpkd-Bz112c-LgbsSe-OWXEXe-KVuj8d-Q3DXx{-webkit-box-align:center;-webkit-align-items:center;align-items:center;display:-webkit-inline-box;display:-webkit-inline-flex;display:inline-flex;-webkit-box-pack:center;-webkit-justify-content:center;justify-content:center}.VfPpkd-Bz112c-J1Ukfc-LhBDec{pointer-events:none;border:2px solid transparent;border-radius:6px;-webkit-box-sizing:content-box;box-sizing:content-box;position:absolute;top:50%;left:50%;-webkit-transform:translate(-50%,-50%);-ms-transform:translate(-50%,-50%);transform:translate(-50%,-50%);height:100%;width:100%;display:none}@media screen and (forced-colors:active){.VfPpkd-Bz112c-J1Ukfc-LhBDec{border-color:CanvasText}}.VfPpkd-Bz112c-J1Ukfc-LhBDec::after{content:"";border:2px solid transparent;border-radius:8px;display:block;position:absolute;top:50%;left:50%;-webkit-transform:translate(-50%,-50%);-ms-transform:translate(-50%,-50%);transform:translate(-50%,-50%);height:calc(100% + 4px);width:calc(100% + 4px)}@media screen and (forced-colors:active){.VfPpkd-Bz112c-J1Ukfc-LhBDec::after{border-color:CanvasText}}.VfPpkd-Bz112c-kBDsod{display:inline-block}.VfPpkd-Bz112c-kBDsod.VfPpkd-Bz112c-kBDsod-OWXEXe-IT5dJd,.VfPpkd-Bz112c-LgbsSe-OWXEXe-IT5dJd .VfPpkd-Bz112c-kBDsod{display:none}.VfPpkd-Bz112c-LgbsSe-OWXEXe-IT5dJd .VfPpkd-Bz112c-kBDsod.VfPpkd-Bz112c-kBDsod-OWXEXe-IT5dJd{display:inline-block}.VfPpkd-Bz112c-mRLv6{height:100%;left:0;outline:none;position:absolute;top:0;width:100%}.VfPpkd-Bz112c-LgbsSe{--mdc-ripple-fg-size:0;--mdc-ripple-left:0;--mdc-ripple-top:0;--mdc-ripple-fg-scale:1;--mdc-ripple-fg-translate-end:0;--mdc-ripple-fg-translate-start:0;-webkit-tap-highlight-color:rgba(0,0,0,0);will-change:transform,opacity}.VfPpkd-Bz112c-LgbsSe .VfPpkd-Bz112c-Jh9lGc::before,.VfPpkd-Bz112c-LgbsSe .VfPpkd-Bz112c-Jh9lGc::after{position:absolute;border-radius:50%;opacity:0;pointer-events:none;content:""}.VfPpkd-Bz112c-LgbsSe .VfPpkd-Bz112c-Jh9lGc::before{-webkit-transition:opacity 15ms linear,background-color 15ms linear;transition:opacity 15ms linear,background-color 15ms linear;z-index:1;z-index:var(--mdc-ripple-z-index,1)}.VfPpkd-Bz112c-LgbsSe .VfPpkd-Bz112c-Jh9lGc::after{z-index:0;z-index:var(--mdc-ripple-z-index,0)}.VfPpkd-Bz112c-LgbsSe.VfPpkd-ksKsZd-mWPk3d .VfPpkd-Bz112c-Jh9lGc::before{-webkit-transform:scale(var(--mdc-ripple-fg-scale,1));-ms-transform:scale(var(--mdc-ripple-fg-scale,1));transform:scale(var(--mdc-ripple-fg-scale,1))}.VfPpkd-Bz112c-LgbsSe.VfPpkd-ksKsZd-mWPk3d .VfPpkd-Bz112c-Jh9lGc::after{top:0;left:0;-webkit-transform:scale(0);-ms-transform:scale(0);transform:scale(0);-webkit-transform-origin:center center;-ms-transform-origin:center center;transform-origin:center center}.VfPpkd-Bz112c-LgbsSe.VfPpkd-ksKsZd-mWPk3d-OWXEXe-ZNMTqd .VfPpkd-Bz112c-Jh9lGc::after{top:var(--mdc-ripple-top,0);left:var(--mdc-ripple-left,0)}.VfPpkd-Bz112c-LgbsSe.VfPpkd-ksKsZd-mWPk3d-OWXEXe-Tv8l5d-lJfZMc .VfPpkd-Bz112c-Jh9lGc::after{-webkit-animation:mdc-ripple-fg-radius-in 225ms forwards,mdc-ripple-fg-opacity-in 75ms forwards;animation:mdc-ripple-fg-radius-in 225ms forwards,mdc-ripple-fg-opacity-in 75ms forwards}.VfPpkd-Bz112c-LgbsSe.VfPpkd-ksKsZd-mWPk3d-OWXEXe-Tv8l5d-OmS1vf .VfPpkd-Bz112c-Jh9lGc::after{-webkit-animation:mdc-ripple-fg-opacity-out .15s;animation:mdc-ripple-fg-opacity-out .15s;-webkit-transform:translate(var(--mdc-ripple-fg-translate-end,0)) scale(var(--mdc-ripple-fg-scale,1));-ms-transform:translate(var(--mdc-ripple-fg-translate-end,0)) scale(var(--mdc-ripple-fg-scale,1));transform:translate(var(--mdc-ripple-fg-translate-end,0)) scale(var(--mdc-ripple-fg-scale,1))}.VfPpkd-Bz112c-LgbsSe .VfPpkd-Bz112c-Jh9lGc::before,.VfPpkd-Bz112c-LgbsSe .VfPpkd-Bz112c-Jh9lGc::after{top:0;left:0;width:100%;height:100%}.VfPpkd-Bz112c-LgbsSe.VfPpkd-ksKsZd-mWPk3d .VfPpkd-Bz112c-Jh9lGc::before,.VfPpkd-Bz112c-LgbsSe.VfPpkd-ksKsZd-mWPk3d .VfPpkd-Bz112c-Jh9lGc::after{top:var(--mdc-ripple-top,0);left:var(--mdc-ripple-left,0);width:var(--mdc-ripple-fg-size,100%);height:var(--mdc-ripple-fg-size,100%)}.VfPpkd-Bz112c-LgbsSe.VfPpkd-ksKsZd-mWPk3d .VfPpkd-Bz112c-Jh9lGc::after{width:var(--mdc-ripple-fg-size,100%);height:var(--mdc-ripple-fg-size,100%)}.VfPpkd-Bz112c-LgbsSe .VfPpkd-Bz112c-Jh9lGc::before,.VfPpkd-Bz112c-LgbsSe .VfPpkd-Bz112c-Jh9lGc::after{background-color:#000;background-color:var(--mdc-ripple-color,#000)}.VfPpkd-Bz112c-LgbsSe:hover .VfPpkd-Bz112c-Jh9lGc::before,.VfPpkd-Bz112c-LgbsSe.VfPpkd-ksKsZd-XxIAqe-OWXEXe-ZmdkE .VfPpkd-Bz112c-Jh9lGc::before{opacity:.04;opacity:var(--mdc-ripple-hover-opacity,.04)}.VfPpkd-Bz112c-LgbsSe.VfPpkd-ksKsZd-mWPk3d-OWXEXe-AHe6Kc-XpnDCe .VfPpkd-Bz112c-Jh9lGc::before,.VfPpkd-Bz112c-LgbsSe:not(.VfPpkd-ksKsZd-mWPk3d):focus .VfPpkd-Bz112c-Jh9lGc::before{-webkit-transition-duration:75ms;transition-duration:75ms;opacity:.12;opacity:var(--mdc-ripple-focus-opacity,.12)}.VfPpkd-Bz112c-LgbsSe:not(.VfPpkd-ksKsZd-mWPk3d) .VfPpkd-Bz112c-Jh9lGc::after{-webkit-transition:opacity .15s linear;transition:opacity .15s linear}.VfPpkd-Bz112c-LgbsSe:not(.VfPpkd-ksKsZd-mWPk3d):active .VfPpkd-Bz112c-Jh9lGc::after{-webkit-transition-duration:75ms;transition-duration:75ms;opacity:.12;opacity:var(--mdc-ripple-press-opacity,.12)}.VfPpkd-Bz112c-LgbsSe.VfPpkd-ksKsZd-mWPk3d{--mdc-ripple-fg-opacity:var(--mdc-ripple-press-opacity,0.12)}.VfPpkd-Bz112c-LgbsSe:disabled:hover .VfPpkd-Bz112c-Jh9lGc::before,.VfPpkd-Bz112c-LgbsSe:disabled.VfPpkd-ksKsZd-XxIAqe-OWXEXe-ZmdkE .VfPpkd-Bz112c-Jh9lGc::before{opacity:0;opacity:var(--mdc-ripple-hover-opacity,0)}.VfPpkd-Bz112c-LgbsSe:disabled.VfPpkd-ksKsZd-mWPk3d-OWXEXe-AHe6Kc-XpnDCe .VfPpkd-Bz112c-Jh9lGc::before,.VfPpkd-Bz112c-LgbsSe:disabled:not(.VfPpkd-ksKsZd-mWPk3d):focus .VfPpkd-Bz112c-Jh9lGc::before{-webkit-transition-duration:75ms;transition-duration:75ms;opacity:0;opacity:var(--mdc-ripple-focus-opacity,0)}.VfPpkd-Bz112c-LgbsSe:disabled:not(.VfPpkd-ksKsZd-mWPk3d) .VfPpkd-Bz112c-Jh9lGc::after{-webkit-transition:opacity .15s linear;transition:opacity .15s linear}.VfPpkd-Bz112c-LgbsSe:disabled:not(.VfPpkd-ksKsZd-mWPk3d):active .VfPpkd-Bz112c-Jh9lGc::after{-webkit-transition-duration:75ms;transition-duration:75ms;opacity:0;opacity:var(--mdc-ripple-press-opacity,0)}.VfPpkd-Bz112c-LgbsSe:disabled.VfPpkd-ksKsZd-mWPk3d{--mdc-ripple-fg-opacity:var(--mdc-ripple-press-opacity,0)}.VfPpkd-Bz112c-LgbsSe .VfPpkd-Bz112c-Jh9lGc{height:100%;left:0;pointer-events:none;position:absolute;top:0;width:100%;z-index:-1}.VfPpkd-dgl2Hf-ppHlrf-sM5MNb{display:inline}.VfPpkd-LgbsSe{position:relative;display:-webkit-inline-box;display:-webkit-inline-flex;display:inline-flex;-webkit-box-align:center;-webkit-align-items:center;align-items:center;-webkit-box-pack:center;-webkit-justify-content:center;justify-content:center;-webkit-box-sizing:border-box;box-sizing:border-box;min-width:64px;border:none;outline:none;line-height:inherit;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;-webkit-appearance:none;overflow:visible;vertical-align:middle;background:transparent}.VfPpkd-LgbsSe .VfPpkd-BFbNVe-bF1uUb{width:100%;height:100%;top:0;left:0}.VfPpkd-LgbsSe::-moz-focus-inner{padding:0;border:0}.VfPpkd-LgbsSe:active{outline:none}.VfPpkd-LgbsSe:hover{cursor:pointer}.VfPpkd-LgbsSe:disabled{cursor:default;pointer-events:none}.VfPpkd-LgbsSe[hidden]{display:none}.VfPpkd-LgbsSe .VfPpkd-kBDsod{margin-left:0;margin-right:8px;display:inline-block;position:relative;vertical-align:top}[dir=rtl] .VfPpkd-LgbsSe .VfPpkd-kBDsod,.VfPpkd-LgbsSe .VfPpkd-kBDsod[dir=rtl]{margin-left:8px;margin-right:0}.VfPpkd-LgbsSe .VfPpkd-UdE5de-uDEFge{font-size:0;position:absolute;-webkit-transform:translate(-50%,-50%);-ms-transform:translate(-50%,-50%);transform:translate(-50%,-50%);top:50%;left:50%;line-height:normal}.VfPpkd-LgbsSe .VfPpkd-vQzf8d{position:relative}.VfPpkd-LgbsSe .VfPpkd-J1Ukfc-LhBDec{pointer-events:none;border:2px solid transparent;border-radius:6px;-webkit-box-sizing:content-box;box-sizing:content-box;position:absolute;top:50%;left:50%;-webkit-transform:translate(-50%,-50%);-ms-transform:translate(-50%,-50%);transform:translate(-50%,-50%);height:calc(100% + 4px);width:calc(100% + 4px);display:none}@media screen and (forced-colors:active){.VfPpkd-LgbsSe .VfPpkd-J1Ukfc-LhBDec{border-color:CanvasText}}.VfPpkd-LgbsSe .VfPpkd-J1Ukfc-LhBDec::after{content:"";border:2px solid transparent;border-radius:8px;display:block;position:absolute;top:50%;left:50%;-webkit-transform:translate(-50%,-50%);-ms-transform:translate(-50%,-50%);transform:translate(-50%,-50%);height:calc(100% + 4px);width:calc(100% + 4px)}@media screen and (forced-colors:active){.VfPpkd-LgbsSe .VfPpkd-J1Ukfc-LhBDec::after{border-color:CanvasText}}@media screen and (forced-colors:active){.VfPpkd-LgbsSe.VfPpkd-ksKsZd-mWPk3d-OWXEXe-AHe6Kc-XpnDCe .VfPpkd-J1Ukfc-LhBDec,.VfPpkd-LgbsSe:not(.VfPpkd-ksKsZd-mWPk3d):focus .VfPpkd-J1Ukfc-LhBDec{display:block}}.VfPpkd-LgbsSe .VfPpkd-RLmnJb{position:absolute;top:50%;height:48px;left:0;right:0;-webkit-transform:translateY(-50%);-ms-transform:translateY(-50%);transform:translateY(-50%)}.VfPpkd-vQzf8d+.VfPpkd-kBDsod{margin-left:8px;margin-right:0}[dir=rtl] .VfPpkd-vQzf8d+.VfPpkd-kBDsod,.VfPpkd-vQzf8d+.VfPpkd-kBDsod[dir=rtl]{margin-left:0;margin-right:8px}svg.VfPpkd-kBDsod{fill:currentColor}.VfPpkd-LgbsSe-OWXEXe-dgl2Hf{margin-top:6px;margin-bottom:6px}.VfPpkd-LgbsSe{-moz-osx-font-smoothing:grayscale;-webkit-font-smoothing:antialiased;text-decoration:none}.VfPpkd-LgbsSe{padding:0 8px 0 8px}.VfPpkd-LgbsSe-OWXEXe-k8QpJ{-webkit-transition:-webkit-box-shadow .28s cubic-bezier(.4,0,.2,1);transition:-webkit-box-shadow .28s cubic-bezier(.4,0,.2,1);transition:box-shadow .28s cubic-bezier(.4,0,.2,1);transition:box-shadow .28s cubic-bezier(.4,0,.2,1),-webkit-box-shadow .28s cubic-bezier(.4,0,.2,1);padding:0 16px 0 16px}.VfPpkd-LgbsSe-OWXEXe-k8QpJ.VfPpkd-LgbsSe-OWXEXe-Bz112c-UbuQg{padding:0 12px 0 16px}.VfPpkd-LgbsSe-OWXEXe-k8QpJ.VfPpkd-LgbsSe-OWXEXe-Bz112c-M1Soyc{padding:0 16px 0 12px}.VfPpkd-LgbsSe-OWXEXe-MV7yeb{-webkit-transition:-webkit-box-shadow .28s cubic-bezier(.4,0,.2,1);transition:-webkit-box-shadow .28s cubic-bezier(.4,0,.2,1);transition:box-shadow .28s cubic-bezier(.4,0,.2,1);transition:box-shadow .28s cubic-bezier(.4,0,.2,1),-webkit-box-shadow .28s cubic-bezier(.4,0,.2,1);padding:0 16px 0 16px}.VfPpkd-LgbsSe-OWXEXe-MV7yeb.VfPpkd-LgbsSe-OWXEXe-Bz112c-UbuQg{padding:0 12px 0 16px}.VfPpkd-LgbsSe-OWXEXe-MV7yeb.VfPpkd-LgbsSe-OWXEXe-Bz112c-M1Soyc{padding:0 16px 0 12px}.VfPpkd-LgbsSe-OWXEXe-INsAgc{border-style:solid;-webkit-transition:border .28s cubic-bezier(.4,0,.2,1);transition:border .28s cubic-bezier(.4,0,.2,1)}.VfPpkd-LgbsSe-OWXEXe-INsAgc .VfPpkd-Jh9lGc{border-style:solid;border-color:transparent}.VfPpkd-LgbsSe{--mdc-ripple-fg-size:0;--mdc-ripple-left:0;--mdc-ripple-top:0;--mdc-ripple-fg-scale:1;--mdc-ripple-fg-translate-end:0;--mdc-ripple-fg-translate-start:0;-webkit-tap-highlight-color:rgba(0,0,0,0);will-change:transform,opacity}.VfPpkd-LgbsSe .VfPpkd-Jh9lGc::before,.VfPpkd-LgbsSe .VfPpkd-Jh9lGc::after{position:absolute;border-radius:50%;opacity:0;pointer-events:none;content:""}.VfPpkd-LgbsSe .VfPpkd-Jh9lGc::before{-webkit-transition:opacity 15ms linear,background-color 15ms linear;transition:opacity 15ms linear,background-color 15ms linear;z-index:1}.VfPpkd-LgbsSe .VfPpkd-Jh9lGc::after{z-index:0}.VfPpkd-LgbsSe.VfPpkd-ksKsZd-mWPk3d .VfPpkd-Jh9lGc::before{-webkit-transform:scale(var(--mdc-ripple-fg-scale,1));-ms-transform:scale(var(--mdc-ripple-fg-scale,1));transform:scale(var(--mdc-ripple-fg-scale,1))}.VfPpkd-LgbsSe.VfPpkd-ksKsZd-mWPk3d .VfPpkd-Jh9lGc::after{top:0;left:0;-webkit-transform:scale(0);-ms-transform:scale(0);transform:scale(0);-webkit-transform-origin:center center;-ms-transform-origin:center center;transform-origin:center center}.VfPpkd-LgbsSe.VfPpkd-ksKsZd-mWPk3d-OWXEXe-ZNMTqd .VfPpkd-Jh9lGc::after{top:var(--mdc-ripple-top,0);left:var(--mdc-ripple-left,0)}.VfPpkd-LgbsSe.VfPpkd-ksKsZd-mWPk3d-OWXEXe-Tv8l5d-lJfZMc .VfPpkd-Jh9lGc::after{-webkit-animation:mdc-ripple-fg-radius-in 225ms forwards,mdc-ripple-fg-opacity-in 75ms forwards;animation:mdc-ripple-fg-radius-in 225ms forwards,mdc-ripple-fg-opacity-in 75ms forwards}.VfPpkd-LgbsSe.VfPpkd-ksKsZd-mWPk3d-OWXEXe-Tv8l5d-OmS1vf .VfPpkd-Jh9lGc::after{-webkit-animation:mdc-ripple-fg-opacity-out .15s;animation:mdc-ripple-fg-opacity-out .15s;-webkit-transform:translate(var(--mdc-ripple-fg-translate-end,0)) scale(var(--mdc-ripple-fg-scale,1));-ms-transform:translate(var(--mdc-ripple-fg-translate-end,0)) scale(var(--mdc-ripple-fg-scale,1));transform:translate(var(--mdc-ripple-fg-translate-end,0)) scale(var(--mdc-ripple-fg-scale,1))}.VfPpkd-LgbsSe .VfPpkd-Jh9lGc::before,.VfPpkd-LgbsSe .VfPpkd-Jh9lGc::after{top:-50%;left:-50%;width:200%;height:200%}.VfPpkd-LgbsSe.VfPpkd-ksKsZd-mWPk3d .VfPpkd-Jh9lGc::after{width:var(--mdc-ripple-fg-size,100%);height:var(--mdc-ripple-fg-size,100%)}.VfPpkd-Jh9lGc{position:absolute;-webkit-box-sizing:content-box;box-sizing:content-box;overflow:hidden;z-index:0;top:0;left:0;bottom:0;right:0}.VfPpkd-LgbsSe{font-family:Roboto,sans-serif;font-size:.875rem;letter-spacing:.0892857143em;font-weight:500;text-transform:uppercase;height:36px;border-radius:4px}.VfPpkd-LgbsSe:not(:disabled){color:#6200ee}.VfPpkd-LgbsSe:disabled{color:rgba(0,0,0,.38)}.VfPpkd-LgbsSe .VfPpkd-kBDsod{font-size:1.125rem;width:1.125rem;height:1.125rem}.VfPpkd-LgbsSe .VfPpkd-Jh9lGc::before{background-color:#6200ee}.VfPpkd-LgbsSe .VfPpkd-Jh9lGc::after{background-color:#6200ee}.VfPpkd-LgbsSe:hover .VfPpkd-Jh9lGc::before,.VfPpkd-LgbsSe.VfPpkd-ksKsZd-XxIAqe-OWXEXe-ZmdkE .VfPpkd-Jh9lGc::before{opacity:.04}.VfPpkd-LgbsSe.VfPpkd-ksKsZd-mWPk3d-OWXEXe-AHe6Kc-XpnDCe .VfPpkd-Jh9lGc::before,.VfPpkd-LgbsSe:not(.VfPpkd-ksKsZd-mWPk3d):focus .VfPpkd-Jh9lGc::before{-webkit-transition-duration:75ms;transition-duration:75ms;opacity:.12}.VfPpkd-LgbsSe:not(.VfPpkd-ksKsZd-mWPk3d) .VfPpkd-Jh9lGc::after{-webkit-transition:opacity .15s linear;transition:opacity .15s linear}.VfPpkd-LgbsSe:not(.VfPpkd-ksKsZd-mWPk3d):active .VfPpkd-Jh9lGc::after{-webkit-transition-duration:75ms;transition-duration:75ms;opacity:.12}.VfPpkd-LgbsSe.VfPpkd-ksKsZd-mWPk3d{--mdc-ripple-fg-opacity:var(--mdc-text-button-pressed-state-layer-opacity,0.12)}.VfPpkd-LgbsSe .VfPpkd-Jh9lGc{border-radius:4px}.VfPpkd-LgbsSe .VfPpkd-J1Ukfc-LhBDec{border-radius:2px}.VfPpkd-LgbsSe .VfPpkd-J1Ukfc-LhBDec::after{border-radius:4px}.VfPpkd-LgbsSe-OWXEXe-k8QpJ{font-family:Roboto,sans-serif;font-size:.875rem;letter-spacing:.0892857143em;font-weight:500;text-transform:uppercase;height:36px;border-radius:4px}.VfPpkd-LgbsSe-OWXEXe-k8QpJ:not(:disabled){background-color:#6200ee}.VfPpkd-LgbsSe-OWXEXe-k8QpJ:disabled{background-color:rgba(0,0,0,.12)}.VfPpkd-LgbsSe-OWXEXe-k8QpJ:not(:disabled){color:#fff}.VfPpkd-LgbsSe-OWXEXe-k8QpJ:disabled{color:rgba(0,0,0,.38)}.VfPpkd-LgbsSe-OWXEXe-k8QpJ .VfPpkd-kBDsod{font-size:1.125rem;width:1.125rem;height:1.125rem}.VfPpkd-LgbsSe-OWXEXe-k8QpJ .VfPpkd-Jh9lGc::before{background-color:#fff}.VfPpkd-LgbsSe-OWXEXe-k8QpJ .VfPpkd-Jh9lGc::after{background-color:#fff}.VfPpkd-LgbsSe-OWXEXe-k8QpJ:hover .VfPpkd-Jh9lGc::before,.VfPpkd-LgbsSe-OWXEXe-k8QpJ.VfPpkd-ksKsZd-XxIAqe-OWXEXe-ZmdkE .VfPpkd-Jh9lGc::before{opacity:.08}.VfPpkd-LgbsSe-OWXEXe-k8QpJ.VfPpkd-ksKsZd-mWPk3d-OWXEXe-AHe6Kc-XpnDCe .VfPpkd-Jh9lGc::before,.VfPpkd-LgbsSe-OWXEXe-k8QpJ:not(.VfPpkd-ksKsZd-mWPk3d):focus .VfPpkd-Jh9lGc::before{-webkit-transition-duration:75ms;transition-duration:75ms;opacity:.24}.VfPpkd-LgbsSe-OWXEXe-k8QpJ:not(.VfPpkd-ksKsZd-mWPk3d) .VfPpkd-Jh9lGc::after{-webkit-transition:opacity .15s linear;transition:opacity .15s linear}.VfPpkd-LgbsSe-OWXEXe-k8QpJ:not(.VfPpkd-ksKsZd-mWPk3d):active .VfPpkd-Jh9lGc::after{-webkit-transition-duration:75ms;transition-duration:75ms;opacity:.24}.VfPpkd-LgbsSe-OWXEXe-k8QpJ.VfPpkd-ksKsZd-mWPk3d{--mdc-ripple-fg-opacity:var(--mdc-filled-button-pressed-state-layer-opacity,0.24)}.VfPpkd-LgbsSe-OWXEXe-k8QpJ .VfPpkd-Jh9lGc{border-radius:4px}.VfPpkd-LgbsSe-OWXEXe-k8QpJ .VfPpkd-J1Ukfc-LhBDec{border-radius:2px}.VfPpkd-LgbsSe-OWXEXe-k8QpJ .VfPpkd-J1Ukfc-LhBDec::after{border-radius:4px}.VfPpkd-LgbsSe-OWXEXe-MV7yeb{font-family:Roboto,sans-serif;font-size:.875rem;letter-spacing:.0892857143em;font-weight:500;text-transform:uppercase;height:36px;border-radius:4px;-webkit-box-shadow:0 3px 1px -2px rgba(0,0,0,.2),0 2px 2px 0 rgba(0,0,0,.14),0 1px 5px 0 rgba(0,0,0,.12);box-shadow:0 3px 1px -2px rgba(0,0,0,.2),0 2px 2px 0 rgba(0,0,0,.14),0 1px 5px 0 rgba(0,0,0,.12)}.VfPpkd-LgbsSe-OWXEXe-MV7yeb:not(:disabled){background-color:#6200ee}.VfPpkd-LgbsSe-OWXEXe-MV7yeb:disabled{background-color:rgba(0,0,0,.12)}.VfPpkd-LgbsSe-OWXEXe-MV7yeb:not(:disabled){color:#fff}.VfPpkd-LgbsSe-OWXEXe-MV7yeb:disabled{color:rgba(0,0,0,.38)}.VfPpkd-LgbsSe-OWXEXe-MV7yeb .VfPpkd-kBDsod{font-size:1.125rem;width:1.125rem;height:1.125rem}.VfPpkd-LgbsSe-OWXEXe-MV7yeb .VfPpkd-Jh9lGc::before{background-color:#fff}.VfPpkd-LgbsSe-OWXEXe-MV7yeb .VfPpkd-Jh9lGc::after{background-color:#fff}.VfPpkd-LgbsSe-OWXEXe-MV7yeb:hover .VfPpkd-Jh9lGc::before,.VfPpkd-LgbsSe-OWXEXe-MV7yeb.VfPpkd-ksKsZd-XxIAqe-OWXEXe-ZmdkE .VfPpkd-Jh9lGc::before{opacity:.08}.VfPpkd-LgbsSe-OWXEXe-MV7yeb.VfPpkd-ksKsZd-mWPk3d-OWXEXe-AHe6Kc-XpnDCe .VfPpkd-Jh9lGc::before,.VfPpkd-LgbsSe-OWXEXe-MV7yeb:not(.VfPpkd-ksKsZd-mWPk3d):focus .VfPpkd-Jh9lGc::before{-webkit-transition-duration:75ms;transition-duration:75ms;opacity:.24}.VfPpkd-LgbsSe-OWXEXe-MV7yeb:not(.VfPpkd-ksKsZd-mWPk3d) .VfPpkd-Jh9lGc::after{-webkit-transition:opacity .15s linear;transition:opacity .15s linear}.VfPpkd-LgbsSe-OWXEXe-MV7yeb:not(.VfPpkd-ksKsZd-mWPk3d):active .VfPpkd-Jh9lGc::after{-webkit-transition-duration:75ms;transition-duration:75ms;opacity:.24}.VfPpkd-LgbsSe-OWXEXe-MV7yeb.VfPpkd-ksKsZd-mWPk3d{--mdc-ripple-fg-opacity:var(--mdc-protected-button-pressed-state-layer-opacity,0.24)}.VfPpkd-LgbsSe-OWXEXe-MV7yeb .VfPpkd-Jh9lGc{border-radius:4px}.VfPpkd-LgbsSe-OWXEXe-MV7yeb .VfPpkd-J1Ukfc-LhBDec{border-radius:2px}.VfPpkd-LgbsSe-OWXEXe-MV7yeb .VfPpkd-J1Ukfc-LhBDec::after{border-radius:4px}.VfPpkd-LgbsSe-OWXEXe-MV7yeb.VfPpkd-ksKsZd-mWPk3d-OWXEXe-AHe6Kc-XpnDCe,.VfPpkd-LgbsSe-OWXEXe-MV7yeb:not(.VfPpkd-ksKsZd-mWPk3d):focus{-webkit-box-shadow:0 2px 4px -1px rgba(0,0,0,.2),0 4px 5px 0 rgba(0,0,0,.14),0 1px 10px 0 rgba(0,0,0,.12);box-shadow:0 2px 4px -1px rgba(0,0,0,.2),0 4px 5px 0 rgba(0,0,0,.14),0 1px 10px 0 rgba(0,0,0,.12)}.VfPpkd-LgbsSe-OWXEXe-MV7yeb:hover{-webkit-box-shadow:0 2px 4px -1px rgba(0,0,0,.2),0 4px 5px 0 rgba(0,0,0,.14),0 1px 10px 0 rgba(0,0,0,.12);box-shadow:0 2px 4px -1px rgba(0,0,0,.2),0 4px 5px 0 rgba(0,0,0,.14),0 1px 10px 0 rgba(0,0,0,.12)}.VfPpkd-LgbsSe-OWXEXe-MV7yeb:not(:disabled):active{-webkit-box-shadow:0 5px 5px -3px rgba(0,0,0,.2),0 8px 10px 1px rgba(0,0,0,.14),0 3px 14px 2px rgba(0,0,0,.12);box-shadow:0 5px 5px -3px rgba(0,0,0,.2),0 8px 10px 1px rgba(0,0,0,.14),0 3px 14px 2px rgba(0,0,0,.12)}.VfPpkd-LgbsSe-OWXEXe-MV7yeb:disabled{-webkit-box-shadow:0 0 0 0 rgba(0,0,0,.2),0 0 0 0 rgba(0,0,0,.14),0 0 0 0 rgba(0,0,0,.12);box-shadow:0 0 0 0 rgba(0,0,0,.2),0 0 0 0 rgba(0,0,0,.14),0 0 0 0 rgba(0,0,0,.12)}.VfPpkd-LgbsSe-OWXEXe-INsAgc{font-family:Roboto,sans-serif;font-size:.875rem;letter-spacing:.0892857143em;font-weight:500;text-transform:uppercase;height:36px;border-radius:4px;padding:0 15px 0 15px;border-width:1px}.VfPpkd-LgbsSe-OWXEXe-INsAgc:not(:disabled){color:#6200ee}.VfPpkd-LgbsSe-OWXEXe-INsAgc:disabled{color:rgba(0,0,0,.38)}.VfPpkd-LgbsSe-OWXEXe-INsAgc .VfPpkd-kBDsod{font-size:1.125rem;width:1.125rem;height:1.125rem}.VfPpkd-LgbsSe-OWXEXe-INsAgc .VfPpkd-Jh9lGc::before{background-color:#6200ee}.VfPpkd-LgbsSe-OWXEXe-INsAgc .VfPpkd-Jh9lGc::after{background-color:#6200ee}.VfPpkd-LgbsSe-OWXEXe-INsAgc:hover .VfPpkd-Jh9lGc::before,.VfPpkd-LgbsSe-OWXEXe-INsAgc.VfPpkd-ksKsZd-XxIAqe-OWXEXe-ZmdkE .VfPpkd-Jh9lGc::before{opacity:.04}.VfPpkd-LgbsSe-OWXEXe-INsAgc.VfPpkd-ksKsZd-mWPk3d-OWXEXe-AHe6Kc-XpnDCe .VfPpkd-Jh9lGc::before,.VfPpkd-LgbsSe-OWXEXe-INsAgc:not(.VfPpkd-ksKsZd-mWPk3d):focus .VfPpkd-Jh9lGc::before{-webkit-transition-duration:75ms;transition-duration:75ms;opacity:.12}.VfPpkd-LgbsSe-OWXEXe-INsAgc:not(.VfPpkd-ksKsZd-mWPk3d) .VfPpkd-Jh9lGc::after{-webkit-transition:opacity .15s linear;transition:opacity .15s linear}.VfPpkd-LgbsSe-OWXEXe-INsAgc:not(.VfPpkd-ksKsZd-mWPk3d):active .VfPpkd-Jh9lGc::after{-webkit-transition-duration:75ms;transition-duration:75ms;opacity:.12}.VfPpkd-LgbsSe-OWXEXe-INsAgc.VfPpkd-ksKsZd-mWPk3d{--mdc-ripple-fg-opacity:var(--mdc-outlined-button-pressed-state-layer-opacity,0.12)}.VfPpkd-LgbsSe-OWXEXe-INsAgc .VfPpkd-Jh9lGc{border-radius:4px}.VfPpkd-LgbsSe-OWXEXe-INsAgc .VfPpkd-J1Ukfc-LhBDec{border-radius:2px}.VfPpkd-LgbsSe-OWXEXe-INsAgc .VfPpkd-J1Ukfc-LhBDec::after{border-radius:4px}.VfPpkd-LgbsSe-OWXEXe-INsAgc:not(:disabled){border-color:rgba(0,0,0,.12)}.VfPpkd-LgbsSe-OWXEXe-INsAgc:disabled{border-color:rgba(0,0,0,.12)}.VfPpkd-LgbsSe-OWXEXe-INsAgc.VfPpkd-LgbsSe-OWXEXe-Bz112c-UbuQg{padding:0 11px 0 15px}.VfPpkd-LgbsSe-OWXEXe-INsAgc.VfPpkd-LgbsSe-OWXEXe-Bz112c-M1Soyc{padding:0 15px 0 11px}.VfPpkd-LgbsSe-OWXEXe-INsAgc .VfPpkd-Jh9lGc{top:-1px;left:-1px;bottom:-1px;right:-1px;border-width:1px}.VfPpkd-LgbsSe-OWXEXe-INsAgc .VfPpkd-RLmnJb{left:-1px;width:calc(100% + 2px)}.nCP5yc{font-family:"Google Sans",Roboto,Arial,sans-serif;font-size:.875rem;letter-spacing:.0107142857em;font-weight:500;text-transform:none;-webkit-transition:border .28s cubic-bezier(.4,0,.2,1),-webkit-box-shadow .28s cubic-bezier(.4,0,.2,1);transition:border .28s cubic-bezier(.4,0,.2,1),-webkit-box-shadow .28s cubic-bezier(.4,0,.2,1);transition:border .28s cubic-bezier(.4,0,.2,1),box-shadow .28s cubic-bezier(.4,0,.2,1);transition:border .28s cubic-bezier(.4,0,.2,1),box-shadow .28s cubic-bezier(.4,0,.2,1),-webkit-box-shadow .28s cubic-bezier(.4,0,.2,1);-webkit-box-shadow:none;box-shadow:none}.nCP5yc .VfPpkd-Jh9lGc{height:100%;position:absolute;overflow:hidden;width:100%;z-index:0}.nCP5yc:not(:disabled){background-color:rgb(26,115,232);background-color:var(--gm-fillbutton-container-color,rgb(26,115,232))}.nCP5yc:not(:disabled){color:#fff;color:var(--gm-fillbutton-ink-color,#fff)}.nCP5yc:disabled{background-color:rgba(60,64,67,.12);background-color:var(--gm-fillbutton-disabled-container-color,rgba(60,64,67,.12))}.nCP5yc:disabled{color:rgba(60,64,67,.38);color:var(--gm-fillbutton-disabled-ink-color,rgba(60,64,67,.38))}.nCP5yc .VfPpkd-Jh9lGc::before,.nCP5yc .VfPpkd-Jh9lGc::after{background-color:rgb(32,33,36);background-color:var(--gm-fillbutton-state-color,rgb(32,33,36))}.nCP5yc:hover .VfPpkd-Jh9lGc::before,.nCP5yc.VfPpkd-ksKsZd-XxIAqe-OWXEXe-ZmdkE .VfPpkd-Jh9lGc::before{opacity:.16;opacity:var(--mdc-ripple-hover-opacity,.16)}.nCP5yc.VfPpkd-ksKsZd-mWPk3d-OWXEXe-AHe6Kc-XpnDCe .VfPpkd-Jh9lGc::before,.nCP5yc:not(.VfPpkd-ksKsZd-mWPk3d):focus .VfPpkd-Jh9lGc::before{-webkit-transition-duration:75ms;transition-duration:75ms;opacity:.24;opacity:var(--mdc-ripple-focus-opacity,.24)}.nCP5yc:not(.VfPpkd-ksKsZd-mWPk3d) .VfPpkd-Jh9lGc::after{-webkit-transition:opacity .15s linear;transition:opacity .15s linear}.nCP5yc:not(.VfPpkd-ksKsZd-mWPk3d):active .VfPpkd-Jh9lGc::after{-webkit-transition-duration:75ms;transition-duration:75ms;opacity:.2;opacity:var(--mdc-ripple-press-opacity,.2)}.nCP5yc.VfPpkd-ksKsZd-mWPk3d{--mdc-ripple-fg-opacity:var(--mdc-ripple-press-opacity,0.2)}.nCP5yc .VfPpkd-BFbNVe-bF1uUb{opacity:0}.nCP5yc .VfPpkd-UdE5de-uDEFge .VfPpkd-JGcpL-uI4vCe-LkdAo,.nCP5yc .VfPpkd-UdE5de-uDEFge .VfPpkd-JGcpL-IdXvz-LkdAo-Bd00G{stroke:#fff}@media (-ms-high-contrast:active),screen and (forced-colors:active){.nCP5yc .VfPpkd-UdE5de-uDEFge .VfPpkd-JGcpL-uI4vCe-LkdAo,.nCP5yc .VfPpkd-UdE5de-uDEFge .VfPpkd-JGcpL-IdXvz-LkdAo-Bd00G{stroke:CanvasText}}.nCP5yc:hover{-webkit-box-shadow:0 1px 2px 0 rgba(60,64,67,.3),0 1px 3px 1px rgba(60,64,67,.15);box-shadow:0 1px 2px 0 rgba(60,64,67,.3),0 1px 3px 1px rgba(60,64,67,.15);-webkit-box-shadow:0 1px 2px 0 var(--gm-fillbutton-keyshadow-color,rgba(60,64,67,.3)),0 1px 3px 1px var(--gm-fillbutton-ambientshadow-color,rgba(60,64,67,.15));box-shadow:0 1px 2px 0 var(--gm-fillbutton-keyshadow-color,rgba(60,64,67,.3)),0 1px 3px 1px var(--gm-fillbutton-ambientshadow-color,rgba(60,64,67,.15))}.nCP5yc:hover .VfPpkd-BFbNVe-bF1uUb{opacity:0}.nCP5yc:active{-webkit-box-shadow:0 1px 2px 0 rgba(60,64,67,.3),0 2px 6px 2px rgba(60,64,67,.15);box-shadow:0 1px 2px 0 rgba(60,64,67,.3),0 2px 6px 2px rgba(60,64,67,.15);-webkit-box-shadow:0 1px 2px 0 var(--gm-fillbutton-keyshadow-color,rgba(60,64,67,.3)),0 2px 6px 2px var(--gm-fillbutton-ambientshadow-color,rgba(60,64,67,.15));box-shadow:0 1px 2px 0 var(--gm-fillbutton-keyshadow-color,rgba(60,64,67,.3)),0 2px 6px 2px var(--gm-fillbutton-ambientshadow-color,rgba(60,64,67,.15))}.nCP5yc:active .VfPpkd-BFbNVe-bF1uUb{opacity:0}.nCP5yc:disabled{-webkit-box-shadow:none;box-shadow:none}.nCP5yc:disabled:hover .VfPpkd-Jh9lGc::before,.nCP5yc:disabled.VfPpkd-ksKsZd-XxIAqe-OWXEXe-ZmdkE .VfPpkd-Jh9lGc::before{opacity:0;opacity:var(--mdc-ripple-hover-opacity,0)}.nCP5yc:disabled.VfPpkd-ksKsZd-mWPk3d-OWXEXe-AHe6Kc-XpnDCe .VfPpkd-Jh9lGc::before,.nCP5yc:disabled:not(.VfPpkd-ksKsZd-mWPk3d):focus .VfPpkd-Jh9lGc::before{-webkit-transition-duration:75ms;transition-duration:75ms;opacity:0;opacity:var(--mdc-ripple-focus-opacity,0)}.nCP5yc:disabled:not(.VfPpkd-ksKsZd-mWPk3d) .VfPpkd-Jh9lGc::after{-webkit-transition:opacity .15s linear;transition:opacity .15s linear}.nCP5yc:disabled:not(.VfPpkd-ksKsZd-mWPk3d):active .VfPpkd-Jh9lGc::after{-webkit-transition-duration:75ms;transition-duration:75ms;opacity:0;opacity:var(--mdc-ripple-press-opacity,0)}.nCP5yc:disabled.VfPpkd-ksKsZd-mWPk3d{--mdc-ripple-fg-opacity:var(--mdc-ripple-press-opacity,0)}.nCP5yc:disabled .VfPpkd-BFbNVe-bF1uUb{opacity:0}.Rj2Mlf{font-family:"Google Sans",Roboto,Arial,sans-serif;font-size:.875rem;letter-spacing:.0107142857em;font-weight:500;text-transform:none;-webkit-transition:border .28s cubic-bezier(.4,0,.2,1),-webkit-box-shadow .28s cubic-bezier(.4,0,.2,1);transition:border .28s cubic-bezier(.4,0,.2,1),-webkit-box-shadow .28s cubic-bezier(.4,0,.2,1);transition:border .28s cubic-bezier(.4,0,.2,1),box-shadow .28s cubic-bezier(.4,0,.2,1);transition:border .28s cubic-bezier(.4,0,.2,1),box-shadow .28s cubic-bezier(.4,0,.2,1),-webkit-box-shadow .28s cubic-bezier(.4,0,.2,1);-webkit-box-shadow:none;box-shadow:none}.Rj2Mlf .VfPpkd-Jh9lGc{height:100%;position:absolute;overflow:hidden;width:100%;z-index:0}.Rj2Mlf:not(:disabled){color:rgb(26,115,232);color:var(--gm-hairlinebutton-ink-color,rgb(26,115,232))}.Rj2Mlf:not(:disabled){border-color:rgb(218,220,224);border-color:var(--gm-hairlinebutton-outline-color,rgb(218,220,224))}.Rj2Mlf:not(:disabled):hover{border-color:rgb(218,220,224);border-color:var(--gm-hairlinebutton-outline-color,rgb(218,220,224))}.Rj2Mlf:not(:disabled).VfPpkd-ksKsZd-mWPk3d-OWXEXe-AHe6Kc-XpnDCe,.Rj2Mlf:not(:disabled):not(.VfPpkd-ksKsZd-mWPk3d):focus{border-color:rgb(23,78,166);border-color:var(--gm-hairlinebutton-outline-color--stateful,rgb(23,78,166))}.Rj2Mlf:not(:disabled):active,.Rj2Mlf:not(:disabled):focus:active{border-color:rgb(218,220,224);border-color:var(--gm-hairlinebutton-outline-color,rgb(218,220,224))}.Rj2Mlf:disabled{color:rgba(60,64,67,.38);color:var(--gm-hairlinebutton-disabled-ink-color,rgba(60,64,67,.38))}.Rj2Mlf:disabled{border-color:rgba(60,64,67,.12);border-color:var(--gm-hairlinebutton-disabled-outline-color,rgba(60,64,67,.12))}.Rj2Mlf:hover:not(:disabled),.Rj2Mlf.VfPpkd-ksKsZd-mWPk3d-OWXEXe-AHe6Kc-XpnDCe:not(:disabled),.Rj2Mlf:not(.VfPpkd-ksKsZd-mWPk3d):focus:not(:disabled),.Rj2Mlf:active:not(:disabled){color:rgb(23,78,166);color:var(--gm-hairlinebutton-ink-color--stateful,rgb(23,78,166))}.Rj2Mlf .VfPpkd-BFbNVe-bF1uUb{opacity:0}.Rj2Mlf .VfPpkd-UdE5de-uDEFge .VfPpkd-JGcpL-uI4vCe-LkdAo,.Rj2Mlf .VfPpkd-UdE5de-uDEFge .VfPpkd-JGcpL-IdXvz-LkdAo-Bd00G{stroke:rgb(26,115,232)}@media (-ms-high-contrast:active),screen and (forced-colors:active){.Rj2Mlf .VfPpkd-UdE5de-uDEFge .VfPpkd-JGcpL-uI4vCe-LkdAo,.Rj2Mlf .VfPpkd-UdE5de-uDEFge .VfPpkd-JGcpL-IdXvz-LkdAo-Bd00G{stroke:CanvasText}}.Rj2Mlf .VfPpkd-Jh9lGc::before,.Rj2Mlf .VfPpkd-Jh9lGc::after{background-color:rgb(26,115,232);background-color:var(--gm-hairlinebutton-state-color,rgb(26,115,232))}.Rj2Mlf:hover .VfPpkd-Jh9lGc::before,.Rj2Mlf.VfPpkd-ksKsZd-XxIAqe-OWXEXe-ZmdkE .VfPpkd-Jh9lGc::before{opacity:.04;opacity:var(--mdc-ripple-hover-opacity,.04)}.Rj2Mlf.VfPpkd-ksKsZd-mWPk3d-OWXEXe-AHe6Kc-XpnDCe .VfPpkd-Jh9lGc::before,.Rj2Mlf:not(.VfPpkd-ksKsZd-mWPk3d):focus .VfPpkd-Jh9lGc::before{-webkit-transition-duration:75ms;transition-duration:75ms;opacity:.12;opacity:var(--mdc-ripple-focus-opacity,.12)}.Rj2Mlf:not(.VfPpkd-ksKsZd-mWPk3d) .VfPpkd-Jh9lGc::after{-webkit-transition:opacity .15s linear;transition:opacity .15s linear}.Rj2Mlf:not(.VfPpkd-ksKsZd-mWPk3d):active .VfPpkd-Jh9lGc::after{-webkit-transition-duration:75ms;transition-duration:75ms;opacity:.12;opacity:var(--mdc-ripple-press-opacity,.12)}.Rj2Mlf.VfPpkd-ksKsZd-mWPk3d{--mdc-ripple-fg-opacity:var(--mdc-ripple-press-opacity,0.12)}.Rj2Mlf:disabled:hover .VfPpkd-Jh9lGc::before,.Rj2Mlf:disabled.VfPpkd-ksKsZd-XxIAqe-OWXEXe-ZmdkE .VfPpkd-Jh9lGc::before{opacity:0;opacity:var(--mdc-ripple-hover-opacity,0)}.Rj2Mlf:disabled.VfPpkd-ksKsZd-mWPk3d-OWXEXe-AHe6Kc-XpnDCe .VfPpkd-Jh9lGc::before,.Rj2Mlf:disabled:not(.VfPpkd-ksKsZd-mWPk3d):focus .VfPpkd-Jh9lGc::before{-webkit-transition-duration:75ms;transition-duration:75ms;opacity:0;opacity:var(--mdc-ripple-focus-opacity,0)}.Rj2Mlf:disabled:not(.VfPpkd-ksKsZd-mWPk3d) .VfPpkd-Jh9lGc::after{-webkit-transition:opacity .15s linear;transition:opacity .15s linear}.Rj2Mlf:disabled:not(.VfPpkd-ksKsZd-mWPk3d):active .VfPpkd-Jh9lGc::after{-webkit-transition-duration:75ms;transition-duration:75ms;opacity:0;opacity:var(--mdc-ripple-press-opacity,0)}.Rj2Mlf:disabled.VfPpkd-ksKsZd-mWPk3d{--mdc-ripple-fg-opacity:var(--mdc-ripple-press-opacity,0)}.b9hyVd{font-family:"Google Sans",Roboto,Arial,sans-serif;font-size:.875rem;letter-spacing:.0107142857em;font-weight:500;text-transform:none;-webkit-transition:border .28s cubic-bezier(.4,0,.2,1),-webkit-box-shadow .28s cubic-bezier(.4,0,.2,1);transition:border .28s cubic-bezier(.4,0,.2,1),-webkit-box-shadow .28s cubic-bezier(.4,0,.2,1);transition:border .28s cubic-bezier(.4,0,.2,1),box-shadow .28s cubic-bezier(.4,0,.2,1);transition:border .28s cubic-bezier(.4,0,.2,1),box-shadow .28s cubic-bezier(.4,0,.2,1),-webkit-box-shadow .28s cubic-bezier(.4,0,.2,1);border-width:0;-webkit-box-shadow:0 1px 2px 0 rgba(60,64,67,.3),0 1px 3px 1px rgba(60,64,67,.15);box-shadow:0 1px 2px 0 rgba(60,64,67,.3),0 1px 3px 1px rgba(60,64,67,.15);-webkit-box-shadow:0 1px 2px 0 var(--gm-protectedbutton-keyshadow-color,rgba(60,64,67,.3)),0 1px 3px 1px var(--gm-protectedbutton-ambientshadow-color,rgba(60,64,67,.15));box-shadow:0 1px 2px 0 var(--gm-protectedbutton-keyshadow-color,rgba(60,64,67,.3)),0 1px 3px 1px var(--gm-protectedbutton-ambientshadow-color,rgba(60,64,67,.15))}.b9hyVd .VfPpkd-Jh9lGc{height:100%;position:absolute;overflow:hidden;width:100%;z-index:0}.b9hyVd:not(:disabled){background-color:#fff;background-color:var(--gm-protectedbutton-container-color,#fff)}.b9hyVd:not(:disabled){color:rgb(26,115,232);color:var(--gm-protectedbutton-ink-color,rgb(26,115,232))}.b9hyVd:disabled{background-color:rgba(60,64,67,.12);background-color:var(--gm-protectedbutton-disabled-container-color,rgba(60,64,67,.12))}.b9hyVd:disabled{color:rgba(60,64,67,.38);color:var(--gm-protectedbutton-disabled-ink-color,rgba(60,64,67,.38))}.b9hyVd:hover:not(:disabled),.b9hyVd.VfPpkd-ksKsZd-mWPk3d-OWXEXe-AHe6Kc-XpnDCe:not(:disabled),.b9hyVd:not(.VfPpkd-ksKsZd-mWPk3d):focus:not(:disabled),.b9hyVd:active:not(:disabled){color:rgb(23,78,166);color:var(--gm-protectedbutton-ink-color--stateful,rgb(23,78,166))}.b9hyVd .VfPpkd-BFbNVe-bF1uUb{opacity:0}.b9hyVd .VfPpkd-UdE5de-uDEFge .VfPpkd-JGcpL-uI4vCe-LkdAo,.b9hyVd .VfPpkd-UdE5de-uDEFge .VfPpkd-JGcpL-IdXvz-LkdAo-Bd00G{stroke:rgb(26,115,232)}@media (-ms-high-contrast:active),screen and (forced-colors:active){.b9hyVd .VfPpkd-UdE5de-uDEFge .VfPpkd-JGcpL-uI4vCe-LkdAo,.b9hyVd .VfPpkd-UdE5de-uDEFge .VfPpkd-JGcpL-IdXvz-LkdAo-B | 2026-01-13T09:30:35 |
https://docs.aws.amazon.com/zh_cn/lambda/latest/dg/configuration-versions.html#versioning-versions-using | 管理 Lambda 函数版本 - AWS Lambda 管理 Lambda 函数版本 - AWS Lambda 文档 AWS Lambda 开发人员指南 创建函数版本 使用版本 授予权限 管理 Lambda 函数版本 您可以使用版本来管理函数的部署。例如,您可以发布函数的新版本用于测试版测试,而不会影响稳定的生产版本的用户。您每次发布函数时,Lambda 都会为函数创建一个新版本。新版本是函数的未发布版本的副本。未发布版本的名为 $LATEST 。 重要的是,每当您部署函数代码时,都会覆盖 $LATEST 中的当前代码。要保存 $LATEST 的当前迭代,请创建一个新的函数版本。如果 $LATEST 与之前发布的版本相同,则在将更改部署到 $LATEST 之前,您无法创建新版本。这些更改可能会包括更新代码或修改函数配置设置。 发布函数版本后,其代码、运行时、架构、内存、层和大多数其他配置设置都不可变。这意味着,如果不从 $LATEST 发布新版本,则无法更改这些设置。您可以为已发布函数版本配置以下项目: 触发 目标 预配置并发 异步调用 数据库连接和代理 注意 在 自动 模式下使用 运行时管理控件 时,此函数版本使用的运行时版本会自动更新。使用 Function update (函数更新)或 Manual (手动)模式时,不会更新运行时版本。有关更多信息,请参阅 了解 Lambda 如何管理运行时版本更新 。 Sections 创建函数版本 使用版本 授予权限 创建函数版本 只能在函数的未发布版本上更改函数代码和设置。在您发布版本时,Lambda 会锁定代码和大多数设置,以便为该版本的用户维持一致的体验。 您可以使用 Lambda 控制台创建函数版本。 创建新函数版本 打开 Lamba 控制台的 函数页面 。 选择一个函数,然后选择 版本 选项卡。 在版本配置页面上,选择 Publish new version(发布新版本) 。 (可选)输入版本说明。 选择 发布 。 或者,您可以使用 PublishVersion API 操作发布函数版本。 以下 AWS CLI 命令发布函数的新版本。响应返回有关新版本的配置信息,包括版本号和具有版本后缀的函数 ARN。 aws lambda publish-version --function-name my-function 您应看到以下输出: { "FunctionName": "my-function", "FunctionArn": "arn:aws:lambda:us-east-2:123456789012:function:my-function:1", "Version": "1", "Role": "arn:aws:iam::123456789012:role/lambda-role", "Handler": "function.handler", "Runtime": "nodejs22.x", ... } 注意 Lambda 会分配单调递增的序列号,以便进行版本控制。Lambda 不会重复使用版本号,即使是删除并重新创建函数之后也是如此。 使用版本 您可以使用限定的 ARN 或非限定的 ARN 来引用您的 Lambda 函数。 限定的 ARN – 具有版本后缀的函数 ARN。以下示例引用 helloworld 函数的版本 42。 arn:aws:lambda:aws-region:acct-id:function:helloworld:42 非限定的 ARN – 不具有版本后缀的函数 ARN。 arn:aws:lambda:aws-region:acct-id:function:helloworld 您可以在所有相关 API 操作中使用限定或非非限定的 ARN。但是,不能使用非限定 ARN 来创建别名。 如果您决定不发布函数版本,可以使用 事件源映射 中的限定或非限定 ARN 来调用函数。当您使用非限定 ARN 调用函数时,Lambda 会隐式调用 $LATEST 。 每个 Lambda 函数版本的限定 ARN 都是唯一的。发布版本后,您无法更改 ARN 或函数代码。 Lambda 仅在代码从未发布过或自上次发布版本后已发生更改时,才会发布新函数版本。如果没有任何更改,函数版本将保持为上次发布的版本。 当您发布版本时,Lambda 会创建函数代码和配置的不可变快照。并非所有配置更改都会触发新版本的发布。以下配置更改使函数有资格发布版本: 函数代码 环境变量 运行时 处理程序 图层 内存大小 超时 VPC 配置 死信队列 (DLQ) 配置 IAM 角色 描述 架构(x86_64 或 arm64) 临时存储大小 包类型 日志记录配置 文件系统配置 SnapStart 跟踪配置 预留并发 等操作设置在更改时不会触发新版本的发布。 授予权限 您可以使用基于 资源的策略 或 基于身份的策略 授予对函数的访问权限。权限的范围取决于您要将策略应用于整个函数还是函数的某个版本。有关策略中的函数资源名称的更多信息,请参阅 微调策略的“资源和条件”部分 。 您可以使用函数别名,简化事件源和 AWS Identity and Access Management (IAM) 策略的管理。有关更多信息,请参阅 为 Lambda 函数创建别名 。 Javascript 在您的浏览器中被禁用或不可用。 要使用 Amazon Web Services 文档,必须启用 Javascript。请参阅浏览器的帮助页面以了解相关说明。 文档惯例 加权别名 标签 此页面对您有帮助吗?- 是 感谢您对我们工作的肯定! 如果不耽误您的时间,请告诉我们做得好的地方,让我们做得更好。 此页面对您有帮助吗?- 否 感谢您告诉我们本页内容还需要完善。很抱歉让您失望了。 如果不耽误您的时间,请告诉我们如何改进文档。 | 2026-01-13T09:30:35 |
https://docs.aws.amazon.com/zh_tw/lambda/latest/dg/with-s3-example.html | 教學課程:使用 Amazon S3 觸發條件調用 Lambda 函數 - AWS Lambda 教學課程:使用 Amazon S3 觸發條件調用 Lambda 函數 - AWS Lambda 文件 AWS Lambda 開發人員指南 建立 Amazon S3 儲存貯體 將測試物件上傳至儲存貯體 建立許可政策 建立執行角色 建立 Lambda 函式 部署函數程式碼 建立 Amazon S3 觸發條件 測試 Lambda 函數 清除您的資源 後續步驟 本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。 教學課程:使用 Amazon S3 觸發條件調用 Lambda 函數 在本教學課程中,您將使用主控台建立 Lambda 函數,並設定 Amazon Simple Storage Service (Amazon S3) 儲存貯體的觸發條件。每當有物件新增至 Amazon S3 儲存貯體,該函數都會執行,然後將物件類型輸出至 Amazon CloudWatch Logs。 本教學課程示範如何。 建立 Amazon S3 儲存貯體。 建立一個 Lambda 函數,用於傳回 Amazon S3 儲存貯體物件的物件類型。 設定一個 Lambda 觸發條件,用於在有物件上傳至儲存貯體時調用函數。 先使用虛擬事件測試函數,再使用觸發條件進行測試。 完成這些步驟後,您將了解如何設定 Lambda 函數,讓函數在 Amazon S3 儲存貯體中有物件新增或刪除時執行。您只能使用 AWS 管理主控台 來完成本教學課程。 建立 Amazon S3 儲存貯體 建立 Amazon S3 儲存貯體 開啟 Amazon S3 主控台 ,然後選取 一般用途儲存貯體 頁面。 選取最 AWS 區域 接近您地理位置的 。可使用螢幕頂端的下拉式清單來變更區域。在本教學課程稍後的階段,您必須在同一區域中建立 Lambda 函數。 選擇 建立儲存貯體 。 在 General configuration (一般組態) 下,執行下列動作: 在 儲存貯體類型 欄位中,選取 一般用途 。 在 儲存貯體名稱 欄位中,輸入符合 Amazon S3 儲存貯體命名規則 的全域唯一名稱。儲存貯體名稱只能包含小寫字母、數字、句點 (.) 和連字號 (-)。 其他所有選項維持設為預設值,然後選擇 建立儲存貯體 。 將測試物件上傳至儲存貯體 上傳測試物件 開啟 Amazon S3 主控台的 儲存貯體 頁面,然後選擇您在上一個步驟中建立的儲存貯體。 選擇 上傳 。 選擇 新增檔案 ,然後選取要上傳的物件。您可以選取任何檔案 (例如 HappyFace.jpg )。 選擇 開啟 ,然後選擇 上傳 。 在本教學課程的稍後部分,您將使用此物件測試 Lambda 函數。 建立許可政策 建立許可政策,以允許 Lambda 從 Amazon S3 儲存貯體取得物件,以及寫入 Amazon CloudWatch Logs。 建立政策 開啟 IAM 主控台中的 政策頁面 。 選擇 建立政策 。 選擇 JSON 索引標籤,然後將下列政策貼到 JSON 編輯器。 JSON { "Version":"2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "logs:PutLogEvents", "logs:CreateLogGroup", "logs:CreateLogStream" ], "Resource": "arn:aws:logs:*:*:*" }, { "Effect": "Allow", "Action": [ "s3:GetObject" ], "Resource": "arn:aws:s3:::*/*" } ] } 選擇下 一步:標籤 。 選擇下 一步:檢閱 。 在 檢閱政策下 ,針對政策 名稱 ,輸入 s3-trigger-tutorial 。 選擇 建立政策 。 建立執行角色 執行角色 是 AWS Identity and Access Management (IAM) 角色,授予 Lambda 函數存取 AWS 服務 和資源的許可。在此步驟中,使用您在上一個步驟中建立的許可政策來建立執行角色。 建立執行角色並附加自訂許可政策 開啟 IAM 主控台中的 角色頁面 。 選擇 建立角色 。 信任的實體類型請選擇 AWS 服務 ,使用案例則選擇 Lambda 。 選擇 下一步 。 在政策搜尋方塊中,輸入 s3-trigger-tutorial 。 在搜尋結果中,選取您建立的政策 ( s3-trigger-tutorial ),然後選擇 下一步 。 在 角色詳細資料 底下, 角色名稱 請輸入 lambda-s3-trigger-role ,然後選擇 建立角色 。 建立 Lambda 函式 使用 Python 3.14 執行時間在主控台中建立 Lambda 函數。 建立 Lambda 函數 開啟 Lambda 主控台中的 函數頁面 。 請確定您使用 AWS 區域 與建立 Amazon S3 儲存貯體相同的 。您可使用螢幕頂端的下拉式清單來變更區域。 選擇 Create function (建立函數) 。 選擇 從頭開始撰寫 在 基本資訊 下,請執行下列動作: 在 函數名稱 輸入 s3-trigger-tutorial 針對 執行期 ,選擇 Python 3.14。 對於 Architecture (架構),選擇 x86_64 。 在 變更預設執行角色 索引標籤中,執行下列操作: 展開索引標籤,然後選擇 使用現有角色 。 選擇您之前建立的 lambda-s3-trigger-role 。 選擇 Create function (建立函數) 。 部署函數程式碼 本教學課程使用 Python 3.14 執行時間,但我們也提供其他執行時間的範例程式碼檔案。您可以在下列方塊中選取索引標籤,查看您感興趣的執行期程式碼。 該 Lambda 函數收到 Amazon S3 傳來的 event 參數後,會從該參數擷取上傳物件的金鑰名稱以及儲存貯體的名稱。然後,函數會使用來自 的 get_object 適用於 Python (Boto3) 的 AWS SDK 方法來擷取物件的中繼資料,包括上傳物件的內容類型 (MIME 類型)。 部署函數程式碼 在以下方塊中選擇 Python 索引標籤,然後複製程式碼。 .NET 適用於 .NET 的 SDK 注意 GitHub 上提供更多範例。尋找完整範例,並了解如何在 無伺服器範例 儲存庫中設定和執行。 使用 .NET 搭配 Lambda 來使用 S3 事件。 // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System.Threading.Tasks; using Amazon.Lambda.Core; using Amazon.S3; using System; using Amazon.Lambda.S3Events; using System.Web; // Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class. [assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] namespace S3Integration { public class Function { private static AmazonS3Client _s3Client; public Function() : this(null) { } internal Function(AmazonS3Client s3Client) { _s3Client = s3Client ?? new AmazonS3Client(); } public async Task<string> Handler(S3Event evt, ILambdaContext context) { try { if (evt.Records.Count <= 0) { context.Logger.LogLine("Empty S3 Event received"); return string.Empty; } var bucket = evt.Records[0].S3.Bucket.Name; var key = HttpUtility.UrlDecode(evt.Records[0].S3.Object.Key); context.Logger.LogLine($"Request is for { bucket} and { key}"); var objectResult = await _s3Client.GetObjectAsync(bucket, key); context.Logger.LogLine($"Returning { objectResult.Key}"); return objectResult.Key; } catch (Exception e) { context.Logger.LogLine($"Error processing request - { e.Message}"); return string.Empty; } } } } Go SDK for Go V2 注意 GitHub 上提供更多範例。尋找完整範例,並了解如何在 無伺服器範例 儲存庫中設定和執行。 使用 Go 搭配 Lambda 來使用 S3 事件。 // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package main import ( "context" "log" "github.com/aws/aws-lambda-go/events" "github.com/aws/aws-lambda-go/lambda" "github.com/aws/aws-sdk-go-v2/config" "github.com/aws/aws-sdk-go-v2/service/s3" ) func handler(ctx context.Context, s3Event events.S3Event) error { sdkConfig, err := config.LoadDefaultConfig(ctx) if err != nil { log.Printf("failed to load default config: %s", err) return err } s3Client := s3.NewFromConfig(sdkConfig) for _, record := range s3Event.Records { bucket := record.S3.Bucket.Name key := record.S3.Object.URLDecodedKey headOutput, err := s3Client.HeadObject(ctx, &s3.HeadObjectInput { Bucket: &bucket, Key: &key, }) if err != nil { log.Printf("error getting head of object %s/%s: %s", bucket, key, err) return err } log.Printf("successfully retrieved %s/%s of type %s", bucket, key, *headOutput.ContentType) } return nil } func main() { lambda.Start(handler) } Java SDK for Java 2.x 注意 GitHub 上提供更多範例。尋找完整範例,並了解如何在 無伺服器範例 儲存庫中設定和執行。 使用 Java 搭配 Lambda 來使用 S3 事件。 // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package example; import software.amazon.awssdk.services.s3.model.HeadObjectRequest; import software.amazon.awssdk.services.s3.model.HeadObjectResponse; import software.amazon.awssdk.services.s3.S3Client; import com.amazonaws.services.lambda.runtime.Context; import com.amazonaws.services.lambda.runtime.RequestHandler; import com.amazonaws.services.lambda.runtime.events.S3Event; import com.amazonaws.services.lambda.runtime.events.models.s3.S3EventNotification.S3EventNotificationRecord; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class Handler implements RequestHandler<S3Event, String> { private static final Logger logger = LoggerFactory.getLogger(Handler.class); @Override public String handleRequest(S3Event s3event, Context context) { try { S3EventNotificationRecord record = s3event.getRecords().get(0); String srcBucket = record.getS3().getBucket().getName(); String srcKey = record.getS3().getObject().getUrlDecodedKey(); S3Client s3Client = S3Client.builder().build(); HeadObjectResponse headObject = getHeadObject(s3Client, srcBucket, srcKey); logger.info("Successfully retrieved " + srcBucket + "/" + srcKey + " of type " + headObject.contentType()); return "Ok"; } catch (Exception e) { throw new RuntimeException(e); } } private HeadObjectResponse getHeadObject(S3Client s3Client, String bucket, String key) { HeadObjectRequest headObjectRequest = HeadObjectRequest.builder() .bucket(bucket) .key(key) .build(); return s3Client.headObject(headObjectRequest); } } JavaScript 適用於 JavaScript (v3) 的 SDK 注意 GitHub 上提供更多範例。尋找完整範例,並了解如何在 無伺服器範例 儲存庫中設定和執行。 使用 JavaScript 搭配 Lambda 來使用 S3 事件。 import { S3Client, HeadObjectCommand } from "@aws-sdk/client-s3"; const client = new S3Client(); export const handler = async (event, context) => { // Get the object from the event and show its content type const bucket = event.Records[0].s3.bucket.name; const key = decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g, ' ')); try { const { ContentType } = await client.send(new HeadObjectCommand( { Bucket: bucket, Key: key, })); console.log('CONTENT TYPE:', ContentType); return ContentType; } catch (err) { console.log(err); const message = `Error getting object $ { key} from bucket $ { bucket}. Make sure they exist and your bucket is in the same region as this function.`; console.log(message); throw new Error(message); } }; 使用 TypeScript 搭配 Lambda 來使用 S3 事件。 // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 import { S3Event } from 'aws-lambda'; import { S3Client, HeadObjectCommand } from '@aws-sdk/client-s3'; const s3 = new S3Client( { region: process.env.AWS_REGION }); export const handler = async (event: S3Event): Promise<string | undefined> => { // Get the object from the event and show its content type const bucket = event.Records[0].s3.bucket.name; const key = decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g, ' ')); const params = { Bucket: bucket, Key: key, }; try { const { ContentType } = await s3.send(new HeadObjectCommand(params)); console.log('CONTENT TYPE:', ContentType); return ContentType; } catch (err) { console.log(err); const message = `Error getting object $ { key} from bucket $ { bucket}. Make sure they exist and your bucket is in the same region as this function.`; console.log(message); throw new Error(message); } }; PHP 適用於 PHP 的 SDK 注意 GitHub 上提供更多範例。尋找完整範例,並了解如何在 無伺服器範例 儲存庫中設定和執行。 使用 PHP 搭配 Lambda 來使用 S3 事件。 <?php use Bref\Context\Context; use Bref\Event\S3\S3Event; use Bref\Event\S3\S3Handler; use Bref\Logger\StderrLogger; require __DIR__ . '/vendor/autoload.php'; class Handler extends S3Handler { private StderrLogger $logger; public function __construct(StderrLogger $logger) { $this->logger = $logger; } public function handleS3(S3Event $event, Context $context) : void { $this->logger->info("Processing S3 records"); // Get the object from the event and show its content type $records = $event->getRecords(); foreach ($records as $record) { $bucket = $record->getBucket()->getName(); $key = urldecode($record->getObject()->getKey()); try { $fileSize = urldecode($record->getObject()->getSize()); echo "File Size: " . $fileSize . "\n"; // TODO: Implement your custom processing logic here } catch (Exception $e) { echo $e->getMessage() . "\n"; echo 'Error getting object ' . $key . ' from bucket ' . $bucket . '. Make sure they exist and your bucket is in the same region as this function.' . "\n"; throw $e; } } } } $logger = new StderrLogger(); return new Handler($logger); Python 適用於 Python 的 SDK (Boto3) 注意 GitHub 上提供更多範例。尋找完整範例,並了解如何在 無伺服器範例 儲存庫中設定和執行。 使用 Python 搭配 Lambda 來使用 S3 事件。 # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 import json import urllib.parse import boto3 print('Loading function') s3 = boto3.client('s3') def lambda_handler(event, context): #print("Received event: " + json.dumps(event, indent=2)) # Get the object from the event and show its content type bucket = event['Records'][0]['s3']['bucket']['name'] key = urllib.parse.unquote_plus(event['Records'][0]['s3']['object']['key'], encoding='utf-8') try: response = s3.get_object(Bucket=bucket, Key=key) print("CONTENT TYPE: " + response['ContentType']) return response['ContentType'] except Exception as e: print(e) print('Error getting object { } from bucket { }. Make sure they exist and your bucket is in the same region as this function.'.format(key, bucket)) raise e Ruby SDK for Ruby 注意 GitHub 上提供更多範例。尋找完整範例,並了解如何在 無伺服器範例 儲存庫中設定和執行。 使用 Ruby 搭配 Lambda 來使用 S3 事件。 require 'json' require 'uri' require 'aws-sdk' puts 'Loading function' def lambda_handler(event:, context:) s3 = Aws::S3::Client.new(region: 'region') # Your AWS region # puts "Received event: # { JSON.dump(event)}" # Get the object from the event and show its content type bucket = event['Records'][0]['s3']['bucket']['name'] key = URI.decode_www_form_component(event['Records'][0]['s3']['object']['key'], Encoding::UTF_8) begin response = s3.get_object(bucket: bucket, key: key) puts "CONTENT TYPE: # { response.content_type}" return response.content_type rescue StandardError => e puts e.message puts "Error getting object # { key} from bucket # { bucket}. Make sure they exist and your bucket is in the same region as this function." raise e end end Rust 適用於 Rust 的 SDK 注意 GitHub 上提供更多範例。尋找完整範例,並了解如何在 無伺服器範例 儲存庫中設定和執行。 使用 Rust 搭配 Lambda 來使用 S3 事件。 // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 use aws_lambda_events::event::s3::S3Event; use aws_sdk_s3:: { Client}; use lambda_runtime:: { run, service_fn, Error, LambdaEvent}; /// Main function #[tokio::main] async fn main() -> Result<(), Error> { tracing_subscriber::fmt() .with_max_level(tracing::Level::INFO) .with_target(false) .without_time() .init(); // Initialize the AWS SDK for Rust let config = aws_config::load_from_env().await; let s3_client = Client::new(&config); let res = run(service_fn(|request: LambdaEvent<S3Event>| { function_handler(&s3_client, request) })).await; res } async fn function_handler( s3_client: &Client, evt: LambdaEvent<S3Event> ) -> Result<(), Error> { tracing::info!(records = ?evt.payload.records.len(), "Received request from SQS"); if evt.payload.records.len() == 0 { tracing::info!("Empty S3 event received"); } let bucket = evt.payload.records[0].s3.bucket.name.as_ref().expect("Bucket name to exist"); let key = evt.payload.records[0].s3.object.key.as_ref().expect("Object key to exist"); tracing::info!("Request is for { } and object { }", bucket, key); let s3_get_object_result = s3_client .get_object() .bucket(bucket) .key(key) .send() .await; match s3_get_object_result { Ok(_) => tracing::info!("S3 Get Object success, the s3GetObjectResult contains a 'body' property of type ByteStream"), Err(_) => tracing::info!("Failure with S3 Get Object request") } Ok(()) } 在 Lambda 主控台的 程式碼來源 窗格中,將程式碼貼到程式碼編輯器中,取代 Lambda 建立的程式碼。 在 DEPLOY 區段中,選擇 部署 以更新函數的程式碼: 建立 Amazon S3 觸發條件 若要建立 Amazon S3 觸發條件 在 函數概觀 窗格中,選擇 新增觸發條件 。 選取 S3 。 在 儲存貯體 下,選取您在本教學課程中稍早建立的儲存貯體。 在 事件類型 下,選取 所有物件建立事件 。 在 遞迴調用 下,選取核取方塊,確認您了解不建議使用相同的 Amazon S3 儲存貯體進行輸入和輸出作業。 選擇 新增 。 注意 當您使用 Lambda 主控台為 Lambda 函數建立 Amazon S3 觸發條件時,Amazon S3 會在您指定的儲存貯體上設定 事件通知 。在設定此事件通知之前,Amazon S3 會執行一系列檢查,以確認該事件目的地存在,且具有所需的 IAM 政策。Amazon S3 也會對針對為該儲存貯體設定的任何其他事件通知執行這些測試。 由於此檢查的存在,如果儲存貯體先前已為不再存在的資源設定事件目的地,或為沒有必要許可政策的資源設定事件目的地,則 Amazon S3 將無法建立新的事件通知。您將看到以下錯誤訊息,指出無法建立觸發條件: An error occurred when creating the trigger: Unable to validate the following destination configurations. 如果您先前已使用相同的儲存貯體為另一個 Lambda 函數設定觸發條件,且在之後刪除了相關函數或修改了其許可政策,則會顯示此錯誤。 使用虛擬事件來測試 Lambda 函數 使用虛擬事件來測試 Lambda 函數 在函數的 Lambda 主控台頁面中,選擇 測試 索引標籤。 事件名稱 輸入 MyTestEvent 。 在 事件 JSON 中,貼上以下測試事件。務必取代這些值: 將 us-east-1 取代為您用來建立 Amazon S3 儲存貯體的區域。 將 amzn-s3-demo-bucket 的兩個執行個體取代為您的 Amazon S3 儲存貯體名稱。 將 test%2FKey 取代為您之前上傳到儲存貯體的測試物件名稱 (例如 HappyFace.jpg )。 { "Records": [ { "eventVersion": "2.0", "eventSource": "aws:s3", "awsRegion": " us-east-1 ", "eventTime": "1970-01-01T00:00:00.000Z", "eventName": "ObjectCreated:Put", "userIdentity": { "principalId": "EXAMPLE" }, "requestParameters": { "sourceIPAddress": "127.0.0.1" }, "responseElements": { "x-amz-request-id": "EXAMPLE123456789", "x-amz-id-2": "EXAMPLE123/5678abcdefghijklambdaisawesome/mnopqrstuvwxyzABCDEFGH" }, "s3": { "s3SchemaVersion": "1.0", "configurationId": "testConfigRule", "bucket": { "name": " amzn-s3-demo-bucket ", "ownerIdentity": { "principalId": "EXAMPLE" }, "arn": "arn:aws:s3::: amzn-s3-demo-bucket " }, "object": { "key": " test%2Fkey ", "size": 1024, "eTag": "0123456789abcdef0123456789abcdef", "sequencer": "0A1B2C3D4E5F678901" } } } ] } 選擇 儲存 。 選擇 測試 。 如果函數成功運作,您會在 執行結果 索引標籤中看到類似以下內容的輸出。 Response "image/jpeg" Function Logs START RequestId: 12b3cae7-5f4e-415e-93e6-416b8f8b66e6 Version: $LATEST 2021-02-18T21:40:59.280Z 12b3cae7-5f4e-415e-93e6-416b8f8b66e6 INFO INPUT BUCKET AND KEY: { Bucket: 'amzn-s3-demo-bucket', Key: 'HappyFace.jpg' } 2021-02-18T21:41:00.215Z 12b3cae7-5f4e-415e-93e6-416b8f8b66e6 INFO CONTENT TYPE: image/jpeg END RequestId: 12b3cae7-5f4e-415e-93e6-416b8f8b66e6 REPORT RequestId: 12b3cae7-5f4e-415e-93e6-416b8f8b66e6 Duration: 976.25 ms Billed Duration: 977 ms Memory Size: 128 MB Max Memory Used: 90 MB Init Duration: 430.47 ms Request ID 12b3cae7-5f4e-415e-93e6-416b8f8b66e6 使用 Amazon S3 觸發條件測試 Lambda 函數 若要使用已設定的觸發條件來測試函數,需使用主控台將物件上傳至 Amazon S3 儲存貯體。若要確認 Lambda 函數如預期執行,請使用 CloudWatch Logs 來檢視函數的輸出。 將物件上傳至 Amazon S3 儲存貯體 開啟 Amazon S3 主控台的 儲存貯體 頁面,然後選擇您稍早建立的儲存貯體。 選擇 上傳 。 選擇 新增檔案 ,然後使用檔案選擇器選擇您要上傳的物件。此物件可以是您自選的任何檔案。 選擇 開啟 ,然後選擇 上傳 。 若要使用 CloudWatch Logs 驗證函數調用 開啟 CloudWatch 主控台 。 請確定您在 AWS 區域 建立 Lambda 函數的相同 中工作。您可使用螢幕頂端的下拉式清單來變更區域。 選擇 日誌 ,然後選擇 日誌群組 。 為函數 ( /aws/lambda/s3-trigger-tutorial ) 選擇日誌群組名稱。 在 日誌串流 下,選擇最新的日誌串流。 如果系統已正確調用函數以回應 Amazon S3 觸發條件,您會看到類似以下內容的輸出。您看到的 CONTENT TYPE 取決於您上傳到儲存貯體的檔案類型。 2022-05-09T23:17:28.702Z 0cae7f5a-b0af-4c73-8563-a3430333cc10 INFO CONTENT TYPE: image/jpeg 清除您的資源 除非您想要保留為此教學課程建立的資源,否則您現在便可刪除。透過刪除您不再使用 AWS 的資源,您可以避免不必要的 費用 AWS 帳戶。 若要刪除 Lambda 函數 開啟 Lambda 主控台中的 函數頁面 。 選擇您建立的函數。 選擇 Actions (動作)、 Delete (刪除)。 在文字輸入欄位中輸入 confirm ,然後選擇 刪除 。 刪除執行角色 開啟 IAM 主控台中的 角色頁面 。 選取您建立的執行角色。 選擇 刪除 。 在文字輸入欄位中輸入角色的名稱,然後選擇 刪除 。 刪除 S3 儲存貯體 開啟 Amazon S3 主控台 。 選擇您建立的儲存貯體。 選擇 刪除 。 在文字輸入欄位中輸入儲存貯體的名稱。 選擇 刪除儲存貯體 。 後續步驟 在 教學課程:使用 Amazon S3 觸發條件建立縮圖影像 中,Amazon S3 觸發條件會調用函數,為上傳至 S3 儲存貯體的每個影像檔建立縮圖影像。本教學課程需要中等程度的 AWS 和 Lambda 網域知識。它示範如何使用 AWS Command Line Interface (AWS CLI) 建立資源,以及如何為函數及其相依性建立 .zip 檔案封存部署套件。 您的瀏覽器已停用或無法使用 Javascript。 您必須啟用 Javascript,才能使用 AWS 文件。請參閱您的瀏覽器說明頁以取得說明。 文件慣用形式 S3 教學課程:使用 Amazon S3 觸發條件建立縮圖 此頁面是否有幫助? - 是 感謝您,讓我們知道我們做得很好! 若您有空,歡迎您告知我們值得讚許的地方,這樣才能保持良好服務。 此頁面是否有幫助? - 否 感謝讓我們知道此頁面仍須改善。很抱歉,讓您失望。 若您有空,歡迎您提供改善文件的方式。 | 2026-01-13T09:30:35 |
https://docs.aws.amazon.com/zh_cn/lambda/latest/dg/configuration-tags.html | 在 Lambda 函数上使用标签 - AWS Lambda 在 Lambda 函数上使用标签 - AWS Lambda 文档 AWS Lambda 开发人员指南 使用标签所需的权限 通过控制台使用标签 通过 AWS CLI 使用标签 在 Lambda 函数上使用标签 可以通过为函数添加标签来组织和管理资源。标签是与资源关联的自由格式键值对,在 AWS 服务中受支持。有关标签用例的更多信息,请参阅《Tagging AWS Resources and Tag Editor Guide》 中的 Common tagging strategies 。 标签应用在函数级别,而不是应用于版本或别名。标签不会包含在您发布版本时 AWS Lambda 创建快照的版本特定配置的快照中。可以使用 Lambda API 来查看和更新标签。在 Lambda 控制台中管理特定函数时,还可以查看和更新标签。 Sections 使用标签所需的权限 通过 Lambda 控制台使用标签 通过 AWS CLI 使用标签 使用标签所需的权限 要允许 AWS Identity and Access Management(IAM)身份(用户、组或角色)读取资源或为其设置标签,请授予该身份相应的权限: lambda:ListTags – 当资源有标签时,将此权限授予需要在其上调用 ListTags 的任何人。对于带标签的函数, GetFunction 也需要此权限。 lambda:TagResource – 将此权限授予需要调用 TagResource 或执行在创建时授予标记的操作的任何人。 或者,也可以考虑授予 lambda:UntagResource 权限以允许 UntagResource 调用该资源。 有关更多信息,请参阅 Lambda 的基于身份的 IAM policy 。 通过 Lambda 控制台使用标签 您可以使用 Lambda 控制台创建具有标签的函数、向现有函数添加标签以及按添加的标签筛选函数。 要在创建函数时添加标签 打开 Lamba 控制台的 Functions page (函数页面)。 选择 Create function (创建函数)。 选择 Author from scratch (从头开始编写)或 Container image (容器映像)。 在 基本信息 下,设置您的函数。有关配置函数的更多信息,请参阅 配置 AWS Lambda 函数 。 展开 Advanced settings (高级设置),然后选择 Enable tags (启用标签)。 选择 Add new tag (添加新标签),然后输入 Key (键)和可选 Value (值)。要添加更多标签,请重复此步骤。 选择 Create function (创建函数)。 要将标签添加到现有函数 打开 Lamba 控制台的 函数页面 。 选择一个函数的名称。 选择 Configuration (配置),然后选择 Tags (标签)。 在 标签 下,选择 管理标签 。 选择 Add new tag (添加新标签),然后输入 Key (键)和可选 Value (值)。要添加更多标签,请重复此步骤。 选择 保存 。 使用标签过滤函数 打开 Lamba 控制台的 函数页面 。 选择搜索框以查看函数属性和标签键列表。 选择一个标签键以查看当前 AWS 区域中正在使用的值的列表。 选择 使用:“tag-name” 以查看所有使用此键标记的函数,或者选择一个 运算符 进一步按值筛选。 选择标签值以按标签键和值的组合进行筛选。 搜索栏还支持搜索标签键。输入 tag 以仅查看标签键列表,或输入键的名称以在列表中查找它。 通过 AWS CLI 使用标签 可以使用 Lambda API 在现有 Lambda 资源(包括函数)上添加和删除标签。还可以在创建函数时添加标签,这样就可以在资源的整个生命周期中对其进行标记。 使用 Lambda 标签 API 更新标签 可以通过 TagResource 和 UntagResource API 操作,添加和删除受支持 Lambda 资源的标签。 可以使用 AWS CLI 调用这些操作。要向现有资源添加标签,请使用 tag-resource 命令。此示例添加了两个标签,一个带有键 Department ,另一个带有键 CostCenter 。 aws lambda tag-resource \ --resource arn:aws:lambda: us-east-2:123456789012:resource-type:my-resource \ --tags Department = Marketing , CostCenter = 1234ABCD 要删除标签,请使用 untag-resource 命令。此示例删除了键为 Department 的标签。 aws lambda untag-resource --resource arn:aws:lambda:us-east-1:123456789012:resource-type:resource-identifier \ --tag-keys Department 在创建函数时添加标签 要使用标签创建新的 Lambda 函数,请使用 CreateFunction API 操作。指定 Tags 参数。您可以使用 create-function CLI 命令和 --tags 选项调用此操作。在将标签参数与 CreateFunction 一起使用之前,请确保您的角色拥有标记资源的权限以及此操作所需的常规权限。有关标记权限的更多信息,请参阅 使用标签所需的权限 。此示例添加了两个标签,一个带有键 Department ,另一个带有键 CostCenter 。 aws lambda create-function --function-name my-function --handler index.js --runtime nodejs22.x \ --role arn:aws:iam:: 123456789012 :role/ lambda-role \ --tags Department=Marketing,CostCenter=1234ABCD 查看函数上的标签 要查看应用于特定 Lambda 资源的标签,请使用 ListTags API 操作。有关更多信息,请参阅 ListTags 。 可以提供 ARN(Amazon 资源名称),以使用 list-tags AWS CLI 命令调用此操作。 aws lambda list-tags --resource arn:aws:lambda:us-east-1:123456789012:resource-type:resource-identifier 可以通过 GetFunction API 操作来查看应用于特定资源的标签。类似的功能不适用于其他资源类型。 可以使用 get-function CLI 命令调用此操作: aws lambda get-function --function-name my-function 按标签筛选资源 您可以使用 AWS Resource Groups Tagging API GetResources API 操作按标签筛选资源。 GetResources 操作最多可接收 10 个筛选条件,每个筛选条件包含一个标签键和最多 10 个标签值。提供具有 ResourceType 的 GetResources ,可按特定资源类型进行筛选。 可以使用 get-resources AWS CLI 命令调用此操作。有关使用 get-resources 的示例,请参阅《AWS CLI Command Reference》 中的 get-resources 。 Javascript 在您的浏览器中被禁用或不可用。 要使用 Amazon Web Services 文档,必须启用 Javascript。请参阅浏览器的帮助页面以了解相关说明。 文档惯例 版本 响应流式处理 此页面对您有帮助吗?- 是 感谢您对我们工作的肯定! 如果不耽误您的时间,请告诉我们做得好的地方,让我们做得更好。 此页面对您有帮助吗?- 否 感谢您告诉我们本页内容还需要完善。很抱歉让您失望了。 如果不耽误您的时间,请告诉我们如何改进文档。 | 2026-01-13T09:30:35 |
https://docs.aws.amazon.com/ko_kr/lambda/latest/dg/with-s3-example.html | 자습서: Amazon S3 트리거를 사용하여 Lambda 함수 호출 - AWS Lambda 자습서: Amazon S3 트리거를 사용하여 Lambda 함수 호출 - AWS Lambda 설명서 AWS Lambda 개발자 안내서 Amazon S3 버킷 생성 버킷에 테스트 객체 업로드 권한 정책 생성 실행 역할 만들기 Lambda 함수 생성 함수 코드 배포 Amazon S3 트리거를 생성합니다 Lambda 함수 테스트 리소스 정리 다음 단계 자습서: Amazon S3 트리거를 사용하여 Lambda 함수 호출 이 자습서에서는 콘솔을 사용하여 Lambda 함수를 생성하고 Amazon Simple Storage Service(Amazon S3) 버킷에 대한 트리거를 구성합니다. Amazon S3 버킷에 객체를 추가할 때마다 함수가 실행되고 Amazon CloudWatch Logs에 객체 유형을 출력합니다. 이 자습서에서는 다음을 수행하는 방법을 설명합니다. Amazon S3 버킷을 생성합니다. Amazon S3 버킷에 있는 객체의 유형을 반환하는 Lambda 함수를 생성합니다. 객체가 버킷에 업로드될 때 함수를 간접 호출하는 Lambda 트리거를 구성합니다. 먼저 더미 이벤트로 함수를 테스트한 다음 트리거를 사용하여 함수를 테스트합니다. 이 단계를 완료하면 Amazon S3 버킷에서 객체가 추가되거나 삭제될 때마다 실행되도록 Lambda 함수를 구성하는 방법을 알게 됩니다. AWS Management 콘솔만 사용하여 이 자습서를 완료할 수 있습니다. Amazon S3 버킷 생성 Amazon S3 버킷을 생성하려면 Amazon S3 콘솔 을 열고 범용 버킷 페이지를 선택합니다. 지리적 위치와 가장 가까운 AWS 리전을 선택합니다. 화면 상단의 드롭다운 목록을 사용하여 리전을 변경할 수 있습니다. 자습서 뒷부분에서 동일한 리전에 Lambda 함수를 생성해야 합니다. 버킷 만들기 를 선택합니다. [ 일반 구성(General configuration) ]에서 다음을 수행합니다. 버킷 유형 에서 범용 을 선택했는지 확인합니다. 버킷 이름 에 Amazon S3 버킷 이름 지정 규칙 을 충족하는 전역적으로 고유한 이름을 입력합니다. 버킷 이름은 소문자, 숫자, 점(.) 및 하이픈(-)만 포함할 수 있습니다. 다른 모든 옵션을 기본값으로 두고 버킷 생성 을 선택합니다. 버킷에 테스트 객체 업로드 테스트 객체 업로드 Amazon S3 콘솔의 버킷 페이지를 열고 이전 단계 중 생성한 버킷을 선택합니다. 업로드 를 선택합니다. 파일 추가 를 선택하고 업로드하려는 객체를 선택합니다. 모든 파일을 선택할 수 있습니다(예: HappyFace.jpg ). 열기 를 선택한 후 업로드 를 선택합니다. 자습서의 뒷부분에서 이 객체를 사용하여 Lambda 함수를 테스트합니다. 권한 정책 생성 Lambda가 Amazon S3 버킷에서 객체를 가져오고 Amazon CloudWatch Logs에 쓸 수 있도록 허용하는 권한 정책을 생성합니다. 정책 생성 IAM 콘솔에서 정책 페이지 를 엽니다. 정책 생성 을 선택하세요. JSON 탭에서 다음과 같은 사용자 지정 정책을 JSON 편집기에 붙여 넣습니다. JSON { "Version":"2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "logs:PutLogEvents", "logs:CreateLogGroup", "logs:CreateLogStream" ], "Resource": "arn:aws:logs:*:*:*" }, { "Effect": "Allow", "Action": [ "s3:GetObject" ], "Resource": "arn:aws:s3:::*/*" } ] } 다음: 태그 를 선택합니다. 다음: 검토(Next: Review) 를 선택합니다. 정책 검토 의 이름 에 s3-trigger-tutorial 를 입력합니다. 정책 생성 을 선택합니다. 실행 역할 만들기 실행 역할 은 AWS 서비스 및 리소스에 액세스할 수 있는 권한을 Lambda 함수에 부여하는 AWS Identity and Access Management(IAM) 역할입니다. 이 단계에서는 이전 단계에서 생성한 권한 정책을 사용하여 실행 역할을 생성하세요. 실행 역할을 생성하고 사용자 지정 권한 정책을 연결하려면 IAM 콘솔에서 역할 페이지 를 엽니다. 역할 생성 을 선택합니다. 신뢰할 수 있는 엔터티의 유형으로 AWS 서비스 를 선택한 다음 사용 사례로 Lambda 를 선택합니다. 다음 을 선택합니다. 정책 검색 상자에 s3-trigger-tutorial 를 입력합니다. 검색 결과에서 생성한 정책( s3-trigger-tutorial )을 선택한 후, 다음(Next) 을 선택합니다. Role details (역할 세부 정보)에서 Role name (역할 이름)에 lambda-s3-trigger-role 을 입력한 다음 Create role (역할 생성)을 선택합니다. Lambda 함수 생성 Python 3.13 런타임을 사용하여 콘솔에서 Lambda 함수를 생성합니다. Lambda 함수를 만들려면 Lambda 콘솔의 함수 페이지 를 엽니다. Amazon S3 버킷을 생성한 동일한 AWS 리전에서 작업 중인지 확인합니다. 화면 상단의 드롭다운 목록을 사용하여 리전을 변경할 수 있습니다. 함수 생성 을 선택합니다. 새로 작성 을 선택합니다. 기본 정보 에서 다음과 같이 합니다. 함수 이름 에 s3-trigger-tutorial 을 입력합니다. 런타임 에서 Python 3.13 을 선택합니다. 아키텍처 에서는 x86_64 를 선택합니다. 기본 실행 역할 변경 탭에서 다음을 수행합니다. 탭을 확장한 다음 기존 역할 사용 을 선택합니다. 이전에 생성한 lambda-s3-trigger-role 을 선택합니다. 함수 생성 을 선택합니다. 함수 코드 배포 이 자습서에서는 Python 3.13 런타임을 사용하지만 다른 런타임의 예시 코드 파일도 제공했습니다. 다음 상자에서 탭을 선택하여 관심 있는 런타임에 대한 코드를 볼 수 있습니다. Lambda 함수는 Amazon S3에서 수신한 event 파라미터에서 업로드된 객체의 키 이름과 버킷 이름을 검색합니다. 그런 다음 함수는 AWS SDK for Python (Boto3)의 get_object 메서드를 사용하여 업로드된 객체의 콘텐츠 유형(MIME 유형)을 비롯한 객체의 메타데이터를 검색합니다. 함수 코드 배포 다음 상자에서 Python 탭을 선택하고 코드를 복사합니다. .NET SDK for .NET 참고 GitHub에 더 많은 내용이 있습니다. 서버리스 예제 리포지토리에서 전체 예제를 찾아보고 설정 및 실행 방법을 알아봅니다. .NET을 사용하여 Lambda로 S3 이벤트를 사용합니다. // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System.Threading.Tasks; using Amazon.Lambda.Core; using Amazon.S3; using System; using Amazon.Lambda.S3Events; using System.Web; // Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class. [assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] namespace S3Integration { public class Function { private static AmazonS3Client _s3Client; public Function() : this(null) { } internal Function(AmazonS3Client s3Client) { _s3Client = s3Client ?? new AmazonS3Client(); } public async Task<string> Handler(S3Event evt, ILambdaContext context) { try { if (evt.Records.Count <= 0) { context.Logger.LogLine("Empty S3 Event received"); return string.Empty; } var bucket = evt.Records[0].S3.Bucket.Name; var key = HttpUtility.UrlDecode(evt.Records[0].S3.Object.Key); context.Logger.LogLine($"Request is for { bucket} and { key}"); var objectResult = await _s3Client.GetObjectAsync(bucket, key); context.Logger.LogLine($"Returning { objectResult.Key}"); return objectResult.Key; } catch (Exception e) { context.Logger.LogLine($"Error processing request - { e.Message}"); return string.Empty; } } } } Go SDK for Go V2 참고 GitHub에 더 많은 내용이 있습니다. 서버리스 예제 리포지토리에서 전체 예제를 찾아보고 설정 및 실행 방법을 알아봅니다. Go를 사용하여 Lambda로 S3 이벤트를 사용합니다. // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package main import ( "context" "log" "github.com/aws/aws-lambda-go/events" "github.com/aws/aws-lambda-go/lambda" "github.com/aws/aws-sdk-go-v2/config" "github.com/aws/aws-sdk-go-v2/service/s3" ) func handler(ctx context.Context, s3Event events.S3Event) error { sdkConfig, err := config.LoadDefaultConfig(ctx) if err != nil { log.Printf("failed to load default config: %s", err) return err } s3Client := s3.NewFromConfig(sdkConfig) for _, record := range s3Event.Records { bucket := record.S3.Bucket.Name key := record.S3.Object.URLDecodedKey headOutput, err := s3Client.HeadObject(ctx, &s3.HeadObjectInput { Bucket: &bucket, Key: &key, }) if err != nil { log.Printf("error getting head of object %s/%s: %s", bucket, key, err) return err } log.Printf("successfully retrieved %s/%s of type %s", bucket, key, *headOutput.ContentType) } return nil } func main() { lambda.Start(handler) } Java SDK for Java 2.x 참고 GitHub에 더 많은 내용이 있습니다. 서버리스 예제 리포지토리에서 전체 예제를 찾아보고 설정 및 실행 방법을 알아봅니다. Java를 사용하여 Lambda로 S3 이벤트를 사용합니다. // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package example; import software.amazon.awssdk.services.s3.model.HeadObjectRequest; import software.amazon.awssdk.services.s3.model.HeadObjectResponse; import software.amazon.awssdk.services.s3.S3Client; import com.amazonaws.services.lambda.runtime.Context; import com.amazonaws.services.lambda.runtime.RequestHandler; import com.amazonaws.services.lambda.runtime.events.S3Event; import com.amazonaws.services.lambda.runtime.events.models.s3.S3EventNotification.S3EventNotificationRecord; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class Handler implements RequestHandler<S3Event, String> { private static final Logger logger = LoggerFactory.getLogger(Handler.class); @Override public String handleRequest(S3Event s3event, Context context) { try { S3EventNotificationRecord record = s3event.getRecords().get(0); String srcBucket = record.getS3().getBucket().getName(); String srcKey = record.getS3().getObject().getUrlDecodedKey(); S3Client s3Client = S3Client.builder().build(); HeadObjectResponse headObject = getHeadObject(s3Client, srcBucket, srcKey); logger.info("Successfully retrieved " + srcBucket + "/" + srcKey + " of type " + headObject.contentType()); return "Ok"; } catch (Exception e) { throw new RuntimeException(e); } } private HeadObjectResponse getHeadObject(S3Client s3Client, String bucket, String key) { HeadObjectRequest headObjectRequest = HeadObjectRequest.builder() .bucket(bucket) .key(key) .build(); return s3Client.headObject(headObjectRequest); } } JavaScript SDK for JavaScript (v3) 참고 GitHub에 더 많은 내용이 있습니다. 서버리스 예제 리포지토리에서 전체 예제를 찾아보고 설정 및 실행 방법을 알아봅니다. JavaScript를 사용하여 Lambda로 S3 이벤트를 사용합니다. import { S3Client, HeadObjectCommand } from "@aws-sdk/client-s3"; const client = new S3Client(); export const handler = async (event, context) => { // Get the object from the event and show its content type const bucket = event.Records[0].s3.bucket.name; const key = decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g, ' ')); try { const { ContentType } = await client.send(new HeadObjectCommand( { Bucket: bucket, Key: key, })); console.log('CONTENT TYPE:', ContentType); return ContentType; } catch (err) { console.log(err); const message = `Error getting object $ { key} from bucket $ { bucket}. Make sure they exist and your bucket is in the same region as this function.`; console.log(message); throw new Error(message); } }; TypeScript를 사용하여 Lambda로 S3 이벤트를 사용합니다. // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 import { S3Event } from 'aws-lambda'; import { S3Client, HeadObjectCommand } from '@aws-sdk/client-s3'; const s3 = new S3Client( { region: process.env.AWS_REGION }); export const handler = async (event: S3Event): Promise<string | undefined> => { // Get the object from the event and show its content type const bucket = event.Records[0].s3.bucket.name; const key = decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g, ' ')); const params = { Bucket: bucket, Key: key, }; try { const { ContentType } = await s3.send(new HeadObjectCommand(params)); console.log('CONTENT TYPE:', ContentType); return ContentType; } catch (err) { console.log(err); const message = `Error getting object $ { key} from bucket $ { bucket}. Make sure they exist and your bucket is in the same region as this function.`; console.log(message); throw new Error(message); } }; PHP SDK for PHP 참고 GitHub에 더 많은 내용이 있습니다. 서버리스 예제 리포지토리에서 전체 예제를 찾아보고 설정 및 실행 방법을 알아봅니다. PHP를 사용하여 Lambda로 S3 이벤트 사용. <?php use Bref\Context\Context; use Bref\Event\S3\S3Event; use Bref\Event\S3\S3Handler; use Bref\Logger\StderrLogger; require __DIR__ . '/vendor/autoload.php'; class Handler extends S3Handler { private StderrLogger $logger; public function __construct(StderrLogger $logger) { $this->logger = $logger; } public function handleS3(S3Event $event, Context $context) : void { $this->logger->info("Processing S3 records"); // Get the object from the event and show its content type $records = $event->getRecords(); foreach ($records as $record) { $bucket = $record->getBucket()->getName(); $key = urldecode($record->getObject()->getKey()); try { $fileSize = urldecode($record->getObject()->getSize()); echo "File Size: " . $fileSize . "\n"; // TODO: Implement your custom processing logic here } catch (Exception $e) { echo $e->getMessage() . "\n"; echo 'Error getting object ' . $key . ' from bucket ' . $bucket . '. Make sure they exist and your bucket is in the same region as this function.' . "\n"; throw $e; } } } } $logger = new StderrLogger(); return new Handler($logger); Python SDK for Python (Boto3) 참고 GitHub에 더 많은 내용이 있습니다. 서버리스 예제 리포지토리에서 전체 예제를 찾아보고 설정 및 실행 방법을 알아봅니다. Python을 사용하여 Lambda로 S3 이벤트를 사용합니다. # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 import json import urllib.parse import boto3 print('Loading function') s3 = boto3.client('s3') def lambda_handler(event, context): #print("Received event: " + json.dumps(event, indent=2)) # Get the object from the event and show its content type bucket = event['Records'][0]['s3']['bucket']['name'] key = urllib.parse.unquote_plus(event['Records'][0]['s3']['object']['key'], encoding='utf-8') try: response = s3.get_object(Bucket=bucket, Key=key) print("CONTENT TYPE: " + response['ContentType']) return response['ContentType'] except Exception as e: print(e) print('Error getting object { } from bucket { }. Make sure they exist and your bucket is in the same region as this function.'.format(key, bucket)) raise e Ruby SDK for Ruby 참고 GitHub에 더 많은 내용이 있습니다. 서버리스 예제 리포지토리에서 전체 예제를 찾아보고 설정 및 실행 방법을 알아봅니다. Ruby를 사용하여 Lambda로 S3 이벤트 사용. require 'json' require 'uri' require 'aws-sdk' puts 'Loading function' def lambda_handler(event:, context:) s3 = Aws::S3::Client.new(region: 'region') # Your AWS region # puts "Received event: # { JSON.dump(event)}" # Get the object from the event and show its content type bucket = event['Records'][0]['s3']['bucket']['name'] key = URI.decode_www_form_component(event['Records'][0]['s3']['object']['key'], Encoding::UTF_8) begin response = s3.get_object(bucket: bucket, key: key) puts "CONTENT TYPE: # { response.content_type}" return response.content_type rescue StandardError => e puts e.message puts "Error getting object # { key} from bucket # { bucket}. Make sure they exist and your bucket is in the same region as this function." raise e end end Rust SDK for Rust 참고 GitHub에 더 많은 내용이 있습니다. 서버리스 예제 리포지토리에서 전체 예제를 찾아보고 설정 및 실행 방법을 알아봅니다. Rust를 사용하여 Lambda로 S3 이벤트를 사용합니다. // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 use aws_lambda_events::event::s3::S3Event; use aws_sdk_s3:: { Client}; use lambda_runtime:: { run, service_fn, Error, LambdaEvent}; /// Main function #[tokio::main] async fn main() -> Result<(), Error> { tracing_subscriber::fmt() .with_max_level(tracing::Level::INFO) .with_target(false) .without_time() .init(); // Initialize the AWS SDK for Rust let config = aws_config::load_from_env().await; let s3_client = Client::new(&config); let res = run(service_fn(|request: LambdaEvent<S3Event>| { function_handler(&s3_client, request) })).await; res } async fn function_handler( s3_client: &Client, evt: LambdaEvent<S3Event> ) -> Result<(), Error> { tracing::info!(records = ?evt.payload.records.len(), "Received request from SQS"); if evt.payload.records.len() == 0 { tracing::info!("Empty S3 event received"); } let bucket = evt.payload.records[0].s3.bucket.name.as_ref().expect("Bucket name to exist"); let key = evt.payload.records[0].s3.object.key.as_ref().expect("Object key to exist"); tracing::info!("Request is for { } and object { }", bucket, key); let s3_get_object_result = s3_client .get_object() .bucket(bucket) .key(key) .send() .await; match s3_get_object_result { Ok(_) => tracing::info!("S3 Get Object success, the s3GetObjectResult contains a 'body' property of type ByteStream"), Err(_) => tracing::info!("Failure with S3 Get Object request") } Ok(()) } Lambda 콘솔의 코드 소스 창에서 코드 편집기에 코드를 붙여넣고 Lambda가 생성한 코드를 바꿉니다. 배포 섹션에서 배포 를 선택하여 함수의 코드를 업데이트하세요. Amazon S3 트리거를 생성합니다 Amazon S3 트리거 생성 방법 함수 개요 창에서 트리거 추가 를 선택합니다. S3 를 선택합니다. 버킷 에서 자습서 앞부분에서 생성한 버킷을 선택합니다. 이벤트 유형 에서 모든 객체 생성 이벤트 를 선택합니다. 재귀 호출 에서 확인란을 선택하여 입력 및 출력에 동일한 Amazon S3 버킷 사용이 권장되지 않음을 확인합니다. 추가 를 선택합니다. 참고 Lambda 콘솔을 사용하여 Lambda 함수에 대한 Amazon S3 트리거를 생성하면 Amazon S3는 사용자가 지정한 버킷에 대한 이벤트 알림 을 구성합니다. Amazon S3는 이 이벤트 알림을 구성하기 전에 일련의 검사를 수행하여 이벤트 대상이 존재하고 필수 IAM 정책을 갖추고 있는지 확인합니다. Amazon S3는 해당 버킷에 대해 구성된 다른 모든 이벤트 알림에 대해서도 이러한 테스트를 수행합니다. 이 검사 때문에 버킷이 이전에 더 이상 존재하지 않는 리소스나 필요한 권한 정책이 없는 리소스에 대한 이벤트 대상을 구성한 경우 Amazon S3는 새 이벤트 알림을 생성할 수 없습니다. 트리거를 생성할 수 없음을 나타내는 다음 오류 메시지가 나타납니다. An error occurred when creating the trigger: Unable to validate the following destination configurations. 이전에 동일한 버킷을 사용하여 다른 Lambda 함수에 대한 트리거를 구성한 후 함수를 삭제하거나 해당 권한 정책을 수정한 경우 이 오류가 나타날 수 있습니다. 더미 이벤트로 Lambda 함수 테스트 더미 이벤트로 Lambda 함수 테스트 함수의 Lambda 콘솔 페이지에서 테스트 탭을 선택합니다. 이벤트 이름 에 MyTestEvent 를 입력합니다. 이벤트 JSON 에서 다음 테스트 이벤트를 붙여넣습니다. 해당 값을 바꿉니다. us-east-1 을 Amazon S3 버킷을 생성한 리전으로 바꿉니다. amzn-s3-demo-bucket 의 두 인스턴스를 모두 자체 Amazon S3 버킷의 이름으로 바꿉니다. test%2FKey 를 이전에 버킷에 업로드한 테스트 객체의 이름(예: HappyFace.jpg )으로 바꿉니다. { "Records": [ { "eventVersion": "2.0", "eventSource": "aws:s3", "awsRegion": " us-east-1 ", "eventTime": "1970-01-01T00:00:00.000Z", "eventName": "ObjectCreated:Put", "userIdentity": { "principalId": "EXAMPLE" }, "requestParameters": { "sourceIPAddress": "127.0.0.1" }, "responseElements": { "x-amz-request-id": "EXAMPLE123456789", "x-amz-id-2": "EXAMPLE123/5678abcdefghijklambdaisawesome/mnopqrstuvwxyzABCDEFGH" }, "s3": { "s3SchemaVersion": "1.0", "configurationId": "testConfigRule", "bucket": { "name": " amzn-s3-demo-bucket ", "ownerIdentity": { "principalId": "EXAMPLE" }, "arn": "arn:aws:s3::: amzn-s3-demo-bucket " }, "object": { "key": " test%2Fkey ", "size": 1024, "eTag": "0123456789abcdef0123456789abcdef", "sequencer": "0A1B2C3D4E5F678901" } } } ] } 저장 을 선택합니다. 테스트 를 선택합니다. 함수가 성공적으로 실행되면 실행 결과 탭에 다음과 비슷한 출력이 표시됩니다. Response "image/jpeg" Function Logs START RequestId: 12b3cae7-5f4e-415e-93e6-416b8f8b66e6 Version: $LATEST 2021-02-18T21:40:59.280Z 12b3cae7-5f4e-415e-93e6-416b8f8b66e6 INFO INPUT BUCKET AND KEY: { Bucket: 'amzn-s3-demo-bucket', Key: 'HappyFace.jpg' } 2021-02-18T21:41:00.215Z 12b3cae7-5f4e-415e-93e6-416b8f8b66e6 INFO CONTENT TYPE: image/jpeg END RequestId: 12b3cae7-5f4e-415e-93e6-416b8f8b66e6 REPORT RequestId: 12b3cae7-5f4e-415e-93e6-416b8f8b66e6 Duration: 976.25 ms Billed Duration: 977 ms Memory Size: 128 MB Max Memory Used: 90 MB Init Duration: 430.47 ms Request ID 12b3cae7-5f4e-415e-93e6-416b8f8b66e6 Amazon S3 트리거로 Lambda 함수 테스트 구성된 트리거로 함수를 테스트하려면 콘솔을 사용하여 Amazon S3 버킷에 객체를 업로드합니다. Lambda 함수가 예상대로 실행되었는지 확인하려면 CloudWatch 로그를 사용하여 함수의 출력을 확인합니다. Amazon S3 버킷에 객체 업로드 Amazon S3 콘솔의 버킷 페이지를 열고 앞서 생성한 버킷을 선택합니다. 업로드 를 선택합니다. 파일 추가 를 선택하고 파일 선택기를 사용하여 업로드할 객체를 선택합니다. 이 객체는 사용자가 선택한 임의의 파일이 될 수 있습니다. 열기 를 선택한 후 업로드 를 선택합니다. CloudWatch Logs를 사용하여 함수 간접 호출을 확인하려면 다음을 수행합니다. CloudWatch 콘솔을 엽니다 . Lambda 함수를 생성한 동일한 AWS 리전에서 작업 중인지 확인합니다. 화면 상단의 드롭다운 목록을 사용하여 리전을 변경할 수 있습니다. 로그 를 선택한 후 로그 그룹 을 선택합니다. 함수에 대한 로그 그룹( /aws/lambda/s3-trigger-tutorial )을 선택합니다. 로그 스트림 에서 가장 최근의 로그 스트림을 선택합니다. Amazon S3 트리거에 대한 응답으로 함수가 제대로 간접적으로 간접 호출된 경우 다음과 유사한 출력이 표시됩니다. 표시되는 CONTENT TYPE 은 버킷에 업로드한 파일 유형에 따라 달라집니다. 2022-05-09T23:17:28.702Z 0cae7f5a-b0af-4c73-8563-a3430333cc10 INFO CONTENT TYPE: image/jpeg 리소스 정리 이 자습서 용도로 생성한 리소스를 보관하고 싶지 않다면 지금 삭제할 수 있습니다. 더 이상 사용하지 않는 AWS 리소스를 삭제하면 AWS 계정에 불필요한 요금이 발생하는 것을 방지할 수 있습니다. Lambda 함수를 삭제하려면 Lambda 콘솔의 함수 페이지 를 엽니다. 생성한 함수를 선택합니다. 작업 (Actions), 삭제 (Delete)를 선택합니다. 텍스트 입력 필드에 confirm 를 입력하고 Delete (삭제)를 선택합니다. 집행 역할 삭제 IAM 콘솔에서 역할 페이지 를 엽니다. 생성한 실행 역할을 선택합니다. 삭제 를 선택합니다. 텍스트 입력 필드에 역할의 이름을 입력하고 Delete (삭제)를 선택합니다. S3 버킷을 삭제하려면 Amazon S3 콘솔 을 엽니다. 생성한 버킷을 선택합니다. 삭제 를 선택합니다. 텍스트 입력 필드에 버킷 이름을 입력합니다. 버킷 삭제(Delete bucket) 를 선택합니다. 다음 단계 자습서: Amazon S3 트리거를 사용하여 썸네일 이미지 생성 에서는 Amazon S3 트리거가 함수를 간접적으로 간접 호출하여 버킷에 업로드된 각 이미지 파일에 대해 썸네일 이미지를 생성합니다. 이 자습서를 진행하려면 중급 수준의 AWS 및 Lambda 분야 지식이 필요합니다. AWS Command Line Interface(AWS CLI)를 사용하여 리소스를 생성하는 방법과 함수 및 해당 종속성에 대한 .zip 파일 아카이브 배포 패키지를 생성하는 방법을 설명합니다. javascript가 브라우저에서 비활성화되거나 사용이 불가합니다. AWS 설명서를 사용하려면 Javascript가 활성화되어야 합니다. 지침을 보려면 브라우저의 도움말 페이지를 참조하십시오. 문서 규칙 S3 자습서: Amazon S3 트리거를 사용하여 썸네일 생성 이 페이지의 내용이 도움이 되었습니까? - 예 칭찬해 주셔서 감사합니다! 잠깐 시간을 내어 좋았던 부분을 알려 주시면 더 열심히 만들어 보겠습니다. 이 페이지의 내용이 도움이 되었습니까? - 아니요 이 페이지에 작업이 필요하다는 점을 알려 주셔서 감사합니다. 실망시켜 드려 죄송합니다. 잠깐 시간을 내어 설명서를 향상시킬 수 있는 방법에 대해 말씀해 주십시오. | 2026-01-13T09:30:35 |
https://docs.aws.amazon.com/zh_cn/lambda/latest/dg/configuring-alias-routing.html | 使用加权别名实施 Lambda 金丝雀部署 - AWS Lambda 使用加权别名实施 Lambda 金丝雀部署 - AWS Lambda 文档 AWS Lambda 开发人员指南 创建加权别名 监控流量 滚动部署 使用加权别名实施 Lambda 金丝雀部署 您可以使用加权别名在同一函数的两个不同 版本 之间拆分流量。通过此方法,您可以用一小部分流量测试新版本的函数,并在必要时快速回滚。这称为 金丝雀部署 。金丝雀部署与蓝/绿部署的不同之处在于,它只向部分请求公开新版本,而不是一次切换所有流量。 您可以将别名最多指向两个 Lambda 函数版本。版本必须满足以下条件: 两个版本必须具有相同的 执行角色 。 两个版本必须具有相同的 死信队列 配置,或者都没有死信队列配置。 这两个版本必须都已发布。别名不能指向 $LATEST 。 注意 Lambda 使用简单的概率模型在两个函数版本之间分发流量。低流量级别情况下,您可能会看到每个版本上配置的流量百分比与实际流量百分比之间的差异很大。如果您的函数使用预配置并发,则可以避免 溢出调用 ,方法是在别名路由处于活动状态期间配置更多的预配置并发实例。 创建加权别名 Console 使用控制台对别名配置路由 注意 确保函数至少具有两个已发布版本。要创建其他版本,请按照 创建函数版本 中的说明操作。 打开 Lamba 控制台的 Functions (函数)页面。 选择函数。 选择 Aliases (别名),然后选择 Create alias (创建别名)。 在 创建别名 页面上,执行以下操作: 输入别名的 名称 。 (可选)输入别名的 描述 。 对于 版本 ,选择希望别名指向的第一个函数版本。 展开 加权别名 。 对于 其他版本 ,请选择希望别名指向的第二个函数版本。 对于 权重 (%) ,输入函数的权重值。 权重 是在调用别名时分配给该版本的流量百分比。第一个版本接收剩余权重。例如,如果为 其他版本 指定 10%,则会自动为第一个版本分配 90%。 选择 保存 。 AWS CLI 使用 create-alias 和 update-alias AWS CLI 命令配置两个函数版本之间的流量权重。创建或更新别名时,您可以使用 routing-config 参数指定流量权重。 以下示例会创建一个名为 routing-alias 的 Lambda 函数别名,该别名指向函数的版本 1。函数的版本 2 接收 3% 的流量。其余 97% 的流量路由到版本 1。 aws lambda create-alias \ --name routing-alias \ --function-name my-function \ --function-version 1 \ --routing-config AdditionalVersionWeights= { "2"=0.03} 使用 update-alias 命令可提高流入版本 2 的流量的百分比。在下面的示例中,将该流量提高到 5%。 aws lambda update-alias \ --name routing-alias \ --function-name my-function \ --routing-config AdditionalVersionWeights= { "2"=0.05} 要将所有流量路由到版本 2,请使用 update-alias 命令更改 function-version 属性,以使别名指向版本 2。该命令还将重置路由配置。 aws lambda update-alias \ --name routing-alias \ --function-name my-function \ --function-version 2 \ --routing-config AdditionalVersionWeights= { } 以上步骤中的 AWS CLI 命令对应于以下 Lambda API 操作: CreateAlias UpdateAlias 确定调用的版本 配置两个函数版本之间的流量权重时,可以通过两种方法确定已调用的 Lambda 函数版本: CloudWatch Logs – 对于每次函数调用,Lambda 会自动发出包含调用的版本 ID 的 START 日志条目。示例: START RequestId: 1dh194d3759ed-4v8b-a7b4-1e541f60235f Version: 2 对于别名调用,Lambda 会使用 ExecutedVersion 维度按调用的版本筛选指标数据。有关更多信息,请参阅 查看 Lambda 函数的指标 。 响应负载 (同步调用) – 同步函数调用的响应包含 x-amz-executed-version 标头以指示已调用的函数版本。 使用加权别名创建滚动部署 使用 AWS CodeDeploy 和 AWS Serverless Application Model(AWS SAM)创建滚动部署,该部署可自动检测函数代码的更改、部署函数的新版本,并逐渐增加流向新版本的流量。您可以配置的参数包括流量和增长率。 在滚动部署中,AWS SAM 会执行以下任务: 配置您的 Lambda 函数并创建别名。加权别名路由配置是实施滚动部署的基础功能。 创建一个 CodeDeploy 应用程序和一个部署组。部署组可管理滚动部署和回滚(如果需要)。 检测您何时创建 Lambda 函数的新版本。 触发 CodeDeploy 启动部署新版本。 示例 AWS SAM 模板 下面的示例演示了用于简单滚动部署的 AWS SAM 模板 。 AWSTemplateFormatVersion : '2010-09-09' Transform: AWS::Serverless-2016-10-31 Description: A sample SAM template for deploying Lambda functions Resources: # Details about the myDateTimeFunction Lambda function myDateTimeFunction: Type: AWS::Serverless::Function Properties: Handler: myDateTimeFunction.handler Runtime: nodejs22.x # Creates an alias named "live" for the function, and automatically publishes when you update the function. AutoPublishAlias: live DeploymentPreference: # Specifies the deployment configuration Type: Linear10PercentEvery2Minutes 此模板定义一个名为 myDateTimeFunction 的 Lambda 函数,其中包含以下属性。 AutoPublishAlias AutoPublishAlias 属性创建一个名为 live 的别名。此外,AWS SAM 框架会自动检测您何时为函数保存新代码。然后,框架发布新的函数版本并更新 live 别名以便指向新版本。 DeploymentPreference DeploymentPreference 属性决定 CodeDeploy 应用程序将流量从 Lambda 函数的原始版本转移到新版本的速率。 Linear10PercentEvery2Minutes 值每两分钟将额外 10% 的流量转移到新版本。 有关预定义部署配置的列表,请参阅 部署配置 。 有关如何使用 CodeDeploy 和 AWS SAM 创建滚动部署的更多信息,请参阅以下内容: 教程:Deploy an updated Lambda function with CodeDeploy and the AWS Serverless Application Model Deploying serverless applications gradually with AWS SAM Javascript 在您的浏览器中被禁用或不可用。 要使用 Amazon Web Services 文档,必须启用 Javascript。请参阅浏览器的帮助页面以了解相关说明。 文档惯例 使用别名 版本 此页面对您有帮助吗?- 是 感谢您对我们工作的肯定! 如果不耽误您的时间,请告诉我们做得好的地方,让我们做得更好。 此页面对您有帮助吗?- 否 感谢您告诉我们本页内容还需要完善。很抱歉让您失望了。 如果不耽误您的时间,请告诉我们如何改进文档。 | 2026-01-13T09:30:35 |
https://docs.aws.amazon.com/lambda/latest/dg/with-s3-example.html#with-s3-example-upload-test-object | Tutorial: Using an Amazon S3 trigger to invoke a Lambda function - AWS Lambda Tutorial: Using an Amazon S3 trigger to invoke a Lambda function - AWS Lambda Documentation AWS Lambda Developer Guide Create an Amazon S3 bucket Upload a test object to your bucket Create a permissions policy Create an execution role Create the Lambda function Deploy the function code Create the Amazon S3 trigger Test the Lambda function Clean up your resources Next steps Tutorial: Using an Amazon S3 trigger to invoke a Lambda function In this tutorial, you use the console to create a Lambda function and configure a trigger for an Amazon Simple Storage Service (Amazon S3) bucket. Every time that you add an object to your Amazon S3 bucket, your function runs and outputs the object type to Amazon CloudWatch Logs. This tutorial demonstrates how to: Create an Amazon S3 bucket. Create a Lambda function that returns the object type of objects in an Amazon S3 bucket. Configure a Lambda trigger that invokes your function when objects are uploaded to your bucket. Test your function, first with a dummy event, and then using the trigger. By completing these steps, you’ll learn how to configure a Lambda function to run whenever objects are added to or deleted from an Amazon S3 bucket. You can complete this tutorial using only the AWS Management Console. Create an Amazon S3 bucket To create an Amazon S3 bucket Open the Amazon S3 console and select the General purpose buckets page. Select the AWS Region closest to your geographical location. You can change your region using the drop-down list at the top of the screen. Later in the tutorial, you must create your Lambda function in the same Region. Choose Create bucket . Under General configuration , do the following: For Bucket type , ensure General purpose is selected. For Bucket name , enter a globally unique name that meets the Amazon S3 Bucket naming rules . Bucket names can contain only lower case letters, numbers, dots (.), and hyphens (-). Leave all other options set to their default values and choose Create bucket . Upload a test object to your bucket To upload a test object Open the Buckets page of the Amazon S3 console and choose the bucket you created during the previous step. Choose Upload . Choose Add files and select the object that you want to upload. You can select any file (for example, HappyFace.jpg ). Choose Open , then choose Upload . Later in the tutorial, you’ll test your Lambda function using this object. Create a permissions policy Create a permissions policy that allows Lambda to get objects from an Amazon S3 bucket and to write to Amazon CloudWatch Logs. To create the policy Open the Policies page of the IAM console. Choose Create Policy . Choose the JSON tab, and then paste the following custom policy into the JSON editor. JSON { "Version":"2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "logs:PutLogEvents", "logs:CreateLogGroup", "logs:CreateLogStream" ], "Resource": "arn:aws:logs:*:*:*" }, { "Effect": "Allow", "Action": [ "s3:GetObject" ], "Resource": "arn:aws:s3:::*/*" } ] } Choose Next: Tags . Choose Next: Review . Under Review policy , for the policy Name , enter s3-trigger-tutorial . Choose Create policy . Create an execution role An execution role is an AWS Identity and Access Management (IAM) role that grants a Lambda function permission to access AWS services and resources. In this step, create an execution role using the permissions policy that you created in the previous step. To create an execution role and attach your custom permissions policy Open the Roles page of the IAM console. Choose Create role . For the type of trusted entity, choose AWS service , then for the use case, choose Lambda . Choose Next . In the policy search box, enter s3-trigger-tutorial . In the search results, select the policy that you created ( s3-trigger-tutorial ), and then choose Next . Under Role details , for the Role name , enter lambda-s3-trigger-role , then choose Create role . Create the Lambda function Create a Lambda function in the console using the Python 3.14 runtime. To create the Lambda function Open the Functions page of the Lambda console. Make sure you're working in the same AWS Region you created your Amazon S3 bucket in. You can change your Region using the drop-down list at the top of the screen. Choose Create function . Choose Author from scratch Under Basic information , do the following: For Function name , enter s3-trigger-tutorial For Runtime , choose Python 3.14 . For Architecture , choose x86_64 . In the Change default execution role tab, do the following: Expand the tab, then choose Use an existing role . Select the lambda-s3-trigger-role you created earlier. Choose Create function . Deploy the function code This tutorial uses the Python 3.14 runtime, but we’ve also provided example code files for other runtimes. You can select the tab in the following box to see the code for the runtime you’re interested in. The Lambda function retrieves the key name of the uploaded object and the name of the bucket from the event parameter it receives from Amazon S3. The function then uses the get_object method from the AWS SDK for Python (Boto3) to retrieve the object's metadata, including the content type (MIME type) of the uploaded object. To deploy the function code Choose the Python tab in the following box and copy the code. .NET SDK for .NET Note There's more on GitHub. Find the complete example and learn how to set up and run in the Serverless examples repository. Consuming an S3 event with Lambda using .NET. // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System.Threading.Tasks; using Amazon.Lambda.Core; using Amazon.S3; using System; using Amazon.Lambda.S3Events; using System.Web; // Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class. [assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] namespace S3Integration { public class Function { private static AmazonS3Client _s3Client; public Function() : this(null) { } internal Function(AmazonS3Client s3Client) { _s3Client = s3Client ?? new AmazonS3Client(); } public async Task<string> Handler(S3Event evt, ILambdaContext context) { try { if (evt.Records.Count <= 0) { context.Logger.LogLine("Empty S3 Event received"); return string.Empty; } var bucket = evt.Records[0].S3.Bucket.Name; var key = HttpUtility.UrlDecode(evt.Records[0].S3.Object.Key); context.Logger.LogLine($"Request is for { bucket} and { key}"); var objectResult = await _s3Client.GetObjectAsync(bucket, key); context.Logger.LogLine($"Returning { objectResult.Key}"); return objectResult.Key; } catch (Exception e) { context.Logger.LogLine($"Error processing request - { e.Message}"); return string.Empty; } } } } Go SDK for Go V2 Note There's more on GitHub. Find the complete example and learn how to set up and run in the Serverless examples repository. Consuming an S3 event with Lambda using Go. // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package main import ( "context" "log" "github.com/aws/aws-lambda-go/events" "github.com/aws/aws-lambda-go/lambda" "github.com/aws/aws-sdk-go-v2/config" "github.com/aws/aws-sdk-go-v2/service/s3" ) func handler(ctx context.Context, s3Event events.S3Event) error { sdkConfig, err := config.LoadDefaultConfig(ctx) if err != nil { log.Printf("failed to load default config: %s", err) return err } s3Client := s3.NewFromConfig(sdkConfig) for _, record := range s3Event.Records { bucket := record.S3.Bucket.Name key := record.S3.Object.URLDecodedKey headOutput, err := s3Client.HeadObject(ctx, &s3.HeadObjectInput { Bucket: &bucket, Key: &key, }) if err != nil { log.Printf("error getting head of object %s/%s: %s", bucket, key, err) return err } log.Printf("successfully retrieved %s/%s of type %s", bucket, key, *headOutput.ContentType) } return nil } func main() { lambda.Start(handler) } Java SDK for Java 2.x Note There's more on GitHub. Find the complete example and learn how to set up and run in the Serverless examples repository. Consuming an S3 event with Lambda using Java. // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package example; import software.amazon.awssdk.services.s3.model.HeadObjectRequest; import software.amazon.awssdk.services.s3.model.HeadObjectResponse; import software.amazon.awssdk.services.s3.S3Client; import com.amazonaws.services.lambda.runtime.Context; import com.amazonaws.services.lambda.runtime.RequestHandler; import com.amazonaws.services.lambda.runtime.events.S3Event; import com.amazonaws.services.lambda.runtime.events.models.s3.S3EventNotification.S3EventNotificationRecord; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class Handler implements RequestHandler<S3Event, String> { private static final Logger logger = LoggerFactory.getLogger(Handler.class); @Override public String handleRequest(S3Event s3event, Context context) { try { S3EventNotificationRecord record = s3event.getRecords().get(0); String srcBucket = record.getS3().getBucket().getName(); String srcKey = record.getS3().getObject().getUrlDecodedKey(); S3Client s3Client = S3Client.builder().build(); HeadObjectResponse headObject = getHeadObject(s3Client, srcBucket, srcKey); logger.info("Successfully retrieved " + srcBucket + "/" + srcKey + " of type " + headObject.contentType()); return "Ok"; } catch (Exception e) { throw new RuntimeException(e); } } private HeadObjectResponse getHeadObject(S3Client s3Client, String bucket, String key) { HeadObjectRequest headObjectRequest = HeadObjectRequest.builder() .bucket(bucket) .key(key) .build(); return s3Client.headObject(headObjectRequest); } } JavaScript SDK for JavaScript (v3) Note There's more on GitHub. Find the complete example and learn how to set up and run in the Serverless examples repository. Consuming an S3 event with Lambda using JavaScript. import { S3Client, HeadObjectCommand } from "@aws-sdk/client-s3"; const client = new S3Client(); export const handler = async (event, context) => { // Get the object from the event and show its content type const bucket = event.Records[0].s3.bucket.name; const key = decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g, ' ')); try { const { ContentType } = await client.send(new HeadObjectCommand( { Bucket: bucket, Key: key, })); console.log('CONTENT TYPE:', ContentType); return ContentType; } catch (err) { console.log(err); const message = `Error getting object $ { key} from bucket $ { bucket}. Make sure they exist and your bucket is in the same region as this function.`; console.log(message); throw new Error(message); } }; Consuming an S3 event with Lambda using TypeScript. // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 import { S3Event } from 'aws-lambda'; import { S3Client, HeadObjectCommand } from '@aws-sdk/client-s3'; const s3 = new S3Client( { region: process.env.AWS_REGION }); export const handler = async (event: S3Event): Promise<string | undefined> => { // Get the object from the event and show its content type const bucket = event.Records[0].s3.bucket.name; const key = decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g, ' ')); const params = { Bucket: bucket, Key: key, }; try { const { ContentType } = await s3.send(new HeadObjectCommand(params)); console.log('CONTENT TYPE:', ContentType); return ContentType; } catch (err) { console.log(err); const message = `Error getting object $ { key} from bucket $ { bucket}. Make sure they exist and your bucket is in the same region as this function.`; console.log(message); throw new Error(message); } }; PHP SDK for PHP Note There's more on GitHub. Find the complete example and learn how to set up and run in the Serverless examples repository. Consuming an S3 event with Lambda using PHP. <?php use Bref\Context\Context; use Bref\Event\S3\S3Event; use Bref\Event\S3\S3Handler; use Bref\Logger\StderrLogger; require __DIR__ . '/vendor/autoload.php'; class Handler extends S3Handler { private StderrLogger $logger; public function __construct(StderrLogger $logger) { $this->logger = $logger; } public function handleS3(S3Event $event, Context $context) : void { $this->logger->info("Processing S3 records"); // Get the object from the event and show its content type $records = $event->getRecords(); foreach ($records as $record) { $bucket = $record->getBucket()->getName(); $key = urldecode($record->getObject()->getKey()); try { $fileSize = urldecode($record->getObject()->getSize()); echo "File Size: " . $fileSize . "\n"; // TODO: Implement your custom processing logic here } catch (Exception $e) { echo $e->getMessage() . "\n"; echo 'Error getting object ' . $key . ' from bucket ' . $bucket . '. Make sure they exist and your bucket is in the same region as this function.' . "\n"; throw $e; } } } } $logger = new StderrLogger(); return new Handler($logger); Python SDK for Python (Boto3) Note There's more on GitHub. Find the complete example and learn how to set up and run in the Serverless examples repository. Consuming an S3 event with Lambda using Python. # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 import json import urllib.parse import boto3 print('Loading function') s3 = boto3.client('s3') def lambda_handler(event, context): #print("Received event: " + json.dumps(event, indent=2)) # Get the object from the event and show its content type bucket = event['Records'][0]['s3']['bucket']['name'] key = urllib.parse.unquote_plus(event['Records'][0]['s3']['object']['key'], encoding='utf-8') try: response = s3.get_object(Bucket=bucket, Key=key) print("CONTENT TYPE: " + response['ContentType']) return response['ContentType'] except Exception as e: print(e) print('Error getting object { } from bucket { }. Make sure they exist and your bucket is in the same region as this function.'.format(key, bucket)) raise e Ruby SDK for Ruby Note There's more on GitHub. Find the complete example and learn how to set up and run in the Serverless examples repository. Consuming an S3 event with Lambda using Ruby. require 'json' require 'uri' require 'aws-sdk' puts 'Loading function' def lambda_handler(event:, context:) s3 = Aws::S3::Client.new(region: 'region') # Your AWS region # puts "Received event: # { JSON.dump(event)}" # Get the object from the event and show its content type bucket = event['Records'][0]['s3']['bucket']['name'] key = URI.decode_www_form_component(event['Records'][0]['s3']['object']['key'], Encoding::UTF_8) begin response = s3.get_object(bucket: bucket, key: key) puts "CONTENT TYPE: # { response.content_type}" return response.content_type rescue StandardError => e puts e.message puts "Error getting object # { key} from bucket # { bucket}. Make sure they exist and your bucket is in the same region as this function." raise e end end Rust SDK for Rust Note There's more on GitHub. Find the complete example and learn how to set up and run in the Serverless examples repository. Consuming an S3 event with Lambda using Rust. // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 use aws_lambda_events::event::s3::S3Event; use aws_sdk_s3:: { Client}; use lambda_runtime:: { run, service_fn, Error, LambdaEvent}; /// Main function #[tokio::main] async fn main() -> Result<(), Error> { tracing_subscriber::fmt() .with_max_level(tracing::Level::INFO) .with_target(false) .without_time() .init(); // Initialize the AWS SDK for Rust let config = aws_config::load_from_env().await; let s3_client = Client::new(&config); let res = run(service_fn(|request: LambdaEvent<S3Event>| { function_handler(&s3_client, request) })).await; res } async fn function_handler( s3_client: &Client, evt: LambdaEvent<S3Event> ) -> Result<(), Error> { tracing::info!(records = ?evt.payload.records.len(), "Received request from SQS"); if evt.payload.records.len() == 0 { tracing::info!("Empty S3 event received"); } let bucket = evt.payload.records[0].s3.bucket.name.as_ref().expect("Bucket name to exist"); let key = evt.payload.records[0].s3.object.key.as_ref().expect("Object key to exist"); tracing::info!("Request is for { } and object { }", bucket, key); let s3_get_object_result = s3_client .get_object() .bucket(bucket) .key(key) .send() .await; match s3_get_object_result { Ok(_) => tracing::info!("S3 Get Object success, the s3GetObjectResult contains a 'body' property of type ByteStream"), Err(_) => tracing::info!("Failure with S3 Get Object request") } Ok(()) } In the Code source pane on the Lambda console, paste the code into the code editor, replacing the code that Lambda created. In the DEPLOY section, choose Deploy to update your function's code: Create the Amazon S3 trigger To create the Amazon S3 trigger In the Function overview pane, choose Add trigger . Select S3 . Under Bucket , select the bucket you created earlier in the tutorial. Under Event types , be sure that All object create events is selected. Under Recursive invocation , select the check box to acknowledge that using the same Amazon S3 bucket for input and output is not recommended. Choose Add . Note When you create an Amazon S3 trigger for a Lambda function using the Lambda console, Amazon S3 configures an event notification on the bucket you specify. Before configuring this event notification, Amazon S3 performs a series of checks to confirm that the event destination exists and has the required IAM policies. Amazon S3 also performs these tests on any other event notifications configured for that bucket. Because of this check, if the bucket has previously configured event destinations for resources that no longer exist, or for resources that don't have the required permissions policies, Amazon S3 won't be able to create the new event notification. You'll see the following error message indicating that your trigger couldn't be created: An error occurred when creating the trigger: Unable to validate the following destination configurations. You can see this error if you previously configured a trigger for another Lambda function using the same bucket, and you have since deleted the function or modified its permissions policies. Test your Lambda function with a dummy event To test the Lambda function with a dummy event In the Lambda console page for your function, choose the Test tab. For Event name , enter MyTestEvent . In the Event JSON , paste the following test event. Be sure to replace these values: Replace us-east-1 with the region you created your Amazon S3 bucket in. Replace both instances of amzn-s3-demo-bucket with the name of your own Amazon S3 bucket. Replace test%2FKey with the name of the test object you uploaded to your bucket earlier (for example, HappyFace.jpg ). { "Records": [ { "eventVersion": "2.0", "eventSource": "aws:s3", "awsRegion": " us-east-1 ", "eventTime": "1970-01-01T00:00:00.000Z", "eventName": "ObjectCreated:Put", "userIdentity": { "principalId": "EXAMPLE" }, "requestParameters": { "sourceIPAddress": "127.0.0.1" }, "responseElements": { "x-amz-request-id": "EXAMPLE123456789", "x-amz-id-2": "EXAMPLE123/5678abcdefghijklambdaisawesome/mnopqrstuvwxyzABCDEFGH" }, "s3": { "s3SchemaVersion": "1.0", "configurationId": "testConfigRule", "bucket": { "name": " amzn-s3-demo-bucket ", "ownerIdentity": { "principalId": "EXAMPLE" }, "arn": "arn:aws:s3::: amzn-s3-demo-bucket " }, "object": { "key": " test%2Fkey ", "size": 1024, "eTag": "0123456789abcdef0123456789abcdef", "sequencer": "0A1B2C3D4E5F678901" } } } ] } Choose Save . Choose Test . If your function runs successfully, you’ll see output similar to the following in the Execution results tab. Response "image/jpeg" Function Logs START RequestId: 12b3cae7-5f4e-415e-93e6-416b8f8b66e6 Version: $LATEST 2021-02-18T21:40:59.280Z 12b3cae7-5f4e-415e-93e6-416b8f8b66e6 INFO INPUT BUCKET AND KEY: { Bucket: 'amzn-s3-demo-bucket', Key: 'HappyFace.jpg' } 2021-02-18T21:41:00.215Z 12b3cae7-5f4e-415e-93e6-416b8f8b66e6 INFO CONTENT TYPE: image/jpeg END RequestId: 12b3cae7-5f4e-415e-93e6-416b8f8b66e6 REPORT RequestId: 12b3cae7-5f4e-415e-93e6-416b8f8b66e6 Duration: 976.25 ms Billed Duration: 977 ms Memory Size: 128 MB Max Memory Used: 90 MB Init Duration: 430.47 ms Request ID 12b3cae7-5f4e-415e-93e6-416b8f8b66e6 Test the Lambda function with the Amazon S3 trigger To test your function with the configured trigger, upload an object to your Amazon S3 bucket using the console. To verify that your Lambda function ran as expected, use CloudWatch Logs to view your function’s output. To upload an object to your Amazon S3 bucket Open the Buckets page of the Amazon S3 console and choose the bucket that you created earlier. Choose Upload . Choose Add files and use the file selector to choose an object you want to upload. This object can be any file you choose. Choose Open , then choose Upload . To verify the function invocation using CloudWatch Logs Open the CloudWatch console. Make sure you're working in the same AWS Region you created your Lambda function in. You can change your Region using the drop-down list at the top of the screen. Choose Logs , then choose Log groups . Choose the log group for your function ( /aws/lambda/s3-trigger-tutorial ). Under Log streams , choose the most recent log stream. If your function was invoked correctly in response to your Amazon S3 trigger, you’ll see output similar to the following. The CONTENT TYPE you see depends on the type of file you uploaded to your bucket. 2022-05-09T23:17:28.702Z 0cae7f5a-b0af-4c73-8563-a3430333cc10 INFO CONTENT TYPE: image/jpeg Clean up your resources You can now delete the resources that you created for this tutorial, unless you want to retain them. By deleting AWS resources that you're no longer using, you prevent unnecessary charges to your AWS account. To delete the Lambda function Open the Functions page of the Lambda console. Select the function that you created. Choose Actions , Delete . Type confirm in the text input field and choose Delete . To delete the execution role Open the Roles page of the IAM console. Select the execution role that you created. Choose Delete . Enter the name of the role in the text input field and choose Delete . To delete the S3 bucket Open the Amazon S3 console. Select the bucket you created. Choose Delete . Enter the name of the bucket in the text input field. Choose Delete bucket . Next steps In Tutorial: Using an Amazon S3 trigger to create thumbnail images , the Amazon S3 trigger invokes a function that creates a thumbnail image for each image file that is uploaded to a bucket. This tutorial requires a moderate level of AWS and Lambda domain knowledge. It demonstrates how to create resources using the AWS Command Line Interface (AWS CLI) and how to create a .zip file archive deployment package for the function and its dependencies. Javascript is disabled or is unavailable in your browser. To use the Amazon Web Services Documentation, Javascript must be enabled. Please refer to your browser's Help pages for instructions. Document Conventions S3 Tutorial: Use an Amazon S3 trigger to create thumbnails Did this page help you? - Yes Thanks for letting us know we're doing a good job! If you've got a moment, please tell us what we did right so we can do more of it. Did this page help you? - No Thanks for letting us know this page needs work. We're sorry we let you down. If you've got a moment, please tell us how we can make the documentation better. | 2026-01-13T09:30:35 |
https://docs.aws.amazon.com/lambda/latest/dg/with-s3-example.html#next-steps | Tutorial: Using an Amazon S3 trigger to invoke a Lambda function - AWS Lambda Tutorial: Using an Amazon S3 trigger to invoke a Lambda function - AWS Lambda Documentation AWS Lambda Developer Guide Create an Amazon S3 bucket Upload a test object to your bucket Create a permissions policy Create an execution role Create the Lambda function Deploy the function code Create the Amazon S3 trigger Test the Lambda function Clean up your resources Next steps Tutorial: Using an Amazon S3 trigger to invoke a Lambda function In this tutorial, you use the console to create a Lambda function and configure a trigger for an Amazon Simple Storage Service (Amazon S3) bucket. Every time that you add an object to your Amazon S3 bucket, your function runs and outputs the object type to Amazon CloudWatch Logs. This tutorial demonstrates how to: Create an Amazon S3 bucket. Create a Lambda function that returns the object type of objects in an Amazon S3 bucket. Configure a Lambda trigger that invokes your function when objects are uploaded to your bucket. Test your function, first with a dummy event, and then using the trigger. By completing these steps, you’ll learn how to configure a Lambda function to run whenever objects are added to or deleted from an Amazon S3 bucket. You can complete this tutorial using only the AWS Management Console. Create an Amazon S3 bucket To create an Amazon S3 bucket Open the Amazon S3 console and select the General purpose buckets page. Select the AWS Region closest to your geographical location. You can change your region using the drop-down list at the top of the screen. Later in the tutorial, you must create your Lambda function in the same Region. Choose Create bucket . Under General configuration , do the following: For Bucket type , ensure General purpose is selected. For Bucket name , enter a globally unique name that meets the Amazon S3 Bucket naming rules . Bucket names can contain only lower case letters, numbers, dots (.), and hyphens (-). Leave all other options set to their default values and choose Create bucket . Upload a test object to your bucket To upload a test object Open the Buckets page of the Amazon S3 console and choose the bucket you created during the previous step. Choose Upload . Choose Add files and select the object that you want to upload. You can select any file (for example, HappyFace.jpg ). Choose Open , then choose Upload . Later in the tutorial, you’ll test your Lambda function using this object. Create a permissions policy Create a permissions policy that allows Lambda to get objects from an Amazon S3 bucket and to write to Amazon CloudWatch Logs. To create the policy Open the Policies page of the IAM console. Choose Create Policy . Choose the JSON tab, and then paste the following custom policy into the JSON editor. JSON { "Version":"2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "logs:PutLogEvents", "logs:CreateLogGroup", "logs:CreateLogStream" ], "Resource": "arn:aws:logs:*:*:*" }, { "Effect": "Allow", "Action": [ "s3:GetObject" ], "Resource": "arn:aws:s3:::*/*" } ] } Choose Next: Tags . Choose Next: Review . Under Review policy , for the policy Name , enter s3-trigger-tutorial . Choose Create policy . Create an execution role An execution role is an AWS Identity and Access Management (IAM) role that grants a Lambda function permission to access AWS services and resources. In this step, create an execution role using the permissions policy that you created in the previous step. To create an execution role and attach your custom permissions policy Open the Roles page of the IAM console. Choose Create role . For the type of trusted entity, choose AWS service , then for the use case, choose Lambda . Choose Next . In the policy search box, enter s3-trigger-tutorial . In the search results, select the policy that you created ( s3-trigger-tutorial ), and then choose Next . Under Role details , for the Role name , enter lambda-s3-trigger-role , then choose Create role . Create the Lambda function Create a Lambda function in the console using the Python 3.14 runtime. To create the Lambda function Open the Functions page of the Lambda console. Make sure you're working in the same AWS Region you created your Amazon S3 bucket in. You can change your Region using the drop-down list at the top of the screen. Choose Create function . Choose Author from scratch Under Basic information , do the following: For Function name , enter s3-trigger-tutorial For Runtime , choose Python 3.14 . For Architecture , choose x86_64 . In the Change default execution role tab, do the following: Expand the tab, then choose Use an existing role . Select the lambda-s3-trigger-role you created earlier. Choose Create function . Deploy the function code This tutorial uses the Python 3.14 runtime, but we’ve also provided example code files for other runtimes. You can select the tab in the following box to see the code for the runtime you’re interested in. The Lambda function retrieves the key name of the uploaded object and the name of the bucket from the event parameter it receives from Amazon S3. The function then uses the get_object method from the AWS SDK for Python (Boto3) to retrieve the object's metadata, including the content type (MIME type) of the uploaded object. To deploy the function code Choose the Python tab in the following box and copy the code. .NET SDK for .NET Note There's more on GitHub. Find the complete example and learn how to set up and run in the Serverless examples repository. Consuming an S3 event with Lambda using .NET. // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System.Threading.Tasks; using Amazon.Lambda.Core; using Amazon.S3; using System; using Amazon.Lambda.S3Events; using System.Web; // Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class. [assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] namespace S3Integration { public class Function { private static AmazonS3Client _s3Client; public Function() : this(null) { } internal Function(AmazonS3Client s3Client) { _s3Client = s3Client ?? new AmazonS3Client(); } public async Task<string> Handler(S3Event evt, ILambdaContext context) { try { if (evt.Records.Count <= 0) { context.Logger.LogLine("Empty S3 Event received"); return string.Empty; } var bucket = evt.Records[0].S3.Bucket.Name; var key = HttpUtility.UrlDecode(evt.Records[0].S3.Object.Key); context.Logger.LogLine($"Request is for { bucket} and { key}"); var objectResult = await _s3Client.GetObjectAsync(bucket, key); context.Logger.LogLine($"Returning { objectResult.Key}"); return objectResult.Key; } catch (Exception e) { context.Logger.LogLine($"Error processing request - { e.Message}"); return string.Empty; } } } } Go SDK for Go V2 Note There's more on GitHub. Find the complete example and learn how to set up and run in the Serverless examples repository. Consuming an S3 event with Lambda using Go. // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package main import ( "context" "log" "github.com/aws/aws-lambda-go/events" "github.com/aws/aws-lambda-go/lambda" "github.com/aws/aws-sdk-go-v2/config" "github.com/aws/aws-sdk-go-v2/service/s3" ) func handler(ctx context.Context, s3Event events.S3Event) error { sdkConfig, err := config.LoadDefaultConfig(ctx) if err != nil { log.Printf("failed to load default config: %s", err) return err } s3Client := s3.NewFromConfig(sdkConfig) for _, record := range s3Event.Records { bucket := record.S3.Bucket.Name key := record.S3.Object.URLDecodedKey headOutput, err := s3Client.HeadObject(ctx, &s3.HeadObjectInput { Bucket: &bucket, Key: &key, }) if err != nil { log.Printf("error getting head of object %s/%s: %s", bucket, key, err) return err } log.Printf("successfully retrieved %s/%s of type %s", bucket, key, *headOutput.ContentType) } return nil } func main() { lambda.Start(handler) } Java SDK for Java 2.x Note There's more on GitHub. Find the complete example and learn how to set up and run in the Serverless examples repository. Consuming an S3 event with Lambda using Java. // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package example; import software.amazon.awssdk.services.s3.model.HeadObjectRequest; import software.amazon.awssdk.services.s3.model.HeadObjectResponse; import software.amazon.awssdk.services.s3.S3Client; import com.amazonaws.services.lambda.runtime.Context; import com.amazonaws.services.lambda.runtime.RequestHandler; import com.amazonaws.services.lambda.runtime.events.S3Event; import com.amazonaws.services.lambda.runtime.events.models.s3.S3EventNotification.S3EventNotificationRecord; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class Handler implements RequestHandler<S3Event, String> { private static final Logger logger = LoggerFactory.getLogger(Handler.class); @Override public String handleRequest(S3Event s3event, Context context) { try { S3EventNotificationRecord record = s3event.getRecords().get(0); String srcBucket = record.getS3().getBucket().getName(); String srcKey = record.getS3().getObject().getUrlDecodedKey(); S3Client s3Client = S3Client.builder().build(); HeadObjectResponse headObject = getHeadObject(s3Client, srcBucket, srcKey); logger.info("Successfully retrieved " + srcBucket + "/" + srcKey + " of type " + headObject.contentType()); return "Ok"; } catch (Exception e) { throw new RuntimeException(e); } } private HeadObjectResponse getHeadObject(S3Client s3Client, String bucket, String key) { HeadObjectRequest headObjectRequest = HeadObjectRequest.builder() .bucket(bucket) .key(key) .build(); return s3Client.headObject(headObjectRequest); } } JavaScript SDK for JavaScript (v3) Note There's more on GitHub. Find the complete example and learn how to set up and run in the Serverless examples repository. Consuming an S3 event with Lambda using JavaScript. import { S3Client, HeadObjectCommand } from "@aws-sdk/client-s3"; const client = new S3Client(); export const handler = async (event, context) => { // Get the object from the event and show its content type const bucket = event.Records[0].s3.bucket.name; const key = decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g, ' ')); try { const { ContentType } = await client.send(new HeadObjectCommand( { Bucket: bucket, Key: key, })); console.log('CONTENT TYPE:', ContentType); return ContentType; } catch (err) { console.log(err); const message = `Error getting object $ { key} from bucket $ { bucket}. Make sure they exist and your bucket is in the same region as this function.`; console.log(message); throw new Error(message); } }; Consuming an S3 event with Lambda using TypeScript. // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 import { S3Event } from 'aws-lambda'; import { S3Client, HeadObjectCommand } from '@aws-sdk/client-s3'; const s3 = new S3Client( { region: process.env.AWS_REGION }); export const handler = async (event: S3Event): Promise<string | undefined> => { // Get the object from the event and show its content type const bucket = event.Records[0].s3.bucket.name; const key = decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g, ' ')); const params = { Bucket: bucket, Key: key, }; try { const { ContentType } = await s3.send(new HeadObjectCommand(params)); console.log('CONTENT TYPE:', ContentType); return ContentType; } catch (err) { console.log(err); const message = `Error getting object $ { key} from bucket $ { bucket}. Make sure they exist and your bucket is in the same region as this function.`; console.log(message); throw new Error(message); } }; PHP SDK for PHP Note There's more on GitHub. Find the complete example and learn how to set up and run in the Serverless examples repository. Consuming an S3 event with Lambda using PHP. <?php use Bref\Context\Context; use Bref\Event\S3\S3Event; use Bref\Event\S3\S3Handler; use Bref\Logger\StderrLogger; require __DIR__ . '/vendor/autoload.php'; class Handler extends S3Handler { private StderrLogger $logger; public function __construct(StderrLogger $logger) { $this->logger = $logger; } public function handleS3(S3Event $event, Context $context) : void { $this->logger->info("Processing S3 records"); // Get the object from the event and show its content type $records = $event->getRecords(); foreach ($records as $record) { $bucket = $record->getBucket()->getName(); $key = urldecode($record->getObject()->getKey()); try { $fileSize = urldecode($record->getObject()->getSize()); echo "File Size: " . $fileSize . "\n"; // TODO: Implement your custom processing logic here } catch (Exception $e) { echo $e->getMessage() . "\n"; echo 'Error getting object ' . $key . ' from bucket ' . $bucket . '. Make sure they exist and your bucket is in the same region as this function.' . "\n"; throw $e; } } } } $logger = new StderrLogger(); return new Handler($logger); Python SDK for Python (Boto3) Note There's more on GitHub. Find the complete example and learn how to set up and run in the Serverless examples repository. Consuming an S3 event with Lambda using Python. # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 import json import urllib.parse import boto3 print('Loading function') s3 = boto3.client('s3') def lambda_handler(event, context): #print("Received event: " + json.dumps(event, indent=2)) # Get the object from the event and show its content type bucket = event['Records'][0]['s3']['bucket']['name'] key = urllib.parse.unquote_plus(event['Records'][0]['s3']['object']['key'], encoding='utf-8') try: response = s3.get_object(Bucket=bucket, Key=key) print("CONTENT TYPE: " + response['ContentType']) return response['ContentType'] except Exception as e: print(e) print('Error getting object { } from bucket { }. Make sure they exist and your bucket is in the same region as this function.'.format(key, bucket)) raise e Ruby SDK for Ruby Note There's more on GitHub. Find the complete example and learn how to set up and run in the Serverless examples repository. Consuming an S3 event with Lambda using Ruby. require 'json' require 'uri' require 'aws-sdk' puts 'Loading function' def lambda_handler(event:, context:) s3 = Aws::S3::Client.new(region: 'region') # Your AWS region # puts "Received event: # { JSON.dump(event)}" # Get the object from the event and show its content type bucket = event['Records'][0]['s3']['bucket']['name'] key = URI.decode_www_form_component(event['Records'][0]['s3']['object']['key'], Encoding::UTF_8) begin response = s3.get_object(bucket: bucket, key: key) puts "CONTENT TYPE: # { response.content_type}" return response.content_type rescue StandardError => e puts e.message puts "Error getting object # { key} from bucket # { bucket}. Make sure they exist and your bucket is in the same region as this function." raise e end end Rust SDK for Rust Note There's more on GitHub. Find the complete example and learn how to set up and run in the Serverless examples repository. Consuming an S3 event with Lambda using Rust. // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 use aws_lambda_events::event::s3::S3Event; use aws_sdk_s3:: { Client}; use lambda_runtime:: { run, service_fn, Error, LambdaEvent}; /// Main function #[tokio::main] async fn main() -> Result<(), Error> { tracing_subscriber::fmt() .with_max_level(tracing::Level::INFO) .with_target(false) .without_time() .init(); // Initialize the AWS SDK for Rust let config = aws_config::load_from_env().await; let s3_client = Client::new(&config); let res = run(service_fn(|request: LambdaEvent<S3Event>| { function_handler(&s3_client, request) })).await; res } async fn function_handler( s3_client: &Client, evt: LambdaEvent<S3Event> ) -> Result<(), Error> { tracing::info!(records = ?evt.payload.records.len(), "Received request from SQS"); if evt.payload.records.len() == 0 { tracing::info!("Empty S3 event received"); } let bucket = evt.payload.records[0].s3.bucket.name.as_ref().expect("Bucket name to exist"); let key = evt.payload.records[0].s3.object.key.as_ref().expect("Object key to exist"); tracing::info!("Request is for { } and object { }", bucket, key); let s3_get_object_result = s3_client .get_object() .bucket(bucket) .key(key) .send() .await; match s3_get_object_result { Ok(_) => tracing::info!("S3 Get Object success, the s3GetObjectResult contains a 'body' property of type ByteStream"), Err(_) => tracing::info!("Failure with S3 Get Object request") } Ok(()) } In the Code source pane on the Lambda console, paste the code into the code editor, replacing the code that Lambda created. In the DEPLOY section, choose Deploy to update your function's code: Create the Amazon S3 trigger To create the Amazon S3 trigger In the Function overview pane, choose Add trigger . Select S3 . Under Bucket , select the bucket you created earlier in the tutorial. Under Event types , be sure that All object create events is selected. Under Recursive invocation , select the check box to acknowledge that using the same Amazon S3 bucket for input and output is not recommended. Choose Add . Note When you create an Amazon S3 trigger for a Lambda function using the Lambda console, Amazon S3 configures an event notification on the bucket you specify. Before configuring this event notification, Amazon S3 performs a series of checks to confirm that the event destination exists and has the required IAM policies. Amazon S3 also performs these tests on any other event notifications configured for that bucket. Because of this check, if the bucket has previously configured event destinations for resources that no longer exist, or for resources that don't have the required permissions policies, Amazon S3 won't be able to create the new event notification. You'll see the following error message indicating that your trigger couldn't be created: An error occurred when creating the trigger: Unable to validate the following destination configurations. You can see this error if you previously configured a trigger for another Lambda function using the same bucket, and you have since deleted the function or modified its permissions policies. Test your Lambda function with a dummy event To test the Lambda function with a dummy event In the Lambda console page for your function, choose the Test tab. For Event name , enter MyTestEvent . In the Event JSON , paste the following test event. Be sure to replace these values: Replace us-east-1 with the region you created your Amazon S3 bucket in. Replace both instances of amzn-s3-demo-bucket with the name of your own Amazon S3 bucket. Replace test%2FKey with the name of the test object you uploaded to your bucket earlier (for example, HappyFace.jpg ). { "Records": [ { "eventVersion": "2.0", "eventSource": "aws:s3", "awsRegion": " us-east-1 ", "eventTime": "1970-01-01T00:00:00.000Z", "eventName": "ObjectCreated:Put", "userIdentity": { "principalId": "EXAMPLE" }, "requestParameters": { "sourceIPAddress": "127.0.0.1" }, "responseElements": { "x-amz-request-id": "EXAMPLE123456789", "x-amz-id-2": "EXAMPLE123/5678abcdefghijklambdaisawesome/mnopqrstuvwxyzABCDEFGH" }, "s3": { "s3SchemaVersion": "1.0", "configurationId": "testConfigRule", "bucket": { "name": " amzn-s3-demo-bucket ", "ownerIdentity": { "principalId": "EXAMPLE" }, "arn": "arn:aws:s3::: amzn-s3-demo-bucket " }, "object": { "key": " test%2Fkey ", "size": 1024, "eTag": "0123456789abcdef0123456789abcdef", "sequencer": "0A1B2C3D4E5F678901" } } } ] } Choose Save . Choose Test . If your function runs successfully, you’ll see output similar to the following in the Execution results tab. Response "image/jpeg" Function Logs START RequestId: 12b3cae7-5f4e-415e-93e6-416b8f8b66e6 Version: $LATEST 2021-02-18T21:40:59.280Z 12b3cae7-5f4e-415e-93e6-416b8f8b66e6 INFO INPUT BUCKET AND KEY: { Bucket: 'amzn-s3-demo-bucket', Key: 'HappyFace.jpg' } 2021-02-18T21:41:00.215Z 12b3cae7-5f4e-415e-93e6-416b8f8b66e6 INFO CONTENT TYPE: image/jpeg END RequestId: 12b3cae7-5f4e-415e-93e6-416b8f8b66e6 REPORT RequestId: 12b3cae7-5f4e-415e-93e6-416b8f8b66e6 Duration: 976.25 ms Billed Duration: 977 ms Memory Size: 128 MB Max Memory Used: 90 MB Init Duration: 430.47 ms Request ID 12b3cae7-5f4e-415e-93e6-416b8f8b66e6 Test the Lambda function with the Amazon S3 trigger To test your function with the configured trigger, upload an object to your Amazon S3 bucket using the console. To verify that your Lambda function ran as expected, use CloudWatch Logs to view your function’s output. To upload an object to your Amazon S3 bucket Open the Buckets page of the Amazon S3 console and choose the bucket that you created earlier. Choose Upload . Choose Add files and use the file selector to choose an object you want to upload. This object can be any file you choose. Choose Open , then choose Upload . To verify the function invocation using CloudWatch Logs Open the CloudWatch console. Make sure you're working in the same AWS Region you created your Lambda function in. You can change your Region using the drop-down list at the top of the screen. Choose Logs , then choose Log groups . Choose the log group for your function ( /aws/lambda/s3-trigger-tutorial ). Under Log streams , choose the most recent log stream. If your function was invoked correctly in response to your Amazon S3 trigger, you’ll see output similar to the following. The CONTENT TYPE you see depends on the type of file you uploaded to your bucket. 2022-05-09T23:17:28.702Z 0cae7f5a-b0af-4c73-8563-a3430333cc10 INFO CONTENT TYPE: image/jpeg Clean up your resources You can now delete the resources that you created for this tutorial, unless you want to retain them. By deleting AWS resources that you're no longer using, you prevent unnecessary charges to your AWS account. To delete the Lambda function Open the Functions page of the Lambda console. Select the function that you created. Choose Actions , Delete . Type confirm in the text input field and choose Delete . To delete the execution role Open the Roles page of the IAM console. Select the execution role that you created. Choose Delete . Enter the name of the role in the text input field and choose Delete . To delete the S3 bucket Open the Amazon S3 console. Select the bucket you created. Choose Delete . Enter the name of the bucket in the text input field. Choose Delete bucket . Next steps In Tutorial: Using an Amazon S3 trigger to create thumbnail images , the Amazon S3 trigger invokes a function that creates a thumbnail image for each image file that is uploaded to a bucket. This tutorial requires a moderate level of AWS and Lambda domain knowledge. It demonstrates how to create resources using the AWS Command Line Interface (AWS CLI) and how to create a .zip file archive deployment package for the function and its dependencies. Javascript is disabled or is unavailable in your browser. To use the Amazon Web Services Documentation, Javascript must be enabled. Please refer to your browser's Help pages for instructions. Document Conventions S3 Tutorial: Use an Amazon S3 trigger to create thumbnails Did this page help you? - Yes Thanks for letting us know we're doing a good job! If you've got a moment, please tell us what we did right so we can do more of it. Did this page help you? - No Thanks for letting us know this page needs work. We're sorry we let you down. If you've got a moment, please tell us how we can make the documentation better. | 2026-01-13T09:30:35 |
https://docs.aws.amazon.com/zh_cn/lambda/latest/dg/services-rds.html#rds-configuration | 将 AWS Lambda 与 Amazon RDS 结合使用 - AWS Lambda 将 AWS Lambda 与 Amazon RDS 结合使用 - AWS Lambda 文档 AWS Lambda 开发人员指南 配置函数以使用 RDS 资源 使用 Lambda 函数连接到 Amazon RDS 数据库 处理来自 Amazon RDS 的事件通知 Lambda 和 Amazon RDS 完整教程 将 AWS Lambda 与 Amazon RDS 结合使用 您可以将 Lambda 函数直接连接到 Amazon Relational Database Service(Amazon RDS),也可以通过 Amazon RDS 代理连接。直接连接适用于简单的场景,而在生产中则推荐使用代理。数据库代理管理共享数据库连接池,从而让函数能够在不耗尽数据库连接的情况下达到高并发级别。 对于频繁建立短数据库连接或打开和关闭大量数据库连接的 Lambda 函数,我们建议使用 Amazon RDS 代理。有关更多信息,请参阅《Amazon Relational Database Service 开发人员指南》中的 自动连接 Lambda 函数和数据库实例 。 提示 要将 Lambda 函数快速连接到 Amazon RDS 数据库,您可以使用控制台内的引导式向导。要打开向导,执行以下操作: 打开 Lamba 控制台的 函数 页面。 选择要将数据库连接到其中的函数。 在 配置 选项卡上,选择 RDS 数据库 。 选择 连接到 RDS 数据库 。 将函数连接到数据库后,您可以通过选择 添加代理 来创建代理。 配置函数以使用 RDS 资源 在 Lambda 控制台中,您可以预置和配置 Amazon RDS 数据库实例和代理资源。您可以导航到 配置 选项卡下的 RDS 数据库 完成此操作。或者,您也可以在 Amazon RDS 控制台中创建和配置到 Lambda 函数的连接。配置 RDS 数据库实例以便与 Lambda 配合使用时,请注意以下条件: 要连接到数据库,您的函数必须位于数据库在其中运行的 Amazon VPC。 您可以将 Amazon RDS 数据库与 MySQL、MariaDB、PostgreSQL 或 Microsoft SQL Server 引擎一起使用。 您也可以将 Aurora 数据库集群与 MySQL 或 PostgreSQL 引擎一起使用。 您需要提供用于数据库身份验证的 Secrets Manager 密钥。 IAM 角色必须提供使用密钥的权限和必须允许 Amazon RDS 代入角色的信任策略。 使用控制台配置 Amazon RDS 资源并将其连接到函数的 IAM 主体必须具有以下权限: 注意 只有在配置 Amazon RDS 代理来管理数据库连接池时,才需要 Amazon RDS 代理权限。 JSON { "Version":"2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "ec2:CreateSecurityGroup", "ec2:DescribeSecurityGroups", "ec2:DescribeSubnets", "ec2:DescribeVpcs", "ec2:AuthorizeSecurityGroupIngress", "ec2:AuthorizeSecurityGroupEgress", "ec2:RevokeSecurityGroupEgress", "ec2:CreateNetworkInterface", "ec2:DeleteNetworkInterface", "ec2:DescribeNetworkInterfaces" ], "Resource": "*" }, { "Effect": "Allow", "Action": [ "rds-db:connect", "rds:CreateDBProxy", "rds:CreateDBInstance", "rds:CreateDBSubnetGroup", "rds:DescribeDBClusters", "rds:DescribeDBInstances", "rds:DescribeDBSubnetGroups", "rds:DescribeDBProxies", "rds:DescribeDBProxyTargets", "rds:DescribeDBProxyTargetGroups", "rds:RegisterDBProxyTargets", "rds:ModifyDBInstance", "rds:ModifyDBProxy" ], "Resource": "*" }, { "Effect": "Allow", "Action": [ "lambda:CreateFunction", "lambda:ListFunctions", "lambda:UpdateFunctionConfiguration" ], "Resource": "*" }, { "Effect": "Allow", "Action": [ "iam:AttachRolePolicy", "iam:CreateRole", "iam:CreatePolicy" ], "Resource": "*" }, { "Effect": "Allow", "Action": [ "secretsmanager:GetResourcePolicy", "secretsmanager:GetSecretValue", "secretsmanager:DescribeSecret", "secretsmanager:ListSecretVersionIds", "secretsmanager:CreateSecret" ], "Resource": "*" } ] } Amazon RDS 根据数据库实例大小按小时收取代理费率,详情请参阅 RDS 代理定价 。有关通用代理连接的更多信息,请参阅《Amazon RDS 用户指南》中的 使用 Amazon RDS 代理 。 Amazon RDS 连接的 SSL/TLS 要求 要与 Amazon RDS 数据库实例建立安全的 SSL/TLS 连接,您的 Lambda 函数必须使用可信证书来验证数据库服务器的身份。Lambda 会根据您的部署包类型以不同的方式处理这些证书: .zip 文件存档 :证书处理因运行时而异: Node.js 18 及更早版本 :Lambda 会自动包含 CA 证书和 RDS 证书。 Node.js 20 及更高版本 :Lambda 不再默认加载其他 CA 证书。将 NODE_EXTRA_CA_CERTS 环境变量设置为 /var/runtime/ca-cert.pem 。 将新 AWS 区域的 Amazon RDS 证书添加到 Lambda 托管运行时可能需要长达 4 周的时间。 容器映像 :AWS 基础映像仅包含 CA 证书。如果函数连接到 Amazon RDS 数据库实例,则必须在容器映像中包含相应的证书。在您的 Dockerfile 中,下载 与托管数据库的 AWS 区域相对应的证书捆绑包 。示例: RUN curl https://truststore.pki.rds.amazonaws.com/us-east-1/us-east-1-bundle.pem -o /us-east-1-bundle.pem 此命令可下载 Amazon RDS 证书捆绑包并将其保存在容器根目录的绝对路径 /us-east-1-bundle.pem 下。在函数代码中配置数据库连接时,必须引用此确切路径。示例: Node.js readFileSync 函数是必需的,因为 Node.js 数据库客户端需要内存中的实际证书内容,而不仅仅是证书文件的路径。没有 readFileSync ,客户端会将路径字符串解释为证书内容,从而导致“证书链中的自签名证书”错误。 例 OCI 函数的 Node.js 连接配置 import { readFileSync } from 'fs'; // ... let connectionConfig = { host: process.env.ProxyHostName, user: process.env.DBUserName, password: token, database: process.env.DBName, ssl: { ca: readFileSync('/us-east-1-bundle.pem') // Load RDS certificate content from file into memory } }; Python 例 OCI 函数的 Python 连接配置 connection = pymysql.connect( host=proxy_host_name, user=db_username, password=token, db=db_name, port=port, ssl= { 'ca': '/us-east-1-bundle.pem'} #Path to the certificate in container ) Java 对于使用 JDBC 连接的 Java 函数,连接字符串必须包含: useSSL=true requireSSL=true 指向容器映像中 Amazon RDS 证书位置的 sslCA 参数 例 OCI 函数的 Java 连接字符串 // Define connection string String connectionString = String.format("jdbc: mysql://%s:%s/%s?useSSL=true&requireSSL=true&sslCA=/us-east-1-bundle.pem ", // Path to the certificate in container System.getenv("ProxyHostName"), System.getenv("Port"), System.getenv("DBName")); .NET 例 OCI 函数中用于 MySQL 连接的 .NET 连接字符串 /// Build the Connection String with the Token string connectionString = $"Server= { Environment.GetEnvironmentVariable("RDS_ENDPOINT")};" + $"Port= { Environment.GetEnvironmentVariable("RDS_PORT")};" + $"Uid= { Environment.GetEnvironmentVariable("RDS_USERNAME")};" + $"Pwd= { authToken};" + "SslMode=Required;" + "SslCa=/us-east-1-bundle.pem"; // Path to the certificate in container Go 对于使用 MySQL 连接的 Go 函数,请将 Amazon RDS 证书加载到证书池中,并将其注册到 MySQL 驱动程序。然后,连接字符串必须使用 tls 参数来引用此配置。 例 OCI 函数中用于 MySQL 连接的 Go 代码 import ( "crypto/tls" "crypto/x509" "os" "github.com/go-sql-driver/mysql" ) ... // Create certificate pool and register TLS config rootCertPool := x509.NewCertPool() pem, err := os.ReadFile(" /us-east-1-bundle.pem ") // Path to the certificate in container if err != nil { panic("failed to read certificate file: " + err.Error()) } if ok := rootCertPool.AppendCertsFromPEM(pem); !ok { panic("failed to append PEM") } mysql.RegisterTLSConfig(" custom ", &tls.Config { RootCAs: rootCertPool, }) dsn := fmt.Sprintf("%s:%s@tcp(%s)/%s?allowCleartextPasswords=true& tls=custom ", dbUser, authenticationToken, dbEndpoint, dbName, ) Ruby 例 OCI 函数的 Ruby 连接配置 conn = Mysql2::Client.new( host: endpoint, username: user, password: token, port: port, database: db_name, sslca: '/us-east-1-bundle.pem' , # Path to the certificate in container sslverify: true ) 使用 Lambda 函数连接到 Amazon RDS 数据库 以下代码示例显示了如何实现连接到 Amazon RDS 数据库的 Lambda 函数。该函数发出一个简单的数据库请求并返回结果。 注意 这些代码示例仅适用于 .zip 部署包 。如果您使用 容器映像 来部署函数,则必须在函数代码中指定 Amazon RDS 证书文件,如 上一节 所述。 .NET 适用于 .NET 的 SDK 注意 查看 GitHub,了解更多信息。在 无服务器示例 存储库中查找完整示例,并了解如何进行设置和运行。 在 Lambda 函数中使用 .NET 连接到 Amazon RDS 数据库。 using System.Data; using System.Text.Json; using Amazon.Lambda.APIGatewayEvents; using Amazon.Lambda.Core; using MySql.Data.MySqlClient; // Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class. [assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] namespace aws_rds; public class InputModel { public string key1 { get; set; } public string key2 { get; set; } } public class Function { /// <summary> // Handles the Lambda function execution for connecting to RDS using IAM authentication. /// </summary> /// <param name="input">The input event data passed to the Lambda function</param> /// <param name="context">The Lambda execution context that provides runtime information</param> /// <returns>A response object containing the execution result</returns> public async Task<APIGatewayProxyResponse> FunctionHandler(APIGatewayProxyRequest request, ILambdaContext context) { // Sample Input: { "body": " { \"key1\":\"20\", \"key2\":\"25\"}"} var input = JsonSerializer.Deserialize<InputModel>(request.Body); /// Obtain authentication token var authToken = RDSAuthTokenGenerator.GenerateAuthToken( Environment.GetEnvironmentVariable("RDS_ENDPOINT"), Convert.ToInt32(Environment.GetEnvironmentVariable("RDS_PORT")), Environment.GetEnvironmentVariable("RDS_USERNAME") ); /// Build the Connection String with the Token string connectionString = $"Server= { Environment.GetEnvironmentVariable("RDS_ENDPOINT")};" + $"Port= { Environment.GetEnvironmentVariable("RDS_PORT")};" + $"Uid= { Environment.GetEnvironmentVariable("RDS_USERNAME")};" + $"Pwd= { authToken};"; try { await using var connection = new MySqlConnection(connectionString); await connection.OpenAsync(); const string sql = "SELECT @param1 + @param2 AS Sum"; await using var command = new MySqlCommand(sql, connection); command.Parameters.AddWithValue("@param1", int.Parse(input.key1 ?? "0")); command.Parameters.AddWithValue("@param2", int.Parse(input.key2 ?? "0")); await using var reader = await command.ExecuteReaderAsync(); if (await reader.ReadAsync()) { int result = reader.GetInt32("Sum"); //Sample Response: { "statusCode":200,"body":" { \"message\":\"The sum is: 45\"}","isBase64Encoded":false} return new APIGatewayProxyResponse { StatusCode = 200, Body = JsonSerializer.Serialize(new { message = $"The sum is: { result}" }) }; } } catch (Exception ex) { Console.WriteLine($"Error: { ex.Message}"); } return new APIGatewayProxyResponse { StatusCode = 500, Body = JsonSerializer.Serialize(new { error = "Internal server error" }) }; } } Go SDK for Go V2 注意 查看 GitHub,了解更多信息。在 无服务器示例 存储库中查找完整示例,并了解如何进行设置和运行。 在 Lambda 函数中使用 Go 连接到 Amazon RDS 数据库。 /* Golang v2 code here. */ package main import ( "context" "database/sql" "encoding/json" "fmt" "os" "github.com/aws/aws-lambda-go/lambda" "github.com/aws/aws-sdk-go-v2/config" "github.com/aws/aws-sdk-go-v2/feature/rds/auth" _ "github.com/go-sql-driver/mysql" ) type MyEvent struct { Name string `json:"name"` } func HandleRequest(event *MyEvent) (map[string]interface { }, error) { var dbName string = os.Getenv("DatabaseName") var dbUser string = os.Getenv("DatabaseUser") var dbHost string = os.Getenv("DBHost") // Add hostname without https var dbPort int = os.Getenv("Port") // Add port number var dbEndpoint string = fmt.Sprintf("%s:%d", dbHost, dbPort) var region string = os.Getenv("AWS_REGION") cfg, err := config.LoadDefaultConfig(context.TODO()) if err != nil { panic("configuration error: " + err.Error()) } authenticationToken, err := auth.BuildAuthToken( context.TODO(), dbEndpoint, region, dbUser, cfg.Credentials) if err != nil { panic("failed to create authentication token: " + err.Error()) } dsn := fmt.Sprintf("%s:%s@tcp(%s)/%s?tls=true&allowCleartextPasswords=true", dbUser, authenticationToken, dbEndpoint, dbName, ) db, err := sql.Open("mysql", dsn) if err != nil { panic(err) } defer db.Close() var sum int err = db.QueryRow("SELECT ?+? AS sum", 3, 2).Scan(&sum) if err != nil { panic(err) } s := fmt.Sprint(sum) message := fmt.Sprintf("The selected sum is: %s", s) messageBytes, err := json.Marshal(message) if err != nil { return nil, err } messageString := string(messageBytes) return map[string]interface { } { "statusCode": 200, "headers": map[string]string { "Content-Type": "application/json"}, "body": messageString, }, nil } func main() { lambda.Start(HandleRequest) } Java 适用于 Java 的 SDK 2.x 注意 查看 GitHub,了解更多信息。在 无服务器示例 存储库中查找完整示例,并了解如何进行设置和运行。 在 Lambda 函数中使用 Java 连接到 Amazon RDS 数据库。 import com.amazonaws.services.lambda.runtime.Context; import com.amazonaws.services.lambda.runtime.RequestHandler; import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent; import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent; import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.rdsdata.RdsDataClient; import software.amazon.awssdk.services.rdsdata.model.ExecuteStatementRequest; import software.amazon.awssdk.services.rdsdata.model.ExecuteStatementResponse; import software.amazon.awssdk.services.rdsdata.model.Field; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; public class RdsLambdaHandler implements RequestHandler<APIGatewayProxyRequestEvent, APIGatewayProxyResponseEvent> { @Override public APIGatewayProxyResponseEvent handleRequest(APIGatewayProxyRequestEvent event, Context context) { APIGatewayProxyResponseEvent response = new APIGatewayProxyResponseEvent(); try { // Obtain auth token String token = createAuthToken(); // Define connection configuration String connectionString = String.format("jdbc:mysql://%s:%s/%s?useSSL=true&requireSSL=true", System.getenv("ProxyHostName"), System.getenv("Port"), System.getenv("DBName")); // Establish a connection to the database try (Connection connection = DriverManager.getConnection(connectionString, System.getenv("DBUserName"), token); PreparedStatement statement = connection.prepareStatement("SELECT ? + ? AS sum")) { statement.setInt(1, 3); statement.setInt(2, 2); try (ResultSet resultSet = statement.executeQuery()) { if (resultSet.next()) { int sum = resultSet.getInt("sum"); response.setStatusCode(200); response.setBody("The selected sum is: " + sum); } } } } catch (Exception e) { response.setStatusCode(500); response.setBody("Error: " + e.getMessage()); } return response; } private String createAuthToken() { // Create RDS Data Service client RdsDataClient rdsDataClient = RdsDataClient.builder() .region(Region.of(System.getenv("AWS_REGION"))) .credentialsProvider(DefaultCredentialsProvider.create()) .build(); // Define authentication request ExecuteStatementRequest request = ExecuteStatementRequest.builder() .resourceArn(System.getenv("ProxyHostName")) .secretArn(System.getenv("DBUserName")) .database(System.getenv("DBName")) .sql("SELECT 'RDS IAM Authentication'") .build(); // Execute request and obtain authentication token ExecuteStatementResponse response = rdsDataClient.executeStatement(request); Field tokenField = response.records().get(0).get(0); return tokenField.stringValue(); } } JavaScript SDK for JavaScript (v3) 注意 查看 GitHub,了解更多信息。在 无服务器示例 存储库中查找完整示例,并了解如何进行设置和运行。 在 Lambda 函数中使用 JavaScript 连接到 Amazon RDS 数据库。 // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 /* Node.js code here. */ // ES6+ example import { Signer } from "@aws-sdk/rds-signer"; import mysql from 'mysql2/promise'; async function createAuthToken() { // Define connection authentication parameters const dbinfo = { hostname: process.env.ProxyHostName, port: process.env.Port, username: process.env.DBUserName, region: process.env.AWS_REGION, } // Create RDS Signer object const signer = new Signer(dbinfo); // Request authorization token from RDS, specifying the username const token = await signer.getAuthToken(); return token; } async function dbOps() { // Obtain auth token const token = await createAuthToken(); // Define connection configuration let connectionConfig = { host: process.env.ProxyHostName, user: process.env.DBUserName, password: token, database: process.env.DBName, ssl: 'Amazon RDS' } // Create the connection to the DB const conn = await mysql.createConnection(connectionConfig); // Obtain the result of the query const [res,] = await conn.execute('select ?+? as sum', [3, 2]); return res; } export const handler = async (event) => { // Execute database flow const result = await dbOps(); // Return result return { statusCode: 200, body: JSON.stringify("The selected sum is: " + result[0].sum) } }; 在 Lambda 函数中使用 TypeScript 连接到 Amazon RDS 数据库。 import { Signer } from "@aws-sdk/rds-signer"; import mysql from 'mysql2/promise'; // RDS settings // Using '!' (non-null assertion operator) to tell the TypeScript compiler that the DB settings are not null or undefined, const proxy_host_name = process.env.PROXY_HOST_NAME! const port = parseInt(process.env.PORT!) const db_name = process.env.DB_NAME! const db_user_name = process.env.DB_USER_NAME! const aws_region = process.env.AWS_REGION! async function createAuthToken(): Promise<string> { // Create RDS Signer object const signer = new Signer( { hostname: proxy_host_name, port: port, region: aws_region, username: db_user_name }); // Request authorization token from RDS, specifying the username const token = await signer.getAuthToken(); return token; } async function dbOps(): Promise<mysql.QueryResult | undefined> { try { // Obtain auth token const token = await createAuthToken(); const conn = await mysql.createConnection( { host: proxy_host_name, user: db_user_name, password: token, database: db_name, ssl: 'Amazon RDS' // Ensure you have the CA bundle for SSL connection }); const [rows, fields] = await conn.execute('SELECT ? + ? AS sum', [3, 2]); console.log('result:', rows); return rows; } catch (err) { console.log(err); } } export const lambdaHandler = async (event: any): Promise< { statusCode: number; body: string }> => { // Execute database flow const result = await dbOps(); // Return error is result is undefined if (result == undefined) return { statusCode: 500, body: JSON.stringify(`Error with connection to DB host`) } // Return result return { statusCode: 200, body: JSON.stringify(`The selected sum is: $ { result[0].sum}`) }; }; PHP 适用于 PHP 的 SDK 注意 查看 GitHub,了解更多信息。在 无服务器示例 存储库中查找完整示例,并了解如何进行设置和运行。 在 Lambda 函数中使用 PHP 连接到 Amazon RDS 数据库。 <?php # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 # using bref/bref and bref/logger for simplicity use Bref\Context\Context; use Bref\Event\Handler as StdHandler; use Bref\Logger\StderrLogger; use Aws\Rds\AuthTokenGenerator; use Aws\Credentials\CredentialProvider; require __DIR__ . '/vendor/autoload.php'; class Handler implements StdHandler { private StderrLogger $logger; public function __construct(StderrLogger $logger) { $this->logger = $logger; } private function getAuthToken(): string { // Define connection authentication parameters $dbConnection = [ 'hostname' => getenv('DB_HOSTNAME'), 'port' => getenv('DB_PORT'), 'username' => getenv('DB_USERNAME'), 'region' => getenv('AWS_REGION'), ]; // Create RDS AuthTokenGenerator object $generator = new AuthTokenGenerator(CredentialProvider::defaultProvider()); // Request authorization token from RDS, specifying the username return $generator->createToken( $dbConnection['hostname'] . ':' . $dbConnection['port'], $dbConnection['region'], $dbConnection['username'] ); } private function getQueryResults() { // Obtain auth token $token = $this->getAuthToken(); // Define connection configuration $connectionConfig = [ 'host' => getenv('DB_HOSTNAME'), 'user' => getenv('DB_USERNAME'), 'password' => $token, 'database' => getenv('DB_NAME'), ]; // Create the connection to the DB $conn = new PDO( "mysql:host= { $connectionConfig['host']};dbname= { $connectionConfig['database']}", $connectionConfig['user'], $connectionConfig['password'], [ PDO::MYSQL_ATTR_SSL_CA => '/path/to/rds-ca-2019-root.pem', PDO::MYSQL_ATTR_SSL_VERIFY_SERVER_CERT => true, ] ); // Obtain the result of the query $stmt = $conn->prepare('SELECT ?+? AS sum'); $stmt->execute([3, 2]); return $stmt->fetch(PDO::FETCH_ASSOC); } /** * @param mixed $event * @param Context $context * @return array */ public function handle(mixed $event, Context $context): array { $this->logger->info("Processing query"); // Execute database flow $result = $this->getQueryResults(); return [ 'sum' => $result['sum'] ]; } } $logger = new StderrLogger(); return new Handler($logger); Python 适用于 Python 的 SDK (Boto3) 注意 查看 GitHub,了解更多信息。在 无服务器示例 存储库中查找完整示例,并了解如何进行设置和运行。 在 Lambda 函数中使用 Python 连接到 Amazon RDS 数据库。 import json import os import boto3 import pymysql # RDS settings proxy_host_name = os.environ['PROXY_HOST_NAME'] port = int(os.environ['PORT']) db_name = os.environ['DB_NAME'] db_user_name = os.environ['DB_USER_NAME'] aws_region = os.environ['AWS_REGION'] # Fetch RDS Auth Token def get_auth_token(): client = boto3.client('rds') token = client.generate_db_auth_token( DBHostname=proxy_host_name, Port=port DBUsername=db_user_name Region=aws_region ) return token def lambda_handler(event, context): token = get_auth_token() try: connection = pymysql.connect( host=proxy_host_name, user=db_user_name, password=token, db=db_name, port=port, ssl= { 'ca': 'Amazon RDS'} # Ensure you have the CA bundle for SSL connection ) with connection.cursor() as cursor: cursor.execute('SELECT %s + %s AS sum', (3, 2)) result = cursor.fetchone() return result except Exception as e: return (f"Error: { str(e)}") # Return an error message if an exception occurs Ruby 适用于 Ruby 的 SDK 注意 查看 GitHub,了解更多信息。在 无服务器示例 存储库中查找完整示例,并了解如何进行设置和运行。 在 Lambda 函数中使用 Ruby 连接到 Amazon RDS 数据库。 # Ruby code here. require 'aws-sdk-rds' require 'json' require 'mysql2' def lambda_handler(event:, context:) endpoint = ENV['DBEndpoint'] # Add the endpoint without https" port = ENV['Port'] # 3306 user = ENV['DBUser'] region = ENV['DBRegion'] # 'us-east-1' db_name = ENV['DBName'] credentials = Aws::Credentials.new( ENV['AWS_ACCESS_KEY_ID'], ENV['AWS_SECRET_ACCESS_KEY'], ENV['AWS_SESSION_TOKEN'] ) rds_client = Aws::RDS::AuthTokenGenerator.new( region: region, credentials: credentials ) token = rds_client.auth_token( endpoint: endpoint+ ':' + port, user_name: user, region: region ) begin conn = Mysql2::Client.new( host: endpoint, username: user, password: token, port: port, database: db_name, sslca: '/var/task/global-bundle.pem', sslverify: true, enable_cleartext_plugin: true ) a = 3 b = 2 result = conn.query("SELECT # { a} + # { b} AS sum").first['sum'] puts result conn.close { statusCode: 200, body: result.to_json } rescue => e puts "Database connection failed due to # { e}" end end Rust 适用于 Rust 的 SDK 注意 查看 GitHub,了解更多信息。在 无服务器示例 存储库中查找完整示例,并了解如何进行设置和运行。 在 Lambda 函数中使用 Rust 连接到 Amazon RDS 数据库。 use aws_config::BehaviorVersion; use aws_credential_types::provider::ProvideCredentials; use aws_sigv4:: { http_request:: { sign, SignableBody, SignableRequest, SigningSettings}, sign::v4, }; use lambda_runtime:: { run, service_fn, Error, LambdaEvent}; use serde_json:: { json, Value}; use sqlx::postgres::PgConnectOptions; use std::env; use std::time:: { Duration, SystemTime}; const RDS_CERTS: &[u8] = include_bytes!("global-bundle.pem"); async fn generate_rds_iam_token( db_hostname: &str, port: u16, db_username: &str, ) -> Result<String, Error> { let config = aws_config::load_defaults(BehaviorVersion::v2024_03_28()).await; let credentials = config .credentials_provider() .expect("no credentials provider found") .provide_credentials() .await .expect("unable to load credentials"); let identity = credentials.into(); let region = config.region().unwrap().to_string(); let mut signing_settings = SigningSettings::default(); signing_settings.expires_in = Some(Duration::from_secs(900)); signing_settings.signature_location = aws_sigv4::http_request::SignatureLocation::QueryParams; let signing_params = v4::SigningParams::builder() .identity(&identity) .region(&region) .name("rds-db") .time(SystemTime::now()) .settings(signing_settings) .build()?; let url = format!( "https:// { db_hostname}: { port}/?Action=connect&DBUser= { db_user}", db_hostname = db_hostname, port = port, db_user = db_username ); let signable_request = SignableRequest::new("GET", &url, std::iter::empty(), SignableBody::Bytes(&[])) .expect("signable request"); let (signing_instructions, _signature) = sign(signable_request, &signing_params.into())?.into_parts(); let mut url = url::Url::parse(&url).unwrap(); for (name, value) in signing_instructions.params() { url.query_pairs_mut().append_pair(name, &value); } let response = url.to_string().split_off("https://".len()); Ok(response) } #[tokio::main] async fn main() -> Result<(), Error> { run(service_fn(handler)).await } async fn handler(_event: LambdaEvent<Value>) -> Result<Value, Error> { let db_host = env::var("DB_HOSTNAME").expect("DB_HOSTNAME must be set"); let db_port = env::var("DB_PORT") .expect("DB_PORT must be set") .parse::<u16>() .expect("PORT must be a valid number"); let db_name = env::var("DB_NAME").expect("DB_NAME must be set"); let db_user_name = env::var("DB_USERNAME").expect("DB_USERNAME must be set"); let token = generate_rds_iam_token(&db_host, db_port, &db_user_name).await?; let opts = PgConnectOptions::new() .host(&db_host) .port(db_port) .username(&db_user_name) .password(&token) .database(&db_name) .ssl_root_cert_from_pem(RDS_CERTS.to_vec()) .ssl_mode(sqlx::postgres::PgSslMode::Require); let pool = sqlx::postgres::PgPoolOptions::new() .connect_with(opts) .await?; let result: i32 = sqlx::query_scalar("SELECT $1 + $2") .bind(3) .bind(2) .fetch_one(&pool) .await?; println!("Result: { :?}", result); Ok(json!( { "statusCode": 200, "content-type": "text/plain", "body": format!("The selected sum is: { result}") })) } 处理来自 Amazon RDS 的事件通知 您可以使用 Lambda 处理 Amazon RDS 数据库中的事件通知。Amazon RDS 将通知发送到 Amazon Simple Notification Service (Amazon SNS) 主题,您可以将其配置为调用 Lambda 函数。Amazon SNS 将来自 Amazon RDS 的消息封装在其自己的事件文档中,并将其发送到您的函数。 有关配置 Amazon RDS 数据库以发送通知的详细信息,请参阅 使用 Amazon RDS 事件通知 。 例 Amazon SNS 事件中的 Amazon RDS 消息 { "Records": [ { "EventVersion": "1.0", "EventSubscriptionArn": "arn:aws:sns:us-east-2:123456789012:rds-lambda:21be56ed-a058-49f5-8c98-aedd2564c486", "EventSource": "aws:sns", "Sns": { "SignatureVersion": "1", "Timestamp": "2023-01-02T12:45:07.000Z", "Signature": "tcc6faL2yUC6dgZdmrwh1Y4cGa/ebXEkAi6RibDsvpi+tE/1+82j...65r==", "SigningCertUrl": "https://sns.us-east-2.amazonaws.com/SimpleNotificationService-ac565b8b1a6c5d002d285f9598aa1d9b.pem", "MessageId": "95df01b4-ee98-5cb9-9903-4c221d41eb5e", "Message": " { \"Event Source\":\"db-instance\",\"Event Time\":\"2023-01-02 12:45:06.000\",\"Identifier Link\":\"https://console.aws.amazon.com/rds/home?region=eu-west-1#dbinstance:id=dbinstanceid\",\"Source ID\":\"dbinstanceid\",\"Event ID\":\"http://docs.amazonwebservices.com/AmazonRDS/latest/UserGuide/USER_Events.html#RDS-EVENT-0002\",\"Event Message\":\"Finished DB Instance backup\"}", "MessageAttributes": { }, "Type": "Notification", "UnsubscribeUrl": "https://sns.us-east-2.amazonaws.com/?Action=Unsubscribe&amp;SubscriptionArn=arn:aws:sns:us-east-2:123456789012:test-lambda:21be56ed-a058-49f5-8c98-aedd2564c486", "TopicArn":"arn:aws:sns:us-east-2:123456789012:sns-lambda", "Subject": "RDS Notification Message" } } ] } Lambda 和 Amazon RDS 完整教程 使用 Lambda 函数访问 Amazon RDS 数据库 :在《Amazon RDS 用户指南》中,了解如何使用 Lambda 函数通过 Amazon RDS 代理将数据写入 Amazon RDS 数据库。Lambda 函数将从 Amazon SQS 队列中读取记录,每当添加消息时,都将新的项目写入数据库的表中。 Javascript 在您的浏览器中被禁用或不可用。 要使用 Amazon Web Services 文档,必须启用 Javascript。请参阅浏览器的帮助页面以了解相关说明。 文档惯例 故障排除 Amazon RDS 与 DynamoDB 此页面对您有帮助吗?- 是 感谢您对我们工作的肯定! 如果不耽误您的时间,请告诉我们做得好的地方,让我们做得更好。 此页面对您有帮助吗?- 否 感谢您告诉我们本页内容还需要完善。很抱歉让您失望了。 如果不耽误您的时间,请告诉我们如何改进文档。 | 2026-01-13T09:30:35 |
https://docs.aws.amazon.com/lambda/latest/dg/with-s3-example.html#with-s3-example-create-role | Tutorial: Using an Amazon S3 trigger to invoke a Lambda function - AWS Lambda Tutorial: Using an Amazon S3 trigger to invoke a Lambda function - AWS Lambda Documentation AWS Lambda Developer Guide Create an Amazon S3 bucket Upload a test object to your bucket Create a permissions policy Create an execution role Create the Lambda function Deploy the function code Create the Amazon S3 trigger Test the Lambda function Clean up your resources Next steps Tutorial: Using an Amazon S3 trigger to invoke a Lambda function In this tutorial, you use the console to create a Lambda function and configure a trigger for an Amazon Simple Storage Service (Amazon S3) bucket. Every time that you add an object to your Amazon S3 bucket, your function runs and outputs the object type to Amazon CloudWatch Logs. This tutorial demonstrates how to: Create an Amazon S3 bucket. Create a Lambda function that returns the object type of objects in an Amazon S3 bucket. Configure a Lambda trigger that invokes your function when objects are uploaded to your bucket. Test your function, first with a dummy event, and then using the trigger. By completing these steps, you’ll learn how to configure a Lambda function to run whenever objects are added to or deleted from an Amazon S3 bucket. You can complete this tutorial using only the AWS Management Console. Create an Amazon S3 bucket To create an Amazon S3 bucket Open the Amazon S3 console and select the General purpose buckets page. Select the AWS Region closest to your geographical location. You can change your region using the drop-down list at the top of the screen. Later in the tutorial, you must create your Lambda function in the same Region. Choose Create bucket . Under General configuration , do the following: For Bucket type , ensure General purpose is selected. For Bucket name , enter a globally unique name that meets the Amazon S3 Bucket naming rules . Bucket names can contain only lower case letters, numbers, dots (.), and hyphens (-). Leave all other options set to their default values and choose Create bucket . Upload a test object to your bucket To upload a test object Open the Buckets page of the Amazon S3 console and choose the bucket you created during the previous step. Choose Upload . Choose Add files and select the object that you want to upload. You can select any file (for example, HappyFace.jpg ). Choose Open , then choose Upload . Later in the tutorial, you’ll test your Lambda function using this object. Create a permissions policy Create a permissions policy that allows Lambda to get objects from an Amazon S3 bucket and to write to Amazon CloudWatch Logs. To create the policy Open the Policies page of the IAM console. Choose Create Policy . Choose the JSON tab, and then paste the following custom policy into the JSON editor. JSON { "Version":"2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "logs:PutLogEvents", "logs:CreateLogGroup", "logs:CreateLogStream" ], "Resource": "arn:aws:logs:*:*:*" }, { "Effect": "Allow", "Action": [ "s3:GetObject" ], "Resource": "arn:aws:s3:::*/*" } ] } Choose Next: Tags . Choose Next: Review . Under Review policy , for the policy Name , enter s3-trigger-tutorial . Choose Create policy . Create an execution role An execution role is an AWS Identity and Access Management (IAM) role that grants a Lambda function permission to access AWS services and resources. In this step, create an execution role using the permissions policy that you created in the previous step. To create an execution role and attach your custom permissions policy Open the Roles page of the IAM console. Choose Create role . For the type of trusted entity, choose AWS service , then for the use case, choose Lambda . Choose Next . In the policy search box, enter s3-trigger-tutorial . In the search results, select the policy that you created ( s3-trigger-tutorial ), and then choose Next . Under Role details , for the Role name , enter lambda-s3-trigger-role , then choose Create role . Create the Lambda function Create a Lambda function in the console using the Python 3.14 runtime. To create the Lambda function Open the Functions page of the Lambda console. Make sure you're working in the same AWS Region you created your Amazon S3 bucket in. You can change your Region using the drop-down list at the top of the screen. Choose Create function . Choose Author from scratch Under Basic information , do the following: For Function name , enter s3-trigger-tutorial For Runtime , choose Python 3.14 . For Architecture , choose x86_64 . In the Change default execution role tab, do the following: Expand the tab, then choose Use an existing role . Select the lambda-s3-trigger-role you created earlier. Choose Create function . Deploy the function code This tutorial uses the Python 3.14 runtime, but we’ve also provided example code files for other runtimes. You can select the tab in the following box to see the code for the runtime you’re interested in. The Lambda function retrieves the key name of the uploaded object and the name of the bucket from the event parameter it receives from Amazon S3. The function then uses the get_object method from the AWS SDK for Python (Boto3) to retrieve the object's metadata, including the content type (MIME type) of the uploaded object. To deploy the function code Choose the Python tab in the following box and copy the code. .NET SDK for .NET Note There's more on GitHub. Find the complete example and learn how to set up and run in the Serverless examples repository. Consuming an S3 event with Lambda using .NET. // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System.Threading.Tasks; using Amazon.Lambda.Core; using Amazon.S3; using System; using Amazon.Lambda.S3Events; using System.Web; // Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class. [assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] namespace S3Integration { public class Function { private static AmazonS3Client _s3Client; public Function() : this(null) { } internal Function(AmazonS3Client s3Client) { _s3Client = s3Client ?? new AmazonS3Client(); } public async Task<string> Handler(S3Event evt, ILambdaContext context) { try { if (evt.Records.Count <= 0) { context.Logger.LogLine("Empty S3 Event received"); return string.Empty; } var bucket = evt.Records[0].S3.Bucket.Name; var key = HttpUtility.UrlDecode(evt.Records[0].S3.Object.Key); context.Logger.LogLine($"Request is for { bucket} and { key}"); var objectResult = await _s3Client.GetObjectAsync(bucket, key); context.Logger.LogLine($"Returning { objectResult.Key}"); return objectResult.Key; } catch (Exception e) { context.Logger.LogLine($"Error processing request - { e.Message}"); return string.Empty; } } } } Go SDK for Go V2 Note There's more on GitHub. Find the complete example and learn how to set up and run in the Serverless examples repository. Consuming an S3 event with Lambda using Go. // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package main import ( "context" "log" "github.com/aws/aws-lambda-go/events" "github.com/aws/aws-lambda-go/lambda" "github.com/aws/aws-sdk-go-v2/config" "github.com/aws/aws-sdk-go-v2/service/s3" ) func handler(ctx context.Context, s3Event events.S3Event) error { sdkConfig, err := config.LoadDefaultConfig(ctx) if err != nil { log.Printf("failed to load default config: %s", err) return err } s3Client := s3.NewFromConfig(sdkConfig) for _, record := range s3Event.Records { bucket := record.S3.Bucket.Name key := record.S3.Object.URLDecodedKey headOutput, err := s3Client.HeadObject(ctx, &s3.HeadObjectInput { Bucket: &bucket, Key: &key, }) if err != nil { log.Printf("error getting head of object %s/%s: %s", bucket, key, err) return err } log.Printf("successfully retrieved %s/%s of type %s", bucket, key, *headOutput.ContentType) } return nil } func main() { lambda.Start(handler) } Java SDK for Java 2.x Note There's more on GitHub. Find the complete example and learn how to set up and run in the Serverless examples repository. Consuming an S3 event with Lambda using Java. // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package example; import software.amazon.awssdk.services.s3.model.HeadObjectRequest; import software.amazon.awssdk.services.s3.model.HeadObjectResponse; import software.amazon.awssdk.services.s3.S3Client; import com.amazonaws.services.lambda.runtime.Context; import com.amazonaws.services.lambda.runtime.RequestHandler; import com.amazonaws.services.lambda.runtime.events.S3Event; import com.amazonaws.services.lambda.runtime.events.models.s3.S3EventNotification.S3EventNotificationRecord; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class Handler implements RequestHandler<S3Event, String> { private static final Logger logger = LoggerFactory.getLogger(Handler.class); @Override public String handleRequest(S3Event s3event, Context context) { try { S3EventNotificationRecord record = s3event.getRecords().get(0); String srcBucket = record.getS3().getBucket().getName(); String srcKey = record.getS3().getObject().getUrlDecodedKey(); S3Client s3Client = S3Client.builder().build(); HeadObjectResponse headObject = getHeadObject(s3Client, srcBucket, srcKey); logger.info("Successfully retrieved " + srcBucket + "/" + srcKey + " of type " + headObject.contentType()); return "Ok"; } catch (Exception e) { throw new RuntimeException(e); } } private HeadObjectResponse getHeadObject(S3Client s3Client, String bucket, String key) { HeadObjectRequest headObjectRequest = HeadObjectRequest.builder() .bucket(bucket) .key(key) .build(); return s3Client.headObject(headObjectRequest); } } JavaScript SDK for JavaScript (v3) Note There's more on GitHub. Find the complete example and learn how to set up and run in the Serverless examples repository. Consuming an S3 event with Lambda using JavaScript. import { S3Client, HeadObjectCommand } from "@aws-sdk/client-s3"; const client = new S3Client(); export const handler = async (event, context) => { // Get the object from the event and show its content type const bucket = event.Records[0].s3.bucket.name; const key = decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g, ' ')); try { const { ContentType } = await client.send(new HeadObjectCommand( { Bucket: bucket, Key: key, })); console.log('CONTENT TYPE:', ContentType); return ContentType; } catch (err) { console.log(err); const message = `Error getting object $ { key} from bucket $ { bucket}. Make sure they exist and your bucket is in the same region as this function.`; console.log(message); throw new Error(message); } }; Consuming an S3 event with Lambda using TypeScript. // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 import { S3Event } from 'aws-lambda'; import { S3Client, HeadObjectCommand } from '@aws-sdk/client-s3'; const s3 = new S3Client( { region: process.env.AWS_REGION }); export const handler = async (event: S3Event): Promise<string | undefined> => { // Get the object from the event and show its content type const bucket = event.Records[0].s3.bucket.name; const key = decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g, ' ')); const params = { Bucket: bucket, Key: key, }; try { const { ContentType } = await s3.send(new HeadObjectCommand(params)); console.log('CONTENT TYPE:', ContentType); return ContentType; } catch (err) { console.log(err); const message = `Error getting object $ { key} from bucket $ { bucket}. Make sure they exist and your bucket is in the same region as this function.`; console.log(message); throw new Error(message); } }; PHP SDK for PHP Note There's more on GitHub. Find the complete example and learn how to set up and run in the Serverless examples repository. Consuming an S3 event with Lambda using PHP. <?php use Bref\Context\Context; use Bref\Event\S3\S3Event; use Bref\Event\S3\S3Handler; use Bref\Logger\StderrLogger; require __DIR__ . '/vendor/autoload.php'; class Handler extends S3Handler { private StderrLogger $logger; public function __construct(StderrLogger $logger) { $this->logger = $logger; } public function handleS3(S3Event $event, Context $context) : void { $this->logger->info("Processing S3 records"); // Get the object from the event and show its content type $records = $event->getRecords(); foreach ($records as $record) { $bucket = $record->getBucket()->getName(); $key = urldecode($record->getObject()->getKey()); try { $fileSize = urldecode($record->getObject()->getSize()); echo "File Size: " . $fileSize . "\n"; // TODO: Implement your custom processing logic here } catch (Exception $e) { echo $e->getMessage() . "\n"; echo 'Error getting object ' . $key . ' from bucket ' . $bucket . '. Make sure they exist and your bucket is in the same region as this function.' . "\n"; throw $e; } } } } $logger = new StderrLogger(); return new Handler($logger); Python SDK for Python (Boto3) Note There's more on GitHub. Find the complete example and learn how to set up and run in the Serverless examples repository. Consuming an S3 event with Lambda using Python. # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 import json import urllib.parse import boto3 print('Loading function') s3 = boto3.client('s3') def lambda_handler(event, context): #print("Received event: " + json.dumps(event, indent=2)) # Get the object from the event and show its content type bucket = event['Records'][0]['s3']['bucket']['name'] key = urllib.parse.unquote_plus(event['Records'][0]['s3']['object']['key'], encoding='utf-8') try: response = s3.get_object(Bucket=bucket, Key=key) print("CONTENT TYPE: " + response['ContentType']) return response['ContentType'] except Exception as e: print(e) print('Error getting object { } from bucket { }. Make sure they exist and your bucket is in the same region as this function.'.format(key, bucket)) raise e Ruby SDK for Ruby Note There's more on GitHub. Find the complete example and learn how to set up and run in the Serverless examples repository. Consuming an S3 event with Lambda using Ruby. require 'json' require 'uri' require 'aws-sdk' puts 'Loading function' def lambda_handler(event:, context:) s3 = Aws::S3::Client.new(region: 'region') # Your AWS region # puts "Received event: # { JSON.dump(event)}" # Get the object from the event and show its content type bucket = event['Records'][0]['s3']['bucket']['name'] key = URI.decode_www_form_component(event['Records'][0]['s3']['object']['key'], Encoding::UTF_8) begin response = s3.get_object(bucket: bucket, key: key) puts "CONTENT TYPE: # { response.content_type}" return response.content_type rescue StandardError => e puts e.message puts "Error getting object # { key} from bucket # { bucket}. Make sure they exist and your bucket is in the same region as this function." raise e end end Rust SDK for Rust Note There's more on GitHub. Find the complete example and learn how to set up and run in the Serverless examples repository. Consuming an S3 event with Lambda using Rust. // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 use aws_lambda_events::event::s3::S3Event; use aws_sdk_s3:: { Client}; use lambda_runtime:: { run, service_fn, Error, LambdaEvent}; /// Main function #[tokio::main] async fn main() -> Result<(), Error> { tracing_subscriber::fmt() .with_max_level(tracing::Level::INFO) .with_target(false) .without_time() .init(); // Initialize the AWS SDK for Rust let config = aws_config::load_from_env().await; let s3_client = Client::new(&config); let res = run(service_fn(|request: LambdaEvent<S3Event>| { function_handler(&s3_client, request) })).await; res } async fn function_handler( s3_client: &Client, evt: LambdaEvent<S3Event> ) -> Result<(), Error> { tracing::info!(records = ?evt.payload.records.len(), "Received request from SQS"); if evt.payload.records.len() == 0 { tracing::info!("Empty S3 event received"); } let bucket = evt.payload.records[0].s3.bucket.name.as_ref().expect("Bucket name to exist"); let key = evt.payload.records[0].s3.object.key.as_ref().expect("Object key to exist"); tracing::info!("Request is for { } and object { }", bucket, key); let s3_get_object_result = s3_client .get_object() .bucket(bucket) .key(key) .send() .await; match s3_get_object_result { Ok(_) => tracing::info!("S3 Get Object success, the s3GetObjectResult contains a 'body' property of type ByteStream"), Err(_) => tracing::info!("Failure with S3 Get Object request") } Ok(()) } In the Code source pane on the Lambda console, paste the code into the code editor, replacing the code that Lambda created. In the DEPLOY section, choose Deploy to update your function's code: Create the Amazon S3 trigger To create the Amazon S3 trigger In the Function overview pane, choose Add trigger . Select S3 . Under Bucket , select the bucket you created earlier in the tutorial. Under Event types , be sure that All object create events is selected. Under Recursive invocation , select the check box to acknowledge that using the same Amazon S3 bucket for input and output is not recommended. Choose Add . Note When you create an Amazon S3 trigger for a Lambda function using the Lambda console, Amazon S3 configures an event notification on the bucket you specify. Before configuring this event notification, Amazon S3 performs a series of checks to confirm that the event destination exists and has the required IAM policies. Amazon S3 also performs these tests on any other event notifications configured for that bucket. Because of this check, if the bucket has previously configured event destinations for resources that no longer exist, or for resources that don't have the required permissions policies, Amazon S3 won't be able to create the new event notification. You'll see the following error message indicating that your trigger couldn't be created: An error occurred when creating the trigger: Unable to validate the following destination configurations. You can see this error if you previously configured a trigger for another Lambda function using the same bucket, and you have since deleted the function or modified its permissions policies. Test your Lambda function with a dummy event To test the Lambda function with a dummy event In the Lambda console page for your function, choose the Test tab. For Event name , enter MyTestEvent . In the Event JSON , paste the following test event. Be sure to replace these values: Replace us-east-1 with the region you created your Amazon S3 bucket in. Replace both instances of amzn-s3-demo-bucket with the name of your own Amazon S3 bucket. Replace test%2FKey with the name of the test object you uploaded to your bucket earlier (for example, HappyFace.jpg ). { "Records": [ { "eventVersion": "2.0", "eventSource": "aws:s3", "awsRegion": " us-east-1 ", "eventTime": "1970-01-01T00:00:00.000Z", "eventName": "ObjectCreated:Put", "userIdentity": { "principalId": "EXAMPLE" }, "requestParameters": { "sourceIPAddress": "127.0.0.1" }, "responseElements": { "x-amz-request-id": "EXAMPLE123456789", "x-amz-id-2": "EXAMPLE123/5678abcdefghijklambdaisawesome/mnopqrstuvwxyzABCDEFGH" }, "s3": { "s3SchemaVersion": "1.0", "configurationId": "testConfigRule", "bucket": { "name": " amzn-s3-demo-bucket ", "ownerIdentity": { "principalId": "EXAMPLE" }, "arn": "arn:aws:s3::: amzn-s3-demo-bucket " }, "object": { "key": " test%2Fkey ", "size": 1024, "eTag": "0123456789abcdef0123456789abcdef", "sequencer": "0A1B2C3D4E5F678901" } } } ] } Choose Save . Choose Test . If your function runs successfully, you’ll see output similar to the following in the Execution results tab. Response "image/jpeg" Function Logs START RequestId: 12b3cae7-5f4e-415e-93e6-416b8f8b66e6 Version: $LATEST 2021-02-18T21:40:59.280Z 12b3cae7-5f4e-415e-93e6-416b8f8b66e6 INFO INPUT BUCKET AND KEY: { Bucket: 'amzn-s3-demo-bucket', Key: 'HappyFace.jpg' } 2021-02-18T21:41:00.215Z 12b3cae7-5f4e-415e-93e6-416b8f8b66e6 INFO CONTENT TYPE: image/jpeg END RequestId: 12b3cae7-5f4e-415e-93e6-416b8f8b66e6 REPORT RequestId: 12b3cae7-5f4e-415e-93e6-416b8f8b66e6 Duration: 976.25 ms Billed Duration: 977 ms Memory Size: 128 MB Max Memory Used: 90 MB Init Duration: 430.47 ms Request ID 12b3cae7-5f4e-415e-93e6-416b8f8b66e6 Test the Lambda function with the Amazon S3 trigger To test your function with the configured trigger, upload an object to your Amazon S3 bucket using the console. To verify that your Lambda function ran as expected, use CloudWatch Logs to view your function’s output. To upload an object to your Amazon S3 bucket Open the Buckets page of the Amazon S3 console and choose the bucket that you created earlier. Choose Upload . Choose Add files and use the file selector to choose an object you want to upload. This object can be any file you choose. Choose Open , then choose Upload . To verify the function invocation using CloudWatch Logs Open the CloudWatch console. Make sure you're working in the same AWS Region you created your Lambda function in. You can change your Region using the drop-down list at the top of the screen. Choose Logs , then choose Log groups . Choose the log group for your function ( /aws/lambda/s3-trigger-tutorial ). Under Log streams , choose the most recent log stream. If your function was invoked correctly in response to your Amazon S3 trigger, you’ll see output similar to the following. The CONTENT TYPE you see depends on the type of file you uploaded to your bucket. 2022-05-09T23:17:28.702Z 0cae7f5a-b0af-4c73-8563-a3430333cc10 INFO CONTENT TYPE: image/jpeg Clean up your resources You can now delete the resources that you created for this tutorial, unless you want to retain them. By deleting AWS resources that you're no longer using, you prevent unnecessary charges to your AWS account. To delete the Lambda function Open the Functions page of the Lambda console. Select the function that you created. Choose Actions , Delete . Type confirm in the text input field and choose Delete . To delete the execution role Open the Roles page of the IAM console. Select the execution role that you created. Choose Delete . Enter the name of the role in the text input field and choose Delete . To delete the S3 bucket Open the Amazon S3 console. Select the bucket you created. Choose Delete . Enter the name of the bucket in the text input field. Choose Delete bucket . Next steps In Tutorial: Using an Amazon S3 trigger to create thumbnail images , the Amazon S3 trigger invokes a function that creates a thumbnail image for each image file that is uploaded to a bucket. This tutorial requires a moderate level of AWS and Lambda domain knowledge. It demonstrates how to create resources using the AWS Command Line Interface (AWS CLI) and how to create a .zip file archive deployment package for the function and its dependencies. Javascript is disabled or is unavailable in your browser. To use the Amazon Web Services Documentation, Javascript must be enabled. Please refer to your browser's Help pages for instructions. Document Conventions S3 Tutorial: Use an Amazon S3 trigger to create thumbnails Did this page help you? - Yes Thanks for letting us know we're doing a good job! If you've got a moment, please tell us what we did right so we can do more of it. Did this page help you? - No Thanks for letting us know this page needs work. We're sorry we let you down. If you've got a moment, please tell us how we can make the documentation better. | 2026-01-13T09:30:35 |
https://docs.aws.amazon.com/lambda/latest/dg/python-package.html | Working with .zip file archives for Python Lambda functions - AWS Lambda Working with .zip file archives for Python Lambda functions - AWS Lambda Documentation AWS Lambda Developer Guide Runtime dependencies in Python Creating a .zip deployment package with no dependencies Creating a .zip deployment package with dependencies Dependency search path and runtime-included libraries Using __pycache__ folders Creating .zip deployment packages with native libraries Creating and updating Python Lambda functions using .zip files Working with .zip file archives for Python Lambda functions Your AWS Lambda function’s code comprises a .py file containing your function’s handler code, together with any additional packages and modules your code depends on. To deploy this function code to Lambda, you use a deployment package . This package may either be a .zip file archive or a container image. For more information about using container images with Python, see Deploy Python Lambda functions with container images . To create your deployment package as .zip file archive, you can use your command-line tool’s built-in .zip file archive utility, or any other .zip file utility such as 7zip . The examples shown in the following sections assume you’re using a command-line zip tool in a Linux or MacOS environment. To use the same commands in Windows, you can install the Windows Subsystem for Linux to get a Windows-integrated version of Ubuntu and Bash. Note that Lambda uses POSIX file permissions, so you may need to set permissions for the deployment package folder before you create the .zip file archive. Topics Runtime dependencies in Python Creating a .zip deployment package with no dependencies Creating a .zip deployment package with dependencies Dependency search path and runtime-included libraries Using __pycache__ folders Creating .zip deployment packages with native libraries Creating and updating Python Lambda functions using .zip files Runtime dependencies in Python For Lambda functions that use the Python runtime, a dependency can be any Python package or module. When you deploy your function using a .zip archive, you can either add these dependencies to your .zip file with your function code or use a Lambda layer . A layer is a separate .zip file that can contain additional code and other content. To learn more about using Lambda layers in Python, see Working with layers for Python Lambda functions . The Lambda Python runtimes include the AWS SDK for Python (Boto3) and its dependencies. Lambda provides the SDK in the runtime for deployment scenarios where you are unable to add your own dependencies. These scenarios include creating functions in the console using the built-in code editor or using inline functions in AWS Serverless Application Model (AWS SAM) or CloudFormation templates. Lambda periodically updates the libraries in the Python runtime to include the latest updates and security patches. If your function uses the version of the Boto3 SDK included in the runtime but your deployment package includes SDK dependencies, this can cause version misalignment issues. For example, your deployment package could include the SDK dependency urllib3. When Lambda updates the SDK in the runtime, compatibility issues between the new version of the runtime and the version of urllib3 in your deployment package can cause your function to fail. Important To maintain full control over your dependencies and to avoid possible version misalignment issues, we recommend you add all of your function’s dependencies to your deployment package, even if versions of them are included in the Lambda runtime. This includes the Boto3 SDK. To find out which version of the SDK for Python (Boto3) is included in the runtime you're using, see Runtime-included SDK versions . Under the AWS shared responsibility model , you are responsible for the management of any dependencies in your functions' deployment packages. This includes applying updates and security patches. To update dependencies in your function's deployment package, first create a new .zip file and then upload it to Lambda. See Creating a .zip deployment package with dependencies and Creating and updating Python Lambda functions using .zip files for more information. Creating a .zip deployment package with no dependencies If your function code has no dependencies, your .zip file contains only the .py file with your function’s handler code. Use your preferred zip utility to create a .zip file with your .py file at the root. If the .py file is not at the root of your .zip file, Lambda won’t be able to run your code. To learn how to deploy your .zip file to create a new Lambda function or update an existing one, see Creating and updating Python Lambda functions using .zip files . Creating a .zip deployment package with dependencies If your function code depends on additional packages or modules, you can either add these dependencies to your .zip file with your function code or use a Lambda layer . The instructions in this section show you how to include your dependencies in your .zip deployment package. For Lambda to run your code, the .py file containing your handler code and all of your function's dependencies must be installed at the root of the .zip file. Suppose your function code is saved in a file named lambda_function.py . The following example CLI commands create a .zip file named my_deployment_package.zip containing your function code and its dependencies. You can either install your dependencies directly to a folder in your project directory or use a Python virtual environment. To create the deployment package (project directory) Navigate to the project directory containing your lambda_function.py source code file. In this example, the directory is named my_function . cd my_function Create a new directory named package into which you will install your dependencies. mkdir package Note that for a .zip deployment package, Lambda expects your source code and its dependencies all to be at the root of the .zip file. However, installing dependencies directly in your project directory can introduce a large number of new files and folders and make navigating around your IDE difficult. You create a separate package directory here to keep your dependencies separate from your source code. Install your dependencies in the package directory. The example below installs the Boto3 SDK from the Python Package Index using pip. If your function code uses Python packages you have created yourself, save them in the package directory. pip install --target ./package boto3 Create a .zip file with the installed libraries at the root. cd package zip -r ../my_deployment_package.zip . This generates a my_deployment_package.zip file in your project directory. Add the lambda_function.py file to the root of the .zip file cd .. zip my_deployment_package.zip lambda_function.py Your .zip file should have a flat directory structure, with your function's handler code and all your dependency folders installed at the root as follows. my_deployment_package.zip |- bin | |-jp.py |- boto3 | |-compat.py | |-data | |-docs ... |- lambda_function.py If the .py file containing your function’s handler code is not at the root of your .zip file, Lambda will not be able to run your code. To create the deployment package (virtual environment) Create and activate a virtual environment in your project directory. In this example the project directory is named my_function . ~$ cd my_function ~/my_function$ python3.14 -m venv my_virtual_env ~/my_function$ source ./my_virtual_env/bin/activate Install your required libraries using pip. The following example installs the Boto3 SDK (my_virtual_env) ~/my_function$ pip install boto3 Use pip show to find the location in your virtual environment where pip has installed your dependencies. (my_virtual_env) ~/my_function$ pip show <package_name> The folder in which pip installs your libraries may be named site-packages or dist-packages . This folder may be located in either the lib/python3.x or lib64/python3.x directory (where python3.x represents the version of Python you are using). Deactivate the virtual environment (my_virtual_env) ~/my_function$ deactivate Navigate into the directory containing the dependencies you installed with pip and create a .zip file in your project directory with the installed dependencies at the root. In this example, pip has installed your dependencies in the my_virtual_env/lib/python3.14/site-packages directory. ~/my_function$ cd my_virtual_env/lib/python3.14/site-packages ~/my_function/my_virtual_env/lib/python3.14/site-packages$ zip -r ../../../../my_deployment_package.zip . Navigate to the root of your project directory where the .py file containing your handler code is located and add that file to the root of your .zip package. In this example, your function code file is named lambda_function.py . ~/my_function/my_virtual_env/lib/python3.14/site-packages$ cd ../../../../ ~/my_function$ zip my_deployment_package.zip lambda_function.py Dependency search path and runtime-included libraries When you use an import statement in your code, the Python runtime searches the directories in its search path until it finds the module or package. By default, the first location the runtime searches is the directory into which your .zip deployment package is decompressed and mounted ( /var/task ). If you include a version of a runtime-included library in your deployment package, your version will take precedence over the version that's included in the runtime. Dependencies in your deployment package also have precedence over dependencies in layers. When you add a dependency to a layer, Lambda extracts this to /opt/python/lib/python3.x/site-packages (where python3.x represents the version of the runtime you're using) or /opt/python . In the search path, these directories have precedence over the directories containing the runtime-included libraries and pip-installed libraries ( /var/runtime and /var/lang/lib/python3.x/site-packages ). Libraries in function layers therefore have precedence over versions included in the runtime. Note In the Python 3.11 managed runtime and base image, the AWS SDK and its dependencies are installed in the /var/lang/lib/python3.11/site-packages directory. You can see the full search path for your Lambda function by adding the following code snippet. import sys search_path = sys.path print(search_path) Note Because dependencies in your deployment package or layers take precedence over runtime-included libraries, this can cause version misalignment problems if you include an SDK dependency such as urllib3 in your package without including the SDK as well. If you deploy your own version of a Boto3 dependency, you must also deploy Boto3 as a dependency in your deployment package. We recommend that you package all of your function’s dependencies, even if versions of them are included in the runtime. You can also add dependencies in a separate folder inside your .zip package. For example, you might add a version of the Boto3 SDK to a folder in your .zip package called common . When your .zip package is decompressed and mounted, this folder is placed inside the /var/task directory. To use a dependency from a folder in your .zip deployment package in your code, use an import from statement. For example, to use a version of Boto3 from a folder named common in your .zip package, use the following statement. from common import boto3 Using __pycache__ folders We recommend that you don't include __pycache__ folders in your function's deployment package. Python bytecode that's compiled on a build machine with a different architecture or operating system might not be compatible with the Lambda execution environment. Creating .zip deployment packages with native libraries If your function uses only pure Python packages and modules, you can use the pip install command to install your dependencies on any local build machine and create your .zip file. Many popular Python libraries, including NumPy and Pandas, are not pure Python and contain code written in C or C++. When you add libraries containing C/C++ code to your deployment package, you must build your package correctly to ensure that it’s compatible with the Lambda execution environment. Most packages available on the Python Package Index ( PyPI ) are available as “wheels” (.whl files). A .whl file is a type of ZIP file which contains a built distribution with pre-compiled binaries for a particular operating system and instruction set architecture. To make your deployment package compatible with Lambda, you install the wheel for Linux operating systems and your function’s instruction set architecture. Some packages may only be available as source distributions. For these packages, you need to compile and build the C/C++ components yourself. To see what distributions are available for your required package, do the following: Search for the name of the package on the Python Package Index main page . Choose the version of the package you want to use. Choose Download files . Working with built distributions (wheels) To download a wheel that’s compatible with Lambda, you use the pip --platform option. If your Lambda function uses the x86_64 instruction set architecture, run the following pip install command to install a compatible wheel in your package directory. Replace --python 3.x with the version of the Python runtime you are using. pip install \ --platform manylinux2014_x86_64 \ --target=package \ --implementation cp \ --python-version 3.x \ --only-binary=:all: --upgrade \ <package_name> If your function uses the arm64 instruction set architecture, run the following command. Replace --python 3.x with the version of the Python runtime you are using. pip install \ --platform manylinux2014_aarch64 \ --target=package \ --implementation cp \ --python-version 3.x \ --only-binary=:all: --upgrade \ <package_name> Working with source distributions If your package is only available as a source distribution, you need to build the C/C++ libraries yourself. To make your package compatible with the Lambda execution environment, you need to build it in an environment that uses the same Amazon Linux operating system. You can do this by building your package in an Amazon Elastic Compute Cloud (Amazon EC2) Linux instance. To learn how to launch and connect to an Amazon EC2 Linux instance, see Get started with Amazon EC2 in the Amazon EC2 User Guide . Creating and updating Python Lambda functions using .zip files After you have created your .zip deployment package, you can use it to create a new Lambda function or update an existing one. You can deploy your .zip package using the Lambda console, the AWS Command Line Interface, and the Lambda API. You can also create and update Lambda functions using AWS Serverless Application Model (AWS SAM) and CloudFormation. The maximum size for a .zip deployment package for Lambda is 250 MB (unzipped). Note that this limit applies to the combined size of all the files you upload, including any Lambda layers. The Lambda runtime needs permission to read the files in your deployment package. In Linux permissions octal notation, Lambda needs 644 permissions for non-executable files (rw-r--r--) and 755 permissions (rwxr-xr-x) for directories and executable files. In Linux and MacOS, use the chmod command to change file permissions on files and directories in your deployment package. For example, to give a non-executable file the correct permissions, run the following command. chmod 644 <filepath> To change file permissions in Windows, see Set, View, Change, or Remove Permissions on an Object in the Microsoft Windows documentation. Note If you don't grant Lambda the permissions it needs to access directories in your deployment package, Lambda sets the permissions for those directories to 755 (rwxr-xr-x). Creating and updating functions with .zip files using the console To create a new function, you must first create the function in the console, then upload your .zip archive. To update an existing function, open the page for your function, then follow the same procedure to add your updated .zip file. If your .zip file is less than 50MB, you can create or update a function by uploading the file directly from your local machine. For .zip files greater than 50MB, you must upload your package to an Amazon S3 bucket first. For instructions on how to upload a file to an Amazon S3 bucket using the AWS Management Console, see Getting started with Amazon S3 . To upload files using the AWS CLI, see Move objects in the AWS CLI User Guide . Note You cannot change the deployment package type (.zip or container image) for an existing function. For example, you cannot convert a container image function to use a .zip file archive. You must create a new function. To create a new function (console) Open the Functions page of the Lambda console and choose Create Function . Choose Author from scratch . Under Basic information , do the following: For Function name , enter the name for your function. For Runtime , select the runtime you want to use. (Optional) For Architecture , choose the instruction set architecture for your function. The default architecture is x86_64. Ensure that the .zip deployment package for your function is compatible with the instruction set architecture you select. (Optional) Under Permissions , expand Change default execution role . You can create a new Execution role or use an existing one. Choose Create function . Lambda creates a basic 'Hello world' function using your chosen runtime. To upload a .zip archive from your local machine (console) In the Functions page of the Lambda console, choose the function you want to upload the .zip file for. Select the Code tab. In the Code source pane, choose Upload from . Choose .zip file . To upload the .zip file, do the following: Select Upload , then select your .zip file in the file chooser. Choose Open . Choose Save . To upload a .zip archive from an Amazon S3 bucket (console) In the Functions page of the Lambda console, choose the function you want to upload a new .zip file for. Select the Code tab. In the Code source pane, choose Upload from . Choose Amazon S3 location . Paste the Amazon S3 link URL of your .zip file and choose Save . Updating .zip file functions using the console code editor For some functions with .zip deployment packages, you can use the Lambda console’s built-in code editor to update your function code directly. To use this feature, your function must meet the following criteria: Your function must use one of the interpreted language runtimes (Python, Node.js, or Ruby) Your function’s deployment package must be smaller than 50 MB (unzipped). Function code for functions with container image deployment packages cannot be edited directly in the console. To update function code using the console code editor Open the Functions page of the Lambda console and select your function. Select the Code tab. In the Code source pane, select your source code file and edit it in the integrated code editor. In the DEPLOY section, choose Deploy to update your function's code: Creating and updating functions with .zip files using the AWS CLI You can can use the AWS CLI to create a new function or to update an existing one using a .zip file. Use the create-function and update-function-code commands to deploy your .zip package. If your .zip file is smaller than 50MB, you can upload the .zip package from a file location on your local build machine. For larger files, you must upload your .zip package from an Amazon S3 bucket. For instructions on how to upload a file to an Amazon S3 bucket using the AWS CLI, see Move objects in the AWS CLI User Guide . Note If you upload your .zip file from an Amazon S3 bucket using the AWS CLI, the bucket must be located in the same AWS Region as your function. To create a new function using a .zip file with the AWS CLI, you must specify the following: The name of your function ( --function-name ) Your function’s runtime ( --runtime ) The Amazon Resource Name (ARN) of your function’s execution role ( --role ) The name of the handler method in your function code ( --handler ) You must also specify the location of your .zip file. If your .zip file is located in a folder on your local build machine, use the --zip-file option to specify the file path, as shown in the following example command. aws lambda create-function --function-name myFunction \ --runtime python3.14 --handler lambda_function.lambda_handler \ --role arn:aws:iam::111122223333:role/service-role/my-lambda-role \ --zip-file fileb://myFunction.zip To specify the location of .zip file in an Amazon S3 bucket, use the --code option as shown in the following example command. You only need to use the S3ObjectVersion parameter for versioned objects. aws lambda create-function --function-name myFunction \ --runtime python3.14 --handler lambda_function.lambda_handler \ --role arn:aws:iam::111122223333:role/service-role/my-lambda-role \ --code S3Bucket=amzn-s3-demo-bucket,S3Key=myFileName.zip,S3ObjectVersion=myObjectVersion To update an existing function using the CLI, you specify the the name of your function using the --function-name parameter. You must also specify the location of the .zip file you want to use to update your function code. If your .zip file is located in a folder on your local build machine, use the --zip-file option to specify the file path, as shown in the following example command. aws lambda update-function-code --function-name myFunction \ --zip-file fileb://myFunction.zip To specify the location of .zip file in an Amazon S3 bucket, use the --s3-bucket and --s3-key options as shown in the following example command. You only need to use the --s3-object-version parameter for versioned objects. aws lambda update-function-code --function-name myFunction \ --s3-bucket amzn-s3-demo-bucket --s3-key myFileName.zip --s3-object-version myObject Version Creating and updating functions with .zip files using the Lambda API To create and update functions using a .zip file archive, use the following API operations: CreateFunction UpdateFunctionCode Creating and updating functions with .zip files using AWS SAM The AWS Serverless Application Model (AWS SAM) is a toolkit that helps streamline the process of building and running serverless applications on AWS. You define the resources for your application in a YAML or JSON template and use the AWS SAM command line interface (AWS SAM CLI) to build, package, and deploy your applications. When you build a Lambda function from an AWS SAM template, AWS SAM automatically creates a .zip deployment package or container image with your function code and any dependencies you specify. To learn more about using AWS SAM to build and deploy Lambda functions, see Getting started with AWS SAM in the AWS Serverless Application Model Developer Guide . You can also use AWS SAM to create a Lambda function using an existing .zip file archive. To create a Lambda function using AWS SAM, you can save your .zip file in an Amazon S3 bucket or in a local folder on your build machine. For instructions on how to upload a file to an Amazon S3 bucket using the AWS CLI, see Move objects in the AWS CLI User Guide . In your AWS SAM template, the AWS::Serverless::Function resource specifies your Lambda function. In this resource, set the following properties to create a function using a .zip file archive: PackageType - set to Zip CodeUri - set to the function code's Amazon S3 URI, path to local folder, or FunctionCode object Runtime - Set to your chosen runtime With AWS SAM, if your .zip file is larger than 50MB, you don’t need to upload it to an Amazon S3 bucket first. AWS SAM can upload .zip packages up to the maximum allowed size of 250MB (unzipped) from a location on your local build machine. To learn more about deploying functions using .zip file in AWS SAM, see AWS::Serverless::Function in the AWS SAM Developer Guide . Creating and updating functions with .zip files using CloudFormation You can use CloudFormation to create a Lambda function using a .zip file archive. To create a Lambda function from a .zip file, you must first upload your file to an Amazon S3 bucket. For instructions on how to upload a file to an Amazon S3 bucket using the AWS CLI, see Move objects in the AWS CLI User Guide. For Node.js and Python runtimes, you can also provide inline source code in your CloudFormation template. CloudFormation then creates a .zip file containing your code when you build your function. Using an existing .zip file In your CloudFormation template, the AWS::Lambda::Function resource specifies your Lambda function. In this resource, set the following properties to create a function using a .zip file archive: PackageType - Set to Zip Code - Enter the Amazon S3 bucket name and the .zip file name in the S3Bucket and S3Key fields Runtime - Set to your chosen runtime Creating a .zip file from inline code You can declare simple functions written in Python or Node.js inline in an CloudFormation template. Because the code is embedded in YAML or JSON, you can't add any external dependenices to your deployment package. This means your function has to use the version of the AWS SDK that's included in the runtime. The requirements of the template, such as having to escape certain characters, also make it harder to use your IDE's syntax checking and code completion features. This means that your template might require additional testing. Because of these limitations, declaring functions inline is best suited for very simple code that does not change frequently. To create a .zip file from inline code for Node.js and Python runtimes, set the following properties in your template’s AWS::Lambda::Function resource: PackageType - Set to Zip Code - Enter your function code in the ZipFile field Runtime - Set to your chosen runtime The .zip file that CloudFormation generates cannot exceed 4MB. To learn more about deploying functions using .zip file in CloudFormation, see AWS::Lambda::Function in the CloudFormation User Guide . Javascript is disabled or is unavailable in your browser. To use the Amazon Web Services Documentation, Javascript must be enabled. Please refer to your browser's Help pages for instructions. Document Conventions Handler Deploy container images Did this page help you? - Yes Thanks for letting us know we're doing a good job! If you've got a moment, please tell us what we did right so we can do more of it. Did this page help you? - No Thanks for letting us know this page needs work. We're sorry we let you down. If you've got a moment, please tell us how we can make the documentation better. | 2026-01-13T09:30:35 |
https://support.microsoft.com/hu-hu/windows/cookie-k-kezel%C3%A9se-a-microsoft-edge-ben-megtekint%C3%A9s-enged%C3%A9lyez%C3%A9s-letilt%C3%A1s-t%C3%B6rl%C3%A9s-%C3%A9s-haszn%C3%A1lat-168dab11-0753-043d-7c16-ede5947fc64d | Cookie-k kezelése a Microsoft Edge-ben: Megtekintés, engedélyezés, letiltás, törlés és használat - A Microsoft ügyfélszolgálata Kapcsolódó témakörök × Windows biztonság, védettség és adatvédelem Áttekintés Biztonság, védettség és adatvédelem – áttekintés Biztonság a Windowsban Segítség kérése a Windows biztonság alkalmazással Védelem a Windows biztonság alkalmazással Mielőtt újrahasznosítja, eladja vagy elajándékozza az Xbox vagy Windows rendszerű PC-jét Kártevők eltávolítása windowsos PC-ről Windows biztonság Segítség kérése a Windows biztonság alkalmazással A Microsoft Edge böngészőben megtekintheti és törölheti a böngészési előzményeket Cookie-k törlése és kezelése Értékes tartalom biztonságos eltávolítása a Windows újratelepítésekor Elveszett windowsos eszköz megkeresése és zárolása Windows-adatvédelem A Windows-adatvédelemmel kapcsolatos segítség kérése Az alkalmazások által használt Windows adatvédelmi beállítások Adatok megtekintése az adatvédelmi irányítópulton Ugrás a tartalomtörzsre Microsoft Terméktámogatás Terméktámogatás Terméktámogatás Kezdőlap Microsoft 365 Office Termékek Microsoft 365 Outlook Microsoft Teams OneDrive Microsoft Copilot OneNote Windows egyebek ... Eszközök Surface PC-tartozékok Xbox PC-s játékok HoloLens Surface Hub Hardvergaranciák Fiók & számlázás Fiók Microsoft Store és számlázás Források Újdonságok Forumi zajednice Microsoft 365 rendszergazdák Kisvállalati portál Fejlesztő Oktatás Támogatási csalás bejelentése Termékbiztonság Több A Microsoft 365 megvásárlása Minden ami Microsoft Global Microsoft 365 Teams Copilot Windows Surface Xbox Támogatás Szoftverek Szoftverek Windows-alkalmazások Mesterséges intelligencia OneDrive Outlook Áttérés a Skype-ról a Teamsre OneNote Microsoft Teams Számítógépek és eszközök Számítógépek és eszközök Xbox vásárlása Tartozékok Szórakozás Szórakozás Xbox Game Pass Ultimate Xbox és játékok PC játékok Üzlet Üzlet Microsoft-biztonság Azure Dynamics 365 Microsoft 365 vállalatok számára Microsoft Ipar Microsoft Power Platform Windows 365 Fejlesztők és IT Fejlesztők és IT Microsoft-fejlesztő Microsoft Learn AI piactéri alkalmazások támogatása Microsoft Tech Community Microsoft Marketplace Visual Studio Marketplace Rewards Egyéb Egyéb Díjmentes letöltések és biztonság Oktatás Ajándékkártyák Oldaltérkép megtekintése Keresés Segítség keresése Nincs találat Mégse Bejelentkezés Bejelentkezés Microsoft-fiókkal Jelentkezzen be, vagy hozzon létre egy fiókot. Üdvözöljük! Válasszon másik fiókot. Több fiókja van Válassza ki a bejelentkezéshez használni kívánt fiókot. Kapcsolódó témakörök Windows biztonság, védettség és adatvédelem Áttekintés Biztonság, védettség és adatvédelem – áttekintés Biztonság a Windowsban Segítség kérése a Windows biztonság alkalmazással Védelem a Windows biztonság alkalmazással Mielőtt újrahasznosítja, eladja vagy elajándékozza az Xbox vagy Windows rendszerű PC-jét Kártevők eltávolítása windowsos PC-ről Windows biztonság Segítség kérése a Windows biztonság alkalmazással A Microsoft Edge böngészőben megtekintheti és törölheti a böngészési előzményeket Cookie-k törlése és kezelése Értékes tartalom biztonságos eltávolítása a Windows újratelepítésekor Elveszett windowsos eszköz megkeresése és zárolása Windows-adatvédelem A Windows-adatvédelemmel kapcsolatos segítség kérése Az alkalmazások által használt Windows adatvédelmi beállítások Adatok megtekintése az adatvédelmi irányítópulton Cookie-k kezelése a Microsoft Edge-ben: Megtekintés, engedélyezés, letiltás, törlés és használat Hatókör Windows 10 Windows 11 Microsoft Edge A cookie-k olyan kis méretű adatok, amelyeket a felkeresett webhelyek tárolnak az eszközön. Különböző célokat szolgálnak, például a bejelentkezési hitelesítő adatok megjegyzését, a webhelybeállításokat és a felhasználói viselkedés nyomon követését. Előfordulhat azonban, hogy adatvédelmi okokból vagy a böngészési problémák megoldása érdekében törölni szeretné a cookie-kat. Ez a cikk a következő útmutatást nyújtja: Az összes cookie megtekintése Az összes cookie engedélyezése Cookie-k engedélyezése egy adott webhelyről Harmadik féltől származó cookie-k letiltása Az összes cookie blokkolása: Cookie-k letiltása egy adott webhelyről Az összes cookie törlése Cookie-k törlése adott webhelyről Cookie-k törlése a böngésző minden egyes bezárásakor Cookie-k használata az oldal előzetes betöltéséhez a gyorsabb böngészés érdekében Az összes cookie megtekintése Nyissa meg az Edge böngészőt, és válassza a Beállítások és egyebek elemet a böngészőablak jobb felső sarkában. Válassza a Beállítások > Adatvédelem, keresés és szolgáltatások lehetőséget . Válassza a Cookie-k lehetőséget, majd kattintson az Összes cookie és webhelyadat megtekintése elemre az összes tárolt cookie és a kapcsolódó webhelyadatok megtekintéséhez. Az összes cookie engedélyezése A cookie-k engedélyezésével a webhelyek adatokat menthetnek és lekérhetnek a böngészőben, ami a beállítások és a bejelentkezési adatok megjegyzésével javíthatja a böngészési élményt. Nyissa meg az Edge böngészőt, és válassza a Beállítások és egyebek elemet a böngészőablak jobb felső sarkában. Válassza a Beállítások > Adatvédelem, keresés és szolgáltatások lehetőséget . Válassza a Cookie-k lehetőséget, és engedélyezze a Cookie-adatok mentésének és olvasásának engedélyezése a webhelyek számára (ajánlott) kapcsolót az összes cookie engedélyezéséhez. Cookie-k engedélyezése egy adott webhelyről A cookie-k engedélyezésével a webhelyek adatokat menthetnek és lekérhetnek a böngészőben, ami a beállítások és a bejelentkezési adatok megjegyzésével javíthatja a böngészési élményt. Nyissa meg az Edge böngészőt, és válassza a Beállítások és egyebek elemet a böngészőablak jobb felső sarkában. Válassza a Beállítások > Adatvédelem, keresés és szolgáltatások lehetőséget . Válassza a Cookie-k lehetőséget, majd a Cookie-k mentéséhez válassza az Engedélyezett lehetőséget. Válassza a Webhely hozzáadása lehetőséget a cookie-k webhelyenkénti engedélyezéséhez a webhely URL-címének megadásával. Harmadik féltől származó cookie-k letiltása Ha nem szeretné, hogy a harmadik felek webhelyei cookie-kat tároljanak a számítógépén, letilthatja a cookie-kat. Ha ezt teszi, akkor előfordulhat, hogy egyes weblapok nem jelennek meg megfelelően, illetve a webhely üzenetben tájékoztatja, hogy megtekintéséhez engedélyeznie kell a cookie-kat. Nyissa meg az Edge böngészőt, és válassza a Beállítások és egyebek elemet a böngészőablak jobb felső sarkában. Válassza a Beállítások > Adatvédelem, keresés és szolgáltatások lehetőséget . Válassza a Cookie-k lehetőséget, és engedélyezze a Külső cookie-k letiltása kapcsolót. Az összes cookie blokkolása: Ha nem szeretné, hogy a harmadik felek webhelyei cookie-kat tároljanak a számítógépén, letilthatja a cookie-kat. Ha ezt teszi, akkor előfordulhat, hogy egyes weblapok nem jelennek meg megfelelően, illetve a webhely üzenetben tájékoztatja, hogy megtekintéséhez engedélyeznie kell a cookie-kat. Nyissa meg az Edge böngészőt, és válassza a Beállítások és egyebek elemet a böngészőablak jobb felső sarkában. Válassza a Beállítások > Adatvédelem, keresés és szolgáltatások lehetőséget . Válassza a Cookie-k lehetőséget, és tiltsa le a Cookie-adatok mentésének és olvasásának engedélyezése a webhelyek számára (ajánlott) beállítást az összes cookie letiltásához. Cookie-k letiltása egy adott webhelyről A Microsoft Edge lehetővé teszi, hogy letiltsa a cookie-kat egy adott webhelyről, de ez megakadályozhatja, hogy egyes lapok megfelelően jelenjenek meg, vagy egy webhely üzenete tájékoztatja Arról, hogy engedélyeznie kell a cookie-kat a webhely megtekintéséhez. Cookie-k letiltása egy adott webhelyről: Nyissa meg az Edge böngészőt, és válassza a Beállítások és egyebek elemet a böngészőablak jobb felső sarkában. Válassza a Beállítások > Adatvédelem, keresés és szolgáltatások lehetőséget . Válassza a Cookie-k lehetőséget, és lépjen a Nem engedélyezett a cookie-k mentéséhez és olvasásához . Válassza a Webhely hozzáadása lehetőséget a cookie-k webhelyenkénti letiltásához a webhely URL-címének megadásával. Az összes cookie törlése Nyissa meg az Edge böngészőt, és válassza a Beállítások és egyebek elemet a böngészőablak jobb felső sarkában. Válassza a Beállítások > Adatvédelem, keresés és szolgáltatások lehetőséget. Válassza a Böngészési adatok törlése lehetőséget, majd válassza a Böngészési adatok törlése elem mellett található törlési elemet. Az Időtartomány listában jelöljön ki egy időtartományt. Jelölje be a Cookie-k és egyéb webhelyadatok jelölőnégyzetet, és válassza a Törlés most gombot. Megjegyzés: Másik lehetőségként törölheti a cookie-kat a CTRL + SHIFT + DELETE billentyűkombináció együttes lenyomásával, majd a 4. és 5. lépéssel. A cookie-k és az egyéb webhelyadatok mostantól törlődnek a kiválasztott időtartományban. Ez kijelentkezteti a legtöbb webhelyről. Cookie-k törlése adott webhelyről Nyissa meg az Edge böngészőt, válassza a Beállítások és egyebek > Beállítások > Adatvédelem, keresés és szolgáltatások lehetőséget . Válassza a Cookie-k lehetőséget, majd kattintson az Összes cookie és webhelyadat megtekintése elemre, és keresse meg azt a webhelyet, amelynek a cookie-ját törölni szeretné. Válassza a lefelé mutató nyilat annak a webhelynek a jobb oldalán, amelynek a cookie-jait törölni szeretné, majd válassza a Törlés lehetőséget. A kiválasztott webhely cookie-jának törlése megtörtént. Ismételje meg ezt a lépést minden olyan webhely esetében, amelynek a cookie-jait törölni szeretné. Cookie-k törlése a böngésző minden egyes bezárásakor Nyissa meg az Edge böngészőt, válassza a Beállítások és egyebek > Beállítások > Adatvédelem, keresés és szolgáltatások lehetőséget . Válassza a Böngészési adatok törlése lehetőséget, majd válassza a Válassza ki, hogy mit töröljön a böngésző minden egyes bezárásakor . Kapcsolja be a Cookie-k és egyéb webhelyadatok váltógombot. Ha ez a funkció be van kapcsolva, minden alkalommal, amikor bezárja az Edge böngészőt, a cookie-k és más webhelyadatok törlődnek. Ez kijelentkezteti a legtöbb webhelyről. Cookie-k használata az oldal előzetes betöltéséhez a gyorsabb böngészés érdekében Nyissa meg az Edge böngészőt, és válassza a Beállítások és egyebek elemet a böngészőablak jobb felső sarkában. Válassza a Beállítások > Adatvédelem, keresés és szolgáltatások lehetőséget. Válassza a Cookie-k lehetőséget, és engedélyezze az Oldalak előzetes betöltése váltógombot a gyorsabb böngészéshez és kereséshez. FELIRATKOZÁS RSS-HÍRCSATORNÁKRA További segítségre van szüksége? További lehetőségeket szeretne? Felfedezés Közösség Kapcsolatfelvétel Fedezze fel az előfizetés előnyeit, böngésszen az oktatóanyagok között, ismerje meg, hogyan teheti biztonságossá eszközét, és így tovább. A Microsoft 365-előfizetés előnyei Microsoft 365-képzés Microsoft Biztonság Akadálymentességi központ A közösségek segítségével kérdéseket tehet fel és válaszolhat meg, visszajelzést adhat, és részletes ismeretekkel rendelkező szakértőktől hallhat. Kérdezze meg a Microsoft-közösséget Microsoft technikai közösség Windows Insider-résztvevők Microsoft 365 Insider-résztvevők Megoldást találhat gyakori problémákra, vagy segítséget kaphat egy támogatási szakembertől. Online támogatás Hasznos volt ez az információ? Igen Nem Köszönjük! Van további visszajelzése a Microsoft számára? Segítene nekünk a fejlesztésben? (Küldjön visszajelzést a Microsoftnak, hogy segíthessünk.) Mennyire elégedett a fordítás minőségével? Mi volt hatással a felhasználói élményére? Megoldódott a probléma Világos útmutatás Könnyen követhető Zsargon nélküli szöveg A képek segítettek A fordítás minősége Nem jelent meg megfelelően a képernyőmön Helytelen utasítások Túl technikai Nincs elég információ Nincs elég kép A fordítás minősége Szeretne további visszajelzést küldeni? (Nem kötelező) Visszajelzés küldése Ha elküldi a visszajelzést, a Microsoft felhasználja azt a termékei és szolgáltatásai továbbfejlesztéséhez. Az informatikai rendszergazda képes lesz ezeket az adatokat összegyűjteni. Adatvédelmi nyilatkozat. Köszönjük a visszajelzését! × Újdonságok Copilot szervezeteknek Copilot személyes használatra Microsoft 365 Fedezze fel a Microsoft termékeit Windows 11-alkalmazások Microsoft Store Fiókprofil Letöltőközpont Microsoft Store-támogatás Visszaküldés Rendeléskövetés Újrahasznosítás Commercial Warranties Oktatás Microsoft Education Oktatási eszközök Microsoft Teams oktatáshoz Microsoft 365 Education Office oktatási verzió Oktatóképzés és -fejlesztés Ajánlatok diákoknak és szülőknek Azure diákoknak Üzlet Microsoft-biztonság Azure Dynamics 365 Microsoft 365 Microsoft Advertising Microsoft 365 Copilot Microsoft Teamshez készült Fejlesztők és IT Microsoft-fejlesztő Microsoft Learn AI piactéri alkalmazások támogatása Microsoft Tech Community Microsoft Marketplace Microsoft Power Platform Marketplace Rewards Visual Studio Vállalat Karrier A Microsoft bemutatása Vállalati hírek Adatvédelem a Microsoftnál Befektetők Korrupció- és Vesztegetésellenes Elkötelezettségünk Fenntarthatóság Magyar (Magyarország) Adatvédelmi beállítások elutasítása ikon Adatvédelemmel kapcsolatos választási lehetőségek Adatvédelmi beállítások elutasítása ikon Adatvédelemmel kapcsolatos választási lehetőségek Fogyasztói állapot adatainak védelme Kapcsolatfelvétel a Microsofttal Adatvédelem Cookie-k kezelése Használati feltételek Védjegyek A hirdetéseinkről EU Compliance DoCs © Microsoft 2026 | 2026-01-13T09:30:35 |
https://support.microsoft.com/sr-latn-rs/windows/upravljanje-kola%C4%8Di%C4%87ima-u-pregleda%C4%8Du-microsoft-edge-prikaz-dozvoljavanje-blokiranje-brisanje-i-kori%C5%A1%C4%87enje-168dab11-0753-043d-7c16-ede5947fc64d | Upravljanje kolačićima u pregledaču Microsoft Edge: prikaz, dozvoljavanje, blokiranje, brisanje i korišćenje - Microsoft podrška Srodne teme × Windows bezbednost, sigurnost i privatnost Pregled Pregled bezbednosti, sigurnosti i privatnosti Windows bezbednost Pronalaženje pomoći uz Windows bezbednost Ostanite zaštićeni uz Windows bezbednost Pre nego što reciklirate, prodate ili poklonite svoj Xbox ili Windows PC Uklonite malver sa Windows PC Windows sigurnost Pronalaženje pomoći uz Windows sigurnost Prikaz i brisanje istorije u pregledaču Microsoft Edge Izbrišite kolačiće i upravljajte njima Bezbedno uklonite dragocen sadržaj prilikom ponovne instalacije operativnog sistema Windows Pronalaženje i zaključavanje izgubljenog Windows uređaja Windows privatnost Pronalaženje pomoći uz Windows privatnost​ Windows 10 postavke privatnosti koje koriste aplikacije Prikaz podataka na kontrolnoj tabli za privatnost Pređi na glavni sadržaj Microsoft Podrška Podrška Podrška Početak Microsoft 365 Office Proizvodi Microsoft 365 Outlook Microsoft Teams OneDrive Microsoft Copilot OneNote Windows još... Uređaji Surface Računarski pribor Xbox Igranje igara na ličnom računaru HoloLens Surface Hub Garancije na hardver Nalog i naplata Nalog Prodavnica Microsoft Store i naplata Resursi Šta je novo Forumi zajednice Microsoft 365 administratori Portal za mala preduzeća Programer Obrazovanje Prijavite lažnu podršku Bezbednost proizvoda Još Kupite Microsoft 365 Svi Microsoft proizvodi Global Microsoft 365 Teams Copilot Windows Podrška Software Software Windows aplikacije AI Outlook Microsoft Teams PCs & Devices PCs & Devices Kupite Xbox Business Business Microsoft Security Azure Dynamics 365 Microsoft 365 for business Microsoft industrijska rešenja Microsoft Power Platform Windows 365 Developer & IT Developer & IT Microsoft projektant Dokumentacija Microsoft Learn Microsoft Tech zajednica Microsoft Marketplace Visual Studio Marketplace Rewards Druge Druge Besplatna preuzimanja i bezbednost Obrazovanje Prikaži mapu lokacije Pretraga Potražite pomoć Nema rezultata Otkaži Prijavljivanje Prijavite se pomoću Microsoft naloga Prijavite se ili kreirajte nalog. Zdravo, Izaberite drugi nalog. Imate više naloga Odaberite nalog pomoću kojeg želite da se prijavite. Srodne teme Windows bezbednost, sigurnost i privatnost Pregled Pregled bezbednosti, sigurnosti i privatnosti Windows bezbednost Pronalaženje pomoći uz Windows bezbednost Ostanite zaštićeni uz Windows bezbednost Pre nego što reciklirate, prodate ili poklonite svoj Xbox ili Windows PC Uklonite malver sa Windows PC Windows sigurnost Pronalaženje pomoći uz Windows sigurnost Prikaz i brisanje istorije u pregledaču Microsoft Edge Izbrišite kolačiće i upravljajte njima Bezbedno uklonite dragocen sadržaj prilikom ponovne instalacije operativnog sistema Windows Pronalaženje i zaključavanje izgubljenog Windows uređaja Windows privatnost Pronalaženje pomoći uz Windows privatnost​ Windows 10 postavke privatnosti koje koriste aplikacije Prikaz podataka na kontrolnoj tabli za privatnost Upravljanje kolačićima u pregledaču Microsoft Edge: prikaz, dozvoljavanje, blokiranje, brisanje i korišćenje Primenjuje se na Windows 10 Windows 11 Microsoft Edge Kolačići su mali delovi podataka koje veb lokacije koje posećujete na uređaju skladište na uređaju. One služe različitim svrhama, kao što su pamćenje akreditiva za prijavljivanje, željene postavke lokacije i praćenje ponašanja korisnika. Međutim, možda ćete želeti da izbrišete kolačiće iz razloga privatnosti ili da rešite probleme sa pregledanjem. Ovaj članak pruža uputstva o tome kako da: Prikaži sve kolačiće Dozvoli sve kolačiće Dozvoli kolačiće sa određene veb lokacije Blokiranje kolačića nezavisnih proizvođača Blokiraj sve kolačiće Blokiranje kolačića sa određenog sajta Izbriši sve kolačiće Brisanje kolačića sa određene lokacije Brisanje kolačića svaki put kada zatvorite pregledač Koristite kolačiće da biste unapred učitali stranicu za brže pregledanje Prikaži sve kolačiće Otvorite pregledač Edge, izaberite stavku Postavke i još mnogo toga u gornjem desnom uglu prozora pregledača. Izaberite postavke > privatnost, pretragu i usluge . Izaberite stavku Kolačići , a zatim izaberite stavku Prikaži sve kolačiće i podatke o lokaciji da biste prikazali sve uskladištene kolačiće i srodne informacije o lokaciji. Dozvoli sve kolačiće Dozvoljavanjem kolačića, veb lokacije će moći da sačuvaju i preuzmu podatke u pregledaču, što može da poboljša vaše iskustvo pregledanja pamćenjem željenih opcija i informacija o prijavljivanju. Otvorite pregledač Edge, izaberite stavku Postavke i još mnogo toga u gornjem desnom uglu prozora pregledača. Izaberite postavke > privatnost, pretragu i usluge . Izaberite kolačiće i omogućite preklopnik Dozvoli lokacijama da čuvaju i čitaju podatke kolačića (preporučuje se ) da biste dozvolili sve kolačiće. Dozvoli kolačiće sa određene lokacije Dozvoljavanjem kolačića, veb lokacije će moći da sačuvaju i preuzmu podatke u pregledaču, što može da poboljša vaše iskustvo pregledanja pamćenjem željenih opcija i informacija o prijavljivanju. Otvorite pregledač Edge, izaberite stavku Postavke i još mnogo toga u gornjem desnom uglu prozora pregledača. Izaberite postavke > privatnost, pretragu i usluge . Izaberite stavku Kolačići i idite na stavku Dozvoljeno za čuvanje kolačića. Izaberite stavku Dodaj sajt da biste dozvolili kolačiće po lokaciji tako što ćete uneti URL adresu sajta. Blokiranje kolačića nezavisnih proizvođača Ako ne želite da lokacije nezavisnih proizvođača skladište kolačiće na računaru, možete da blokirate kolačiće. Međutim, ako to uradite, neke stranice će se možda sprečiti da se ispravno prikažu ili ćete možda dobiti poruku sa lokacije koja vas obaveštava da je potrebno da dozvolite kolačićima da prikažu tu lokaciju. Otvorite pregledač Edge, izaberite stavku Postavke i još mnogo toga u gornjem desnom uglu prozora pregledača. Izaberite postavke > privatnost, pretragu i usluge . Izaberite stavku Kolačići i omogućite preklopnik Blokiraj kolačiće nezavisnih proizvođača. Blokiraj sve kolačiće Ako ne želite da lokacije nezavisnih proizvođača skladište kolačiće na računaru, možete da blokirate kolačiće. Međutim, ako to uradite, neke stranice će se možda sprečiti da se ispravno prikažu ili ćete možda dobiti poruku sa lokacije koja vas obaveštava da je potrebno da dozvolite kolačićima da prikažu tu lokaciju. Otvorite pregledač Edge, izaberite stavku Postavke i još mnogo toga u gornjem desnom uglu prozora pregledača. Izaberite postavke > privatnost, pretragu i usluge . Izaberite Kolačići i onemogućite opciju Dozvoli lokacijama da čuvaju i čitaju podatke kolačića (preporučuje se) da biste blokirali sve kolačiće. Blokiranje kolačića sa određenog sajta Microsoft Edge vam omogućava da blokirate kolačiće sa određene lokacije, ali to može sprečiti ispravno prikazivanje nekih stranica ili ćete dobiti poruku sa sajta koja vas obaveštava da morate da dozvolite kolačićima da prikažu tu lokaciju. Da biste blokirali kolačiće sa određene lokacije: Otvorite pregledač Edge, izaberite stavku Postavke i još mnogo toga u gornjem desnom uglu prozora pregledača. Izaberite postavke > privatnost, pretragu i usluge . Izaberite stavku Kolačići i idite na Nije dozvoljeno čuvanje i čitanje kolačića . Izaberite stavku Dodaj sajt da biste blokirali kolačiće po lokaciji tako što ćete uneti URL adresu sajta. Izbriši sve kolačiće Otvorite pregledač Edge, izaberite stavku Postavke i još mnogo toga u gornjem desnom uglu prozora pregledača. Izaberite postavke > privatnost, pretragu i usluge . Izaberite stavku Obriši podatke o pregledanju , a zatim izaberite stavku Odaberite šta želite da obrišete pored stavke Obriši podatke o pregledanju odmah . U okviru Opseg vremena odaberite vremenski opseg sa liste. Izaberite stavku Kolačići i drugi podaci sajta , a zatim izaberite stavku Obriši odmah . Napomena: Druga mogućnost je da izbrišete kolačiće tako što ćete pritisnuti kombinaciju tastera CTRL + SHIFT + DELETE , a zatim nastaviti sa koracima 4 i 5. Svi kolačići i drugi podaci sajta sada će biti izbrisani za izabrani vremenski opseg. Ovo vas odjavljuje sa većine sajtova. Brisanje kolačića sa određene lokacije Otvorite pregledač Edge, izaberite Postavke i dodatne opcije > Postavke > Privatnost, pretraga i usluge . Izaberite stavku Kolačići , a zatim izaberite stavku Prikaži sve kolačiće i podatke o lokaciji i potražite lokaciju čije kolačiće želite da izbrišete. Kliknite na strelicu nadole sa desne strane sajta čiji kolačići želite da izbrišete i izaberite stavku Izbriši . Kolačići za lokaciju koju ste izabrali sada se brišu. Ponovite ovaj korak za bilo koju lokaciju čije kolačiće želite da izbrišete. Brisanje kolačića svaki put kada zatvorite pregledač Otvorite pregledač Edge, izaberite Postavke i dodatne opcije > Postavke > Privatnost, pretraga i usluge . Izaberite stavku Obriši podatke o pregledanju, a zatim izaberite stavku Odaberite šta želite da obrišete svaki put kada zatvorite pregledač . Uključite preklopnik Kolačići i drugi podaci sajta. Kada uključite ovu funkciju, svaki put kada zatvorite Pregledač Edge, brišu se svi kolačići i drugi podaci sajta. Ovo vas odjavljuje sa većine sajtova. Koristite kolačiće da biste unapred učitali stranicu za brže pregledanje Otvorite pregledač Edge, izaberite stavku Postavke i još mnogo toga u gornjem desnom uglu prozora pregledača. Izaberite postavke > privatnost, pretragu i usluge . Izaberite stavku Kolačići i omogućite preklopnik Unapred učitaj stranice za brže pregledanje i pretragu. PRETPLATITE SE NA RSS FEEDOVE Da li vam je potrebna dodatna pomoć? Želite još opcija? Otkrivanje Zajednica Obratite nam se Istražite pogodnosti pretplate, pregledajte kurseve za obuku, saznajte kako da obezbedite uređaj i još mnogo toga. Pogodnosti pretplate na Microsoft 365 Obuka za Microsoft 365 Microsoft bezbednost Centar za pristupačnost Zajednice vam pomažu da postavljate pitanja i odgovarate na pitanja, dajete povratne informacije i čujete mišljenje od stručnjaka sa bogatim znanjem. Pitajte Microsoft zajednicu Microsoft Tech zajednica Windows insajderi Microsoft 365 insajderi Pronađite rešenja za uobičajene probleme ili potražite pomoć od agenta za podršku. Podrška na mreži Da li su vam ove informacije koristile? Da Ne Hvala! Imate li još povratnih informacija za korporaciju Microsoft? Možete li nam pomoći da se poboljšamo? (Pošaljite povratne informacije korporaciji Microsoft da bismo mogli da vam pomognemo.) Koliko ste zadovoljni kvalitetom jezika? Šta je uticalo na vaše iskustvo? Rešio/la sam problem Obriši uputstva Lako za praćenje Bez žargona Slike su pomogle Kvalitet prevoda Ne podudara se sa mojim ekranom Netačna uputstva Previše tehnički Nema dovoljno informacija Nema dovoljno slika Kvalitet prevoda Imate li dodatne povratne informacije? (Opcionalno) Prosledite povratne informacije Kada kliknete na dugme Prosledi“, vaše povratne informacije će se koristiti za poboljšanje Microsoft proizvoda i usluga. Vaš IT administrator će moći da prikupi ove podatke. Izjava o privatnosti. Hvala vam na povratnim informacijama! × Šta je novo Microsoft Copilot Microsoft 365 Aplikacije za Windows 11 Microsoft Store Profil naloga Centar za preuzimanje Praćenje porudžbine Obrazovanje Microsoft Education Uređaji za obrazovanje Microsoft Teams za obrazovanje Microsoft 365 Education Office Education Obuka i razvoj predavača Ponude za studente i roditelje Azure za studente Poslovanje Microsoft Security Azure Dynamics 365 Microsoft 365 Microsoft Advertising Microsoft 365 Copilot Microsoft Teams ПројектантProjektant i IT Microsoft projektant Microsoft Learn Microsoft Tech zajednica Microsoft Marketplace Microsoft Power Platform Visual Studio Marketplace Rewards Preduzeće Zaposlenje Privatnost u kompaniji Microsoft Investitori Sustainability Srpski (Srbija) Ikona „Odbij saglasnost za opcije privatnosti“ Vaši izbori privatnosti Ikona „Odbij saglasnost za opcije privatnosti“ Vaši izbori privatnosti Zaštita privatnosti potrošača Obratite se korporaciji Microsoft Privatnost Upravljanje kolačićima Uslovi korišćenja Žigovi O našim oglasima © Microsoft 2026 | 2026-01-13T09:30:35 |
https://docs.aws.amazon.com/ko_kr/lambda/latest/dg/with-s3-example.html | 자습서: Amazon S3 트리거를 사용하여 Lambda 함수 호출 - AWS Lambda 자습서: Amazon S3 트리거를 사용하여 Lambda 함수 호출 - AWS Lambda 설명서 AWS Lambda 개발자 안내서 Amazon S3 버킷 생성 버킷에 테스트 객체 업로드 권한 정책 생성 실행 역할 만들기 Lambda 함수 생성 함수 코드 배포 Amazon S3 트리거를 생성합니다 Lambda 함수 테스트 리소스 정리 다음 단계 자습서: Amazon S3 트리거를 사용하여 Lambda 함수 호출 이 자습서에서는 콘솔을 사용하여 Lambda 함수를 생성하고 Amazon Simple Storage Service(Amazon S3) 버킷에 대한 트리거를 구성합니다. Amazon S3 버킷에 객체를 추가할 때마다 함수가 실행되고 Amazon CloudWatch Logs에 객체 유형을 출력합니다. 이 자습서에서는 다음을 수행하는 방법을 설명합니다. Amazon S3 버킷을 생성합니다. Amazon S3 버킷에 있는 객체의 유형을 반환하는 Lambda 함수를 생성합니다. 객체가 버킷에 업로드될 때 함수를 간접 호출하는 Lambda 트리거를 구성합니다. 먼저 더미 이벤트로 함수를 테스트한 다음 트리거를 사용하여 함수를 테스트합니다. 이 단계를 완료하면 Amazon S3 버킷에서 객체가 추가되거나 삭제될 때마다 실행되도록 Lambda 함수를 구성하는 방법을 알게 됩니다. AWS Management 콘솔만 사용하여 이 자습서를 완료할 수 있습니다. Amazon S3 버킷 생성 Amazon S3 버킷을 생성하려면 Amazon S3 콘솔 을 열고 범용 버킷 페이지를 선택합니다. 지리적 위치와 가장 가까운 AWS 리전을 선택합니다. 화면 상단의 드롭다운 목록을 사용하여 리전을 변경할 수 있습니다. 자습서 뒷부분에서 동일한 리전에 Lambda 함수를 생성해야 합니다. 버킷 만들기 를 선택합니다. [ 일반 구성(General configuration) ]에서 다음을 수행합니다. 버킷 유형 에서 범용 을 선택했는지 확인합니다. 버킷 이름 에 Amazon S3 버킷 이름 지정 규칙 을 충족하는 전역적으로 고유한 이름을 입력합니다. 버킷 이름은 소문자, 숫자, 점(.) 및 하이픈(-)만 포함할 수 있습니다. 다른 모든 옵션을 기본값으로 두고 버킷 생성 을 선택합니다. 버킷에 테스트 객체 업로드 테스트 객체 업로드 Amazon S3 콘솔의 버킷 페이지를 열고 이전 단계 중 생성한 버킷을 선택합니다. 업로드 를 선택합니다. 파일 추가 를 선택하고 업로드하려는 객체를 선택합니다. 모든 파일을 선택할 수 있습니다(예: HappyFace.jpg ). 열기 를 선택한 후 업로드 를 선택합니다. 자습서의 뒷부분에서 이 객체를 사용하여 Lambda 함수를 테스트합니다. 권한 정책 생성 Lambda가 Amazon S3 버킷에서 객체를 가져오고 Amazon CloudWatch Logs에 쓸 수 있도록 허용하는 권한 정책을 생성합니다. 정책 생성 IAM 콘솔에서 정책 페이지 를 엽니다. 정책 생성 을 선택하세요. JSON 탭에서 다음과 같은 사용자 지정 정책을 JSON 편집기에 붙여 넣습니다. JSON { "Version":"2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "logs:PutLogEvents", "logs:CreateLogGroup", "logs:CreateLogStream" ], "Resource": "arn:aws:logs:*:*:*" }, { "Effect": "Allow", "Action": [ "s3:GetObject" ], "Resource": "arn:aws:s3:::*/*" } ] } 다음: 태그 를 선택합니다. 다음: 검토(Next: Review) 를 선택합니다. 정책 검토 의 이름 에 s3-trigger-tutorial 를 입력합니다. 정책 생성 을 선택합니다. 실행 역할 만들기 실행 역할 은 AWS 서비스 및 리소스에 액세스할 수 있는 권한을 Lambda 함수에 부여하는 AWS Identity and Access Management(IAM) 역할입니다. 이 단계에서는 이전 단계에서 생성한 권한 정책을 사용하여 실행 역할을 생성하세요. 실행 역할을 생성하고 사용자 지정 권한 정책을 연결하려면 IAM 콘솔에서 역할 페이지 를 엽니다. 역할 생성 을 선택합니다. 신뢰할 수 있는 엔터티의 유형으로 AWS 서비스 를 선택한 다음 사용 사례로 Lambda 를 선택합니다. 다음 을 선택합니다. 정책 검색 상자에 s3-trigger-tutorial 를 입력합니다. 검색 결과에서 생성한 정책( s3-trigger-tutorial )을 선택한 후, 다음(Next) 을 선택합니다. Role details (역할 세부 정보)에서 Role name (역할 이름)에 lambda-s3-trigger-role 을 입력한 다음 Create role (역할 생성)을 선택합니다. Lambda 함수 생성 Python 3.13 런타임을 사용하여 콘솔에서 Lambda 함수를 생성합니다. Lambda 함수를 만들려면 Lambda 콘솔의 함수 페이지 를 엽니다. Amazon S3 버킷을 생성한 동일한 AWS 리전에서 작업 중인지 확인합니다. 화면 상단의 드롭다운 목록을 사용하여 리전을 변경할 수 있습니다. 함수 생성 을 선택합니다. 새로 작성 을 선택합니다. 기본 정보 에서 다음과 같이 합니다. 함수 이름 에 s3-trigger-tutorial 을 입력합니다. 런타임 에서 Python 3.13 을 선택합니다. 아키텍처 에서는 x86_64 를 선택합니다. 기본 실행 역할 변경 탭에서 다음을 수행합니다. 탭을 확장한 다음 기존 역할 사용 을 선택합니다. 이전에 생성한 lambda-s3-trigger-role 을 선택합니다. 함수 생성 을 선택합니다. 함수 코드 배포 이 자습서에서는 Python 3.13 런타임을 사용하지만 다른 런타임의 예시 코드 파일도 제공했습니다. 다음 상자에서 탭을 선택하여 관심 있는 런타임에 대한 코드를 볼 수 있습니다. Lambda 함수는 Amazon S3에서 수신한 event 파라미터에서 업로드된 객체의 키 이름과 버킷 이름을 검색합니다. 그런 다음 함수는 AWS SDK for Python (Boto3)의 get_object 메서드를 사용하여 업로드된 객체의 콘텐츠 유형(MIME 유형)을 비롯한 객체의 메타데이터를 검색합니다. 함수 코드 배포 다음 상자에서 Python 탭을 선택하고 코드를 복사합니다. .NET SDK for .NET 참고 GitHub에 더 많은 내용이 있습니다. 서버리스 예제 리포지토리에서 전체 예제를 찾아보고 설정 및 실행 방법을 알아봅니다. .NET을 사용하여 Lambda로 S3 이벤트를 사용합니다. // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System.Threading.Tasks; using Amazon.Lambda.Core; using Amazon.S3; using System; using Amazon.Lambda.S3Events; using System.Web; // Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class. [assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] namespace S3Integration { public class Function { private static AmazonS3Client _s3Client; public Function() : this(null) { } internal Function(AmazonS3Client s3Client) { _s3Client = s3Client ?? new AmazonS3Client(); } public async Task<string> Handler(S3Event evt, ILambdaContext context) { try { if (evt.Records.Count <= 0) { context.Logger.LogLine("Empty S3 Event received"); return string.Empty; } var bucket = evt.Records[0].S3.Bucket.Name; var key = HttpUtility.UrlDecode(evt.Records[0].S3.Object.Key); context.Logger.LogLine($"Request is for { bucket} and { key}"); var objectResult = await _s3Client.GetObjectAsync(bucket, key); context.Logger.LogLine($"Returning { objectResult.Key}"); return objectResult.Key; } catch (Exception e) { context.Logger.LogLine($"Error processing request - { e.Message}"); return string.Empty; } } } } Go SDK for Go V2 참고 GitHub에 더 많은 내용이 있습니다. 서버리스 예제 리포지토리에서 전체 예제를 찾아보고 설정 및 실행 방법을 알아봅니다. Go를 사용하여 Lambda로 S3 이벤트를 사용합니다. // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package main import ( "context" "log" "github.com/aws/aws-lambda-go/events" "github.com/aws/aws-lambda-go/lambda" "github.com/aws/aws-sdk-go-v2/config" "github.com/aws/aws-sdk-go-v2/service/s3" ) func handler(ctx context.Context, s3Event events.S3Event) error { sdkConfig, err := config.LoadDefaultConfig(ctx) if err != nil { log.Printf("failed to load default config: %s", err) return err } s3Client := s3.NewFromConfig(sdkConfig) for _, record := range s3Event.Records { bucket := record.S3.Bucket.Name key := record.S3.Object.URLDecodedKey headOutput, err := s3Client.HeadObject(ctx, &s3.HeadObjectInput { Bucket: &bucket, Key: &key, }) if err != nil { log.Printf("error getting head of object %s/%s: %s", bucket, key, err) return err } log.Printf("successfully retrieved %s/%s of type %s", bucket, key, *headOutput.ContentType) } return nil } func main() { lambda.Start(handler) } Java SDK for Java 2.x 참고 GitHub에 더 많은 내용이 있습니다. 서버리스 예제 리포지토리에서 전체 예제를 찾아보고 설정 및 실행 방법을 알아봅니다. Java를 사용하여 Lambda로 S3 이벤트를 사용합니다. // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package example; import software.amazon.awssdk.services.s3.model.HeadObjectRequest; import software.amazon.awssdk.services.s3.model.HeadObjectResponse; import software.amazon.awssdk.services.s3.S3Client; import com.amazonaws.services.lambda.runtime.Context; import com.amazonaws.services.lambda.runtime.RequestHandler; import com.amazonaws.services.lambda.runtime.events.S3Event; import com.amazonaws.services.lambda.runtime.events.models.s3.S3EventNotification.S3EventNotificationRecord; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class Handler implements RequestHandler<S3Event, String> { private static final Logger logger = LoggerFactory.getLogger(Handler.class); @Override public String handleRequest(S3Event s3event, Context context) { try { S3EventNotificationRecord record = s3event.getRecords().get(0); String srcBucket = record.getS3().getBucket().getName(); String srcKey = record.getS3().getObject().getUrlDecodedKey(); S3Client s3Client = S3Client.builder().build(); HeadObjectResponse headObject = getHeadObject(s3Client, srcBucket, srcKey); logger.info("Successfully retrieved " + srcBucket + "/" + srcKey + " of type " + headObject.contentType()); return "Ok"; } catch (Exception e) { throw new RuntimeException(e); } } private HeadObjectResponse getHeadObject(S3Client s3Client, String bucket, String key) { HeadObjectRequest headObjectRequest = HeadObjectRequest.builder() .bucket(bucket) .key(key) .build(); return s3Client.headObject(headObjectRequest); } } JavaScript SDK for JavaScript (v3) 참고 GitHub에 더 많은 내용이 있습니다. 서버리스 예제 리포지토리에서 전체 예제를 찾아보고 설정 및 실행 방법을 알아봅니다. JavaScript를 사용하여 Lambda로 S3 이벤트를 사용합니다. import { S3Client, HeadObjectCommand } from "@aws-sdk/client-s3"; const client = new S3Client(); export const handler = async (event, context) => { // Get the object from the event and show its content type const bucket = event.Records[0].s3.bucket.name; const key = decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g, ' ')); try { const { ContentType } = await client.send(new HeadObjectCommand( { Bucket: bucket, Key: key, })); console.log('CONTENT TYPE:', ContentType); return ContentType; } catch (err) { console.log(err); const message = `Error getting object $ { key} from bucket $ { bucket}. Make sure they exist and your bucket is in the same region as this function.`; console.log(message); throw new Error(message); } }; TypeScript를 사용하여 Lambda로 S3 이벤트를 사용합니다. // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 import { S3Event } from 'aws-lambda'; import { S3Client, HeadObjectCommand } from '@aws-sdk/client-s3'; const s3 = new S3Client( { region: process.env.AWS_REGION }); export const handler = async (event: S3Event): Promise<string | undefined> => { // Get the object from the event and show its content type const bucket = event.Records[0].s3.bucket.name; const key = decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g, ' ')); const params = { Bucket: bucket, Key: key, }; try { const { ContentType } = await s3.send(new HeadObjectCommand(params)); console.log('CONTENT TYPE:', ContentType); return ContentType; } catch (err) { console.log(err); const message = `Error getting object $ { key} from bucket $ { bucket}. Make sure they exist and your bucket is in the same region as this function.`; console.log(message); throw new Error(message); } }; PHP SDK for PHP 참고 GitHub에 더 많은 내용이 있습니다. 서버리스 예제 리포지토리에서 전체 예제를 찾아보고 설정 및 실행 방법을 알아봅니다. PHP를 사용하여 Lambda로 S3 이벤트 사용. <?php use Bref\Context\Context; use Bref\Event\S3\S3Event; use Bref\Event\S3\S3Handler; use Bref\Logger\StderrLogger; require __DIR__ . '/vendor/autoload.php'; class Handler extends S3Handler { private StderrLogger $logger; public function __construct(StderrLogger $logger) { $this->logger = $logger; } public function handleS3(S3Event $event, Context $context) : void { $this->logger->info("Processing S3 records"); // Get the object from the event and show its content type $records = $event->getRecords(); foreach ($records as $record) { $bucket = $record->getBucket()->getName(); $key = urldecode($record->getObject()->getKey()); try { $fileSize = urldecode($record->getObject()->getSize()); echo "File Size: " . $fileSize . "\n"; // TODO: Implement your custom processing logic here } catch (Exception $e) { echo $e->getMessage() . "\n"; echo 'Error getting object ' . $key . ' from bucket ' . $bucket . '. Make sure they exist and your bucket is in the same region as this function.' . "\n"; throw $e; } } } } $logger = new StderrLogger(); return new Handler($logger); Python SDK for Python (Boto3) 참고 GitHub에 더 많은 내용이 있습니다. 서버리스 예제 리포지토리에서 전체 예제를 찾아보고 설정 및 실행 방법을 알아봅니다. Python을 사용하여 Lambda로 S3 이벤트를 사용합니다. # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 import json import urllib.parse import boto3 print('Loading function') s3 = boto3.client('s3') def lambda_handler(event, context): #print("Received event: " + json.dumps(event, indent=2)) # Get the object from the event and show its content type bucket = event['Records'][0]['s3']['bucket']['name'] key = urllib.parse.unquote_plus(event['Records'][0]['s3']['object']['key'], encoding='utf-8') try: response = s3.get_object(Bucket=bucket, Key=key) print("CONTENT TYPE: " + response['ContentType']) return response['ContentType'] except Exception as e: print(e) print('Error getting object { } from bucket { }. Make sure they exist and your bucket is in the same region as this function.'.format(key, bucket)) raise e Ruby SDK for Ruby 참고 GitHub에 더 많은 내용이 있습니다. 서버리스 예제 리포지토리에서 전체 예제를 찾아보고 설정 및 실행 방법을 알아봅니다. Ruby를 사용하여 Lambda로 S3 이벤트 사용. require 'json' require 'uri' require 'aws-sdk' puts 'Loading function' def lambda_handler(event:, context:) s3 = Aws::S3::Client.new(region: 'region') # Your AWS region # puts "Received event: # { JSON.dump(event)}" # Get the object from the event and show its content type bucket = event['Records'][0]['s3']['bucket']['name'] key = URI.decode_www_form_component(event['Records'][0]['s3']['object']['key'], Encoding::UTF_8) begin response = s3.get_object(bucket: bucket, key: key) puts "CONTENT TYPE: # { response.content_type}" return response.content_type rescue StandardError => e puts e.message puts "Error getting object # { key} from bucket # { bucket}. Make sure they exist and your bucket is in the same region as this function." raise e end end Rust SDK for Rust 참고 GitHub에 더 많은 내용이 있습니다. 서버리스 예제 리포지토리에서 전체 예제를 찾아보고 설정 및 실행 방법을 알아봅니다. Rust를 사용하여 Lambda로 S3 이벤트를 사용합니다. // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 use aws_lambda_events::event::s3::S3Event; use aws_sdk_s3:: { Client}; use lambda_runtime:: { run, service_fn, Error, LambdaEvent}; /// Main function #[tokio::main] async fn main() -> Result<(), Error> { tracing_subscriber::fmt() .with_max_level(tracing::Level::INFO) .with_target(false) .without_time() .init(); // Initialize the AWS SDK for Rust let config = aws_config::load_from_env().await; let s3_client = Client::new(&config); let res = run(service_fn(|request: LambdaEvent<S3Event>| { function_handler(&s3_client, request) })).await; res } async fn function_handler( s3_client: &Client, evt: LambdaEvent<S3Event> ) -> Result<(), Error> { tracing::info!(records = ?evt.payload.records.len(), "Received request from SQS"); if evt.payload.records.len() == 0 { tracing::info!("Empty S3 event received"); } let bucket = evt.payload.records[0].s3.bucket.name.as_ref().expect("Bucket name to exist"); let key = evt.payload.records[0].s3.object.key.as_ref().expect("Object key to exist"); tracing::info!("Request is for { } and object { }", bucket, key); let s3_get_object_result = s3_client .get_object() .bucket(bucket) .key(key) .send() .await; match s3_get_object_result { Ok(_) => tracing::info!("S3 Get Object success, the s3GetObjectResult contains a 'body' property of type ByteStream"), Err(_) => tracing::info!("Failure with S3 Get Object request") } Ok(()) } Lambda 콘솔의 코드 소스 창에서 코드 편집기에 코드를 붙여넣고 Lambda가 생성한 코드를 바꿉니다. 배포 섹션에서 배포 를 선택하여 함수의 코드를 업데이트하세요. Amazon S3 트리거를 생성합니다 Amazon S3 트리거 생성 방법 함수 개요 창에서 트리거 추가 를 선택합니다. S3 를 선택합니다. 버킷 에서 자습서 앞부분에서 생성한 버킷을 선택합니다. 이벤트 유형 에서 모든 객체 생성 이벤트 를 선택합니다. 재귀 호출 에서 확인란을 선택하여 입력 및 출력에 동일한 Amazon S3 버킷 사용이 권장되지 않음을 확인합니다. 추가 를 선택합니다. 참고 Lambda 콘솔을 사용하여 Lambda 함수에 대한 Amazon S3 트리거를 생성하면 Amazon S3는 사용자가 지정한 버킷에 대한 이벤트 알림 을 구성합니다. Amazon S3는 이 이벤트 알림을 구성하기 전에 일련의 검사를 수행하여 이벤트 대상이 존재하고 필수 IAM 정책을 갖추고 있는지 확인합니다. Amazon S3는 해당 버킷에 대해 구성된 다른 모든 이벤트 알림에 대해서도 이러한 테스트를 수행합니다. 이 검사 때문에 버킷이 이전에 더 이상 존재하지 않는 리소스나 필요한 권한 정책이 없는 리소스에 대한 이벤트 대상을 구성한 경우 Amazon S3는 새 이벤트 알림을 생성할 수 없습니다. 트리거를 생성할 수 없음을 나타내는 다음 오류 메시지가 나타납니다. An error occurred when creating the trigger: Unable to validate the following destination configurations. 이전에 동일한 버킷을 사용하여 다른 Lambda 함수에 대한 트리거를 구성한 후 함수를 삭제하거나 해당 권한 정책을 수정한 경우 이 오류가 나타날 수 있습니다. 더미 이벤트로 Lambda 함수 테스트 더미 이벤트로 Lambda 함수 테스트 함수의 Lambda 콘솔 페이지에서 테스트 탭을 선택합니다. 이벤트 이름 에 MyTestEvent 를 입력합니다. 이벤트 JSON 에서 다음 테스트 이벤트를 붙여넣습니다. 해당 값을 바꿉니다. us-east-1 을 Amazon S3 버킷을 생성한 리전으로 바꿉니다. amzn-s3-demo-bucket 의 두 인스턴스를 모두 자체 Amazon S3 버킷의 이름으로 바꿉니다. test%2FKey 를 이전에 버킷에 업로드한 테스트 객체의 이름(예: HappyFace.jpg )으로 바꿉니다. { "Records": [ { "eventVersion": "2.0", "eventSource": "aws:s3", "awsRegion": " us-east-1 ", "eventTime": "1970-01-01T00:00:00.000Z", "eventName": "ObjectCreated:Put", "userIdentity": { "principalId": "EXAMPLE" }, "requestParameters": { "sourceIPAddress": "127.0.0.1" }, "responseElements": { "x-amz-request-id": "EXAMPLE123456789", "x-amz-id-2": "EXAMPLE123/5678abcdefghijklambdaisawesome/mnopqrstuvwxyzABCDEFGH" }, "s3": { "s3SchemaVersion": "1.0", "configurationId": "testConfigRule", "bucket": { "name": " amzn-s3-demo-bucket ", "ownerIdentity": { "principalId": "EXAMPLE" }, "arn": "arn:aws:s3::: amzn-s3-demo-bucket " }, "object": { "key": " test%2Fkey ", "size": 1024, "eTag": "0123456789abcdef0123456789abcdef", "sequencer": "0A1B2C3D4E5F678901" } } } ] } 저장 을 선택합니다. 테스트 를 선택합니다. 함수가 성공적으로 실행되면 실행 결과 탭에 다음과 비슷한 출력이 표시됩니다. Response "image/jpeg" Function Logs START RequestId: 12b3cae7-5f4e-415e-93e6-416b8f8b66e6 Version: $LATEST 2021-02-18T21:40:59.280Z 12b3cae7-5f4e-415e-93e6-416b8f8b66e6 INFO INPUT BUCKET AND KEY: { Bucket: 'amzn-s3-demo-bucket', Key: 'HappyFace.jpg' } 2021-02-18T21:41:00.215Z 12b3cae7-5f4e-415e-93e6-416b8f8b66e6 INFO CONTENT TYPE: image/jpeg END RequestId: 12b3cae7-5f4e-415e-93e6-416b8f8b66e6 REPORT RequestId: 12b3cae7-5f4e-415e-93e6-416b8f8b66e6 Duration: 976.25 ms Billed Duration: 977 ms Memory Size: 128 MB Max Memory Used: 90 MB Init Duration: 430.47 ms Request ID 12b3cae7-5f4e-415e-93e6-416b8f8b66e6 Amazon S3 트리거로 Lambda 함수 테스트 구성된 트리거로 함수를 테스트하려면 콘솔을 사용하여 Amazon S3 버킷에 객체를 업로드합니다. Lambda 함수가 예상대로 실행되었는지 확인하려면 CloudWatch 로그를 사용하여 함수의 출력을 확인합니다. Amazon S3 버킷에 객체 업로드 Amazon S3 콘솔의 버킷 페이지를 열고 앞서 생성한 버킷을 선택합니다. 업로드 를 선택합니다. 파일 추가 를 선택하고 파일 선택기를 사용하여 업로드할 객체를 선택합니다. 이 객체는 사용자가 선택한 임의의 파일이 될 수 있습니다. 열기 를 선택한 후 업로드 를 선택합니다. CloudWatch Logs를 사용하여 함수 간접 호출을 확인하려면 다음을 수행합니다. CloudWatch 콘솔을 엽니다 . Lambda 함수를 생성한 동일한 AWS 리전에서 작업 중인지 확인합니다. 화면 상단의 드롭다운 목록을 사용하여 리전을 변경할 수 있습니다. 로그 를 선택한 후 로그 그룹 을 선택합니다. 함수에 대한 로그 그룹( /aws/lambda/s3-trigger-tutorial )을 선택합니다. 로그 스트림 에서 가장 최근의 로그 스트림을 선택합니다. Amazon S3 트리거에 대한 응답으로 함수가 제대로 간접적으로 간접 호출된 경우 다음과 유사한 출력이 표시됩니다. 표시되는 CONTENT TYPE 은 버킷에 업로드한 파일 유형에 따라 달라집니다. 2022-05-09T23:17:28.702Z 0cae7f5a-b0af-4c73-8563-a3430333cc10 INFO CONTENT TYPE: image/jpeg 리소스 정리 이 자습서 용도로 생성한 리소스를 보관하고 싶지 않다면 지금 삭제할 수 있습니다. 더 이상 사용하지 않는 AWS 리소스를 삭제하면 AWS 계정에 불필요한 요금이 발생하는 것을 방지할 수 있습니다. Lambda 함수를 삭제하려면 Lambda 콘솔의 함수 페이지 를 엽니다. 생성한 함수를 선택합니다. 작업 (Actions), 삭제 (Delete)를 선택합니다. 텍스트 입력 필드에 confirm 를 입력하고 Delete (삭제)를 선택합니다. 집행 역할 삭제 IAM 콘솔에서 역할 페이지 를 엽니다. 생성한 실행 역할을 선택합니다. 삭제 를 선택합니다. 텍스트 입력 필드에 역할의 이름을 입력하고 Delete (삭제)를 선택합니다. S3 버킷을 삭제하려면 Amazon S3 콘솔 을 엽니다. 생성한 버킷을 선택합니다. 삭제 를 선택합니다. 텍스트 입력 필드에 버킷 이름을 입력합니다. 버킷 삭제(Delete bucket) 를 선택합니다. 다음 단계 자습서: Amazon S3 트리거를 사용하여 썸네일 이미지 생성 에서는 Amazon S3 트리거가 함수를 간접적으로 간접 호출하여 버킷에 업로드된 각 이미지 파일에 대해 썸네일 이미지를 생성합니다. 이 자습서를 진행하려면 중급 수준의 AWS 및 Lambda 분야 지식이 필요합니다. AWS Command Line Interface(AWS CLI)를 사용하여 리소스를 생성하는 방법과 함수 및 해당 종속성에 대한 .zip 파일 아카이브 배포 패키지를 생성하는 방법을 설명합니다. javascript가 브라우저에서 비활성화되거나 사용이 불가합니다. AWS 설명서를 사용하려면 Javascript가 활성화되어야 합니다. 지침을 보려면 브라우저의 도움말 페이지를 참조하십시오. 문서 규칙 S3 자습서: Amazon S3 트리거를 사용하여 썸네일 생성 이 페이지의 내용이 도움이 되었습니까? - 예 칭찬해 주셔서 감사합니다! 잠깐 시간을 내어 좋았던 부분을 알려 주시면 더 열심히 만들어 보겠습니다. 이 페이지의 내용이 도움이 되었습니까? - 아니요 이 페이지에 작업이 필요하다는 점을 알려 주셔서 감사합니다. 실망시켜 드려 죄송합니다. 잠깐 시간을 내어 설명서를 향상시킬 수 있는 방법에 대해 말씀해 주십시오. | 2026-01-13T09:30:35 |
https://aws.amazon.com/blogs/compute/upcoming-updates-to-the-aws-lambda-execution-environment/ | Upcoming updates to the AWS Lambda and AWS Lambda@Edge execution environment | AWS Compute Blog Skip to Main Content Filter: All English Contact us AWS Marketplace Support My account Search Filter: All Sign in to console Create account AWS Blogs Home Blogs Editions AWS Compute Blog Upcoming updates to the AWS Lambda and AWS Lambda@Edge execution environment by Chris Munns on 14 MAY 2019 in AWS Lambda , Lambda@Edge Permalink Share NOTE: On May 23 we announced an update to the timeframe seen below. AWS Lambda was first announced at AWS re:Invent 2014. Amazon CTO Werner Vogels highlighted the aspect of needing to run no servers, no instances, nothing, you just write your code . In 2016, we announced the launch of Lambda@Edge, which lets you run Lambda functions to customize content that CloudFront delivers, executing the functions in AWS locations closer to the viewer. At AWS, we talk often about “shared responsibility” models. Essentially, those are the places where there is a handoff between what we as a technology provider offer you and what you as the customer are responsible for. In the case of Lambda and Lambda@Edge, one of the key things that we manage is the “execution environment.” The execution environment is what your code runs inside of. It is composed of the underlying operating system, system packages, the runtime for your language (if a managed one), and common capabilities like environment variables. From the customer standpoint, your primary responsibility is for your application code and configuration. In this post, we outline an upcoming change to the execution environment for Lambda and Lambda@Edge functions for all runtimes with the exception of Node.js v10. As with any update, some functionality could be affected. We encourage you to read through this post to understand the changes and any actions that you might need to take. Update overview AWS Lambda and AWS Lambda@Edge run on top of the Amazon Linux operating system distribution and maintain updates to both the core OS and managed language runtimes. We are updating the Lambda execution environment AMI to version 2018.03 of Amazon Linux. This newer AMI brings updates that offer improvements in capabilities, performance, security, and updated packages that your application code might interface with. This does not apply to the recently announced Node.js v10 runtime which today runs on Amazon Linux 2. The majority of functions will benefit seamlessly from the enhancements in this update without any action from you. However, in rare cases, package updates may introduce compatibility issues. Potential impacted functions may be those that contain libraries or application code compiled against specific underlying OS packages or other system libraries. If you are primarily using an AWS SDK or the AWS X-Ray SDK with no other dependencies, you will see no impact. You have the following options in terms of next steps: Take no action before the automatic update of the execution environment starting June 11 for all newly created functions, June 25th for all updates to previously existing functions and July 16 for all existing functions. Proactively test your functions against the new environment starting today. Configure your functions to delay the execution environment update until July 23 to allow for a longer testing window. In addition to the overall timeline for this change, this post also provides instructions on the following: How to test your functions for this new execution environment locally and on Lambda/Lambda@Edge. How to proactively update your functions. How to delay the migration until July 23. Update timeline The following is the timeline for the update, which is broken up over five phases: May 14, 2019 – Begin Testing: You can begin testing your functions for the new execution environment locally with AWS SAM CLI or using an Amazon EC2 instance running on Amazon Linux 2018.03. You can also proactively enable the new environment in AWS Lambda using the opt-in mechanism described in the original announcement post. June 11, 2019 – New Function Create: All newly created functions will result in those functions running on the new execution environment, unless they have a delayed-update layer configured. June 25, 2019 – Existing Function Update: All newly created functions or existing functions that you update will result in those functions running on the new execution environment, unless they have a delayed-update layer configured. July 16, 2019 – General Update: Existing functions begin using the new execution environment on invoke, unless they have a delayed-update layer configured. July 23, 2019 – Delayed Update End : All functions with a delayed-update layer configured start being migrated automatically. July 29, 2019 – Migration End : All functions have been migrated over to the new execution environment. Recommended Approach You only have to act if your application uses dependencies that are compiled to work on the previous execution environment. Otherwise, you can continue to deploy new and updated Lambda functions without needing to perform any other testing steps. For those who aren’t sure if their functions use such dependencies, we encourage you to do a new deployment of your functions and to test their functionality. There are two options for when you can start testing your functions on the new execution environment: You can begin testing today using the opt-in mechanism described later. Starting June 11, all newly created functions use the new execution environment. If you confirm that your functions would be affected by the new execution environment, you can begin re-compiling or building your dependencies using the new reference AMI for the execution environment today and then repeating the testing. The final step for existing applications is to redeploy them after June 25 to use the new execution environment or to deploy them with the opt-in configured starting today. Building your dependencies and application for the new execution environment Because we are basing the environment off of an existing Amazon Linux AMI, you can start with building and testing your code against that AMI on EC2. With an updated EC2 instance running this AMI, you can compile and build your packages using your normal processes. For the list of AMI IDs in all public Regions, check the release notes . To start an EC2 instance running this AMI, follow the steps in the Launching an Instance Using the Launch Instance Wizard topic in the Amazon EC2 User Guide. Opt-in/Delayed-Update with Lambda layers Some of you may want to begin testing as soon as you’ve read this announcement. Some know that they should postpone until later in the timeline. To give you some control over testing, we’re releasing two special Lambda layers . Lambda layers can be used to provide shared resources, code, or data between Lambda functions and can simplify the deployment and update process. These layers don’t actually contain any data or code. Instead, they act as a special flag to Lambda to run your function executions either specifically on the new or old execution environment. The Opt-In layer allows you to start testing today. You can use the Delayed-Update layer when aren’t ready to deploy to the new execution environment, but you know that you need to create new functions or make updates to your existing functions or their configuration after June 11. The Delayed-Update layer extends the initial period available to you to deploy your functions by one week until the end of July 22, without changing the execution environment. Neither layer brings any performance or runtime changes beyond this. After July 22, the layers will have no functionality. In a future deployment, you should remove them from any function configurations. The ARNs for the two scenarios: To OPT-IN to the update to the new execution environment, add the following layer: arn:aws:lambda:::awslayer:AmazonLinux1803 To DELAY THE UPDATE to the new execution environment until July 22, add the following layer: arn:aws:lambda:::awslayer:AmazonLinux1703 The action for adding a layer to your existing functions requires an update to the Lambda function’s configuration . You can do this with the AWS CLI , AWS CloudFormation or AWS SAM , popular third-party frameworks, the AWS Management Console, or an AWS SDK. Validating your functions There are several ways for you to test your function code and assure that it will work after the execution environment has been updated. Local testing We’re providing an update to the AWS SAM CLI to enable you to test your functions locally against this new execution environment. The AWS SAM CLI uses a Docker image that mirrors the live Lambda environment locally wherever you do development. To test against this new update, make sure that you have the most recent update to AWS SAM CLI version 0.16.0 . You also should have an AWS SAM template configured for your function. Install or update the AWS SAM CLI: $ pip install --upgrade aws-sam-cli -Or- $ pip install aws-sam-cli Confirm that you have a valid AWS SAM template: $ sam validate -t <template file name> If you don’t have a valid AWS SAM template, you can begin with a basic template to test your functions. The following example represents the basic needs for running your function against a variety. The Runtime value must be listed in the AWS Lambda Runtimes topic. AWSTemplateFormatVersion: 2010-09-09 Transform: 'AWS::Serverless-2016-10-31' Resources: myFunction: Type: 'AWS::Serverless::Function' Properties: CodeUri: ./ Handler: YOUR_HANDLER Runtime: YOUR_RUNTIME With a valid template, you can begin testing your function with mock event payloads. To generate a mock event payload, you can use the AWS SAM CLI local generate-event command. Here is an example of that command being run to generate an Amazon S3 notification type of event: sam local generate-event s3 put --bucket amzn-s3-demo-bucket --key somephoto.jpeg { "Records": [ { "eventVersion": "2.0", "eventTime": "1970-01-01T00:00:00.000Z", "requestParameters": { "sourceIPAddress": "127.0.0.1" }, "s3": { "configurationId": "testConfigRule", "object": { "eTag": "0123456789abcdef0123456789abcdef", "sequencer": "0A1B2C3D4E5F678901", "key": "somephoto.jpeg", "size": 1024 }, "bucket": { "arn": "arn:aws:s3:::amzn-s3-demo-bucket", "name": "amzn-s3-demo-bucket", "ownerIdentity": { "principalId": "EXAMPLE" } }, "s3SchemaVersion": "1.0" }, "responseElements": { "x-amz-id-2": "EXAMPLE123/5678abcdefghijklambdaisawesome/mnopqrstuvwxyzABCDEFGH", "x-amz-request-id": "EXAMPLE123456789" }, "awsRegion": "us-east-1", "eventName": "ObjectCreated:Put", "userIdentity": { "principalId": "EXAMPLE" }, "eventSource": "aws:s3" } ] } You can then use the AWS SAM CLI local invoke command and pipe in the output from the previous command. Or, you can save the output from the previous command to a file and then pass in a reference to the file’s name and location with the -e flag. Here is an example of the pipe event method: sam local generate-event s3 put --bucket amzn-s3-demo-bucket --key somephoto.jpeg | sam local invoke myFunction 2019-02-19 18:45:53 Reading invoke payload from stdin (you can also pass it from file with --event) 2019-02-19 18:45:53 Found credentials in shared credentials file: ~/.aws/credentials 2019-02-19 18:45:53 Invoking index.handler (python2.7) Fetching lambci/lambda:python2.7 Docker container image...... 2019-02-19 18:45:53 Mounting /home/ec2-user/environment/forblog as /var/task:ro inside runtime container START RequestId: 7c14eea1-96e9-4b7d-ab54-ed1f50bd1a34 Version: $LATEST {"Records": [{"eventVersion": "2.0", "eventTime": "1970-01-01T00:00:00.000Z", "requestParameters": {"sourceIPAddress": "127.0.0.1"}, "s3": {"configurationId": "testConfigRule", "object": {"eTag": "0123456789abcdef0123456789abcdef", "key": "somephoto.jpeg", "sequencer": "0A1B2C3D4E5F678901", "size": 1024}, "bucket": {"ownerIdentity": {"principalId": "EXAMPLE"}, "name": "amzn-s3-demo-bucket", "arn": "arn:aws:s3:::amzn-s3-demo-bucket"}, "s3SchemaVersion": "1.0"}, "responseElements": {"x-amz-id-2": "EXAMPLE123/5678abcdefghijklambdaisawesome/mnopqrstuvwxyzABCDEFGH", "x-amz-request-id": "EXAMPLE123456789"}, "awsRegion": "us-east-1", "eventName": "ObjectCreated:Put", "userIdentity": {"principalId": "EXAMPLE"}, "eventSource": "aws:s3"}]} END RequestId: 7c14eea1-96e9-4b7d-ab54-ed1f50bd1a34 REPORT RequestId: 7c14eea1-96e9-4b7d-ab54-ed1f50bd1a34 Duration: 1 ms Billed Duration: 100 ms Memory Size: 128 MB Max Memory Used: 14 MB "Success! Parsed Events" You can see the full output of your function in the logs that follow the invoke command. In this example, the Python function prints out the event payload and then exits. With the AWS SAM CLI, you can pass in valid test payloads that interface with data in other AWS services. You can also have your Lambda function talk to other AWS resources that exist in your account, for example Amazon DynamoDB tables, Amazon S3 buckets, and so on. You could also test an API interface using the local start-api command , provided that you have configured your AWS SAM template with events of the API type . Follow the full instructions for setting up and configuring the AWS SAM CLI in Installing the AWS SAM CLI . Find the full syntax guide for AWS SAM templates in the AWS Serverless Application Model documentation. Testing in the Lambda console After you have deployed your functions after the start of the Update/Create phase or with the Opt-In layer added, test your functions in the Lambda console. In the Lambda console, select the function to test. Select a test event and choose Test . If no test event exists, choose Configure test events . Choose Event template and select the relevant invocation service from which to test. Name the test event. Modify the event payload for your specific function. Choose Create and then return to step 2. The results from the test are displayed. Conclusion With Lambda and Lambda@Edge, AWS has allowed developers to focus on just application code without the need to think about the work involved managing the actual servers that run the code. We believe that the mechanisms provided and processes described in this post allow you to easily test and update your functions for this new execution environment. Some of you may have questions about this process, and we are ready to help you. Please contact us through AWS Support, the AWS forums, or AWS account teams. TAGS: AWS Lambda , Lambda@Edge Resources Serverless Computing and Applications Amazon Container Services AWS Messaging Cloud Compute with AWS Desktop and Application Streaming Follow Twitter Facebook LinkedIn Twitch Email Updates @charset "UTF-8";[data-eb-6a8f3296] .rgft_9e423fbb.rgft_1b2a14d4{position:relative;transition:box-shadow .3s ease}[data-eb-6a8f3296] .rgft_9e423fbb.rgft_1b2a14d4:not(:disabled,.rgft_3ef5a62a).rgft_3d631df0,[data-eb-6a8f3296] .rgft_9e423fbb.rgft_1b2a14d4:not(:disabled,.rgft_3ef5a62a).rgft_b27cc003,[data-eb-6a8f3296] .rgft_9e423fbb.rgft_1b2a14d4:not(:disabled,.rgft_3ef5a62a).rgft_5962fadc:hover{box-shadow:var(--rg-shadow-gray-elevation-1, 1px 1px 20px rgba(0, 0, 0, .1))}[data-eb-6a8f3296] .rgft_9e423fbb.rgft_1b2a14d4:not(:disabled,.rgft_3ef5a62a).rgft_3d631df0.rgft_e79955da,[data-eb-6a8f3296] .rgft_9e423fbb.rgft_1b2a14d4:not(:disabled,.rgft_3ef5a62a).rgft_b27cc003.rgft_e79955da,[data-eb-6a8f3296] .rgft_9e423fbb.rgft_1b2a14d4:not(:disabled,.rgft_3ef5a62a).rgft_5962fadc:hover.rgft_e79955da{box-shadow:var(--rg-shadow-gray-elevation-2, 1px 1px 24px rgba(0, 0, 0, .25))}[data-eb-6a8f3296] .rgft_9e423fbb.rgft_1b2a14d4:not(:disabled,.rgft_3ef5a62a).rgft_b27cc003:hover{box-shadow:none}[data-eb-6a8f3296] .rgft_9e423fbb.rgft_1ed8cbde{position:relative;transform-style:preserve-3d;overflow:unset!important}[data-eb-6a8f3296] .rgft_9e423fbb.rgft_1ed8cbde:before{content:"";position:absolute;inset:0;border-radius:inherit;transform:translateZ(-1px);pointer-events:none;transition-property:filter,inset;transition-duration:.3s;transition-timing-function:ease;background-clip:content-box!important;padding:1px}[data-eb-6a8f3296] .rgft_9e423fbb.rgft_1ed8cbde:not(:disabled,.rgft_3ef5a62a).rgft_3d631df0:before{filter:blur(15px)}[data-eb-6a8f3296] .rgft_9e423fbb.rgft_1ed8cbde:not(:disabled,.rgft_3ef5a62a).rgft_3d631df0.rgft_4df65418:hover:before{filter:blur(20px)}[data-eb-6a8f3296] .rgft_9e423fbb.rgft_1ed8cbde:not(:disabled,.rgft_3ef5a62a).rgft_5962fadc:hover:before{filter:blur(15px)}[data-eb-6a8f3296] .rgft_9e423fbb.rgft_1ed8cbde:not(:disabled,.rgft_3ef5a62a).rgft_b27cc003:before{filter:blur(15px)}[data-eb-6a8f3296] .rgft_9e423fbb.rgft_1ed8cbde:not(:disabled,.rgft_3ef5a62a).rgft_b27cc003:hover:before{filter:none}[data-eb-6a8f3296] .rgft_9e423fbb.rgft_1ed8cbde:not(:disabled,.rgft_3ef5a62a).rgft_e90ac70d:active:before{filter:blur(8px)!important}[data-eb-6a8f3296] .rgft_9e423fbb.rgft_1ed8cbde:not(:disabled,.rgft_3ef5a62a).rgft_a4f580d2:before{filter:blur(8px)!important}[data-eb-6a8f3296] [data-rg-mode=light][data-rg-theme=fuchsia] .rgft_9e423fbb.rgft_1ed8cbde:not(:disabled,.rgft_3ef5a62a).rgft_38d8ffac:before,[data-eb-6a8f3296] [data-rg-mode=light][data-rg-theme=fuchsia].rgft_9e423fbb.rgft_1ed8cbde.rgft_38d8ffac:not(:disabled,.rgft_3ef5a62a):before{background:var(--rg-shadow-gradient-fuchsia, linear-gradient(123deg, #fa6f00 0%, #e433ff 50%, #8575ff 100%))}[data-eb-6a8f3296] [data-rg-mode=dark][data-rg-theme=fuchsia] .rgft_9e423fbb.rgft_1ed8cbde:not(:disabled,.rgft_3ef5a62a).rgft_38d8ffac:before,[data-eb-6a8f3296] [data-rg-mode=dark][data-rg-theme=fuchsia].rgft_9e423fbb.rgft_1ed8cbde.rgft_38d8ffac:not(:disabled,.rgft_3ef5a62a):before{background:var(--rg-shadow-gradient-fuchsia, linear-gradient(123deg, #d14600 0%, #c300e0 50%, #6842ff 100%))}[data-eb-6a8f3296] [data-rg-mode=light][data-rg-theme=indigo] .rgft_9e423fbb.rgft_1ed8cbde:not(:disabled,.rgft_3ef5a62a).rgft_38d8ffac:before,[data-eb-6a8f3296] [data-rg-mode=light][data-rg-theme=indigo].rgft_9e423fbb.rgft_1ed8cbde.rgft_38d8ffac:not(:disabled,.rgft_3ef5a62a):before{background:var(--rg-shadow-gradient-indigo, linear-gradient(123deg, #0099ff 0%, #5c7fff 50%, #8575ff 100%))}[data-eb-6a8f3296] [data-rg-mode=dark][data-rg-theme=indigo] .rgft_9e423fbb.rgft_1ed8cbde:not(:disabled,.rgft_3ef5a62a).rgft_38d8ffac:before,[data-eb-6a8f3296] [data-rg-mode=dark][data-rg-theme=indigo].rgft_9e423fbb.rgft_1ed8cbde.rgft_38d8ffac:not(:disabled,.rgft_3ef5a62a):before{background:var(--rg-shadow-gradient-indigo, linear-gradient(123deg, #006ce0 0%, #295eff 50%, #6842ff 100%))}[data-eb-6a8f3296] [data-rg-mode=light][data-rg-theme=orange] .rgft_9e423fbb.rgft_1ed8cbde:not(:disabled,.rgft_3ef5a62a).rgft_38d8ffac:before,[data-eb-6a8f3296] [data-rg-mode=light][data-rg-theme=orange].rgft_9e423fbb.rgft_1ed8cbde.rgft_38d8ffac:not(:disabled,.rgft_3ef5a62a):before{background:var(--rg-shadow-gradient-orange, linear-gradient(123deg, #ff1ae0 0%, #ff386a 50%, #fa6f00 100%))}[data-eb-6a8f3296] [data-rg-mode=dark][data-rg-theme=orange] .rgft_9e423fbb.rgft_1ed8cbde:not(:disabled,.rgft_3ef5a62a).rgft_38d8ffac:before,[data-eb-6a8f3296] [data-rg-mode=dark][data-rg-theme=orange].rgft_9e423fbb.rgft_1ed8cbde.rgft_38d8ffac:not(:disabled,.rgft_3ef5a62a):before{background:var(--rg-shadow-gradient-orange, linear-gradient(123deg, #d600ba 0%, #eb003b 50%, #d14600 100%))}[data-eb-6a8f3296] [data-rg-mode=light][data-rg-theme=teal] .rgft_9e423fbb.rgft_1ed8cbde:not(:disabled,.rgft_3ef5a62a).rgft_38d8ffac:before,[data-eb-6a8f3296] [data-rg-mode=light][data-rg-theme=teal].rgft_9e423fbb.rgft_1ed8cbde.rgft_38d8ffac:not(:disabled,.rgft_3ef5a62a):before{background:var(--rg-shadow-gradient-teal, linear-gradient(123deg, #00bd6b 0%, #00a4bd 50%, #0099ff 100%))}[data-eb-6a8f3296] [data-rg-mode=dark][data-rg-theme=teal] .rgft_9e423fbb.rgft_1ed8cbde:not(:disabled,.rgft_3ef5a62a).rgft_38d8ffac:before,[data-eb-6a8f3296] [data-rg-mode=dark][data-rg-theme=teal].rgft_9e423fbb.rgft_1ed8cbde.rgft_38d8ffac:not(:disabled,.rgft_3ef5a62a):before{background:var(--rg-shadow-gradient-teal, linear-gradient(123deg, #008559 0%, #007e94 50%, #006ce0 100%))}[data-eb-6a8f3296] [data-rg-mode=light][data-rg-theme=blue] .rgft_9e423fbb.rgft_1ed8cbde:not(:disabled,.rgft_3ef5a62a).rgft_38d8ffac:before,[data-eb-6a8f3296] [data-rg-mode=light][data-rg-theme=blue].rgft_9e423fbb.rgft_1ed8cbde.rgft_38d8ffac:not(:disabled,.rgft_3ef5a62a):before{background:var(--rg-shadow-gradient-blue, linear-gradient(123deg, #00bd6b 0%, #0099ff 50%, #8575ff 100%))}[data-eb-6a8f3296] [data-rg-mode=dark][data-rg-theme=blue] .rgft_9e423fbb.rgft_1ed8cbde:not(:disabled,.rgft_3ef5a62a).rgft_38d8ffac:before,[data-eb-6a8f3296] [data-rg-mode=dark][data-rg-theme=blue].rgft_9e423fbb.rgft_1ed8cbde.rgft_38d8ffac:not(:disabled,.rgft_3ef5a62a):before{background:var(--rg-shadow-gradient-blue, linear-gradient(123deg, #008559 0%, #006ce0 50%, #6842ff 100%))}[data-eb-6a8f3296] [data-rg-mode=light][data-rg-theme=violet] .rgft_9e423fbb.rgft_1ed8cbde:not(:disabled,.rgft_3ef5a62a).rgft_38d8ffac:before,[data-eb-6a8f3296] [data-rg-mode=light][data-rg-theme=violet].rgft_9e423fbb.rgft_1ed8cbde.rgft_38d8ffac:not(:disabled,.rgft_3ef5a62a):before{background:var(--rg-shadow-gradient-violet, linear-gradient(123deg, #ad5cff 0%, #0099ff 50%, #00a4bd 100%))}[data-eb-6a8f3296] [data-rg-mode=dark][data-rg-theme=violet] .rgft_9e423fbb.rgft_1ed8cbde:not(:disabled,.rgft_3ef5a62a).rgft_38d8ffac:before,[data-eb-6a8f3296] [data-rg-mode=dark][data-rg-theme=violet].rgft_9e423fbb.rgft_1ed8cbde.rgft_38d8ffac:not(:disabled,.rgft_3ef5a62a):before{background:var(--rg-shadow-gradient-violet, linear-gradient(123deg, #962eff 0%, #006ce0 50%, #007e94 100%))}[data-eb-6a8f3296] [data-rg-mode=light][data-rg-theme=purple] .rgft_9e423fbb.rgft_1ed8cbde:not(:disabled,.rgft_3ef5a62a).rgft_38d8ffac:before,[data-eb-6a8f3296] [data-rg-mode=light][data-rg-theme=purple].rgft_9e423fbb.rgft_1ed8cbde.rgft_38d8ffac:not(:disabled,.rgft_3ef5a62a):before{background:var(--rg-shadow-gradient-purple, linear-gradient(123deg, #ff1ae0 0%, #8575ff 50%, #00a4bd 100%))}[data-eb-6a8f3296] [data-rg-mode=dark][data-rg-theme=purple] .rgft_9e423fbb.rgft_1ed8cbde:not(:disabled,.rgft_3ef5a62a).rgft_38d8ffac:before,[data-eb-6a8f3296] [data-rg-mode=dark][data-rg-theme=purple].rgft_9e423fbb.rgft_1ed8cbde.rgft_38d8ffac:not(:disabled,.rgft_3ef5a62a):before{background:var(--rg-shadow-gradient-purple, linear-gradient(123deg, #d600ba 0%, #6842ff 50%, #007e94 100%))}[data-eb-6a8f3296] .rgft_9e423fbb.rgft_1ed8cbde:not(:disabled,.rgft_3ef5a62a):before{background:linear-gradient(123deg,#d14600,#c300e0,#6842ff)}[data-eb-6a8f3296] [data-rg-theme=fuchsia] .rgft_9e423fbb.rgft_1ed8cbde:not(:disabled,.rgft_3ef5a62a):before,[data-eb-6a8f3296] [data-rg-theme=fuchsia].rgft_9e423fbb.rgft_1ed8cbde:not(:disabled,.rgft_3ef5a62a):before{background:var(--rg-shadow-gradient-fuchsia, linear-gradient(123deg, #d14600 0%, #c300e0 50%, #6842ff 100%))}[data-eb-6a8f3296] [data-rg-theme=indigo] .rgft_9e423fbb.rgft_1ed8cbde:not(:disabled,.rgft_3ef5a62a):before,[data-eb-6a8f3296] [data-rg-theme=indigo].rgft_9e423fbb.rgft_1ed8cbde:not(:disabled,.rgft_3ef5a62a):before{background:var(--rg-shadow-gradient-indigo, linear-gradient(123deg, #006ce0 0%, #295eff 50%, #6842ff 100%))}[data-eb-6a8f3296] [data-rg-theme=orange] .rgft_9e423fbb.rgft_1ed8cbde:not(:disabled,.rgft_3ef5a62a):before,[data-eb-6a8f3296] [data-rg-theme=orange].rgft_9e423fbb.rgft_1ed8cbde:not(:disabled,.rgft_3ef5a62a):before{background:var(--rg-shadow-gradient-orange, linear-gradient(123deg, #d600ba 0%, #eb003b 50%, #d14600 100%))}[data-eb-6a8f3296] [data-rg-theme=teal] .rgft_9e423fbb.rgft_1ed8cbde:not(:disabled,.rgft_3ef5a62a):before,[data-eb-6a8f3296] [data-rg-theme=teal].rgft_9e423fbb.rgft_1ed8cbde:not(:disabled,.rgft_3ef5a62a):before{background:var(--rg-shadow-gradient-teal, linear-gradient(123deg, #008559 0%, #007e94 50%, #006ce0 100%))}[data-eb-6a8f3296] [data-rg-theme=blue] .rgft_9e423fbb.rgft_1ed8cbde:not(:disabled,.rgft_3ef5a62a):before,[data-eb-6a8f3296] [data-rg-theme=blue].rgft_9e423fbb.rgft_1ed8cbde:not(:disabled,.rgft_3ef5a62a):before{background:var(--rg-shadow-gradient-blue, linear-gradient(123deg, #008559 0%, #006ce0 50%, #6842ff 100%))}[data-eb-6a8f3296] [data-rg-theme=violet] .rgft_9e423fbb.rgft_1ed8cbde:not(:disabled,.rgft_3ef5a62a):before,[data-eb-6a8f3296] [data-rg-theme=violet].rgft_9e423fbb.rgft_1ed8cbde:not(:disabled,.rgft_3ef5a62a):before{background:var(--rg-shadow-gradient-violet, linear-gradient(123deg, #962eff 0%, #006ce0 50%, #007e94 100%))}[data-eb-6a8f3296] [data-rg-theme=purple] .rgft_9e423fbb.rgft_1ed8cbde:not(:disabled,.rgft_3ef5a62a):before,[data-eb-6a8f3296] [data-rg-theme=purple].rgft_9e423fbb.rgft_1ed8cbde:not(:disabled,.rgft_3ef5a62a):before{background:var(--rg-shadow-gradient-purple, linear-gradient(123deg, #d600ba 0%, #6842ff 50%, #007e94 100%))}[data-eb-6a8f3296] a.rgft_f7822e54,[data-eb-6a8f3296] button.rgft_f7822e54{--button-size: 44px;--button-pad-h: 24px;--button-pad-borderless-h: 26px;border:2px solid var(--rg-color-background-page-inverted, #0F141A);padding:8px var(--button-pad-h, 24px);border-radius:40px!important;align-items:center;justify-content:center;display:inline-flex;height:var(--button-size, 44px);text-decoration:none!important;text-wrap:nowrap;cursor:pointer;position:relative;transition:all .3s ease}[data-eb-6a8f3296] a.rgft_f7822e54.rgft_094d67e1,[data-eb-6a8f3296] button.rgft_f7822e54.rgft_094d67e1{--button-size: 32px;--button-pad-h: 14px;--button-pad-borderless-h: 16px}[data-eb-6a8f3296] a.rgft_f7822e54>span,[data-eb-6a8f3296] button.rgft_f7822e54>span{color:var(--btn-text-color, inherit)!important}[data-eb-6a8f3296] a.rgft_f7822e54:focus-visible,[data-eb-6a8f3296] button.rgft_f7822e54:focus-visible{outline:2px solid var(--rg-color-focus-ring, #006CE0)!important;outline-offset:4px!important;transition:outline 0s}[data-eb-6a8f3296] a.rgft_f7822e54:focus:not(:focus-visible),[data-eb-6a8f3296] button.rgft_f7822e54:focus:not(:focus-visible){outline:none!important}[data-eb-6a8f3296] a.rgft_f7822e54.rgft_303c672b,[data-eb-6a8f3296] button.rgft_f7822e54.rgft_303c672b{--btn-text-color: var(--rg-color-text-utility-inverted, #FFFFFF);background-color:var(--rg-color-btn-primary-bg, #161D26);border:none;padding:10px var(--button-pad-borderless-h, 24px)}[data-eb-6a8f3296] a.rgft_f7822e54.rgft_18409398,[data-eb-6a8f3296] button.rgft_f7822e54.rgft_18409398{--btn-text-color: var(--rg-color-text-utility, #161D26);background-color:var(--rg-color-btn-secondary-bg, #FFFFFF);border-color:var(--rg-color-background-page-inverted, #0F141A)}[data-eb-6a8f3296] a.rgft_f7822e54.rgft_090951dc,[data-eb-6a8f3296] button.rgft_f7822e54.rgft_090951dc{--btn-text-color: var(--rg-color-text-utility, #161D26);background-color:var(--rg-color-background-object, #F3F3F7);border:none;padding:10px var(--button-pad-borderless-h, 24px)}[data-eb-6a8f3296] a.rgft_f7822e54.rgft_15529d9f,[data-eb-6a8f3296] button.rgft_f7822e54.rgft_15529d9f{--btn-text-color: var(--rg-color-text-utility, #161D26);background-color:var(--rg-color-btn-secondary-bg, #FFFFFF);border:none;padding:10px var(--button-pad-borderless-h, 24px)}[data-eb-6a8f3296] a.rgft_f7822e54.rgft_bb950a4e,[data-eb-6a8f3296] button.rgft_f7822e54.rgft_bb950a4e{--btn-text-color: var(--rg-color-text-utility, #161D26);border:none;padding:10px var(--button-pad-borderless-h, 24px)}[data-eb-6a8f3296] a.rgft_f7822e54.rgft_bb950a4e,[data-eb-6a8f3296] button.rgft_f7822e54.rgft_bb950a4e{background-image:linear-gradient(97deg,#ffc0ad,#f8c7ff 37.79%,#d2ccff 75.81%,#c2d1ff)}[data-eb-6a8f3296] a.rgft_f7822e54.rgft_bb950a4e,[data-eb-6a8f3296] button.rgft_f7822e54.rgft_bb950a4e{--rg-gradient-angle:97deg;background-image:var(--rg-gradient-a, linear-gradient(120deg, #f8c7ff 20.08%, #d2ccff 75.81%))}[data-eb-6a8f3296] [data-rg-mode=dark] a.rgft_f7822e54.rgft_bb950a4e,[data-eb-6a8f3296] [data-rg-mode=dark] button.rgft_f7822e54.rgft_bb950a4e,[data-eb-6a8f3296] a[data-rg-mode=dark].rgft_f7822e54.rgft_bb950a4e,[data-eb-6a8f3296] button[data-rg-mode=dark].rgft_f7822e54.rgft_bb950a4e{background-image:var(--rg-gradient-a, linear-gradient(120deg, #78008a 24.25%, #b2008f 69.56%))}[data-eb-6a8f3296] a.rgft_f7822e54.rgft_bb419678,[data-eb-6a8f3296] button.rgft_f7822e54.rgft_bb419678{--btn-text-color: var(--rg-color-text-utility-inverted, #FFFFFF);background-color:var(--rg-color-btn-visited-bg, #656871);border-color:var(--rg-color-btn-visited-bg, #656871)}[data-eb-6a8f3296] a.rgft_f7822e54.rgft_bb419678.rgft_18409398,[data-eb-6a8f3296] a.rgft_f7822e54.rgft_bb419678.rgft_15529d9f,[data-eb-6a8f3296] button.rgft_f7822e54.rgft_bb419678.rgft_18409398,[data-eb-6a8f3296] button.rgft_f7822e54.rgft_bb419678.rgft_15529d9f{--btn-text-color: var(--rg-color-text-utility, #161D26);background-color:var(--rg-color-btn-secondary-visited-bg, #FFFFFF)}[data-eb-6a8f3296] a.rgft_f7822e54.rgft_badebaf5,[data-eb-6a8f3296] button.rgft_f7822e54.rgft_badebaf5{--btn-text-color: var(--rg-color-btn-disabled-text, #B4B4BB);background-color:var(--rg-color-btn-disabled-bg, #F3F3F7);border-color:var(--rg-color-btn-disabled-bg, #F3F3F7);cursor:default}[data-eb-6a8f3296] a.rgft_f7822e54.rgft_badebaf5.rgft_18409398,[data-eb-6a8f3296] a.rgft_f7822e54.rgft_badebaf5.rgft_15529d9f,[data-eb-6a8f3296] button.rgft_f7822e54.rgft_badebaf5.rgft_18409398,[data-eb-6a8f3296] button.rgft_f7822e54.rgft_badebaf5.rgft_15529d9f{border:none;padding:10px var(--button-pad-borderless-h, 24px)}[data-eb-6a8f3296] a.rgft_f7822e54.rgft_badebaf5.rgft_090951dc,[data-eb-6a8f3296] button.rgft_f7822e54.rgft_badebaf5.rgft_090951dc{--btn-text-color: var(--rg-color-btn-tertiary-disabled-text, #B4B4BB);background-color:#0000}[data-eb-6a8f3296] a.rgft_f7822e54:hover:not(.rgft_badebaf5).rgft_18409398:not(.rgft_bb950a4e),[data-eb-6a8f3296] a.rgft_f7822e54:hover:not(.rgft_badebaf5).rgft_15529d9f:not(.rgft_bb950a4e),[data-eb-6a8f3296] button.rgft_f7822e54:hover:not(.rgft_badebaf5).rgft_18409398:not(.rgft_bb950a4e),[data-eb-6a8f3296] button.rgft_f7822e54:hover:not(.rgft_badebaf5).rgft_15529d9f:not(.rgft_bb950a4e){--btn-text-color: var(--rg-color-text-utility, #161D26);background-color:var(--rg-color-btn-secondary-bg, #FFFFFF)}[data-eb-6a8f3296] a.rgft_f7822e54:hover:not(.rgft_badebaf5).rgft_090951dc,[data-eb-6a8f3296] button.rgft_f7822e54:hover:not(.rgft_badebaf5).rgft_090951dc{box-shadow:none}[data-eb-6a8f3296] a.rgft_f7822e54:hover:not(.rgft_badebaf5).rgft_090951dc,[data-eb-6a8f3296] button.rgft_f7822e54:hover:not(.rgft_badebaf5).rgft_090951dc{background-image:linear-gradient(97deg,#ffc0ad80,#f8c7ff80 37.79%,#d2ccff80 75.81%,#c2d1ff80)}[data-eb-6a8f3296] a.rgft_f7822e54:hover:not(.rgft_badebaf5).rgft_090951dc,[data-eb-6a8f3296] button.rgft_f7822e54:hover:not(.rgft_badebaf5).rgft_090951dc{--rg-gradient-angle:97deg;background-image:var(--rg-gradient-a-50, linear-gradient(120deg, #f8c7ff 20.08%, #d2ccff 75.81%))}[data-eb-6a8f3296] [data-rg-mode=dark] a.rgft_f7822e54:hover:not(.rgft_badebaf5).rgft_090951dc,[data-eb-6a8f3296] [data-rg-mode=dark] button.rgft_f7822e54:hover:not(.rgft_badebaf5).rgft_090951dc,[data-eb-6a8f3296] a[data-rg-mode=dark].rgft_f7822e54.rgft_090951dc:hover:not(.rgft_badebaf5),[data-eb-6a8f3296] button[data-rg-mode=dark].rgft_f7822e54.rgft_090951dc:hover:not(.rgft_badebaf5){background-image:var(--rg-gradient-a-50, linear-gradient(120deg, #78008a 24.25%, #b2008f 69.56%))}[data-eb-6a8f3296] a.rgft_f7822e54:active:not(.rgft_badebaf5).rgft_090951dc,[data-eb-6a8f3296] button.rgft_f7822e54:active:not(.rgft_badebaf5).rgft_090951dc{box-shadow:none}[data-eb-6a8f3296] a.rgft_f7822e54:active:not(.rgft_badebaf5).rgft_090951dc,[data-eb-6a8f3296] button.rgft_f7822e54:active:not(.rgft_badebaf5).rgft_090951dc{background-image:linear-gradient(97deg,#ffc0ad,#f8c7ff 37.79%,#d2ccff 75.81%,#c2d1ff)}[data-eb-6a8f3296] a.rgft_f7822e54:active:not(.rgft_badebaf5).rgft_090951dc,[data-eb-6a8f3296] button.rgft_f7822e54:active:not(.rgft_badebaf5).rgft_090951dc{--rg-gradient-angle:97deg;background-image:var(--rg-gradient-a-pressed, linear-gradient(120deg, rgba(248, 199, 255, .5) 20.08%, #d2ccff 75.81%))}[data-eb-6a8f3296] [data-rg-mode=dark] a.rgft_f7822e54:active:not(.rgft_badebaf5).rgft_090951dc,[data-eb-6a8f3296] [data-rg-mode=dark] button.rgft_f7822e54:active:not(.rgft_badebaf5).rgft_090951dc,[data-eb-6a8f3296] a[data-rg-mode=dark].rgft_f7822e54.rgft_090951dc:active:not(.rgft_badebaf5),[data-eb-6a8f3296] button[data-rg-mode=dark].rgft_f7822e54.rgft_090951dc:active:not(.rgft_badebaf5){background-image:var(--rg-gradient-a-pressed, linear-gradient(120deg, rgba(120, 0, 138, .5) 24.25%, #b2008f 69.56%))}[data-eb-6a8f3296] .rgft_8711ccd9{-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;background:#0000;border:none;margin:0}[data-eb-6a8f3296] .rgft_8711ccd9.rgft_5e58a6df{text-align:center}[data-eb-6a8f3296] .rgft_8711ccd9.rgft_b7ada98b{display:block}[data-eb-6a8f3296] .rgft_8711ccd9.rgft_beb26dc7{font-family:Amazon Ember Mono,Consolas,Andale Mono WT,Andale Mono,Lucida Console,Lucida Sans Typewriter,DejaVu Sans Mono,Bitstream Vera Sans Mono,Liberation Mono,Nimbus Mono L,Monaco,Courier New,Courier,monospace}[data-eb-6a8f3296] .rgft_8711ccd9 a{display:inline;position:relative;cursor:pointer;text-decoration:none!important;color:var(--rg-color-link-default, #006CE0);background:linear-gradient(to right,currentcolor,currentcolor);background-size:100% .1em;background-position:0 100%;background-repeat:no-repeat}[data-eb-6a8f3296] .rgft_8711ccd9 a:focus-visible{color:var(--rg-color-link-focus, #006CE0)}[data-eb-6a8f3296] .rgft_8711ccd9 a:hover{color:var(--rg-color-link-hover, #003B8F);animation:rgft_d72bdead .3s cubic-bezier(0,0,.2,1)}[data-eb-6a8f3296] .rgft_8711ccd9 a:visited{color:var(--rg-color-link-visited, #6842FF)}@keyframes rgft_d72bdead{0%{background-size:0 .1em}to{background-size:100% .1em}}[data-eb-6a8f3296] .rgft_8711ccd9 b,[data-eb-6a8f3296] b.rgft_8711ccd9,[data-eb-6a8f3296] .rgft_8711ccd9 strong,[data-eb-6a8f3296] strong.rgft_8711ccd9{font-weight:700}[data-eb-6a8f3296] i.rgft_8711ccd9,[data-eb-6a8f3296] .rgft_8711ccd9 i,[data-eb-6a8f3296] em.rgft_8711ccd9,[data-eb-6a8f3296] .rgft_8711ccd9 em{font-style:italic}[data-eb-6a8f3296] u.rgft_8711ccd9,[data-eb-6a8f3296] .rgft_8711ccd9 u{text-decoration:underline}[data-eb-6a8f3296] code.rgft_8711ccd9,[data-eb-6a8f3296] .rgft_8711ccd9 code{font-family:Amazon Ember Mono,Consolas,Andale Mono WT,Andale Mono,Lucida Console,Lucida Sans Typewriter,DejaVu Sans Mono,Bitstream Vera Sans Mono,Liberation Mono,Nimbus Mono L,Monaco,Courier New,Courier,monospace;border-radius:4px;border:1px solid var(--rg-color-border-lowcontrast, #CCCCD1);color:var(--rg-color-text-secondary, #232B37);padding-top:var(--rg-padding-8);padding-right:var(--rg-padding-8);padding-bottom:var(--rg-padding-8);padding-left:var(--rg-padding-8)}[data-eb-6a8f3296] .rgft_12e1c6fa{display:inline!important;vertical-align:middle}[data-eb-6a8f3296] .rgft_8711ccd9 p img{aspect-ratio:16/9;height:100%;object-fit:cover;width:100%;border-radius:8px;order:1;margin-bottom:var(--rg-margin-4)}[data-eb-6a8f3296] .rgft_8711ccd9 table{table-layout:fixed;border-spacing:0;width:100%}[data-eb-6a8f3296] .rgft_8711ccd9 table td{font-size:14px;border-right:1px solid var(--rg-color-border-lowcontrast, #CCCCD1);border-bottom:1px solid var(--rg-color-border-lowcontrast, #CCCCD1);padding-top:var(--rg-padding-6);padding-right:var(--rg-padding-6);padding-bottom:var(--rg-padding-6);padding-left:var(--rg-padding-6)}[data-eb-6a8f3296] .rgft_8711ccd9 table td:first-of-type{border-left:1px solid var(--rg-color-border-lowcontrast, #CCCCD1)}[data-eb-6a8f3296] .rgft_8711ccd9 table thead tr:first-of-type>*:first-of-type,[data-eb-6a8f3296] .rgft_8711ccd9 table:not(:has(thead)) tr:first-of-type>*:first-of-type{border-top-left-radius:16px}[data-eb-6a8f3296] .rgft_8711ccd9 table thead tr:first-of-type>*:last-of-type,[data-eb-6a8f3296] .rgft_8711ccd9 table:not(:has(thead)) tr:first-of-type>*:last-of-type{border-top-right-radius:16px}[data-eb-6a8f3296] .rgft_8711ccd9 table tr:last-of-type td:first-of-type{border-bottom-left-radius:16px}[data-eb-6a8f3296] .rgft_8711ccd9 table tr:last-of-type td:last-of-type{border-bottom-right-radius:16px}[data-eb-6a8f3296] .rgft_8711ccd9 table:not(:has(thead),:has(th)) tr:first-of-type td{border-top:1px solid var(--rg-color-border-lowcontrast, #CCCCD1);border-right:1px solid var(--rg-color-border-lowcontrast, #CCCCD1);border-bottom:1px solid var(--rg-color-border-lowcontrast, #CCCCD1)}[data-eb-6a8f3296] .rgft_8711ccd9 table th{color:var(--rg-color-text-primary-inverted, #FFFFFF);min-width:280px;max-width:400px;padding:0;text-align:left;vertical-align:top;background-color:var(--rg-color-background-object-inverted, #232B37);border-left:1px solid var(--rg-color-border-lowcontrast, #CCCCD1);border-right:1px solid var(--rg-color-border-lowcontrast, #CCCCD1);border-bottom:1px solid var(--rg-color-border-lowcontrast, #CCCCD1);padding-top:var(--rg-padding-6);padding-right:var(--rg-padding-6);padding-bottom:var(--rg-padding-6);padding-left:var(--rg-padding-6);row-gap:var(--rg-margin-5);column-gap:var(--rg-margin-5);max-width:100%;min-width:150px}@media (min-width: 480px) and (max-width: 767px){[data-eb-6a8f3296] .rgft_8711ccd9 table th{max-width:100%;min-width:150px}}@media (min-width: 768px) and (max-width: 1023px){[data-eb-6a8f3296] .rgft_8711ccd9 table th{max-width:240px;min-width:180px}}@media (min-width: 1024px) and (max-width: 1279px){[data-eb-6a8f3296] .rgft_8711ccd9 table th{max-width:350px;min-width:240px}}@media (min-width: 1280px) and (max-width: 1599px){[data-eb-6a8f3296] .rgft_8711ccd9 table th{max-width:400px;min-width:280px}}@media (min-width: 1600px){[data-eb-6a8f3296] .rgft_8711ccd9 table th{max-width:400px;min-width:280px}}[data-eb-6a8f3296] .rgft_8711ccd9 table th:first-of-type{border-top-left-radius:16px;border-top:0 solid var(--rg-color-border-lowcontrast, #CCCCD1);border-left:0 solid var(--rg-color-border-lowcontrast, #CCCCD1);border-right:0 solid var(--rg-color-border-lowcontrast, #CCCCD1)}[data-eb-6a8f3296] .rgft_8711ccd9 table th:nth-of-type(n+3){border-left:0 solid var(--rg-color-border-lowcontrast, #CCCCD1)}[data-eb-6a8f3296] .rgft_8711ccd9 table th:last-of-type{border-top-right-radius:16px;border-top:0 solid var(--rg-color-border-lowcontrast, #CCCCD1);border-right:0 solid var(--rg-color-border-lowcontrast, #CCCCD1)}[data-eb-6a8f3296] .rgft_a1b66739{display:inline-flex;flex-direction:column;align-items:center;justify-content:center;color:var(--rg-color-text-primary, #161D26);--icon-color: currentcolor}[data-eb-6a8f3296] .rgft_a1b66739.rgft_bc1a8743{height:16px;width:16px}[data-eb-6a8f3296] .rgft_a1b66739.rgft_c0cbb35d{height:20px;width:20px}[data-eb-6a8f3296] .rgft_a1b66739.rgft_bd40fe12{height:32px;width:32px}[data-eb-6a8f3296] .rgft_a1b66739.rgft_27320e58{height:48px;width:48px}[data-eb-6a8f3296] .rgft_a1b66739 svg{fill:none;stroke:none}[data-eb-6a8f3296] .rgft_a1b66739 path[data-fill]:not([fill]){fill:var(--icon-color)}[data-eb-6a8f3296] .rgft_a1b66739 path[data-stroke]{stroke-width:2}[data-eb-6a8f3296] .rgft_a1b66739 path[data-stroke]:not([stroke]){stroke:var(--icon-color)}[data-eb-6a8f3296] .rgft_3ed66ff4{display:inline-flex;flex-direction:column;align-items:center;justify-content:center;color:var(--rg-color-text-primary, #161D26)}[data-eb-6a8f3296] .rgft_3ed66ff4.rgft_9124b200{height:10px;width:10px}[data-eb-6a8f3296] .rgft_3ed66ff4.rgft_bc1a8743{height:16px;width:16px}[data-eb-6a8f3296] .rgft_3ed66ff4.rgft_c0cbb35d{height:20px;width:20px}[data-eb-6a8f3296] .rgft_3ed66ff4.rgft_bd40fe12{height:32px;width:32px}[data-eb-6a8f3296] .rgft_3ed66ff4.rgft_27320e58{height:48px;width:48px}[data-eb-6a8f3296] .rgft_98b54368{color:var(--rg-color-text-body, #232B37)}[data-eb-6a8f3296] .rgft_98b54368.rgft_275611e5{font-size:calc(1rem * var(--font-size-multiplier, 1.6));line-height:1.5;font-weight:400;font-family:Amazon Ember Display,Amazon Ember,Helvetica Neue,Helvetica,Arial,sans-serif}@media (min-width: 481px) and (max-width: 768px){[data-eb-6a8f3296] .rgft_98b54368.rgft_275611e5{font-size:calc(1rem * var(--font-size-multiplier, 1.6));line-height:1.5;font-weight:400}}@media (max-width: 480px){[data-eb-6a8f3296] .rgft_98b54368.rgft_275611e5{font-size:calc(1rem * var(--font-size-multiplier, 1.6));line-height:1.5;font-weight:400}}[data-eb-6a8f3296] [data-rg-lang=ar] .rgft_98b54368.rgft_275611e5{font-family:AmazonEmberArabic,Helvetica,Arial,sans-serif}[data-eb-6a8f3296] [data-rg-lang=ja] .rgft_98b54368.rgft_275611e5{font-family:ShinGo,\30d2\30e9\30ae\30ce\89d2\30b4 Pro W3,Hiragino Kaku Gothic Pro,Osaka,\30e1\30a4\30ea\30aa,Meiryo,\ff2d\ff33 \ff30\30b4\30b7\30c3\30af,MS PGothic,sans-serif}[data-eb-6a8f3296] [data-rg-lang=ko] .rgft_98b54368.rgft_275611e5{font-family:NotoSansKR,Malgun Gothic,sans-serif}[data-eb-6a8f3296] [data-rg-lang=th] .rgft_98b54368.rgft_275611e5{font-family:NotoSansThai,Helvetica,Arial,sans-serif}[data-eb-6a8f3296] [data-rg-lang=zh] .rgft_98b54368.rgft_275611e5{font-family:NotoSansTC,Helvetica,Arial,Microsoft Yahei,\5fae\8f6f\96c5\9ed1,STXihei,\534e\6587\7ec6\9ed1,sans-serif}[data-eb-6a8f3296] .rgft_98b54368.rgft_007aef8b{font-size:calc(.875rem * var(--font-size-multiplier, 1.6));line-height:1.429;font-weight:400;font-family:Amazon Ember Display,Amazon Ember,Helvetica Neue,Helvetica,Arial,sans-serif}@media (min-width: 481px) and (max-width: 768px){[data-eb-6a8f3296] .rgft_98b54368.rgft_007aef8b{font-size:calc(.875rem * var(--font-size-multiplier, 1.6));line-height:1.429;font-weight:400}}@media (max-width: 480px){[data-eb-6a8f3296] .rgft_98b54368.rgft_007aef8b{font-size:calc(.875rem * var(--font-size-multiplier, 1.6));line-height:1.429;font-weight:400}}[data-eb-6a8f3296] [data-rg-lang=ar] .rgft_98b54368.rgft_007aef8b{font-family:AmazonEmberArabic,Helvetica,Arial,sans-serif}[data-eb-6a8f3296] [data-rg-lang=ja] .rgft_98b54368.rgft_007aef8b{font-family:ShinGo,\30d2\30e9\30ae\30ce\89d2\30b4 Pro W3,Hiragino Kaku Gothic Pro,Osaka,\30e1\30a4\30ea\30aa,Meiryo,\ff2d\ff33 \ff30\30b4\30b7\30c3\30af,MS PGothic,sans-serif}[data-eb-6a8f3296] [data-rg-lang=ko] .rgft_98b54368.rgft_007aef8b{font-family:NotoSansKR,Malgun Gothic,sans-serif}[data-eb-6a8f3296] [data-rg-lang=th] .rgft_98b54368.rgft_007aef8b{font-family:NotoSansThai,Helvetica,Arial,sans-serif}[data-eb-6a8f3296] [data-rg-lang=zh] .rgft_98b54368.rgft_007aef8b{font-family:NotoSansTC,Helvetica,Arial,Microsoft Yahei,\5fae\8f6f\96c5\9ed1,STXihei,\534e\6587\7ec6\9ed1,sans-serif}[data-eb-6a8f3296] .rgft_98b54368.rgft_ff19c5f9{font-size:calc(.75rem * var(--font-size-multiplier, 1.6));line-height:1.333;font-weight:400;font-family:Amazon Ember Display,Amazon Ember,Helvetica Neue,Helvetica,Arial,sans-serif}@media (min-width: 481px) and (max-width: 768px){[data-eb-6a8f3296] .rgft_98b54368.rgft_ff19c5f9{font-size:calc(.75rem * var(--font-size-multiplier, 1.6));line-height:1.333;font-weight:400}}@media (max-width: 480px){[data-eb-6a8f3296] .rgft_98b54368.rgft_ff19c5f9{font-size:calc(.75rem * var(--font-size-multiplier, 1.6));line-height:1.333;font-weight:400}}[data-eb-6a8f3296] [data-rg-lang=ar] .rgft_98b54368.rgft_ff19c5f9{font-family:AmazonEmberArabic,Helvetica,Arial,sans-serif}[data-eb-6a8f3296] [data-rg-lang=ja] .rgft_98b54368.rgft_ff19c5f9{font-family:ShinGo,\30d2\30e9\30ae\30ce\89d2\30b4 Pro W3,Hiragino Kaku Gothic Pro,Osaka,\30e1\30a4\30ea\30aa,Meiryo,\ff2d\ff33 \ff30\30b4\30b7\30c3\30af,MS PGothic,sans-serif}[data-eb-6a8f3296] [data-rg-lang=ko] .rgft_98b54368.rgft_ff19c5f9{font-family:NotoSansKR,Malgun Gothic,sans-serif}[data-eb-6a8f3296] [data-rg-lang=th] .rgft_98b54368.rgft_ff19c5f9{font-family:NotoSansThai,Helvetica,Arial,sans-serif}[data-eb-6a8f3296] [data-rg-lang=zh] .rgft_98b54368.rgft_ff19c5f9{font-family:NotoSansTC,Helvetica,Arial,Microsoft Yahei,\5fae\8f6f\96c5\9ed1,STXihei,\534e\6587\7ec6\9ed1,sans-serif}[data-eb-6a8f3296] .rgft_98b54368 ul{list-style-type:disc;margin-top:2rem}[data-eb-6a8f3296] .rgft_98b54368.rgft_2a7f98ee{display:inline;position:relative;cursor:pointer;text-decoration:none!important;color:var(--rg-color-link-default, #006CE0);background:linear-gradient(to right,currentcolor,currentcolor);background-size:100% .1em;background-position:0 100%;background-repeat:no-repeat}[data-eb-6a8f3296] .rgft_98b54368.rgft_2a7f98ee:focus-visible{color:var(--rg-color-link-focus, #006CE0)}[data-eb-6a8f3296] .rgft_98b54368.rgft_2a7f98ee:hover{color:var(--rg-color-link-hover, #003B8F);animation:rgft_9beb7cc5 .3s cubic-bezier(0,0,.2,1)}[data-eb-6a8f3296] .rgft_98b54368.rgft_2a7f98ee:visited{color:var(--rg-color-link-visited, #6842FF)}@keyframes rgft_9beb7cc5{0%{background-size:0 .1em}to{background-size:100% .1em}}[data-eb-6a8f3296] .rgft_d835af5c{color:var(--rg-color-text-title, #161D26)}[data-eb-6a8f3296] .rgft_d835af5c.rgft_3e9243e1{font-size:calc(4.5rem * var(--font-size-multiplier, 1.6));line-height:1.111;font-weight:500;font-family:Amazon Ember Display,Amazon Ember,Helvetica Neue,Helvetica,Arial,sans-serif}@media (min-width: 481px) and (max-width: 768px){[data-eb-6a8f3296] .rgft_d835af5c.rgft_3e9243e1{font-size:calc(3.75rem * var(--font-size-multiplier, 1.6));line-height:1.133;font-weight:500}}@media (max-width: 480px){[data-eb-6a8f3296] .rgft_d835af5c.rgft_3e9243e1{font-size:calc(3rem * var(--font-size-multiplier, 1.6));line-height:1.167;font-weight:500}}[data-eb-6a8f3296] [data-rg-lang=ar] .rgft_d835af5c.rgft_3e9243e1{font-family:AmazonEmberArabic,Helvetica,Arial,sans-serif}[data-eb-6a8f3296] [data-rg-lang=ja] .rgft_d835af5c.rgft_3e9243e1{font-family:ShinGo,\30d2\30e9\30ae\30ce\89d2\30b4 Pro W3,Hiragino Kaku Gothic Pro,Osaka,\30e1\30a4\30ea\30aa,Meiryo,\ff2d\ff33 \ff30\30b4\30b7\30c3\30af,MS PGothic,sans-serif}[data-eb-6a8f3296] [data-rg-lang=ko] .rgft_d835af5c.rgft_3e9243e1{font-family:NotoSansKR,Malgun Gothic,sans-serif}[data-eb-6a8f3296] [data-rg-lang=th] .rgft_d835af5c.rgft_3e9243e1{font-family:NotoSansThai,Helvetica,Arial,sans-serif}[data-eb-6a8f3296] [data-rg-lang=zh] .rgft_d835af5c.rgft_3e9243e1{font-family:NotoSansTC,Helvetica,Arial,Microsoft Yahei,\5fae\8f6f\96c5\9ed1,STXihei,\534e\6587\7ec6\9ed1,sans-serif}[data-eb-6a8f3296] .rgft_d835af5c.rgft_54816d41{font-size:calc(3.75rem * var(--font-size-multiplier, 1.6));line-height:1.133;font-weight:500;font-family:Amazon Ember Display,Amazon Ember,Helvetica Neue,Helvetica,Arial,sans-serif}@media (min-width: 481px) and (max-width: 768px){[data-eb-6a8f3296] .rgft_d835af5c.rgft_54816d41{font-size:calc(3rem * var(--font-size-multiplier, 1.6));line-height:1.167;font-weight:500}}@media (max-width: 480px){[data-eb-6a8f3296] .rgft_d835af5c.rgft_54816d41{font-size:calc(2.5rem * var(--font-size-multiplier, 1.6));line-height:1.2;font-weight:500}}[data-eb-6a8f3296] [data-rg-lang=ar] .rgft_d835af5c.rgft_54816d41{font-family:AmazonEmberArabic,Helvetica,Arial,sans-serif}[data-eb-6a8f3296] [data-rg-lang=ja] .rgft_d835af5c.rgft_54816d41{font-family:ShinGo,\30d2\30e9\30ae\30ce\89d2\30b4 Pro W3,Hiragino Kaku Gothic Pro,Osaka,\30e1\30a4\30ea\30aa,Meiryo,\ff2d\ff33 \ff30\30b4\30b7\30c3\30af,MS PGothic,sans-serif}[data-eb-6a8f3296] [data-rg-lang=ko] .rgft_d835af5c.rgft_54816d41{font-family:NotoSansKR,Malgun Gothic,sans-serif}[data-eb-6a8f3296] [data-rg-lang=th] .rgft_d835af5c.rgft_54816d41{font-family:NotoSansThai,Helvetica,Arial,sans-serif}[data-eb-6a8f3296] [data-rg-lang=zh] .rgft_d835af5c.rgft_54816d41{font-family:NotoSansTC,Helvetica,Arial,Microsoft Yahei,\5fae\8f6f\96c5\9ed1,STXihei,\534e\6587\7ec6\9ed1,sans-serif}[data-eb-6a8f3296] .rgft_d835af5c.rgft_852a8b78{font-size:calc(3rem * var(--font-size-multiplier, 1.6));line-height:1.167;font-weight:500;font-family:Amazon Ember Display,Amazon Ember,Helvetica Neue,Helvetica,Arial,sans-serif}@media (min-width: 481px) and (max-width: 768px){[data-eb-6a8f3296] .rgft_d835af5c.rgft_852a8b78{font-size:calc(2.5rem * var(--font-size-multiplier, 1.6));line-height:1.2;font-weight:500}}@media (max-width: 480px){[data-eb-6a8f3296] .rgft_d835af5c.rgft_852a8b78{font-size:calc(2rem * var(--font-size-multiplier, 1.6));line-height:1.25;font-weight:500}}[data-eb-6a8f3296] [data-rg-lang=ar] .rgft_d835af5c.rgft_852a8b78{font-family:AmazonEmberArabic,Helvetica,Arial,sans-serif}[data-eb-6a8f3296] [data-rg-lang=ja] .rgft_d835af5c.rgft_852a8b78{font-family:ShinGo,\30d2\30e9\30ae\30ce\89d2\30b4 Pro W3,Hiragino Kaku Gothic Pro,Osaka,\30e1\30a4\30ea\30aa,Meiryo,\ff2d\ff33 \ff30\30b4\30b7\30c3\30af,MS PGothic,sans-serif}[data-eb-6a8f3296] [data-rg-lang=ko] .rgft_d835af5c.rgft_852a8b78{font-family:NotoSansKR,Malgun Gothic,sans-serif}[data-eb-6a8f3296] [data-rg-lang=th] .rgft_d835af5c.rgft_852a8b78{font-family:NotoSansThai,Helvetica,Arial,sans-serif}[data-eb-6a8f3296] [data-rg-lang=zh] .rgft_d835af5c.rgft_852a8b78{font-family:NotoSansTC,Helvetica,Arial,Microsoft Yahei,\5fae\8f6f\96c5\9ed1,STXihei,\534e\6587\7ec6\9ed1,sans-serif}[data-eb-6a8f3296] .rgft_286fbc8d{letter-spacing:1.6px;text-transform:uppercase;color:var(--rg-color-text-eyebrow, #161D26)}[data-eb-6a8f3296] .rgft_286fbc8d.rgft_cf5cdf86{font-size:calc(1rem * var(--font-size-multiplier, 1.6));line-height:1.5;font-weight:400;font-family:Amazon Ember Mono,Consolas,Andale Mono WT,Andale Mono,Lucida Console,Lucida Sans Typewriter,DejaVu Sans Mono,Bitstream Vera Sans Mono,Liberation Mono,Nimbus Mono L,Monaco,Courier New,Courier,monospace}@media (min-width: 481px) and (max-width: 768px){[data-eb-6a8f3296] .rgft_286fbc8d.rgft_cf5cdf86{font-size:calc(.875rem * var(--font-size-multiplier, 1.6));line-height:1.714;font-weight:400}}@media (max-width: 480px){[data-eb-6a8f3296] .rgft_286fbc8d.rgft_cf5cdf86{font-size:calc(.75rem * var(--font-size-multiplier, 1.6));line-height:2;font-weight:400}}[data-eb-6a8f3296] [data-rg-lang=ar] .rgft_286fbc8d.rgft_cf5cdf86{font-family:AmazonEmberArabic,Helvetica,Arial,sans-serif}[data-eb-6a8f3296] [data-rg-lang=ja] .rgft_286fbc8d.rgft_cf5cdf86{font-family:ShinGo,\30d2\30e9\30ae\30ce\89d2\30b4 Pro W3,Hiragino Kaku Gothic Pro,Osaka,\30e1\30a4\30ea\30aa,Meiryo,\ff2d\ff33 \ff30\30b4\30b7\30c3\30af,MS PGothic,sans-serif}[dat | 2026-01-13T09:30:35 |
https://aws.amazon.com/blogs/networking-and-content-delivery/four-steps-for-debugging-your-content-delivery-on-aws/ | Four Steps for Debugging your Content Delivery on AWS | Networking & Content Delivery Skip to Main Content Filter: All English Contact us AWS Marketplace Support My account Search Filter: All Sign in to console Create account AWS Blogs Home Blogs Editions Networking & Content Delivery Four Steps for Debugging your Content Delivery on AWS by Achraf Souk on 20 JUN 2019 in Amazon Athena , Amazon CloudFront , Amazon CloudWatch , Amazon Simple Notification Service (SNS) , Lambda@Edge , Networking & Content Delivery Permalink Share Introduction Werner Vogels, chief technology officer for AWS, has been quoted as saying: “Everything fails all the time.” Well, his quote applies as well to content delivery with Amazon CloudFront and Lambda@Edge. In content delivery, issues might occur in different places, for example: On your origin, when it returns HTTP 5xx errors On CloudFront, when it cannot connect to your origin On Lambda@Edge, when your code throws an unhandled exception The best way to help prevent failures is to plan carefully and design a resilient architecture that works with your specific requirements. However, when content delivery fails despite your efforts, you need to identify the issue quickly and take action to resolve it. In this blog, I provide four steps that guide you in debugging AWS content delivery issues. The goal is to make sure that your application continues to be delivered to your users with minimal disruption. First, enable logging on CloudFront, and then set up alarming using Amazon SNS and Amazon CloudWatch. When an alarm goes off, use the CloudFront Monitoring Dashboard to review data about errors and where they’re occurring, and then leverage AWS services to identify and troubleshoot the issue. Step 1: Enable CloudFront logging To get started, configure CloudFront to create log files that contain detailed information about every user request that CloudFront receives. Sign in to the AWS Management Console and open the CloudFront console, then edit the general configuration of your CloudFront distribution to enable logging. When you enable logging, CloudFront starts delivering access logs in W3C extended log file format to the configured Amazon S3 bucket (with a delay of a few minutes). Tip : To optimize the cost of storing your log files, you can leverage S3 Object Lifecycle management to delete or move your logs to a cheaper storage tier after a certain period. Next, set up Amazon Athena to query CloudFront access logs. Athena is an interactive query service that makes it easy to analyze data in Amazon S3 by using standard SQL queries. Athena is serverless, so there’s no infrastructure to manage, and you pay only for the queries that you run. You can set up Athena in few minutes by following these steps . Tip: To reduce the cost and time it takes to query CloudFront logs, you can partition the log files by following the guidance in this blog post . Step 2: Set up alarming Log files give you data to work with when there’s an issue, but you also need mechanisms to notify your operation team whenever there’s a potential problem. To deliver alarm notifications, we’ll use Amazon SNS , a fully-managed pub/sub messaging service. Since CloudFront publishes CloudWatch metrics to us-east-1 AWS Region, you need to set up the SNS topic my_application_delivery in that Region, and then subscribe your operation team to the SNS topic. To keep it simple, I subscribed the operation team email to receive notifications. You can also choose to send notifications to other destinations, such as to a custom monitoring dashboard, or to commercial solutions like PagerDuty using SNS webhooks integration . Then, you need to configure alarming using Amazon CloudWatch . Amazon CloudWatch is a monitoring and management service that provides you with data and actionable insights to monitor your applications, understand and respond to system-wide performance changes. CloudFront is integrated with CloudWatch, and automatically publishes six operational metrics per distribution (Requests, Bytes Downloaded, Bytes Uploaded, 4xx Error Rate, 5xx Error Rate) at a 1-minute granularity for no additional cost. CloudFront also publishes additional three operational metrics per distribution ( Lambda Execution Errors , Invalid Function Response Errors , and Lambda Throttles ), if you have a lambda function associated with your distribution. You can set alarms based on these metrics in the CloudFront console, or in the CloudWatch console (with standard CloudWatch rates ). For example, to set an alarm based on 5xxErrorRate metric in the CloudWatch console, do the following. This metric represents the percentage of all requests for which the HTTP status code is 5xx. In the AWS Console, open the CloudWatch console in the us-east-1 Region. On the Alarms tab, choose Create Alarm > Select metric > CloudFront > Per-Distribution Metrics > 5xxErrorRate for my CloudFront distribution id, and then, for Period, enter 1 minute. Note that you must send some requests to your distribution before the metric appears in the list. Set an alarm to be triggered whenever 5xxErrorRate is more than 0.1% for 1 minute, or adjust the values to be appropriate for your own application and requirements. Under Actions, for Send notification to: , select the SNS topic you created earlier. Choose Create Alarm . At first the State for the alarm will be INSUFFICIENT_DATA, but it will quickly change to OK . Step 3: Troubleshoot delivery on CloudFront When an alarm goes off or another issue occurs, you need to understand whether the problem is caused by CloudFront or a Lambda@Edge function so you can troubleshoot using the right tools. To help determine what is behind the error, go to the recently enhanced Monitoring dashboard on the CloudFront console where you can select and view both distribution metrics and any associated function metrics, right in the console. For example, say you’ve gotten a notification based on the alarm that you set for 5xxErrorRate. Follow these steps to track down what’s going on. In the CloudFront console, choose Monitor . Search for and choose your CloudFront distribution, and then choose View distribution metrics . First look at the Error rate dashboard. If you see that there are 5xx errors caused by Lambda@Edge, then you can skip to the next section, Step 4: Debug Lambda@Edge functions . Otherwise, the errors are caused by CloudFront, and you can do some analysis to see what’s causing them. Use the following Athena queries with your CloudFront log files to analyze the errors. The first query that follows figures out the number of requests that are causing 5xx errors, broken down by error code. When you view the results of the query, let’s say that 500 stands out as dominant error code being returned. Next, use the second query to filter on the error code to determine the top URIs that are returning 500 errors. SELECT status, count(status) AS count FROM cloudfront_logs WHERE status >= 500 GROUP BY status ORDER BY count DESC SELECT uri, count(uri) AS count FROM cloudfront_logs WHERE status = 500 GROUP BY uri ORDER BY count DESC Based on the error code, you can identify the problem and take actions to solve it. For example, one of the following might be the problem: CloudFront returns a 504 Gateway Timeout Error error when an origin is not reachable or is not responding. You can check the timestamps of these errors and compare them with your origin logs. If you need more help, open a ticket with AWS Support and provide the associated request ids ( x-edge-request-id ) from your distribution’s log files. Your origin returns 500, 501, or 503 internal errors which are cached on CloudFront. Filter your log files using Athena to find the URLs that are causing the server failure, and then debug your application code. You have misconfigured TLS on your origin which is causing an 502 Bad Gateway error . Verify the TLS certificate and configuration on your origin. For detailed information about different HTTP errors and how to help prevent them, see the CloudFront documentation . Step 4: Debug Lambda@Edge functions If you see a spike in HTTP 5XX errors by Lambda@Edge in the Error rate graph, the next step is to understand what caused it. For example, the spike in errors might be caused by an exception in your code, your function might have returned an invalid response to CloudFront, or your function might have been throttled. To learn more about the types of Lambda@Edge errors, see Testing and Debugging Lambda@Edge Functions . To help you understand what’s causing the error spike in a specific scenario, you can deep-dive into the graphs on the console. Start by choosing the Lambda@Edge Errors tab in the Monitoring dashboard. You’ll see something like the following: Based on the error type, you can navigate through the following decision diagram to debug your Lambda@Edge function. The rest of this blog post provides detailed guidance for debugging each type of error. I – Execution Errors Execution errors are the most common error scenario. These happen when CloudFront doesn’t get a response from Lambda@Edge because there are unhandled exceptions in your function or there’s an error in your code. To fix this, you need to debug your code by analyzing your Lambda@Edge logs in CloudWatch. If your function doesn’t execute correctly , Lambda@Edge attempts to convert the error object to a String with the following format. The string is sent to a CloudWatch log file in the AWS Region that is closest to the end user’s location. { "errorMessage": "something is wrong", "errorType": "Error", "stackTrace": [ "exports.handler (/var/task/index.js:10:17)" ] } To see the error in the log file, in the Monitoring Dashboard, select the Region and the Lambda@Edge function you’re investigating, and then choose View logs . You’ll be redirected to the CloudWatch console to see the details about the log group associated with your function. To analyze logs more quickly in CloudWatch, you can use CloudWatch Logs Insights. Insights enables you to interactively search and analyze your log data. You can run queries to help you quickly understand operational issues so that you can solve them faster. For example, the following query in Insights lets you filter error messages and see just the messages that are relevant to a specific error. You can also use Insights to query the log files that are generated by your code using Console.log(). As an example, consider a Lambda@Edge function that is used for A/B testing of a Single Page Application. In my code, I can log which page version was selected in each Lambda@Edge execution by doing the following: console.log('INFO { spaVersion:', spaVersion, "}"); Now I can use the following query in Insights to filter on INFO messages, then extract a selected page version and count each occurrence: fields @timestamp, ddbRegion | filter @message like /INFO/ | sort @timestamp desc | stats count() by ddbRegion II – CloudFront Validation Errors Sometimes a Lambda function returns an invalid response to CloudFront. For example, a validation 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. Note that when you test your function in the Lambda console, your function isn’t validated by CloudFront, which means that your function can run correctly in the console, but still fail when you add it to a distribution and deploy it in CloudFront. CloudFront sends validation logs to CloudWatch Logs in an AWS Region near the user. In the Monitoring Dashboard, select the Region where you want to see the logs, then choose View logs. You’re redirected to the CloudWatch console to view the log group associated with your function. In the logs, you can see the cause of CloudFront validation error, as shown in the following image: III – Throttling On occasion, the Lambda@Edge service throttles your function invocations on per Region basis, if you reach the regional concurrency limit . Your concurrency is the number of simultaneous Lambda@Edge executions in a specific Region. To better understand where and why you reached a concurrency limit, on the Monitoring Dashboard, choose the Lambda@Edge function, and then choose View function metrics . Now check the Invocations and Duration dashboards, which display how often the function was invoked, by Region, and how long the function executed, by Region: There are three scenarios in which your function might get throttled: When a function is invoked more often, because there’s high demand. If this happens, you can ask AWS support for a limit increase on the Concurrent executions in the Regions where your function is being throttled. You can also consider rearchitecting your application to invoke Lambda@Edge less often, for example, by using a more specific CloudFront behavior to configure Lambda@Edge triggers. When your code takes longer to execute. To address this, consider whether your function depends on an external component that is not responding. If so, you can set timeouts in your code and fail over gracefully to defaults. When your application receives a sudden traffic peak in a short period of time (seconds). In this case, Lambda@Edge needs to spin up new execution runtimes for your function, which adds a latency overhead to the execution duration. This latency overhead consumes your available execution concurrency level more quickly. One way you can reduce this overhead is by compacting your function deployment package size. To learn more about optimizing concurrency, consider reading my previous blog post on Lambda@Edge design best practices . Conclusion In this blog, I showed you how to configure alarms for delivery issues, and how to quickly troubleshoot issues using AWS tools and services like the Monitoring dashboard in the CloudFront console, Athena and CloudWatch Logs Insights. Make sure that you adapt these suggestions for your own environment, and then include what you learned in your operational runbooks. Additionally you can enrich your runbooks by doing the following: Consuming additional CloudWatch metrics such as Lambda’s concurrency level per Region Producing custom alerts based on CloudFront logs by using Kinesis Analytics Automating some of the troubleshooting. For example, you can trigger a Lambda function when there’s an alarm, run predefined Athena queries, and then send a pre-diagnostic report to your operations team. Blog: Using AWS Client VPN to securely access AWS and on-premises resources Learn about AWS VPN services Watch re:Invent 2019: Connectivity to AWS and hybrid AWS network architectures TAGS: Amazon CloudFront , Lambda@Edge , monitoring Resources Networking Products Getting Started Amazon CloudFront Follow Twitter Facebook LinkedIn Twitch Email Updates @charset "UTF-8";[data-eb-6a8f3296] .rgft_9e423fbb.rgft_1b2a14d4{position:relative;transition:box-shadow .3s ease}[data-eb-6a8f3296] .rgft_9e423fbb.rgft_1b2a14d4:not(:disabled,.rgft_3ef5a62a).rgft_3d631df0,[data-eb-6a8f3296] .rgft_9e423fbb.rgft_1b2a14d4:not(:disabled,.rgft_3ef5a62a).rgft_b27cc003,[data-eb-6a8f3296] .rgft_9e423fbb.rgft_1b2a14d4:not(:disabled,.rgft_3ef5a62a).rgft_5962fadc:hover{box-shadow:var(--rg-shadow-gray-elevation-1, 1px 1px 20px rgba(0, 0, 0, .1))}[data-eb-6a8f3296] .rgft_9e423fbb.rgft_1b2a14d4:not(:disabled,.rgft_3ef5a62a).rgft_3d631df0.rgft_e79955da,[data-eb-6a8f3296] .rgft_9e423fbb.rgft_1b2a14d4:not(:disabled,.rgft_3ef5a62a).rgft_b27cc003.rgft_e79955da,[data-eb-6a8f3296] .rgft_9e423fbb.rgft_1b2a14d4:not(:disabled,.rgft_3ef5a62a).rgft_5962fadc:hover.rgft_e79955da{box-shadow:var(--rg-shadow-gray-elevation-2, 1px 1px 24px rgba(0, 0, 0, .25))}[data-eb-6a8f3296] .rgft_9e423fbb.rgft_1b2a14d4:not(:disabled,.rgft_3ef5a62a).rgft_b27cc003:hover{box-shadow:none}[data-eb-6a8f3296] .rgft_9e423fbb.rgft_1ed8cbde{position:relative;transform-style:preserve-3d;overflow:unset!important}[data-eb-6a8f3296] .rgft_9e423fbb.rgft_1ed8cbde:before{content:"";position:absolute;inset:0;border-radius:inherit;transform:translateZ(-1px);pointer-events:none;transition-property:filter,inset;transition-duration:.3s;transition-timing-function:ease;background-clip:content-box!important;padding:1px}[data-eb-6a8f3296] .rgft_9e423fbb.rgft_1ed8cbde:not(:disabled,.rgft_3ef5a62a).rgft_3d631df0:before{filter:blur(15px)}[data-eb-6a8f3296] .rgft_9e423fbb.rgft_1ed8cbde:not(:disabled,.rgft_3ef5a62a).rgft_3d631df0.rgft_4df65418:hover:before{filter:blur(20px)}[data-eb-6a8f3296] .rgft_9e423fbb.rgft_1ed8cbde:not(:disabled,.rgft_3ef5a62a).rgft_5962fadc:hover:before{filter:blur(15px)}[data-eb-6a8f3296] .rgft_9e423fbb.rgft_1ed8cbde:not(:disabled,.rgft_3ef5a62a).rgft_b27cc003:before{filter:blur(15px)}[data-eb-6a8f3296] .rgft_9e423fbb.rgft_1ed8cbde:not(:disabled,.rgft_3ef5a62a).rgft_b27cc003:hover:before{filter:none}[data-eb-6a8f3296] .rgft_9e423fbb.rgft_1ed8cbde:not(:disabled,.rgft_3ef5a62a).rgft_e90ac70d:active:before{filter:blur(8px)!important}[data-eb-6a8f3296] .rgft_9e423fbb.rgft_1ed8cbde:not(:disabled,.rgft_3ef5a62a).rgft_a4f580d2:before{filter:blur(8px)!important}[data-eb-6a8f3296] [data-rg-mode=light][data-rg-theme=fuchsia] .rgft_9e423fbb.rgft_1ed8cbde:not(:disabled,.rgft_3ef5a62a).rgft_38d8ffac:before,[data-eb-6a8f3296] [data-rg-mode=light][data-rg-theme=fuchsia].rgft_9e423fbb.rgft_1ed8cbde.rgft_38d8ffac:not(:disabled,.rgft_3ef5a62a):before{background:var(--rg-shadow-gradient-fuchsia, linear-gradient(123deg, #fa6f00 0%, #e433ff 50%, #8575ff 100%))}[data-eb-6a8f3296] [data-rg-mode=dark][data-rg-theme=fuchsia] .rgft_9e423fbb.rgft_1ed8cbde:not(:disabled,.rgft_3ef5a62a).rgft_38d8ffac:before,[data-eb-6a8f3296] [data-rg-mode=dark][data-rg-theme=fuchsia].rgft_9e423fbb.rgft_1ed8cbde.rgft_38d8ffac:not(:disabled,.rgft_3ef5a62a):before{background:var(--rg-shadow-gradient-fuchsia, linear-gradient(123deg, #d14600 0%, #c300e0 50%, #6842ff 100%))}[data-eb-6a8f3296] [data-rg-mode=light][data-rg-theme=indigo] .rgft_9e423fbb.rgft_1ed8cbde:not(:disabled,.rgft_3ef5a62a).rgft_38d8ffac:before,[data-eb-6a8f3296] [data-rg-mode=light][data-rg-theme=indigo].rgft_9e423fbb.rgft_1ed8cbde.rgft_38d8ffac:not(:disabled,.rgft_3ef5a62a):before{background:var(--rg-shadow-gradient-indigo, linear-gradient(123deg, #0099ff 0%, #5c7fff 50%, #8575ff 100%))}[data-eb-6a8f3296] [data-rg-mode=dark][data-rg-theme=indigo] .rgft_9e423fbb.rgft_1ed8cbde:not(:disabled,.rgft_3ef5a62a).rgft_38d8ffac:before,[data-eb-6a8f3296] [data-rg-mode=dark][data-rg-theme=indigo].rgft_9e423fbb.rgft_1ed8cbde.rgft_38d8ffac:not(:disabled,.rgft_3ef5a62a):before{background:var(--rg-shadow-gradient-indigo, linear-gradient(123deg, #006ce0 0%, #295eff 50%, #6842ff 100%))}[data-eb-6a8f3296] [data-rg-mode=light][data-rg-theme=orange] .rgft_9e423fbb.rgft_1ed8cbde:not(:disabled,.rgft_3ef5a62a).rgft_38d8ffac:before,[data-eb-6a8f3296] [data-rg-mode=light][data-rg-theme=orange].rgft_9e423fbb.rgft_1ed8cbde.rgft_38d8ffac:not(:disabled,.rgft_3ef5a62a):before{background:var(--rg-shadow-gradient-orange, linear-gradient(123deg, #ff1ae0 0%, #ff386a 50%, #fa6f00 100%))}[data-eb-6a8f3296] [data-rg-mode=dark][data-rg-theme=orange] .rgft_9e423fbb.rgft_1ed8cbde:not(:disabled,.rgft_3ef5a62a).rgft_38d8ffac:before,[data-eb-6a8f3296] [data-rg-mode=dark][data-rg-theme=orange].rgft_9e423fbb.rgft_1ed8cbde.rgft_38d8ffac:not(:disabled,.rgft_3ef5a62a):before{background:var(--rg-shadow-gradient-orange, linear-gradient(123deg, #d600ba 0%, #eb003b 50%, #d14600 100%))}[data-eb-6a8f3296] [data-rg-mode=light][data-rg-theme=teal] .rgft_9e423fbb.rgft_1ed8cbde:not(:disabled,.rgft_3ef5a62a).rgft_38d8ffac:before,[data-eb-6a8f3296] [data-rg-mode=light][data-rg-theme=teal].rgft_9e423fbb.rgft_1ed8cbde.rgft_38d8ffac:not(:disabled,.rgft_3ef5a62a):before{background:var(--rg-shadow-gradient-teal, linear-gradient(123deg, #00bd6b 0%, #00a4bd 50%, #0099ff 100%))}[data-eb-6a8f3296] [data-rg-mode=dark][data-rg-theme=teal] .rgft_9e423fbb.rgft_1ed8cbde:not(:disabled,.rgft_3ef5a62a).rgft_38d8ffac:before,[data-eb-6a8f3296] [data-rg-mode=dark][data-rg-theme=teal].rgft_9e423fbb.rgft_1ed8cbde.rgft_38d8ffac:not(:disabled,.rgft_3ef5a62a):before{background:var(--rg-shadow-gradient-teal, linear-gradient(123deg, #008559 0%, #007e94 50%, #006ce0 100%))}[data-eb-6a8f3296] [data-rg-mode=light][data-rg-theme=blue] .rgft_9e423fbb.rgft_1ed8cbde:not(:disabled,.rgft_3ef5a62a).rgft_38d8ffac:before,[data-eb-6a8f3296] [data-rg-mode=light][data-rg-theme=blue].rgft_9e423fbb.rgft_1ed8cbde.rgft_38d8ffac:not(:disabled,.rgft_3ef5a62a):before{background:var(--rg-shadow-gradient-blue, linear-gradient(123deg, #00bd6b 0%, #0099ff 50%, #8575ff 100%))}[data-eb-6a8f3296] [data-rg-mode=dark][data-rg-theme=blue] .rgft_9e423fbb.rgft_1ed8cbde:not(:disabled,.rgft_3ef5a62a).rgft_38d8ffac:before,[data-eb-6a8f3296] [data-rg-mode=dark][data-rg-theme=blue].rgft_9e423fbb.rgft_1ed8cbde.rgft_38d8ffac:not(:disabled,.rgft_3ef5a62a):before{background:var(--rg-shadow-gradient-blue, linear-gradient(123deg, #008559 0%, #006ce0 50%, #6842ff 100%))}[data-eb-6a8f3296] [data-rg-mode=light][data-rg-theme=violet] .rgft_9e423fbb.rgft_1ed8cbde:not(:disabled,.rgft_3ef5a62a).rgft_38d8ffac:before,[data-eb-6a8f3296] [data-rg-mode=light][data-rg-theme=violet].rgft_9e423fbb.rgft_1ed8cbde.rgft_38d8ffac:not(:disabled,.rgft_3ef5a62a):before{background:var(--rg-shadow-gradient-violet, linear-gradient(123deg, #ad5cff 0%, #0099ff 50%, #00a4bd 100%))}[data-eb-6a8f3296] [data-rg-mode=dark][data-rg-theme=violet] .rgft_9e423fbb.rgft_1ed8cbde:not(:disabled,.rgft_3ef5a62a).rgft_38d8ffac:before,[data-eb-6a8f3296] [data-rg-mode=dark][data-rg-theme=violet].rgft_9e423fbb.rgft_1ed8cbde.rgft_38d8ffac:not(:disabled,.rgft_3ef5a62a):before{background:var(--rg-shadow-gradient-violet, linear-gradient(123deg, #962eff 0%, #006ce0 50%, #007e94 100%))}[data-eb-6a8f3296] [data-rg-mode=light][data-rg-theme=purple] .rgft_9e423fbb.rgft_1ed8cbde:not(:disabled,.rgft_3ef5a62a).rgft_38d8ffac:before,[data-eb-6a8f3296] [data-rg-mode=light][data-rg-theme=purple].rgft_9e423fbb.rgft_1ed8cbde.rgft_38d8ffac:not(:disabled,.rgft_3ef5a62a):before{background:var(--rg-shadow-gradient-purple, linear-gradient(123deg, #ff1ae0 0%, #8575ff 50%, #00a4bd 100%))}[data-eb-6a8f3296] [data-rg-mode=dark][data-rg-theme=purple] .rgft_9e423fbb.rgft_1ed8cbde:not(:disabled,.rgft_3ef5a62a).rgft_38d8ffac:before,[data-eb-6a8f3296] [data-rg-mode=dark][data-rg-theme=purple].rgft_9e423fbb.rgft_1ed8cbde.rgft_38d8ffac:not(:disabled,.rgft_3ef5a62a):before{background:var(--rg-shadow-gradient-purple, linear-gradient(123deg, #d600ba 0%, #6842ff 50%, #007e94 100%))}[data-eb-6a8f3296] .rgft_9e423fbb.rgft_1ed8cbde:not(:disabled,.rgft_3ef5a62a):before{background:linear-gradient(123deg,#d14600,#c300e0,#6842ff)}[data-eb-6a8f3296] [data-rg-theme=fuchsia] .rgft_9e423fbb.rgft_1ed8cbde:not(:disabled,.rgft_3ef5a62a):before,[data-eb-6a8f3296] [data-rg-theme=fuchsia].rgft_9e423fbb.rgft_1ed8cbde:not(:disabled,.rgft_3ef5a62a):before{background:var(--rg-shadow-gradient-fuchsia, linear-gradient(123deg, #d14600 0%, #c300e0 50%, #6842ff 100%))}[data-eb-6a8f3296] [data-rg-theme=indigo] .rgft_9e423fbb.rgft_1ed8cbde:not(:disabled,.rgft_3ef5a62a):before,[data-eb-6a8f3296] [data-rg-theme=indigo].rgft_9e423fbb.rgft_1ed8cbde:not(:disabled,.rgft_3ef5a62a):before{background:var(--rg-shadow-gradient-indigo, linear-gradient(123deg, #006ce0 0%, #295eff 50%, #6842ff 100%))}[data-eb-6a8f3296] [data-rg-theme=orange] .rgft_9e423fbb.rgft_1ed8cbde:not(:disabled,.rgft_3ef5a62a):before,[data-eb-6a8f3296] [data-rg-theme=orange].rgft_9e423fbb.rgft_1ed8cbde:not(:disabled,.rgft_3ef5a62a):before{background:var(--rg-shadow-gradient-orange, linear-gradient(123deg, #d600ba 0%, #eb003b 50%, #d14600 100%))}[data-eb-6a8f3296] [data-rg-theme=teal] .rgft_9e423fbb.rgft_1ed8cbde:not(:disabled,.rgft_3ef5a62a):before,[data-eb-6a8f3296] [data-rg-theme=teal].rgft_9e423fbb.rgft_1ed8cbde:not(:disabled,.rgft_3ef5a62a):before{background:var(--rg-shadow-gradient-teal, linear-gradient(123deg, #008559 0%, #007e94 50%, #006ce0 100%))}[data-eb-6a8f3296] [data-rg-theme=blue] .rgft_9e423fbb.rgft_1ed8cbde:not(:disabled,.rgft_3ef5a62a):before,[data-eb-6a8f3296] [data-rg-theme=blue].rgft_9e423fbb.rgft_1ed8cbde:not(:disabled,.rgft_3ef5a62a):before{background:var(--rg-shadow-gradient-blue, linear-gradient(123deg, #008559 0%, #006ce0 50%, #6842ff 100%))}[data-eb-6a8f3296] [data-rg-theme=violet] .rgft_9e423fbb.rgft_1ed8cbde:not(:disabled,.rgft_3ef5a62a):before,[data-eb-6a8f3296] [data-rg-theme=violet].rgft_9e423fbb.rgft_1ed8cbde:not(:disabled,.rgft_3ef5a62a):before{background:var(--rg-shadow-gradient-violet, linear-gradient(123deg, #962eff 0%, #006ce0 50%, #007e94 100%))}[data-eb-6a8f3296] [data-rg-theme=purple] .rgft_9e423fbb.rgft_1ed8cbde:not(:disabled,.rgft_3ef5a62a):before,[data-eb-6a8f3296] [data-rg-theme=purple].rgft_9e423fbb.rgft_1ed8cbde:not(:disabled,.rgft_3ef5a62a):before{background:var(--rg-shadow-gradient-purple, linear-gradient(123deg, #d600ba 0%, #6842ff 50%, #007e94 100%))}[data-eb-6a8f3296] a.rgft_f7822e54,[data-eb-6a8f3296] button.rgft_f7822e54{--button-size: 44px;--button-pad-h: 24px;--button-pad-borderless-h: 26px;border:2px solid var(--rg-color-background-page-inverted, #0F141A);padding:8px var(--button-pad-h, 24px);border-radius:40px!important;align-items:center;justify-content:center;display:inline-flex;height:var(--button-size, 44px);text-decoration:none!important;text-wrap:nowrap;cursor:pointer;position:relative;transition:all .3s ease}[data-eb-6a8f3296] a.rgft_f7822e54.rgft_094d67e1,[data-eb-6a8f3296] button.rgft_f7822e54.rgft_094d67e1{--button-size: 32px;--button-pad-h: 14px;--button-pad-borderless-h: 16px}[data-eb-6a8f3296] a.rgft_f7822e54>span,[data-eb-6a8f3296] button.rgft_f7822e54>span{color:var(--btn-text-color, inherit)!important}[data-eb-6a8f3296] a.rgft_f7822e54:focus-visible,[data-eb-6a8f3296] button.rgft_f7822e54:focus-visible{outline:2px solid var(--rg-color-focus-ring, #006CE0)!important;outline-offset:4px!important;transition:outline 0s}[data-eb-6a8f3296] a.rgft_f7822e54:focus:not(:focus-visible),[data-eb-6a8f3296] button.rgft_f7822e54:focus:not(:focus-visible){outline:none!important}[data-eb-6a8f3296] a.rgft_f7822e54.rgft_303c672b,[data-eb-6a8f3296] button.rgft_f7822e54.rgft_303c672b{--btn-text-color: var(--rg-color-text-utility-inverted, #FFFFFF);background-color:var(--rg-color-btn-primary-bg, #161D26);border:none;padding:10px var(--button-pad-borderless-h, 24px)}[data-eb-6a8f3296] a.rgft_f7822e54.rgft_18409398,[data-eb-6a8f3296] button.rgft_f7822e54.rgft_18409398{--btn-text-color: var(--rg-color-text-utility, #161D26);background-color:var(--rg-color-btn-secondary-bg, #FFFFFF);border-color:var(--rg-color-background-page-inverted, #0F141A)}[data-eb-6a8f3296] a.rgft_f7822e54.rgft_090951dc,[data-eb-6a8f3296] button.rgft_f7822e54.rgft_090951dc{--btn-text-color: var(--rg-color-text-utility, #161D26);background-color:var(--rg-color-background-object, #F3F3F7);border:none;padding:10px var(--button-pad-borderless-h, 24px)}[data-eb-6a8f3296] a.rgft_f7822e54.rgft_15529d9f,[data-eb-6a8f3296] button.rgft_f7822e54.rgft_15529d9f{--btn-text-color: var(--rg-color-text-utility, #161D26);background-color:var(--rg-color-btn-secondary-bg, #FFFFFF);border:none;padding:10px var(--button-pad-borderless-h, 24px)}[data-eb-6a8f3296] a.rgft_f7822e54.rgft_bb950a4e,[data-eb-6a8f3296] button.rgft_f7822e54.rgft_bb950a4e{--btn-text-color: var(--rg-color-text-utility, #161D26);border:none;padding:10px var(--button-pad-borderless-h, 24px)}[data-eb-6a8f3296] a.rgft_f7822e54.rgft_bb950a4e,[data-eb-6a8f3296] button.rgft_f7822e54.rgft_bb950a4e{background-image:linear-gradient(97deg,#ffc0ad,#f8c7ff 37.79%,#d2ccff 75.81%,#c2d1ff)}[data-eb-6a8f3296] a.rgft_f7822e54.rgft_bb950a4e,[data-eb-6a8f3296] button.rgft_f7822e54.rgft_bb950a4e{--rg-gradient-angle:97deg;background-image:var(--rg-gradient-a, linear-gradient(120deg, #f8c7ff 20.08%, #d2ccff 75.81%))}[data-eb-6a8f3296] [data-rg-mode=dark] a.rgft_f7822e54.rgft_bb950a4e,[data-eb-6a8f3296] [data-rg-mode=dark] button.rgft_f7822e54.rgft_bb950a4e,[data-eb-6a8f3296] a[data-rg-mode=dark].rgft_f7822e54.rgft_bb950a4e,[data-eb-6a8f3296] button[data-rg-mode=dark].rgft_f7822e54.rgft_bb950a4e{background-image:var(--rg-gradient-a, linear-gradient(120deg, #78008a 24.25%, #b2008f 69.56%))}[data-eb-6a8f3296] a.rgft_f7822e54.rgft_bb419678,[data-eb-6a8f3296] button.rgft_f7822e54.rgft_bb419678{--btn-text-color: var(--rg-color-text-utility-inverted, #FFFFFF);background-color:var(--rg-color-btn-visited-bg, #656871);border-color:var(--rg-color-btn-visited-bg, #656871)}[data-eb-6a8f3296] a.rgft_f7822e54.rgft_bb419678.rgft_18409398,[data-eb-6a8f3296] a.rgft_f7822e54.rgft_bb419678.rgft_15529d9f,[data-eb-6a8f3296] button.rgft_f7822e54.rgft_bb419678.rgft_18409398,[data-eb-6a8f3296] button.rgft_f7822e54.rgft_bb419678.rgft_15529d9f{--btn-text-color: var(--rg-color-text-utility, #161D26);background-color:var(--rg-color-btn-secondary-visited-bg, #FFFFFF)}[data-eb-6a8f3296] a.rgft_f7822e54.rgft_badebaf5,[data-eb-6a8f3296] button.rgft_f7822e54.rgft_badebaf5{--btn-text-color: var(--rg-color-btn-disabled-text, #B4B4BB);background-color:var(--rg-color-btn-disabled-bg, #F3F3F7);border-color:var(--rg-color-btn-disabled-bg, #F3F3F7);cursor:default}[data-eb-6a8f3296] a.rgft_f7822e54.rgft_badebaf5.rgft_18409398,[data-eb-6a8f3296] a.rgft_f7822e54.rgft_badebaf5.rgft_15529d9f,[data-eb-6a8f3296] button.rgft_f7822e54.rgft_badebaf5.rgft_18409398,[data-eb-6a8f3296] button.rgft_f7822e54.rgft_badebaf5.rgft_15529d9f{border:none;padding:10px var(--button-pad-borderless-h, 24px)}[data-eb-6a8f3296] a.rgft_f7822e54.rgft_badebaf5.rgft_090951dc,[data-eb-6a8f3296] button.rgft_f7822e54.rgft_badebaf5.rgft_090951dc{--btn-text-color: var(--rg-color-btn-tertiary-disabled-text, #B4B4BB);background-color:#0000}[data-eb-6a8f3296] a.rgft_f7822e54:hover:not(.rgft_badebaf5).rgft_18409398:not(.rgft_bb950a4e),[data-eb-6a8f3296] a.rgft_f7822e54:hover:not(.rgft_badebaf5).rgft_15529d9f:not(.rgft_bb950a4e),[data-eb-6a8f3296] button.rgft_f7822e54:hover:not(.rgft_badebaf5).rgft_18409398:not(.rgft_bb950a4e),[data-eb-6a8f3296] button.rgft_f7822e54:hover:not(.rgft_badebaf5).rgft_15529d9f:not(.rgft_bb950a4e){--btn-text-color: var(--rg-color-text-utility, #161D26);background-color:var(--rg-color-btn-secondary-bg, #FFFFFF)}[data-eb-6a8f3296] a.rgft_f7822e54:hover:not(.rgft_badebaf5).rgft_090951dc,[data-eb-6a8f3296] button.rgft_f7822e54:hover:not(.rgft_badebaf5).rgft_090951dc{box-shadow:none}[data-eb-6a8f3296] a.rgft_f7822e54:hover:not(.rgft_badebaf5).rgft_090951dc,[data-eb-6a8f3296] button.rgft_f7822e54:hover:not(.rgft_badebaf5).rgft_090951dc{background-image:linear-gradient(97deg,#ffc0ad80,#f8c7ff80 37.79%,#d2ccff80 75.81%,#c2d1ff80)}[data-eb-6a8f3296] a.rgft_f7822e54:hover:not(.rgft_badebaf5).rgft_090951dc,[data-eb-6a8f3296] button.rgft_f7822e54:hover:not(.rgft_badebaf5).rgft_090951dc{--rg-gradient-angle:97deg;background-image:var(--rg-gradient-a-50, linear-gradient(120deg, #f8c7ff 20.08%, #d2ccff 75.81%))}[data-eb-6a8f3296] [data-rg-mode=dark] a.rgft_f7822e54:hover:not(.rgft_badebaf5).rgft_090951dc,[data-eb-6a8f3296] [data-rg-mode=dark] button.rgft_f7822e54:hover:not(.rgft_badebaf5).rgft_090951dc,[data-eb-6a8f3296] a[data-rg-mode=dark].rgft_f7822e54.rgft_090951dc:hover:not(.rgft_badebaf5),[data-eb-6a8f3296] button[data-rg-mode=dark].rgft_f7822e54.rgft_090951dc:hover:not(.rgft_badebaf5){background-image:var(--rg-gradient-a-50, linear-gradient(120deg, #78008a 24.25%, #b2008f 69.56%))}[data-eb-6a8f3296] a.rgft_f7822e54:active:not(.rgft_badebaf5).rgft_090951dc,[data-eb-6a8f3296] button.rgft_f7822e54:active:not(.rgft_badebaf5).rgft_090951dc{box-shadow:none}[data-eb-6a8f3296] a.rgft_f7822e54:active:not(.rgft_badebaf5).rgft_090951dc,[data-eb-6a8f3296] button.rgft_f7822e54:active:not(.rgft_badebaf5).rgft_090951dc{background-image:linear-gradient(97deg,#ffc0ad,#f8c7ff 37.79%,#d2ccff 75.81%,#c2d1ff)}[data-eb-6a8f3296] a.rgft_f7822e54:active:not(.rgft_badebaf5).rgft_090951dc,[data-eb-6a8f3296] button.rgft_f7822e54:active:not(.rgft_badebaf5).rgft_090951dc{--rg-gradient-angle:97deg;background-image:var(--rg-gradient-a-pressed, linear-gradient(120deg, rgba(248, 199, 255, .5) 20.08%, #d2ccff 75.81%))}[data-eb-6a8f3296] [data-rg-mode=dark] a.rgft_f7822e54:active:not(.rgft_badebaf5).rgft_090951dc,[data-eb-6a8f3296] [data-rg-mode=dark] button.rgft_f7822e54:active:not(.rgft_badebaf5).rgft_090951dc,[data-eb-6a8f3296] a[data-rg-mode=dark].rgft_f7822e54.rgft_090951dc:active:not(.rgft_badebaf5),[data-eb-6a8f3296] button[data-rg-mode=dark].rgft_f7822e54.rgft_090951dc:active:not(.rgft_badebaf5){background-image:var(--rg-gradient-a-pressed, linear-gradient(120deg, rgba(120, 0, 138, .5) 24.25%, #b2008f 69.56%))}[data-eb-6a8f3296] .rgft_8711ccd9{-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;background:#0000;border:none;margin:0}[data-eb-6a8f3296] .rgft_8711ccd9.rgft_5e58a6df{text-align:center}[data-eb-6a8f3296] .rgft_8711ccd9.rgft_b7ada98b{display:block}[data-eb-6a8f3296] .rgft_8711ccd9.rgft_beb26dc7{font-family:Amazon Ember Mono,Consolas,Andale Mono WT,Andale Mono,Lucida Console,Lucida Sans Typewriter,DejaVu Sans Mono,Bitstream Vera Sans Mono,Liberation Mono,Nimbus Mono L,Monaco,Courier New,Courier,monospace}[data-eb-6a8f3296] .rgft_8711ccd9 a{display:inline;position:relative;cursor:pointer;text-decoration:none!important;color:var(--rg-color-link-default, #006CE0);background:linear-gradient(to right,currentcolor,currentcolor);background-size:100% .1em;background-position:0 100%;background-repeat:no-repeat}[data-eb-6a8f3296] .rgft_8711ccd9 a:focus-visible{color:var(--rg-color-link-focus, #006CE0)}[data-eb-6a8f3296] .rgft_8711ccd9 a:hover{color:var(--rg-color-link-hover, #003B8F);animation:rgft_d72bdead .3s cubic-bezier(0,0,.2,1)}[data-eb-6a8f3296] .rgft_8711ccd9 a:visited{color:var(--rg-color-link-visited, #6842FF)}@keyframes rgft_d72bdead{0%{background-size:0 .1em}to{background-size:100% .1em}}[data-eb-6a8f3296] .rgft_8711ccd9 b,[data-eb-6a8f3296] b.rgft_8711ccd9,[data-eb-6a8f3296] .rgft_8711ccd9 strong,[data-eb-6a8f3296] strong.rgft_8711ccd9{font-weight:700}[data-eb-6a8f3296] i.rgft_8711ccd9,[data-eb-6a8f3296] .rgft_8711ccd9 i,[data-eb-6a8f3296] em.rgft_8711ccd9,[data-eb-6a8f3296] .rgft_8711ccd9 em{font-style:italic}[data-eb-6a8f3296] u.rgft_8711ccd9,[data-eb-6a8f3296] .rgft_8711ccd9 u{text-decoration:underline}[data-eb-6a8f3296] code.rgft_8711ccd9,[data-eb-6a8f3296] .rgft_8711ccd9 code{font-family:Amazon Ember Mono,Consolas,Andale Mono WT,Andale Mono,Lucida Console,Lucida Sans Typewriter,DejaVu Sans Mono,Bitstream Vera Sans Mono,Liberation Mono,Nimbus Mono L,Monaco,Courier New,Courier,monospace;border-radius:4px;border:1px solid var(--rg-color-border-lowcontrast, #CCCCD1);color:var(--rg-color-text-secondary, #232B37);padding-top:var(--rg-padding-8);padding-right:var(--rg-padding-8);padding-bottom:var(--rg-padding-8);padding-left:var(--rg-padding-8)}[data-eb-6a8f3296] .rgft_12e1c6fa{display:inline!important;vertical-align:middle}[data-eb-6a8f3296] .rgft_8711ccd9 p img{aspect-ratio:16/9;height:100%;object-fit:cover;width:100%;border-radius:8px;order:1;margin-bottom:var(--rg-margin-4)}[data-eb-6a8f3296] .rgft_8711ccd9 table{table-layout:fixed;border-spacing:0;width:100%}[data-eb-6a8f3296] .rgft_8711ccd9 table td{font-size:14px;border-right:1px solid var(--rg-color-border-lowcontrast, #CCCCD1);border-bottom:1px solid var(--rg-color-border-lowcontrast, #CCCCD1);padding-top:var(--rg-padding-6);padding-right:var(--rg-padding-6);padding-bottom:var(--rg-padding-6);padding-left:var(--rg-padding-6)}[data-eb-6a8f3296] .rgft_8711ccd9 table td:first-of-type{border-left:1px solid var(--rg-color-border-lowcontrast, #CCCCD1)}[data-eb-6a8f3296] .rgft_8711ccd9 table thead tr:first-of-type>*:first-of-type,[data-eb-6a8f3296] .rgft_8711ccd9 table:not(:has(thead)) tr:first-of-type>*:first-of-type{border-top-left-radius:16px}[data-eb-6a8f3296] .rgft_8711ccd9 table thead tr:first-of-type>*:last-of-type,[data-eb-6a8f3296] .rgft_8711ccd9 table:not(:has(thead)) tr:first-of-type>*:last-of-type{border-top-right-radius:16px}[data-eb-6a8f3296] .rgft_8711ccd9 table tr:last-of-type td:first-of-type{border-bottom-left-radius:16px}[data-eb-6a8f3296] .rgft_8711ccd9 table tr:last-of-type td:last-of-type{border-bottom-right-radius:16px}[data-eb-6a8f3296] .rgft_8711ccd9 table:not(:has(thead),:has(th)) tr:first-of-type td{border-top:1px solid var(--rg-color-border-lowcontrast, #CCCCD1);border-right:1px solid var(--rg-color-border-lowcontrast, #CCCCD1);border-bottom:1px solid var(--rg-color-border-lowcontrast, #CCCCD1)}[data-eb-6a8f3296] .rgft_8711ccd9 table th{color:var(--rg-color-text-primary-inverted, #FFFFFF);min-width:280px;max-width:400px;padding:0;text-align:left;vertical-align:top;background-color:var(--rg-color-background-object-inverted, #232B37);border-left:1px solid var(--rg-color-border-lowcontrast, #CCCCD1);border-right:1px solid var(--rg-color-border-lowcontrast, #CCCCD1);border-bottom:1px solid var(--rg-color-border-lowcontrast, #CCCCD1);padding-top:var(--rg-padding-6);padding-right:var(--rg-padding-6);padding-bottom:var(--rg-padding-6);padding-left:var(--rg-padding-6);row-gap:var(--rg-margin-5);column-gap:var(--rg-margin-5);max-width:100%;min-width:150px}@media (min-width: 480px) and (max-width: 767px){[data-eb-6a8f3296] .rgft_8711ccd9 table th{max-width:100%;min-width:150px}}@media (min-width: 768px) and (max-width: 1023px){[data-eb-6a8f3296] .rgft_8711ccd9 table th{max-width:240px;min-width:180px}}@media (min-width: 1024px) and (max-width: 1279px){[data-eb-6a8f3296] .rgft_8711ccd9 table th{max-width:350px;min-width:240px}}@media (min-width: 1280px) and (max-width: 1599px){[data-eb-6a8f3296] .rgft_8711ccd9 table th{max-width:400px;min-width:280px}}@media (min-width: 1600px){[data-eb-6a8f3296] .rgft_8711ccd9 table th{max-width:400px;min-width:280px}}[data-eb-6a8f3296] .rgft_8711ccd9 table th:first-of-type{border-top-left-radius:16px;border-top:0 solid var(--rg-color-border-lowcontrast, #CCCCD1);border-left:0 solid var(--rg-color-border-lowcontrast, #CCCCD1);border-right:0 solid var(--rg-color-border-lowcontrast, #CCCCD1)}[data-eb-6a8f3296] .rgft_8711ccd9 table th:nth-of-type(n+3){border-left:0 solid var(--rg-color-border-lowcontrast, #CCCCD1)}[data-eb-6a8f3296] .rgft_8711ccd9 table th:last-of-type{border-top-right-radius:16px;border-top:0 solid var(--rg-color-border-lowcontrast, #CCCCD1);border-right:0 solid var(--rg-color-border-lowcontrast, #CCCCD1)}[data-eb-6a8f3296] .rgft_a1b66739{display:inline-flex;flex-direction:column;align-items:center;justify-content:center;color:var(--rg-color-text-primary, #161D26);--icon-color: currentcolor}[data-eb-6a8f3296] .rgft_a1b66739.rgft_bc1a8743{height:16px;width:16px}[data-eb-6a8f3296] .rgft_a1b66739.rgft_c0cbb35d{height:20px;width:20px}[data-eb-6a8f3296] .rgft_a1b66739.rgft_bd40fe12{height:32px;width:32px}[data-eb-6a8f3296] .rgft_a1b66739.rgft_27320e58{height:48px;width:48px}[data-eb-6a8f3296] .rgft_a1b66739 svg{fill:none;stroke:none}[data-eb-6a8f3296] .rgft_a1b66739 path[data-fill]:not([fill]){fill:var(--icon-color)}[data-eb-6a8f3296] .rgft_a1b66739 path[data-stroke]{stroke-width:2}[data-eb-6a8f3296] .rgft_a1b66739 path[data-stroke]:not([stroke]){stroke:var(--icon-color)}[data-eb-6a8f3296] .rgft_3ed66ff4{display:inline-flex;flex-direction:column;align-items:center;justify-content:center;color:var(--rg-color-text-primary, #161D26)}[data-eb-6a8f3296] .rgft_3ed66ff4.rgft_9124b200{height:10px;width:10px}[data-eb-6a8f3296] .rgft_3ed66ff4.rgft_bc1a8743{height:16px;width:16px}[data-eb-6a8f3296] .rgft_3ed66ff4.rgft_c0cbb35d{height:20px;width:20px}[data-eb-6a8f3296] .rgft_3ed66ff4.rgft_bd40fe12{height:32px;width:32px}[data-eb-6a8f3296] .rgft_3ed66ff4.rgft_27320e58{height:48px;width:48px}[data-eb-6a8f3296] .rgft_98b54368{color:var(--rg-color-text-body, #232B37)}[data-eb-6a8f3296] .rgft_98b54368.rgft_275611e5{font-size:calc(1rem * var(--font-size-multiplier, 1.6));line-height:1.5;font-weight:400;font-family:Amazon Ember Display,Amazon Ember,Helvetica Neue,Helvetica,Arial,sans-serif}@media (min-width: 481px) and (max-width: 768px){[data-eb-6a8f3296] .rgft_98b54368.rgft_275611e5{font-size:calc(1rem * var(--font-size-multiplier, 1.6));line-height:1.5;font-weight:400}}@media (max-width: 480px){[data-eb-6a8f3296] .rgft_98b54368.rgft_275611e5{font-size:calc(1rem * var(--font-size-multiplier, 1.6));line-height:1.5;font-weight:400}}[data-eb-6a8f3296] [data-rg-lang=ar] .rgft_98b54368.rgft_275611e5{font-family:AmazonEmberArabic,Helvetica,Arial,sans-serif}[data-eb-6a8f3296] [data-rg-lang=ja] .rgft_98b54368.rgft_275611e5{font-family:ShinGo,\30d2\30e9\30ae\30ce\89d2\30b4 Pro W3,Hiragino Kaku Gothic Pro,Osaka,\30e1\30a4\30ea\30aa,Meiryo,\ff2d\ff33 \ff30\30b4\30b7\30c3\30af,MS PGothic,sans-serif}[data-eb-6a8f3296] [data-rg-lang=ko] .rgft_98b54368.rgft_275611e5{font-family:NotoSansKR,Malgun Gothic,sans-serif}[data-eb-6a8f3296] [data-rg-lang=th] .rgft_98b54368.rgft_275611e5{font-family:NotoSansThai,Helvetica,Arial,sans-serif}[data-eb-6a8f3296] [data-rg-lang=zh] .rgft_98b54368.rgft_275611e5{font-family:NotoSansTC,Helvetica,Arial,Microsoft Yahei,\5fae\8f6f\96c5\9ed1,STXihei,\534e\6587\7ec6\9ed1,sans-serif}[data-eb-6a8f3296] .rgft_98b54368.rgft_007aef8b{font-size:calc(.875rem * var(--font-size-multiplier, 1.6));line-height:1.429;font-weight:400;font-family:Amazon Ember Display,Amazon Ember,Helvetica Neue,Helvetica,Arial,sans-serif}@media (min-width: 481px) and (max-width: 768px){[data-eb-6a8f3296] .rgft_98b54368.rgft_007aef8b{font-size:calc(.875rem * var(--font-size-multiplier, 1.6));line-height:1.429;font-weight:400}}@media (max-width: 480px){[data-eb-6a8f3296] .rgft_98b54368.rgft_007aef8b{font-size:calc(.875rem * var(--font-size-multiplier, 1.6));line-height:1.429;font-weight:400}}[data-eb-6a8f3296] [data-rg-lang=ar] .rgft_98b54368.rgft_007aef8b{font-family:AmazonEmberArabic,Helvetica,Arial,sans-serif}[data-eb-6a8f3296] [data-rg-lang=ja] .rgft_98b54368.rgft_007aef8b{font-family:ShinGo,\30d2\30e9\30ae\30ce\89d2\30b4 Pro W3,Hiragino Kaku Gothic Pro,Osaka,\30e1\30a4\30ea\30aa,Meiryo,\ff2d\ff33 \ff30\30b4\30b7\30c3\30af,MS PGothic,sans-serif}[data-eb-6a8f3296] [data-rg-lang=ko] .rgft_98b54368.rgft_007aef8b{font-family:NotoSansKR,Malgun Gothic,sans-serif}[data-eb-6a8f3296] [data-rg-lang=th] .rgft_98b54368.rgft_007aef8b{font-family:NotoSansThai,Helvetica,Arial,sans-serif}[data-eb-6a8f3296] [data-rg-lang=zh] .rgft_98b54368.rgft_007aef8b{font-family:NotoSansTC,Helvetica,Arial,Microsoft Yahei,\5fae\8f6f\96c5\9ed1,STXihei,\534e\6587\7ec6\9ed1,sans-serif}[data-eb-6a8f3296] .rgft_98b54368.rgft_ff19c5f9{font-size:calc(.75rem * var(--font-size-multiplier, 1.6));line-height:1.333;font-weight:400;font-family:Amazon Ember Display,Amazon Ember,Helvetica Neue,Helvetica,Arial,sans-serif}@media (min-width: 481px) and (max-width: 768px){[data-eb-6a8f3296] .rgft_98b54368.rgft_ff19c5f9{font-size:calc(.75rem * var(--font-size-multiplier, 1.6));line-height:1.333;font-weight:400}}@media (max-width: 480px){[data-eb-6a8f3296] .rgft_98b54368.rgft_ff19c5f9{font-size:calc(.75rem * var(--font-size-multiplier, 1.6));line-height:1.333;font-weight:400}}[data-eb-6a8f3296] [data-rg-lang=ar] .rgft_98b54368.rgft_ff19c5f9{font-family:AmazonEmberArabic,Helvetica,Arial,sans-serif}[data-eb-6a8f3296] [data-rg-lang=ja] .rgft_98b54368.rgft_ff19c5f9{font-family:ShinGo,\30d2\30e9\30ae\30ce\89d2\30b4 Pro W3,Hiragino Kaku Gothic Pro,Osaka,\30e1\30a4\30ea\30aa,Meiryo,\ff2d\ff33 \ff30\30b4\30b7\30c3\30af,MS PGothic,sans-serif}[data-eb-6a8f3296] [data-rg-lang=ko] .rgft_98b54368.rgft_ff19c5f9{font-family:NotoSansKR,Malgun Gothic,sans-serif}[data-eb-6a8f3296] [data-rg-lang=th] .rgft_98b54368.rgft_ff19c5f9{font-family:NotoSansThai,Helvetica,Arial,sans-serif}[data-eb-6a8f3296] [data-rg-lang=zh] .rgft_98b54368.rgft_ff19c5f9{font-family:NotoSansTC,Helvetica,Arial,Microsoft Yahei,\5fae\8f6f\96c5\9ed1,STXihei,\534e\6587\7ec6\9ed1,sans-serif}[data-eb-6a8f3296] .rgft_98b54368 ul{list-style-type:disc;margin-top:2rem}[data-eb-6a8f3296] .rgft_98b54368.rgft_2a7f98ee{display:inline;position:relative;cursor:pointer;text-decoration:none!important;color:var(--rg-color-link-default, #006CE0);background:linear-gradient(to right,currentcolor,currentcolor);background-size:100% .1em;background-position:0 100%;background-repeat:no-repeat}[data-eb-6a8f3296] .rgft_98b54368.rgft_2a7f98ee:focus-visible{color:var(--rg-color-link-focus, #006CE0)}[data-eb-6a8f3296] .rgft_98b54368.rgft_2a7f98ee:hover{color:var(--rg-color-link-hover, #003B8F);animation:rgft_9beb7cc5 .3s cubic-bezier(0,0,.2,1)}[data-eb-6a8f3296] .rgft_98b54368.rgft_2a7f98ee:visited{color:var(--rg-color-link-visited, #6842FF)}@keyframes rgft_9beb7cc5{0%{background-size:0 .1em}to{background-size:100% .1em}}[data-eb-6a8f3296] .rgft_d835af5c{color:var(--rg-color-text-title, #161D26)}[data-eb-6a8f3296] .rgft_d835af5c.rgft_3e9243e1{font-size:calc(4.5rem * var(--font-size-multiplier, 1.6));line-height:1.111;font-weight:500;font-family:Amazon Ember Display,Amazon Ember,Helvetica Neue,Helvetica,Arial,sans-serif}@media (min-width: 481px) and (max-width: 768px){[data-eb-6a8f3296] .rgft_d835af5c.rgft_3e9243e1{font-size:calc(3.75rem * var(--font-size-multiplier, 1.6));line-height:1.133;font-weight:500}}@media (max-width: 480px){[data-eb-6a8f3296] .rgft_d835af5c.rgft_3e9243e1{font-size:calc(3rem * var(--font-size-multiplier, 1.6));line-height:1.167;font-weight:500}}[data-eb-6a8f3296] [data-rg-lang=ar] .rgft_d835af5c.rgft_3e9243e1{font-family:AmazonEmberArabic,Helvetica,Arial,sans-serif}[data-eb-6a8f3296] [data-rg-lang=ja] .rgft_d835af5c.rgft_3e9243e1{font-family:ShinGo,\30d2\30e9\30ae\30ce\89d2\30b4 Pro W3,Hiragino Kaku Gothic Pro,Osaka,\30e1\30a4\30ea\30aa,Meiryo,\ff2d\ff33 \ff30\30b4\30b7\30c3\30af,MS PGothic,sans-serif}[data-eb-6a8f3296] [data-rg-lang=ko] .rgft_d835af5c.rgft_3e9243e1{font-family:NotoSansKR,Malgun Gothic,sans-serif}[data-eb-6a8f3296] [data-rg-lang=th] .rgft_d835af5c.rgft_3e9243e1{font-family:NotoSansThai,Helvetica,Arial,sans-serif}[data-eb-6a8f3296] [data-rg-lang=zh] .rgft_d835af5c.rgft_3e9243e1{font-family:NotoSansTC,Helvetica,Arial,Microsoft Yahei,\5fae\8f6f\96c5\9ed1,STXihei,\534e\6587\7ec6\9ed1,sans-serif}[data-eb-6a8f3296] .rgft_d835af5c.rgft_54816d41{font-size:calc(3.75rem * var(--font-size-multiplier, 1.6));line-height:1.133;font-weight:500;font-family:Amazon Ember Display,Amazon Ember,Helvetica Neue,Helvetica,Arial,sans-serif}@media (min-width: 481px) and (max-width: 768px){[data-eb-6a8f3296] .rgft_d835af5c.rgft_54816d41{font-size:calc(3rem * var(--font-size-multiplier, 1.6));line-height:1.167;font-weight:500}}@media (max-width: 480px){[data-eb-6a8f3296] .rgft_d835af5c.rgft_54816d41{font-size:calc(2.5rem * var(--font-size-multiplier, 1.6));line-height:1.2;font-weight:500}}[data-eb-6a8f3296] [data-rg-lang=ar] .rgft_d835af5c.rgft_54816d41{font-family:AmazonEmberArabic,Helvetica,Arial,sans-serif}[data-eb-6a8f3296] [data-rg-lang=ja] .rgft_d835af5c.rgft_54816d41{font-family:ShinGo,\30d2\30e9\30ae\30ce\89d2\30b4 Pro W3,Hiragino Kaku Gothic Pro,Osaka,\30e1\30a4\30ea\30aa,Meiryo,\ff2d\ff33 \ff30\30b4\30b7\30c3\30af,MS PGothic,sans-serif}[data-eb-6a8f3296] [data-rg-lang=ko] .rgft_d835af5c.rgft_54816d41{font-family:NotoSansKR,Malgun Gothic,sans-serif}[data-eb-6a8f3296] [data-rg-lang=th] .rgft_d835af5c.rgft_54816d41{font-family:NotoSansThai,Helvetica,Arial,sans-serif}[data-eb-6a8f3296] [data-rg-lang=zh] .rgft_d835af5c.rgft_54816d41{font-family:NotoSansTC,Helvetica,Arial,Microsoft Yahei,\5fae\8f6f\96c5\9ed1,STXihei,\534e\6587\7ec6\9ed1,sans-serif}[data-eb-6a8f3296] .rgft_d835af5c.rgft_852a8b78{font-size:calc(3rem * var(--font-size-multiplier, 1.6));line-height:1.167;font-weight:500;font-family:Amazon Ember Display,Amazon Ember,Helvetica Neue,Helvetica,Arial,sans-serif}@media (min-width: 481px) and (max-width: 768px){[data-eb-6a8f3296] .rgft_d835af5c.rgft_852a8b78{font-size:calc(2.5rem * var(--font-size-multiplier, 1.6));line-height:1.2;font-weight:500}}@media (max-width: 480px){[data-eb-6a8f3296] .rgft_d835af5c.rgft_852a8b78{font-size:calc(2rem * var(--font-size-multiplier, 1.6));line-height:1.25;font-weight:500}}[data-eb-6a8f3296] [data-rg-lang=ar] .rgft_d835af5c.rgft_852a8b78{font-family:AmazonEmberArabic,Helvetica,Arial,sans-serif}[data-eb-6a8f3296] [data-rg-lang=ja] .rgft_d835af5c.rgft_852a8b78{font-family:ShinGo,\30d2\30e9\30ae\30ce\89d2\30b4 Pro W3,Hiragino Kaku Gothic Pro,Osaka,\30e1\30a4\30ea\30aa,Meiryo,\ff2d\ff33 \ff30\30b4\30b7\30c3\30af,MS PGothic,sans-serif}[data-eb-6a8f3296] [data-rg-lang=ko] .rgft_d835af5c.rgft_852a8b78{font-family:NotoSansKR,Malgun Gothic,sans-serif}[data-eb-6a8f3296] [data-rg-lang=th] .rgft_d835af5c.rgft_852a8b78{font-family:NotoSansThai,Helvetica,Arial,sans-serif}[data-eb-6a8f3296] [data-rg-lang=zh] .rgft_d835af5c.rgft_852a8b78{font-family:NotoSansTC,Helvetica,Arial,Microsoft Yahei,\5fae\8f6f\96c5\9ed1,STXihei,\534e\6587\7ec6\9ed1,sans-serif}[data-eb-6a8f3296] .rgft_286fbc8d{letter-spacing:1.6px;text-transform:uppercase;color:var(--rg-color-text-eyebrow, #161D26)}[data-eb-6a8f3296] .rgft_286fbc8d.rgft_cf5cdf86{font-size:calc(1rem * var(--font-size-multiplier, 1.6));line-height:1.5;font-weight:400;font-family:Amazon Ember Mono,Consolas,Andale Mono WT,Andale Mono,Lucida Console,Lucida Sans Typewriter,DejaVu Sans Mono,Bitstream Vera Sans Mono,Liberation Mono,Nimbus Mono L,Monaco,Courier New,Courier,monospace}@media (min-width: 481px) and (max-width: 768px){[data-eb-6a8f3296] .rgft_286fbc8d.rgft_cf5cdf86{font-size:calc(.875rem * var(--font-size-multiplier, 1.6));line-height:1.714;font-weight:400}}@media (max-width: 480px){[data-eb-6a8f3296] .rgft_286fbc8d.rgft_cf5cdf86{font-size:calc(.75rem * var(--font-size-multiplier, 1.6));line-height:2;font-weight:400}}[data-eb-6a8f3296] [data-rg-lang=ar] .rgft_286fbc8d.rgft_cf5cdf86{font-family:AmazonEmberArabic,Helvetica,Arial,sans-serif}[data-eb-6a8f3296] [ | 2026-01-13T09:30:35 |
https://github.com/aws-samples/serverless-snippets/tree/main/integration-s3-to-lambda | serverless-snippets/integration-s3-to-lambda at main · aws-samples/serverless-snippets · GitHub Skip to content Navigation Menu Toggle navigation Sign in Appearance settings Platform AI CODE CREATION GitHub Copilot Write better code with AI GitHub Spark Build and deploy intelligent apps GitHub Models Manage and compare prompts MCP Registry New Integrate external tools DEVELOPER WORKFLOWS Actions Automate any workflow Codespaces Instant dev environments Issues Plan and track work Code Review Manage code changes APPLICATION SECURITY GitHub Advanced Security Find and fix vulnerabilities Code security Secure your code as you build Secret protection Stop leaks before they start EXPLORE Why GitHub Documentation Blog Changelog Marketplace View all features Solutions BY COMPANY SIZE Enterprises Small and medium teams Startups Nonprofits BY USE CASE App Modernization DevSecOps DevOps CI/CD View all use cases BY INDUSTRY Healthcare Financial services Manufacturing Government View all industries View all solutions Resources EXPLORE BY TOPIC AI Software Development DevOps Security View all topics EXPLORE BY TYPE Customer stories Events & webinars Ebooks & reports Business insights GitHub Skills SUPPORT & SERVICES Documentation Customer support Community forum Trust center Partners Open Source COMMUNITY GitHub Sponsors Fund open source developers PROGRAMS Security Lab Maintainer Community Accelerator Archive Program REPOSITORIES Topics Trending Collections Enterprise ENTERPRISE SOLUTIONS Enterprise platform AI-powered developer platform AVAILABLE ADD-ONS GitHub Advanced Security Enterprise-grade security features Copilot for Business Enterprise-grade AI features Premium Support Enterprise-grade 24/7 support Pricing Search or jump to... Search code, repositories, users, issues, pull requests... --> Search Clear Search syntax tips Provide feedback --> We read every piece of feedback, and take your input very seriously. Include my email address so I can be contacted Cancel Submit feedback Saved searches Use saved searches to filter your results more quickly --> Name Query To see all available qualifiers, see our documentation . Cancel Create saved search Sign in Sign up Appearance settings Resetting focus You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session. Dismiss alert {{ message }} aws-samples / serverless-snippets Public generated from amazon-archives/__template_MIT-0 Notifications You must be signed in to change notification settings Fork 101 Star 162 Code Issues 13 Pull requests 9 Projects 0 Security Uh oh! There was an error while loading. Please reload this page . Insights Additional navigation options Code Issues Pull requests Projects Security Insights Footer © 2026 GitHub, Inc. Footer navigation Terms Privacy Security Status Community Docs Contact Manage cookies Do not share my personal information You can’t perform that action at this time. | 2026-01-13T09:30:35 |
https://support.microsoft.com/nb-no/windows/behandle-informasjonskapsler-i-microsoft-edge-vise-tillate-blokkere-slette-og-bruke-168dab11-0753-043d-7c16-ede5947fc64d | Behandle informasjonskapsler i Microsoft Edge: Vise, tillate, blokkere, slette og bruke - Støtte for Microsoft Relaterte emner × Windows Sikkerhet, trygghet og personvern Oversikt Oversikt over sikkerhet, trygghet og personvern Windows Sikkerhet Få hjelp med Windows Sikkerhet Hold deg beskyttet med Windows Sikkerhet Før du gjenvinner, selger eller gir Windows-PC-en eller Xbox-en i gave Fjerne skadelig programvare fra Windows-PC-en Windows Sikkerhet Få hjelp med Windows Sikkerhet Vise og slette nettleserloggen i Microsoft Edge Slette og administrere informasjonskapsler Fjern verdifullt innhold på en trygg måte når du installerer Windows på nytt Finne og låse en mistet Windows-enhet Personvern for Windows Få hjelp med personvern for Windows Personverninnstillinger for Windows som apper bruker Se opplysningene dine på instrumentbordet for personvern Gå til hovedinnhold Microsoft Støtte Støtte Støtte Hjem Microsoft 365 Office Produkter Microsoft 365 Outlook Microsoft Teams OneDrive Microsoft Copilot OneNote Windows mer... Enheter Surface PC-tilbehør Xbox PC-spill HoloLens Surface Hub Maskinvaregaranti Konto & fakturering Konto Microsoft Store og fakturering Ressurser Nyheter Fellesskapsforum Microsoft 365-administratorer Portal for små bedrifter Utvikler Utdanning Rapporter en kundestøttesvindel Produktsikkerhet Mer Kjøp Microsoft 365 Alt fra Microsoft Global Microsoft 365 Teams Copilot Windows Surface Xbox Spesialtilbud Liten bedrift Kundestøtte Programvare Programvare Windows-apper AI OneDrive Outlook Overgang fra Skype til Teams OneNote Microsoft Teams PCer og enheter PCer og enheter Kjøp Xbox Tilbehør Underholdning Underholdning Xbox Game Pass Ultimate Xbox og spill PC-spill Bedrift Bedrift Microsoft Sikkerhet Azure Dynamics 365 Microsoft 365 for bedrifter Microsoft Industry Microsoft Power Platform Windows 365 Utvikler og IT Utvikler og IT Microsoft Developer Microsoft Learn Støtte for KI-apper på markedsplassen Microsoft Tech-fellesskap Microsoft Marketplace Visual Studio Marketplace Rewards Annen Annen Microsoft Rewards Gratis nedlastinger og sikkerhet Utdanning Gavekort Lisensiering Vis områdekart Søk Søk etter hjelp Ingen resultater Avbryt Logg på Logg på med Microsoft Logg på, eller opprett en konto. Hei, Velg en annen konto. Du har flere kontoer Velg kontoen du vil logge på med. Relaterte emner Windows Sikkerhet, trygghet og personvern Oversikt Oversikt over sikkerhet, trygghet og personvern Windows Sikkerhet Få hjelp med Windows Sikkerhet Hold deg beskyttet med Windows Sikkerhet Før du gjenvinner, selger eller gir Windows-PC-en eller Xbox-en i gave Fjerne skadelig programvare fra Windows-PC-en Windows Sikkerhet Få hjelp med Windows Sikkerhet Vise og slette nettleserloggen i Microsoft Edge Slette og administrere informasjonskapsler Fjern verdifullt innhold på en trygg måte når du installerer Windows på nytt Finne og låse en mistet Windows-enhet Personvern for Windows Få hjelp med personvern for Windows Personverninnstillinger for Windows som apper bruker Se opplysningene dine på instrumentbordet for personvern Behandle informasjonskapsler i Microsoft Edge: Vise, tillate, blokkere, slette og bruke Gjelder for Windows 10 Windows 11 Microsoft Edge Informasjonskapsler er små datadeler som lagres på enheten av nettsteder du besøker. De tjener ulike formål, for eksempel å huske påloggingslegitimasjon, områdeinnstillinger og sporing av brukeratferd. Det kan imidlertid hende du vil slette informasjonskapsler av personvernhensyn eller for å løse problemer med nettlesing. Denne artikkelen inneholder instruksjoner om hvordan du gjør følgende: Vis alle informasjonskapsler Tillat alle informasjonskapsler Tillat informasjonskapsler fra et bestemt nettsted Blokker informasjonskapsler fra tredjeparter Blokker alle informasjonskapsler Blokkere informasjonskapsler fra et bestemt nettsted Slett alle informasjonskapsler Slett informasjonskapsler fra et bestemt nettsted Slette informasjonskapsler hver gang du lukker nettleseren Bruke informasjonskapsler til å forhåndslaste siden for raskere nettlesing Vis alle informasjonskapsler Åpne Edge-nettleseren, velg Innstillinger og mer øverst til høyre i nettleservinduet. Velg Innstillinger > Personvern, søk og tjenester . Velg Informasjonskapsler , og klikk deretter Se alle informasjonskapsler og områdedata for å vise alle lagrede informasjonskapsler og relatert områdeinformasjon. Tillat alle informasjonskapsler Ved å tillate informasjonskapsler kan nettsteder lagre og hente data i nettleseren, noe som kan forbedre nettleseropplevelsen ved å huske innstillingene og påloggingsinformasjonen. Åpne Edge-nettleseren, velg Innstillinger og mer øverst til høyre i nettleservinduet. Velg Innstillinger > personvern, søk og tjenester . Velg Informasjonskapsler, og aktiver veksleknappen Tillat områder å lagre og lese informasjonskapseldata (anbefales) for å tillate alle informasjonskapsler. Tillat informasjonskapsler fra et bestemt nettsted Ved å tillate informasjonskapsler kan nettsteder lagre og hente data i nettleseren, noe som kan forbedre nettleseropplevelsen ved å huske innstillingene og påloggingsinformasjonen. Åpne Edge-nettleseren, velg Innstillinger og mer øverst til høyre i nettleservinduet. Velg Innstillinger > Personvern, søk og tjenester . Velg Informasjonskapsler , og gå til Tillat å lagre informasjonskapsler. Velg Legg til område for å tillate informasjonskapsler per område ved å skrive inn nettadressen for området. Blokker informasjonskapsler fra tredjeparter Hvis du ikke vil at tredjepartsnettsteder skal lagre informasjonskapsler på PC-en, kan du blokkere informasjonskapsler. Men når du gjør dette, kan det imidlertid hende at enkelte sider ikke vises på riktig måte, eller du kan få en melding fra et nettsted om at du må tillate informasjonskapsler for å vise nettstedet. Åpne Edge-nettleseren, velg Innstillinger og mer øverst til høyre i nettleservinduet. Velg Innstillinger > personvern, søk og tjenester . Velg Informasjonskapsler , og aktiver veksleknappen Blokker informasjonskapsler fra tredjeparter. Blokker alle informasjonskapsler Hvis du ikke vil at tredjepartsnettsteder skal lagre informasjonskapsler på PC-en, kan du blokkere informasjonskapsler. Men når du gjør dette, kan det imidlertid hende at enkelte sider ikke vises på riktig måte, eller du kan få en melding fra et nettsted om at du må tillate informasjonskapsler for å vise nettstedet. Åpne Edge-nettleseren, velg Innstillinger og mer øverst til høyre i nettleservinduet. Velg Innstillinger > Personvern, søk og tjenester . Velg Informasjonskapsler , og deaktiver Tillat områder å lagre og lese informasjonskapseldata (anbefales) for å blokkere alle informasjonskapsler. Blokkere informasjonskapsler fra et bestemt nettsted Microsoft Edge lar deg blokkere informasjonskapsler fra et bestemt nettsted, men dette kan hindre at enkelte sider vises riktig, eller du kan få en melding fra et nettsted som forteller deg at du må tillate informasjonskapsler for å vise dette nettstedet. Slik blokkerer du informasjonskapsler fra et bestemt område: Åpne Edge-nettleseren, velg Innstillinger og mer øverst til høyre i nettleservinduet. Velg Innstillinger > Personvern, søk og tjenester . Velg Informasjonskapsler , og gå til Ikke tillatt å lagre og lese informasjonskapseler . Velg Legg til område for å blokkere informasjonskapsler per område ved å skrive inn nettadressen for området. Slett alle informasjonskapsler Åpne Edge-nettleseren, velg Innstillinger og mer øverst til høyre i nettleservinduet. Velg Innstillinger > Personvern, søk og tjenester . Velg Fjern nettleserdata , og velg deretter Velg hva du vil fjerne ved siden av Fjern nettleserdata nå . Velg et tidsintervall fra listen under Tidsintervall . Velg informasjonskapsler og andre nettstedsdata , og velg deretter Slett nå . Obs!: Alternativt kan du slette informasjonskapslene ved å trykke CTRL + SKIFT + DELETE sammen og deretter fortsette med trinn 4 og 5. Alle informasjonskapsler og andre nettstedsdata slettes nå for tidsintervallet du valgte. Dette logger deg av de fleste nettsteder. Slett informasjonskapsler fra et bestemt nettsted Åpne Edge-nettleseren, velg Innstillinger og mer > Innstillinger > Personvern, søk og tjenester . Velg Informasjonskapsler , klikk deretter Vis alle informasjonskapsler og nettstedsdata , og søk etter området du vil slette informasjonskapsler for. Velg pil ned til høyre for nettstedet med informasjonskapsler du vil slette, og velg Slett . Informasjonskapsler for området du valgte, slettes nå. Gjenta dette trinnet for alle nettsteder med informasjonskapsler du vil slette. Slette informasjonskapsler hver gang du lukker nettleseren Åpne Edge-nettleseren, velg Innstillinger og mer > Innstillinger > personvern, søk og tjenester . Velg Fjern nettleserdata , og velg deretter Velg hva du vil fjerne hver gang du lukker nettleseren . Aktiver veksleknappen for Informasjonskapsler og andre nettstedsdata . Når denne funksjonen er aktivert, slettes alle informasjonskapsler og andre nettstedsdata hver gang du lukker Edge-nettleseren. Dette logger deg av de fleste nettsteder. Bruke informasjonskapsler til å forhåndslaste siden for raskere nettlesing Åpne Edge-nettleseren, velg Innstillinger og mer øverst til høyre i nettleservinduet. Velg Innstillinger > Personvern, søk og tjenester . Velg Informasjonskapsler , og aktiver vekslesidene for forhåndslasting for raskere nettlesing og søking. ABONNER PÅ RSS-FEEDER Trenger du mer hjelp? Vil du ha flere alternativer? Oppdag Community Kontakt oss Utforsk abonnementsfordeler, bla gjennom opplæringskurs, finn ut hvordan du sikrer enheten og mer. Abonnementsfordeler for Microsoft 365 Microsoft 365-opplæring Microsoft Sikkerhet Tilgjengelighetssenter Fellesskap hjelper deg med å stille og svare på spørsmål, gi tilbakemelding og høre fra eksperter med stor kunnskap. Spør Microsoft-fellesskapet Teknisk fellesskap for Microsoft Windows Insider-medlemmer Microsoft 365 Insiders Finn løsninger på vanlige problemer, eller få hjelp fra en kundestøtterepresentant. Nettbasert støtte Var denne informasjonen nyttig? Ja Nei Takk! Har du flere tilbakemeldinger til Microsoft? Kan du hjelpe oss med å bli bedre? (Send tilbakemelding til Microsoft, slik at vi kan hjelpe deg.) Hvor fornøyd er du med språkkvaliteten? Hva påvirket opplevelsen din? Løste problemet mitt Tydelige instruksjoner Enkelt å følge Ingen sjargong Bilder hjalp Oversettelseskvalitet Samsvarte ikke med skjermen min Feil instruksjoner For teknisk Ikke nok informasjon Ikke nok bilder Oversettelseskvalitet Har du ytterligere tilbakemeldinger? (Valgfritt) Send tilbakemelding Når du trykker på Send inn, blir tilbakemeldingen brukt til å forbedre Microsoft-produkter og -tjenester. IT-administratoren kan samle inn disse dataene. Personvernerklæring. Takk for tilbakemeldingen! × Nyheter Surface Pro Surface Laptop Surface Laptop Studio 2 Copilot for organisasjoner Copilot til personlig bruk Microsoft 365 Utforsk Microsoft-produkter Windows 11-apper Microsoft Store Kontoprofil Nedlastingssenter Kundestøtte for Microsoft Store Returer Ordresporing Gjenvinning Kommersielle garantier Utdanning Microsoft Education Enheter for utdanning Microsoft Teams for utdanning Microsoft 365 Education Office Education Lærerutdanning og -utvikling Tilbud for elever og foreldre Azure for students Bedrift Microsoft Sikkerhet Azure Dynamics 365 Microsoft 365 Microsoft 365 Copilot Microsoft Teams Liten bedrift Utvikler og IT Microsoft Developer Microsoft Learn Støtte for KI-apper på markedsplassen Microsoft Tech-fellesskap Microsoft Marketplace Microsoft Power Platform Marketplace Rewards Visual Studio Selskap Karriere Om Microsoft Microsoft og personvern Investorer Bærekraft Norsk bokmål (Norge) Ikon for å velge bort personvernvalg Dine personvernvalg Ikon for å velge bort personvernvalg Dine personvernvalg Personvern for forbrukerhelse Kontakt Microsoft Personvern Behandle informasjonskapsler Vilkår for bruk Varemerker Om annonsene © Microsoft 2026 | 2026-01-13T09:30:35 |
https://docs.aws.amazon.com/lambda/latest/dg/with-s3-example.html#with-s3-example-test-dummy-event | Tutorial: Using an Amazon S3 trigger to invoke a Lambda function - AWS Lambda Tutorial: Using an Amazon S3 trigger to invoke a Lambda function - AWS Lambda Documentation AWS Lambda Developer Guide Create an Amazon S3 bucket Upload a test object to your bucket Create a permissions policy Create an execution role Create the Lambda function Deploy the function code Create the Amazon S3 trigger Test the Lambda function Clean up your resources Next steps Tutorial: Using an Amazon S3 trigger to invoke a Lambda function In this tutorial, you use the console to create a Lambda function and configure a trigger for an Amazon Simple Storage Service (Amazon S3) bucket. Every time that you add an object to your Amazon S3 bucket, your function runs and outputs the object type to Amazon CloudWatch Logs. This tutorial demonstrates how to: Create an Amazon S3 bucket. Create a Lambda function that returns the object type of objects in an Amazon S3 bucket. Configure a Lambda trigger that invokes your function when objects are uploaded to your bucket. Test your function, first with a dummy event, and then using the trigger. By completing these steps, you’ll learn how to configure a Lambda function to run whenever objects are added to or deleted from an Amazon S3 bucket. You can complete this tutorial using only the AWS Management Console. Create an Amazon S3 bucket To create an Amazon S3 bucket Open the Amazon S3 console and select the General purpose buckets page. Select the AWS Region closest to your geographical location. You can change your region using the drop-down list at the top of the screen. Later in the tutorial, you must create your Lambda function in the same Region. Choose Create bucket . Under General configuration , do the following: For Bucket type , ensure General purpose is selected. For Bucket name , enter a globally unique name that meets the Amazon S3 Bucket naming rules . Bucket names can contain only lower case letters, numbers, dots (.), and hyphens (-). Leave all other options set to their default values and choose Create bucket . Upload a test object to your bucket To upload a test object Open the Buckets page of the Amazon S3 console and choose the bucket you created during the previous step. Choose Upload . Choose Add files and select the object that you want to upload. You can select any file (for example, HappyFace.jpg ). Choose Open , then choose Upload . Later in the tutorial, you’ll test your Lambda function using this object. Create a permissions policy Create a permissions policy that allows Lambda to get objects from an Amazon S3 bucket and to write to Amazon CloudWatch Logs. To create the policy Open the Policies page of the IAM console. Choose Create Policy . Choose the JSON tab, and then paste the following custom policy into the JSON editor. JSON { "Version":"2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "logs:PutLogEvents", "logs:CreateLogGroup", "logs:CreateLogStream" ], "Resource": "arn:aws:logs:*:*:*" }, { "Effect": "Allow", "Action": [ "s3:GetObject" ], "Resource": "arn:aws:s3:::*/*" } ] } Choose Next: Tags . Choose Next: Review . Under Review policy , for the policy Name , enter s3-trigger-tutorial . Choose Create policy . Create an execution role An execution role is an AWS Identity and Access Management (IAM) role that grants a Lambda function permission to access AWS services and resources. In this step, create an execution role using the permissions policy that you created in the previous step. To create an execution role and attach your custom permissions policy Open the Roles page of the IAM console. Choose Create role . For the type of trusted entity, choose AWS service , then for the use case, choose Lambda . Choose Next . In the policy search box, enter s3-trigger-tutorial . In the search results, select the policy that you created ( s3-trigger-tutorial ), and then choose Next . Under Role details , for the Role name , enter lambda-s3-trigger-role , then choose Create role . Create the Lambda function Create a Lambda function in the console using the Python 3.14 runtime. To create the Lambda function Open the Functions page of the Lambda console. Make sure you're working in the same AWS Region you created your Amazon S3 bucket in. You can change your Region using the drop-down list at the top of the screen. Choose Create function . Choose Author from scratch Under Basic information , do the following: For Function name , enter s3-trigger-tutorial For Runtime , choose Python 3.14 . For Architecture , choose x86_64 . In the Change default execution role tab, do the following: Expand the tab, then choose Use an existing role . Select the lambda-s3-trigger-role you created earlier. Choose Create function . Deploy the function code This tutorial uses the Python 3.14 runtime, but we’ve also provided example code files for other runtimes. You can select the tab in the following box to see the code for the runtime you’re interested in. The Lambda function retrieves the key name of the uploaded object and the name of the bucket from the event parameter it receives from Amazon S3. The function then uses the get_object method from the AWS SDK for Python (Boto3) to retrieve the object's metadata, including the content type (MIME type) of the uploaded object. To deploy the function code Choose the Python tab in the following box and copy the code. .NET SDK for .NET Note There's more on GitHub. Find the complete example and learn how to set up and run in the Serverless examples repository. Consuming an S3 event with Lambda using .NET. // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System.Threading.Tasks; using Amazon.Lambda.Core; using Amazon.S3; using System; using Amazon.Lambda.S3Events; using System.Web; // Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class. [assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] namespace S3Integration { public class Function { private static AmazonS3Client _s3Client; public Function() : this(null) { } internal Function(AmazonS3Client s3Client) { _s3Client = s3Client ?? new AmazonS3Client(); } public async Task<string> Handler(S3Event evt, ILambdaContext context) { try { if (evt.Records.Count <= 0) { context.Logger.LogLine("Empty S3 Event received"); return string.Empty; } var bucket = evt.Records[0].S3.Bucket.Name; var key = HttpUtility.UrlDecode(evt.Records[0].S3.Object.Key); context.Logger.LogLine($"Request is for { bucket} and { key}"); var objectResult = await _s3Client.GetObjectAsync(bucket, key); context.Logger.LogLine($"Returning { objectResult.Key}"); return objectResult.Key; } catch (Exception e) { context.Logger.LogLine($"Error processing request - { e.Message}"); return string.Empty; } } } } Go SDK for Go V2 Note There's more on GitHub. Find the complete example and learn how to set up and run in the Serverless examples repository. Consuming an S3 event with Lambda using Go. // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package main import ( "context" "log" "github.com/aws/aws-lambda-go/events" "github.com/aws/aws-lambda-go/lambda" "github.com/aws/aws-sdk-go-v2/config" "github.com/aws/aws-sdk-go-v2/service/s3" ) func handler(ctx context.Context, s3Event events.S3Event) error { sdkConfig, err := config.LoadDefaultConfig(ctx) if err != nil { log.Printf("failed to load default config: %s", err) return err } s3Client := s3.NewFromConfig(sdkConfig) for _, record := range s3Event.Records { bucket := record.S3.Bucket.Name key := record.S3.Object.URLDecodedKey headOutput, err := s3Client.HeadObject(ctx, &s3.HeadObjectInput { Bucket: &bucket, Key: &key, }) if err != nil { log.Printf("error getting head of object %s/%s: %s", bucket, key, err) return err } log.Printf("successfully retrieved %s/%s of type %s", bucket, key, *headOutput.ContentType) } return nil } func main() { lambda.Start(handler) } Java SDK for Java 2.x Note There's more on GitHub. Find the complete example and learn how to set up and run in the Serverless examples repository. Consuming an S3 event with Lambda using Java. // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package example; import software.amazon.awssdk.services.s3.model.HeadObjectRequest; import software.amazon.awssdk.services.s3.model.HeadObjectResponse; import software.amazon.awssdk.services.s3.S3Client; import com.amazonaws.services.lambda.runtime.Context; import com.amazonaws.services.lambda.runtime.RequestHandler; import com.amazonaws.services.lambda.runtime.events.S3Event; import com.amazonaws.services.lambda.runtime.events.models.s3.S3EventNotification.S3EventNotificationRecord; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class Handler implements RequestHandler<S3Event, String> { private static final Logger logger = LoggerFactory.getLogger(Handler.class); @Override public String handleRequest(S3Event s3event, Context context) { try { S3EventNotificationRecord record = s3event.getRecords().get(0); String srcBucket = record.getS3().getBucket().getName(); String srcKey = record.getS3().getObject().getUrlDecodedKey(); S3Client s3Client = S3Client.builder().build(); HeadObjectResponse headObject = getHeadObject(s3Client, srcBucket, srcKey); logger.info("Successfully retrieved " + srcBucket + "/" + srcKey + " of type " + headObject.contentType()); return "Ok"; } catch (Exception e) { throw new RuntimeException(e); } } private HeadObjectResponse getHeadObject(S3Client s3Client, String bucket, String key) { HeadObjectRequest headObjectRequest = HeadObjectRequest.builder() .bucket(bucket) .key(key) .build(); return s3Client.headObject(headObjectRequest); } } JavaScript SDK for JavaScript (v3) Note There's more on GitHub. Find the complete example and learn how to set up and run in the Serverless examples repository. Consuming an S3 event with Lambda using JavaScript. import { S3Client, HeadObjectCommand } from "@aws-sdk/client-s3"; const client = new S3Client(); export const handler = async (event, context) => { // Get the object from the event and show its content type const bucket = event.Records[0].s3.bucket.name; const key = decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g, ' ')); try { const { ContentType } = await client.send(new HeadObjectCommand( { Bucket: bucket, Key: key, })); console.log('CONTENT TYPE:', ContentType); return ContentType; } catch (err) { console.log(err); const message = `Error getting object $ { key} from bucket $ { bucket}. Make sure they exist and your bucket is in the same region as this function.`; console.log(message); throw new Error(message); } }; Consuming an S3 event with Lambda using TypeScript. // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 import { S3Event } from 'aws-lambda'; import { S3Client, HeadObjectCommand } from '@aws-sdk/client-s3'; const s3 = new S3Client( { region: process.env.AWS_REGION }); export const handler = async (event: S3Event): Promise<string | undefined> => { // Get the object from the event and show its content type const bucket = event.Records[0].s3.bucket.name; const key = decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g, ' ')); const params = { Bucket: bucket, Key: key, }; try { const { ContentType } = await s3.send(new HeadObjectCommand(params)); console.log('CONTENT TYPE:', ContentType); return ContentType; } catch (err) { console.log(err); const message = `Error getting object $ { key} from bucket $ { bucket}. Make sure they exist and your bucket is in the same region as this function.`; console.log(message); throw new Error(message); } }; PHP SDK for PHP Note There's more on GitHub. Find the complete example and learn how to set up and run in the Serverless examples repository. Consuming an S3 event with Lambda using PHP. <?php use Bref\Context\Context; use Bref\Event\S3\S3Event; use Bref\Event\S3\S3Handler; use Bref\Logger\StderrLogger; require __DIR__ . '/vendor/autoload.php'; class Handler extends S3Handler { private StderrLogger $logger; public function __construct(StderrLogger $logger) { $this->logger = $logger; } public function handleS3(S3Event $event, Context $context) : void { $this->logger->info("Processing S3 records"); // Get the object from the event and show its content type $records = $event->getRecords(); foreach ($records as $record) { $bucket = $record->getBucket()->getName(); $key = urldecode($record->getObject()->getKey()); try { $fileSize = urldecode($record->getObject()->getSize()); echo "File Size: " . $fileSize . "\n"; // TODO: Implement your custom processing logic here } catch (Exception $e) { echo $e->getMessage() . "\n"; echo 'Error getting object ' . $key . ' from bucket ' . $bucket . '. Make sure they exist and your bucket is in the same region as this function.' . "\n"; throw $e; } } } } $logger = new StderrLogger(); return new Handler($logger); Python SDK for Python (Boto3) Note There's more on GitHub. Find the complete example and learn how to set up and run in the Serverless examples repository. Consuming an S3 event with Lambda using Python. # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 import json import urllib.parse import boto3 print('Loading function') s3 = boto3.client('s3') def lambda_handler(event, context): #print("Received event: " + json.dumps(event, indent=2)) # Get the object from the event and show its content type bucket = event['Records'][0]['s3']['bucket']['name'] key = urllib.parse.unquote_plus(event['Records'][0]['s3']['object']['key'], encoding='utf-8') try: response = s3.get_object(Bucket=bucket, Key=key) print("CONTENT TYPE: " + response['ContentType']) return response['ContentType'] except Exception as e: print(e) print('Error getting object { } from bucket { }. Make sure they exist and your bucket is in the same region as this function.'.format(key, bucket)) raise e Ruby SDK for Ruby Note There's more on GitHub. Find the complete example and learn how to set up and run in the Serverless examples repository. Consuming an S3 event with Lambda using Ruby. require 'json' require 'uri' require 'aws-sdk' puts 'Loading function' def lambda_handler(event:, context:) s3 = Aws::S3::Client.new(region: 'region') # Your AWS region # puts "Received event: # { JSON.dump(event)}" # Get the object from the event and show its content type bucket = event['Records'][0]['s3']['bucket']['name'] key = URI.decode_www_form_component(event['Records'][0]['s3']['object']['key'], Encoding::UTF_8) begin response = s3.get_object(bucket: bucket, key: key) puts "CONTENT TYPE: # { response.content_type}" return response.content_type rescue StandardError => e puts e.message puts "Error getting object # { key} from bucket # { bucket}. Make sure they exist and your bucket is in the same region as this function." raise e end end Rust SDK for Rust Note There's more on GitHub. Find the complete example and learn how to set up and run in the Serverless examples repository. Consuming an S3 event with Lambda using Rust. // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 use aws_lambda_events::event::s3::S3Event; use aws_sdk_s3:: { Client}; use lambda_runtime:: { run, service_fn, Error, LambdaEvent}; /// Main function #[tokio::main] async fn main() -> Result<(), Error> { tracing_subscriber::fmt() .with_max_level(tracing::Level::INFO) .with_target(false) .without_time() .init(); // Initialize the AWS SDK for Rust let config = aws_config::load_from_env().await; let s3_client = Client::new(&config); let res = run(service_fn(|request: LambdaEvent<S3Event>| { function_handler(&s3_client, request) })).await; res } async fn function_handler( s3_client: &Client, evt: LambdaEvent<S3Event> ) -> Result<(), Error> { tracing::info!(records = ?evt.payload.records.len(), "Received request from SQS"); if evt.payload.records.len() == 0 { tracing::info!("Empty S3 event received"); } let bucket = evt.payload.records[0].s3.bucket.name.as_ref().expect("Bucket name to exist"); let key = evt.payload.records[0].s3.object.key.as_ref().expect("Object key to exist"); tracing::info!("Request is for { } and object { }", bucket, key); let s3_get_object_result = s3_client .get_object() .bucket(bucket) .key(key) .send() .await; match s3_get_object_result { Ok(_) => tracing::info!("S3 Get Object success, the s3GetObjectResult contains a 'body' property of type ByteStream"), Err(_) => tracing::info!("Failure with S3 Get Object request") } Ok(()) } In the Code source pane on the Lambda console, paste the code into the code editor, replacing the code that Lambda created. In the DEPLOY section, choose Deploy to update your function's code: Create the Amazon S3 trigger To create the Amazon S3 trigger In the Function overview pane, choose Add trigger . Select S3 . Under Bucket , select the bucket you created earlier in the tutorial. Under Event types , be sure that All object create events is selected. Under Recursive invocation , select the check box to acknowledge that using the same Amazon S3 bucket for input and output is not recommended. Choose Add . Note When you create an Amazon S3 trigger for a Lambda function using the Lambda console, Amazon S3 configures an event notification on the bucket you specify. Before configuring this event notification, Amazon S3 performs a series of checks to confirm that the event destination exists and has the required IAM policies. Amazon S3 also performs these tests on any other event notifications configured for that bucket. Because of this check, if the bucket has previously configured event destinations for resources that no longer exist, or for resources that don't have the required permissions policies, Amazon S3 won't be able to create the new event notification. You'll see the following error message indicating that your trigger couldn't be created: An error occurred when creating the trigger: Unable to validate the following destination configurations. You can see this error if you previously configured a trigger for another Lambda function using the same bucket, and you have since deleted the function or modified its permissions policies. Test your Lambda function with a dummy event To test the Lambda function with a dummy event In the Lambda console page for your function, choose the Test tab. For Event name , enter MyTestEvent . In the Event JSON , paste the following test event. Be sure to replace these values: Replace us-east-1 with the region you created your Amazon S3 bucket in. Replace both instances of amzn-s3-demo-bucket with the name of your own Amazon S3 bucket. Replace test%2FKey with the name of the test object you uploaded to your bucket earlier (for example, HappyFace.jpg ). { "Records": [ { "eventVersion": "2.0", "eventSource": "aws:s3", "awsRegion": " us-east-1 ", "eventTime": "1970-01-01T00:00:00.000Z", "eventName": "ObjectCreated:Put", "userIdentity": { "principalId": "EXAMPLE" }, "requestParameters": { "sourceIPAddress": "127.0.0.1" }, "responseElements": { "x-amz-request-id": "EXAMPLE123456789", "x-amz-id-2": "EXAMPLE123/5678abcdefghijklambdaisawesome/mnopqrstuvwxyzABCDEFGH" }, "s3": { "s3SchemaVersion": "1.0", "configurationId": "testConfigRule", "bucket": { "name": " amzn-s3-demo-bucket ", "ownerIdentity": { "principalId": "EXAMPLE" }, "arn": "arn:aws:s3::: amzn-s3-demo-bucket " }, "object": { "key": " test%2Fkey ", "size": 1024, "eTag": "0123456789abcdef0123456789abcdef", "sequencer": "0A1B2C3D4E5F678901" } } } ] } Choose Save . Choose Test . If your function runs successfully, you’ll see output similar to the following in the Execution results tab. Response "image/jpeg" Function Logs START RequestId: 12b3cae7-5f4e-415e-93e6-416b8f8b66e6 Version: $LATEST 2021-02-18T21:40:59.280Z 12b3cae7-5f4e-415e-93e6-416b8f8b66e6 INFO INPUT BUCKET AND KEY: { Bucket: 'amzn-s3-demo-bucket', Key: 'HappyFace.jpg' } 2021-02-18T21:41:00.215Z 12b3cae7-5f4e-415e-93e6-416b8f8b66e6 INFO CONTENT TYPE: image/jpeg END RequestId: 12b3cae7-5f4e-415e-93e6-416b8f8b66e6 REPORT RequestId: 12b3cae7-5f4e-415e-93e6-416b8f8b66e6 Duration: 976.25 ms Billed Duration: 977 ms Memory Size: 128 MB Max Memory Used: 90 MB Init Duration: 430.47 ms Request ID 12b3cae7-5f4e-415e-93e6-416b8f8b66e6 Test the Lambda function with the Amazon S3 trigger To test your function with the configured trigger, upload an object to your Amazon S3 bucket using the console. To verify that your Lambda function ran as expected, use CloudWatch Logs to view your function’s output. To upload an object to your Amazon S3 bucket Open the Buckets page of the Amazon S3 console and choose the bucket that you created earlier. Choose Upload . Choose Add files and use the file selector to choose an object you want to upload. This object can be any file you choose. Choose Open , then choose Upload . To verify the function invocation using CloudWatch Logs Open the CloudWatch console. Make sure you're working in the same AWS Region you created your Lambda function in. You can change your Region using the drop-down list at the top of the screen. Choose Logs , then choose Log groups . Choose the log group for your function ( /aws/lambda/s3-trigger-tutorial ). Under Log streams , choose the most recent log stream. If your function was invoked correctly in response to your Amazon S3 trigger, you’ll see output similar to the following. The CONTENT TYPE you see depends on the type of file you uploaded to your bucket. 2022-05-09T23:17:28.702Z 0cae7f5a-b0af-4c73-8563-a3430333cc10 INFO CONTENT TYPE: image/jpeg Clean up your resources You can now delete the resources that you created for this tutorial, unless you want to retain them. By deleting AWS resources that you're no longer using, you prevent unnecessary charges to your AWS account. To delete the Lambda function Open the Functions page of the Lambda console. Select the function that you created. Choose Actions , Delete . Type confirm in the text input field and choose Delete . To delete the execution role Open the Roles page of the IAM console. Select the execution role that you created. Choose Delete . Enter the name of the role in the text input field and choose Delete . To delete the S3 bucket Open the Amazon S3 console. Select the bucket you created. Choose Delete . Enter the name of the bucket in the text input field. Choose Delete bucket . Next steps In Tutorial: Using an Amazon S3 trigger to create thumbnail images , the Amazon S3 trigger invokes a function that creates a thumbnail image for each image file that is uploaded to a bucket. This tutorial requires a moderate level of AWS and Lambda domain knowledge. It demonstrates how to create resources using the AWS Command Line Interface (AWS CLI) and how to create a .zip file archive deployment package for the function and its dependencies. Javascript is disabled or is unavailable in your browser. To use the Amazon Web Services Documentation, Javascript must be enabled. Please refer to your browser's Help pages for instructions. Document Conventions S3 Tutorial: Use an Amazon S3 trigger to create thumbnails Did this page help you? - Yes Thanks for letting us know we're doing a good job! If you've got a moment, please tell us what we did right so we can do more of it. Did this page help you? - No Thanks for letting us know this page needs work. We're sorry we let you down. If you've got a moment, please tell us how we can make the documentation better. | 2026-01-13T09:30:35 |
https://www.php.net/x-myracloud-5958a2bbbed300a9b9ac631223924e0b/1768296244.931 | PHP update page now Downloads Documentation Get Involved Help Search docs Getting Started Introduction A simple tutorial Language Reference Basic syntax Types Variables Constants Expressions Operators Control Structures Functions Classes and Objects Namespaces Enumerations Errors Exceptions Fibers Generators Attributes References Explained Predefined Variables Predefined Exceptions Predefined Interfaces and Classes Predefined Attributes Context options and parameters Supported Protocols and Wrappers Security Introduction General considerations Installed as CGI binary Installed as an Apache module Session Security Filesystem Security Database Security Error Reporting User Submitted Data Hiding PHP Keeping Current Features HTTP authentication with PHP Cookies Sessions Handling file uploads Using remote files Connection handling Persistent Database Connections Command line usage Garbage Collection DTrace Dynamic Tracing Function Reference Affecting PHP's Behaviour Audio Formats Manipulation Authentication Services Command Line Specific Extensions Compression and Archive Extensions Cryptography Extensions Database Extensions Date and Time Related Extensions File System Related Extensions Human Language and Character Encoding Support Image Processing and Generation Mail Related Extensions Mathematical Extensions Non-Text MIME Output Process Control Extensions Other Basic Extensions Other Services Search Engine Extensions Server Specific Extensions Session Extensions Text Processing Variable and Type Related Extensions Web Services Windows Only Extensions XML Manipulation GUI Extensions Keyboard Shortcuts ? This help j Next menu item k Previous menu item g p Previous man page g n Next man page G Scroll to bottom g g Scroll to top g h Goto homepage g s Goto search (current page) / Focus search box A popular general-purpose scripting language that is especially suited to web development. Fast, flexible and pragmatic, PHP powers everything from your blog to the most popular websites in the world. What's new in 8.5 Download 8.5.1 · Changelog · Upgrading 8.4.16 · Changelog · Upgrading 8.3.29 · Changelog · Upgrading 8.2.30 · Changelog · Upgrading 18 Dec 2025 PHP 8.1.34 Released! The PHP development team announces the immediate availability of PHP 8.1.34. This is a security release. All PHP 8.1 users are encouraged to upgrade to this version. For source downloads of PHP 8.1.34 please visit our downloads page , Windows source and binaries can also be found there . The list of changes is recorded in the ChangeLog . 18 Dec 2025 PHP 8.4.16 Released! The PHP development team announces the immediate availability of PHP 8.4.16. This is a security release. All PHP 8.4 users are encouraged to upgrade to this version. For source downloads of PHP 8.4.16 please visit our downloads page , Windows source and binaries can also be found there . The list of changes is recorded in the ChangeLog . 18 Dec 2025 PHP 8.2.30 Released! The PHP development team announces the immediate availability of PHP 8.2.30. This is a security release. All PHP 8.2 users are encouraged to upgrade to this version. For source downloads of PHP 8.2.30 please visit our downloads page , Windows source and binaries can also be found there . The list of changes is recorded in the ChangeLog . 18 Dec 2025 PHP 8.3.29 Released! The PHP development team announces the immediate availability of PHP 8.3.29. This is a security release. All PHP 8.3 users are encouraged to upgrade to this version. For source downloads of PHP 8.3.29 please visit our downloads page , Windows source and binaries can also be found there . The list of changes is recorded in the ChangeLog . 18 Dec 2025 PHP 8.5.1 Released! The PHP development team announces the immediate availability of PHP 8.5.1. This is a security release. All PHP 8.5 users are encouraged to upgrade to this version. For source downloads of PHP 8.5.1 please visit our downloads page , Windows source and binaries can also be found there . The list of changes is recorded in the ChangeLog . 20 Nov 2025 PHP 8.5.0 Released! The PHP development team announces the immediate availability of PHP 8.5.0. This release marks the latest minor release of the PHP language. PHP 8.5 comes with numerous improvements and new features such as: New "URI" extension New pipe operator (|>) Clone With New #[\NoDiscard] attribute Support for closures, casts, and first class callables in constant expressions And much much more... For source downloads of PHP 8.5.0 please visit our downloads page , Windows source and binaries can also be found there . The list of changes is recorded in the ChangeLog . The migration guide is available in the PHP Manual. Please consult it for the detailed list of new features and backward incompatible changes. Kudos to all the contributors and supporters! 20 Nov 2025 PHP 8.4.15 Released! The PHP development team announces the immediate availability of PHP 8.4.15. This is a bug fix release. All PHP 8.4 users are encouraged to upgrade to this version. For source downloads of PHP 8.4.15 please visit our downloads page , Windows source and binaries can also be found there . The list of changes is recorded in the ChangeLog . 20 Nov 2025 PHP 8.3.28 Released! The PHP development team announces the immediate availability of PHP 8.3.28. This is a bug fix release. All PHP 8.3 users are encouraged to upgrade to this version. For source downloads of PHP 8.3.28 please visit our downloads page , Windows source and binaries can also be found there . The list of changes is recorded in the ChangeLog . 13 Nov 2025 PHP 8.5.0 RC 5 available for testing The PHP team is pleased to announce the fifth release candidate of PHP 8.5.0, RC 5. This continues the PHP 8.5 release cycle, the rough outline of which is specified in the PHP Wiki . For source downloads of PHP 8.5.0 RC5, please visit the download page . Please carefully test this version and report any issues found on GitHub . Please DO NOT use this version in production, it is a test version. For more information on the new features and other changes, you can read the NEWS file, or the UPGRADING file for a complete list of upgrading notes. These files can also be found in the release archive. The next release will be the GA release of PHP 8.5.0, planned for 20 Nov 2025. The signatures for the release can be found in the manifest or on the Release Candidates page . Thank you for helping us make PHP better. 06 Nov 2025 PHP 8.5.0 RC4 available for testing The PHP team is pleased to announce the final planned release candidate of PHP 8.5.0, RC 4. This continues the PHP 8.5 release cycle, the rough outline of which is specified in the PHP Wiki . For source downloads of PHP 8.5.0 RC4, please visit the download page . Please carefully test this version and report any issues found on GitHub . Please DO NOT use this version in production, it is a test version. For more information on the new features and other changes, you can read the NEWS file, or the UPGRADING file for a complete list of upgrading notes. These files can also be found in the release archive. The next release will be the GA release of PHP 8.5.0, planned for 20 Nov 2025. The signatures for the release can be found in the manifest or on the Release Candidates page . Thank you for helping us make PHP better. 23 Oct 2025 PHP 8.3.27 Released! The PHP development team announces the immediate availability of PHP 8.3.27. This is a bug fix release. All PHP 8.3 users are encouraged to upgrade to this version. For source downloads of PHP 8.3.27 please visit our downloads page , Windows source and binaries can be found on windows.php.net/download/ . The list of changes is recorded in the ChangeLog . 23 Oct 2025 PHP 8.4.14 Released! The PHP development team announces the immediate availability of PHP 8.4.14. This is a bug fix release. All PHP 8.4 users are encouraged to upgrade to this version. For source downloads of PHP 8.4.14 please visit our downloads page , Windows source and binaries can be found on windows.php.net/download/ . The list of changes is recorded in the ChangeLog . 23 Oct 2025 PHP 8.5.0 RC 3 available for testing The PHP team is pleased to announce the third release candidate of PHP 8.5.0, RC 3. This continues the PHP 8.5 release cycle, the rough outline of which is specified in the PHP Wiki . For source downloads of PHP 8.5.0 RC3, please visit the download page . Please carefully test this version and report any issues found on GitHub . Please DO NOT use this version in production, it is an early test version. For more information on the new features and other changes, you can read the NEWS file, or the UPGRADING file for a complete list of upgrading notes. These files can also be found in the release archive. The next release will be RC4, planned for 6 Nov 2025. The signatures for the release can be found in the manifest or on the Release Candidates page . Thank you for helping us make PHP better. 09 Oct 2025 PHP 8.5.0 RC 2 available for testing The PHP team is pleased to announce the second release candidate of PHP 8.5.0, RC 2. This continues the PHP 8.5 release cycle, the rough outline of which is specified in the PHP Wiki . For source downloads of PHP 8.5.0 RC2, please visit the download page . Please carefully test this version and report any issues found on GitHub . Please DO NOT use this version in production, it is an early test version. For more information on the new features and other changes, you can read the NEWS file, or the UPGRADING file for a complete list of upgrading notes. These files can also be found in the release archive. The next release will be RC3, planned for 23 Oct 2025. The signatures for the release can be found in the manifest or on the Release Candidates page . Thank you for helping us make PHP better. 25 Sep 2025 PHP 8.5.0 RC 1 available for testing The PHP team is pleased to announce the first release candidate of PHP 8.5.0, RC 1. This continues the PHP 8.5 release cycle, the rough outline of which is specified in the PHP Wiki . For source downloads of PHP 8.5.0 RC1, please visit the download page . Please carefully test this version and report any issues found on GitHub . Please DO NOT use this version in production, it is an early test version. For more information on the new features and other changes, you can read the NEWS file, or the UPGRADING file for a complete list of upgrading notes. These files can also be found in the release archive. The next release will be RC2, planned for 9 Oct 2025. The signatures for the release can be found in the manifest or on the Release Candidates page . Thank you for helping us make PHP better. 25 Sep 2025 PHP 8.3.26 Released! The PHP development team announces the immediate availability of PHP 8.3.26. This is a bug fix release. All PHP 8.3 users are encouraged to upgrade to this version. For source downloads of PHP 8.3.26 please visit our downloads page , Windows source and binaries can be found on windows.php.net/download/ . The list of changes is recorded in the ChangeLog . 25 Sep 2025 PHP 8.4.13 Released! The PHP development team announces the immediate availability of PHP 8.4.13. This is a bug fix release. All PHP 8.4 users are encouraged to upgrade to this version. For source downloads of PHP 8.4.13 please visit our downloads page , Windows source and binaries can be found on windows.php.net/download/ . The list of changes is recorded in the ChangeLog . 11 Sep 2025 PHP 8.5.0 Beta 3 available for testing The PHP team is pleased to announce the third beta release of PHP 8.5.0, Beta 3. This continues the PHP 8.5 release cycle, the rough outline of which is specified in the PHP Wiki . For source downloads of PHP 8.5.0 Beta 3, please visit the download page . Please carefully test this version and report any issues found on GitHub . Please DO NOT use this version in production, it is an early test version. For more information on the new features and other changes, you can read the NEWS file, or the UPGRADING file for a complete list of upgrading notes. These files can also be found in the release archive. The next release will be RC1, planned for 25 Sep 2025. The signatures for the release can be found in the manifest or on the Release Candidates page . Thank you for helping us make PHP better. 28 Aug 2025 PHP 8.5.0 Beta 2 available for testing The PHP team is pleased to announce the second beta release of PHP 8.5.0, Beta 2. This continues the PHP 8.5 release cycle, the rough outline of which is specified in the PHP Wiki . For source downloads of PHP 8.5.0 Beta 2 please visit the download page . Please carefully test this version and report any issues found on GitHub . Please DO NOT use this version in production, it is an early test version. For more information on the new features and other changes, you can read the NEWS file, or the UPGRADING file for a complete list of upgrading notes. These files can also be found in the release archive. The next release will be Beta 3, planned for 11 Sep 2025. The signatures for the release can be found in the manifest or on the Release Candidates page . Thank you for helping us make PHP better. 28 Aug 2025 PHP 8.3.25 Released! The PHP development team announces the immediate availability of PHP 8.3.25. This is a bug fix release. All PHP 8.3 users are encouraged to upgrade to this version. For source downloads of PHP 8.3.25 please visit our downloads page , Windows source and binaries can be found on windows.php.net/download/ . The list of changes is recorded in the ChangeLog . 28 Aug 2025 PHP 8.4.12 Released! The PHP development team announces the immediate availability of PHP 8.4.12. This is a bug fix release. All PHP 8.4 users are encouraged to upgrade to this version. For source downloads of PHP 8.4.12 please visit our downloads page , Windows source and binaries can be found on windows.php.net/download/ . The list of changes is recorded in the ChangeLog . 14 Aug 2025 PHP 8.5.0 Beta 1 available for testing The PHP team is pleased to announce the first beta release of PHP 8.5.0, Beta 1. This continues the PHP 8.5 release cycle, the rough outline of which is specified in the PHP Wiki . For source downloads of PHP 8.5.0 Beta 1 please visit the download page . Please carefully test this version and report any issues found on GitHub . Please DO NOT use this version in production, it is an early test version. For more information on the new features and other changes, you can read the NEWS file, or the UPGRADING file for a complete list of upgrading notes. These files can also be found in the release archive. The next release will be Beta 2, planned for 28 Aug 2025. The signatures for the release can be found in the manifest or on the Release Candidates page . Thank you for helping us make PHP better. 01 Aug 2025 PHP 8.5.0 Alpha 4 available for testing The PHP team is pleased to announce the third testing release of PHP 8.5.0, Alpha 4. This continues the PHP 8.5 release cycle, the rough outline of which is specified in the PHP Wiki . For source downloads of PHP 8.5.0 Alpha 4 please visit the download page . Please carefully test this version and report any issues found on GitHub . Please DO NOT use this version in production, it is an early test version. For more information on the new features and other changes, you can read the NEWS file, or the UPGRADING file for a complete list of upgrading notes. These files can also be found in the release archive. The next release will be Beta 1, planned for 14 Aug 2025. The signatures for the release can be found in the manifest or on the Release Candidates page . Thank you for helping us make PHP better. 31 Jul 2025 PHP 8.4.11 Released! The PHP development team announces the immediate availability of PHP 8.4.11. This is a bug fix release. All PHP 8.4 users are encouraged to upgrade to this version. For source downloads of PHP 8.4.11 please visit our downloads page , Windows source and binaries can be found on windows.php.net/download/ . The list of changes is recorded in the ChangeLog . 31 Jul 2025 PHP 8.3.24 Released! The PHP development team announces the immediate availability of PHP 8.3.24. This is a bug fix release. All PHP 8.3 users are encouraged to upgrade to this version. For source downloads of PHP 8.3.24 please visit our downloads page , Windows source and binaries can be found on windows.php.net/download/ . The list of changes is recorded in the ChangeLog . Older News Entries The PHP Foundation The PHP Foundation is a collective of people and organizations, united in the mission to ensure the long-term prosperity of the PHP language. Donate Upcoming conferences International PHP Conference Berlin 2026 Laravel Live Japan Conferences calling for papers Dutch PHP Conference 2026 User Group Events Special Thanks Social media @official_php @php@fosstodon.org @phpnet Copyright © 2001-2026 The PHP Group My PHP.net Contact Other PHP.net sites Privacy policy View Source ↑ and ↓ to navigate • Enter to select • Esc to close • / to open Press Enter without selection to search using Google | 2026-01-13T09:30:35 |
https://www.php.net/x-myracloud-5958a2bbbed300a9b9ac631223924e0b/1768296244.81 | PHP update page now Downloads Documentation Get Involved Help Search docs Getting Started Introduction A simple tutorial Language Reference Basic syntax Types Variables Constants Expressions Operators Control Structures Functions Classes and Objects Namespaces Enumerations Errors Exceptions Fibers Generators Attributes References Explained Predefined Variables Predefined Exceptions Predefined Interfaces and Classes Predefined Attributes Context options and parameters Supported Protocols and Wrappers Security Introduction General considerations Installed as CGI binary Installed as an Apache module Session Security Filesystem Security Database Security Error Reporting User Submitted Data Hiding PHP Keeping Current Features HTTP authentication with PHP Cookies Sessions Handling file uploads Using remote files Connection handling Persistent Database Connections Command line usage Garbage Collection DTrace Dynamic Tracing Function Reference Affecting PHP's Behaviour Audio Formats Manipulation Authentication Services Command Line Specific Extensions Compression and Archive Extensions Cryptography Extensions Database Extensions Date and Time Related Extensions File System Related Extensions Human Language and Character Encoding Support Image Processing and Generation Mail Related Extensions Mathematical Extensions Non-Text MIME Output Process Control Extensions Other Basic Extensions Other Services Search Engine Extensions Server Specific Extensions Session Extensions Text Processing Variable and Type Related Extensions Web Services Windows Only Extensions XML Manipulation GUI Extensions Keyboard Shortcuts ? This help j Next menu item k Previous menu item g p Previous man page g n Next man page G Scroll to bottom g g Scroll to top g h Goto homepage g s Goto search (current page) / Focus search box A popular general-purpose scripting language that is especially suited to web development. Fast, flexible and pragmatic, PHP powers everything from your blog to the most popular websites in the world. What's new in 8.5 Download 8.5.1 · Changelog · Upgrading 8.4.16 · Changelog · Upgrading 8.3.29 · Changelog · Upgrading 8.2.30 · Changelog · Upgrading 18 Dec 2025 PHP 8.1.34 Released! The PHP development team announces the immediate availability of PHP 8.1.34. This is a security release. All PHP 8.1 users are encouraged to upgrade to this version. For source downloads of PHP 8.1.34 please visit our downloads page , Windows source and binaries can also be found there . The list of changes is recorded in the ChangeLog . 18 Dec 2025 PHP 8.4.16 Released! The PHP development team announces the immediate availability of PHP 8.4.16. This is a security release. All PHP 8.4 users are encouraged to upgrade to this version. For source downloads of PHP 8.4.16 please visit our downloads page , Windows source and binaries can also be found there . The list of changes is recorded in the ChangeLog . 18 Dec 2025 PHP 8.2.30 Released! The PHP development team announces the immediate availability of PHP 8.2.30. This is a security release. All PHP 8.2 users are encouraged to upgrade to this version. For source downloads of PHP 8.2.30 please visit our downloads page , Windows source and binaries can also be found there . The list of changes is recorded in the ChangeLog . 18 Dec 2025 PHP 8.3.29 Released! The PHP development team announces the immediate availability of PHP 8.3.29. This is a security release. All PHP 8.3 users are encouraged to upgrade to this version. For source downloads of PHP 8.3.29 please visit our downloads page , Windows source and binaries can also be found there . The list of changes is recorded in the ChangeLog . 18 Dec 2025 PHP 8.5.1 Released! The PHP development team announces the immediate availability of PHP 8.5.1. This is a security release. All PHP 8.5 users are encouraged to upgrade to this version. For source downloads of PHP 8.5.1 please visit our downloads page , Windows source and binaries can also be found there . The list of changes is recorded in the ChangeLog . 20 Nov 2025 PHP 8.5.0 Released! The PHP development team announces the immediate availability of PHP 8.5.0. This release marks the latest minor release of the PHP language. PHP 8.5 comes with numerous improvements and new features such as: New "URI" extension New pipe operator (|>) Clone With New #[\NoDiscard] attribute Support for closures, casts, and first class callables in constant expressions And much much more... For source downloads of PHP 8.5.0 please visit our downloads page , Windows source and binaries can also be found there . The list of changes is recorded in the ChangeLog . The migration guide is available in the PHP Manual. Please consult it for the detailed list of new features and backward incompatible changes. Kudos to all the contributors and supporters! 20 Nov 2025 PHP 8.4.15 Released! The PHP development team announces the immediate availability of PHP 8.4.15. This is a bug fix release. All PHP 8.4 users are encouraged to upgrade to this version. For source downloads of PHP 8.4.15 please visit our downloads page , Windows source and binaries can also be found there . The list of changes is recorded in the ChangeLog . 20 Nov 2025 PHP 8.3.28 Released! The PHP development team announces the immediate availability of PHP 8.3.28. This is a bug fix release. All PHP 8.3 users are encouraged to upgrade to this version. For source downloads of PHP 8.3.28 please visit our downloads page , Windows source and binaries can also be found there . The list of changes is recorded in the ChangeLog . 13 Nov 2025 PHP 8.5.0 RC 5 available for testing The PHP team is pleased to announce the fifth release candidate of PHP 8.5.0, RC 5. This continues the PHP 8.5 release cycle, the rough outline of which is specified in the PHP Wiki . For source downloads of PHP 8.5.0 RC5, please visit the download page . Please carefully test this version and report any issues found on GitHub . Please DO NOT use this version in production, it is a test version. For more information on the new features and other changes, you can read the NEWS file, or the UPGRADING file for a complete list of upgrading notes. These files can also be found in the release archive. The next release will be the GA release of PHP 8.5.0, planned for 20 Nov 2025. The signatures for the release can be found in the manifest or on the Release Candidates page . Thank you for helping us make PHP better. 06 Nov 2025 PHP 8.5.0 RC4 available for testing The PHP team is pleased to announce the final planned release candidate of PHP 8.5.0, RC 4. This continues the PHP 8.5 release cycle, the rough outline of which is specified in the PHP Wiki . For source downloads of PHP 8.5.0 RC4, please visit the download page . Please carefully test this version and report any issues found on GitHub . Please DO NOT use this version in production, it is a test version. For more information on the new features and other changes, you can read the NEWS file, or the UPGRADING file for a complete list of upgrading notes. These files can also be found in the release archive. The next release will be the GA release of PHP 8.5.0, planned for 20 Nov 2025. The signatures for the release can be found in the manifest or on the Release Candidates page . Thank you for helping us make PHP better. 23 Oct 2025 PHP 8.3.27 Released! The PHP development team announces the immediate availability of PHP 8.3.27. This is a bug fix release. All PHP 8.3 users are encouraged to upgrade to this version. For source downloads of PHP 8.3.27 please visit our downloads page , Windows source and binaries can be found on windows.php.net/download/ . The list of changes is recorded in the ChangeLog . 23 Oct 2025 PHP 8.4.14 Released! The PHP development team announces the immediate availability of PHP 8.4.14. This is a bug fix release. All PHP 8.4 users are encouraged to upgrade to this version. For source downloads of PHP 8.4.14 please visit our downloads page , Windows source and binaries can be found on windows.php.net/download/ . The list of changes is recorded in the ChangeLog . 23 Oct 2025 PHP 8.5.0 RC 3 available for testing The PHP team is pleased to announce the third release candidate of PHP 8.5.0, RC 3. This continues the PHP 8.5 release cycle, the rough outline of which is specified in the PHP Wiki . For source downloads of PHP 8.5.0 RC3, please visit the download page . Please carefully test this version and report any issues found on GitHub . Please DO NOT use this version in production, it is an early test version. For more information on the new features and other changes, you can read the NEWS file, or the UPGRADING file for a complete list of upgrading notes. These files can also be found in the release archive. The next release will be RC4, planned for 6 Nov 2025. The signatures for the release can be found in the manifest or on the Release Candidates page . Thank you for helping us make PHP better. 09 Oct 2025 PHP 8.5.0 RC 2 available for testing The PHP team is pleased to announce the second release candidate of PHP 8.5.0, RC 2. This continues the PHP 8.5 release cycle, the rough outline of which is specified in the PHP Wiki . For source downloads of PHP 8.5.0 RC2, please visit the download page . Please carefully test this version and report any issues found on GitHub . Please DO NOT use this version in production, it is an early test version. For more information on the new features and other changes, you can read the NEWS file, or the UPGRADING file for a complete list of upgrading notes. These files can also be found in the release archive. The next release will be RC3, planned for 23 Oct 2025. The signatures for the release can be found in the manifest or on the Release Candidates page . Thank you for helping us make PHP better. 25 Sep 2025 PHP 8.5.0 RC 1 available for testing The PHP team is pleased to announce the first release candidate of PHP 8.5.0, RC 1. This continues the PHP 8.5 release cycle, the rough outline of which is specified in the PHP Wiki . For source downloads of PHP 8.5.0 RC1, please visit the download page . Please carefully test this version and report any issues found on GitHub . Please DO NOT use this version in production, it is an early test version. For more information on the new features and other changes, you can read the NEWS file, or the UPGRADING file for a complete list of upgrading notes. These files can also be found in the release archive. The next release will be RC2, planned for 9 Oct 2025. The signatures for the release can be found in the manifest or on the Release Candidates page . Thank you for helping us make PHP better. 25 Sep 2025 PHP 8.3.26 Released! The PHP development team announces the immediate availability of PHP 8.3.26. This is a bug fix release. All PHP 8.3 users are encouraged to upgrade to this version. For source downloads of PHP 8.3.26 please visit our downloads page , Windows source and binaries can be found on windows.php.net/download/ . The list of changes is recorded in the ChangeLog . 25 Sep 2025 PHP 8.4.13 Released! The PHP development team announces the immediate availability of PHP 8.4.13. This is a bug fix release. All PHP 8.4 users are encouraged to upgrade to this version. For source downloads of PHP 8.4.13 please visit our downloads page , Windows source and binaries can be found on windows.php.net/download/ . The list of changes is recorded in the ChangeLog . 11 Sep 2025 PHP 8.5.0 Beta 3 available for testing The PHP team is pleased to announce the third beta release of PHP 8.5.0, Beta 3. This continues the PHP 8.5 release cycle, the rough outline of which is specified in the PHP Wiki . For source downloads of PHP 8.5.0 Beta 3, please visit the download page . Please carefully test this version and report any issues found on GitHub . Please DO NOT use this version in production, it is an early test version. For more information on the new features and other changes, you can read the NEWS file, or the UPGRADING file for a complete list of upgrading notes. These files can also be found in the release archive. The next release will be RC1, planned for 25 Sep 2025. The signatures for the release can be found in the manifest or on the Release Candidates page . Thank you for helping us make PHP better. 28 Aug 2025 PHP 8.5.0 Beta 2 available for testing The PHP team is pleased to announce the second beta release of PHP 8.5.0, Beta 2. This continues the PHP 8.5 release cycle, the rough outline of which is specified in the PHP Wiki . For source downloads of PHP 8.5.0 Beta 2 please visit the download page . Please carefully test this version and report any issues found on GitHub . Please DO NOT use this version in production, it is an early test version. For more information on the new features and other changes, you can read the NEWS file, or the UPGRADING file for a complete list of upgrading notes. These files can also be found in the release archive. The next release will be Beta 3, planned for 11 Sep 2025. The signatures for the release can be found in the manifest or on the Release Candidates page . Thank you for helping us make PHP better. 28 Aug 2025 PHP 8.3.25 Released! The PHP development team announces the immediate availability of PHP 8.3.25. This is a bug fix release. All PHP 8.3 users are encouraged to upgrade to this version. For source downloads of PHP 8.3.25 please visit our downloads page , Windows source and binaries can be found on windows.php.net/download/ . The list of changes is recorded in the ChangeLog . 28 Aug 2025 PHP 8.4.12 Released! The PHP development team announces the immediate availability of PHP 8.4.12. This is a bug fix release. All PHP 8.4 users are encouraged to upgrade to this version. For source downloads of PHP 8.4.12 please visit our downloads page , Windows source and binaries can be found on windows.php.net/download/ . The list of changes is recorded in the ChangeLog . 14 Aug 2025 PHP 8.5.0 Beta 1 available for testing The PHP team is pleased to announce the first beta release of PHP 8.5.0, Beta 1. This continues the PHP 8.5 release cycle, the rough outline of which is specified in the PHP Wiki . For source downloads of PHP 8.5.0 Beta 1 please visit the download page . Please carefully test this version and report any issues found on GitHub . Please DO NOT use this version in production, it is an early test version. For more information on the new features and other changes, you can read the NEWS file, or the UPGRADING file for a complete list of upgrading notes. These files can also be found in the release archive. The next release will be Beta 2, planned for 28 Aug 2025. The signatures for the release can be found in the manifest or on the Release Candidates page . Thank you for helping us make PHP better. 01 Aug 2025 PHP 8.5.0 Alpha 4 available for testing The PHP team is pleased to announce the third testing release of PHP 8.5.0, Alpha 4. This continues the PHP 8.5 release cycle, the rough outline of which is specified in the PHP Wiki . For source downloads of PHP 8.5.0 Alpha 4 please visit the download page . Please carefully test this version and report any issues found on GitHub . Please DO NOT use this version in production, it is an early test version. For more information on the new features and other changes, you can read the NEWS file, or the UPGRADING file for a complete list of upgrading notes. These files can also be found in the release archive. The next release will be Beta 1, planned for 14 Aug 2025. The signatures for the release can be found in the manifest or on the Release Candidates page . Thank you for helping us make PHP better. 31 Jul 2025 PHP 8.4.11 Released! The PHP development team announces the immediate availability of PHP 8.4.11. This is a bug fix release. All PHP 8.4 users are encouraged to upgrade to this version. For source downloads of PHP 8.4.11 please visit our downloads page , Windows source and binaries can be found on windows.php.net/download/ . The list of changes is recorded in the ChangeLog . 31 Jul 2025 PHP 8.3.24 Released! The PHP development team announces the immediate availability of PHP 8.3.24. This is a bug fix release. All PHP 8.3 users are encouraged to upgrade to this version. For source downloads of PHP 8.3.24 please visit our downloads page , Windows source and binaries can be found on windows.php.net/download/ . The list of changes is recorded in the ChangeLog . Older News Entries The PHP Foundation The PHP Foundation is a collective of people and organizations, united in the mission to ensure the long-term prosperity of the PHP language. Donate Upcoming conferences International PHP Conference Berlin 2026 Laravel Live Japan Conferences calling for papers Dutch PHP Conference 2026 User Group Events Special Thanks Social media @official_php @php@fosstodon.org @phpnet Copyright © 2001-2026 The PHP Group My PHP.net Contact Other PHP.net sites Privacy policy View Source ↑ and ↓ to navigate • Enter to select • Esc to close • / to open Press Enter without selection to search using Google | 2026-01-13T09:30:35 |
https://github.com/aws-samples/serverless-snippets/tree/main/integration-s3-to-lambda | serverless-snippets/integration-s3-to-lambda at main · aws-samples/serverless-snippets · GitHub Skip to content Navigation Menu Toggle navigation Sign in Appearance settings Platform AI CODE CREATION GitHub Copilot Write better code with AI GitHub Spark Build and deploy intelligent apps GitHub Models Manage and compare prompts MCP Registry New Integrate external tools DEVELOPER WORKFLOWS Actions Automate any workflow Codespaces Instant dev environments Issues Plan and track work Code Review Manage code changes APPLICATION SECURITY GitHub Advanced Security Find and fix vulnerabilities Code security Secure your code as you build Secret protection Stop leaks before they start EXPLORE Why GitHub Documentation Blog Changelog Marketplace View all features Solutions BY COMPANY SIZE Enterprises Small and medium teams Startups Nonprofits BY USE CASE App Modernization DevSecOps DevOps CI/CD View all use cases BY INDUSTRY Healthcare Financial services Manufacturing Government View all industries View all solutions Resources EXPLORE BY TOPIC AI Software Development DevOps Security View all topics EXPLORE BY TYPE Customer stories Events & webinars Ebooks & reports Business insights GitHub Skills SUPPORT & SERVICES Documentation Customer support Community forum Trust center Partners Open Source COMMUNITY GitHub Sponsors Fund open source developers PROGRAMS Security Lab Maintainer Community Accelerator Archive Program REPOSITORIES Topics Trending Collections Enterprise ENTERPRISE SOLUTIONS Enterprise platform AI-powered developer platform AVAILABLE ADD-ONS GitHub Advanced Security Enterprise-grade security features Copilot for Business Enterprise-grade AI features Premium Support Enterprise-grade 24/7 support Pricing Search or jump to... Search code, repositories, users, issues, pull requests... --> Search Clear Search syntax tips Provide feedback --> We read every piece of feedback, and take your input very seriously. Include my email address so I can be contacted Cancel Submit feedback Saved searches Use saved searches to filter your results more quickly --> Name Query To see all available qualifiers, see our documentation . Cancel Create saved search Sign in Sign up Appearance settings Resetting focus You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session. Dismiss alert {{ message }} aws-samples / serverless-snippets Public generated from amazon-archives/__template_MIT-0 Notifications You must be signed in to change notification settings Fork 101 Star 162 Code Issues 13 Pull requests 9 Projects 0 Security Uh oh! There was an error while loading. Please reload this page . Insights Additional navigation options Code Issues Pull requests Projects Security Insights Footer © 2026 GitHub, Inc. Footer navigation Terms Privacy Security Status Community Docs Contact Manage cookies Do not share my personal information You can’t perform that action at this time. | 2026-01-13T09:30:35 |
https://www.visma.com/voiceofvisma/ep-15-leading-with-transparency-and-vulnerability-with-ellen-sano | Ep 15: Leading with transparency and vulnerability with Ellen Sano Who we are About us Connected by software – driven by people Become a Visma company Join our family of thriving SaaS companies Technology and AI at Visma Innovation with customer value at its heart Our sponsorship Team Visma | Lease a Bike Sustainability A better impact through software Contact us Find the right contact information What we offer Cloud software We create brilliant ways to work For medium businesses Lead your business with clarity For small businesses Start, run and grow with ease For public sector Empower efficient societies For accounting offices Build your dream accounting office For partners Help us keep customers ahead For investors For investors Latest results, news and strategy Financials Key figures, quarterly and annual results Events Financial calendar Governance Policies, management, board and owners Careers Careers at Visma Join the business software revolution Locations Find your nearest office Open positions Turn your passion into a career Resources News For small businesses Cloud accounting software built for small businesses Who we are About us Technology and AI at Visma Sustainability Become a Visma company Our sponsorship What we offer Cloud software For small businesses For accounting offices For enterprises Public sector For partners For investors Overview Financials Governance News and press Events Careers Careers at Visma Open positions Hubs Resources Blog Visma Developer Trust Centre News Press releases Team Visma | Lease a Bike Podcast Ep 15: Leading with transparency and vulnerability with Ellen Sano Voice of Visma March 19, 2025 Spotify Created with Sketch. YouTube Apple Podcasts Amazon Music <iframe style="border-radius:12px" src="https://www.youtube.com/embed/PDd2-WHZsPc?si=z7CSa2rnUW3AO-dv" width="100%" height="500" frameBorder="0" allowfullscreen="" allow="autoplay; clipboard-write; encrypted-media; fullscreen; picture-in-picture" loading="lazy"></iframe> About the episode What does it mean to be a “firestarter” in business? Today, Ellen joins host Juliette Prado to share what’s worked in leading a multinational company that proudly supports different company cultures. Plus, as we celebrate Women in Tech month, she reflects on the power of diverse leadership and shares her advice for women looking to break into tech. Share More from Voice of Visma We're sitting down with leaders and colleagues from around Visma to share their stories, industry knowledge, and valuable career lessons. With the Voice of Visma podcast, we’re bringing our people and culture closer to you. Get to know the podcast Ep 22: Building, learning, and accelerating growth in the SaaS world with Maxin Schneider Entrepreneurial leadership often grows through experience, and Maxin Schneider has seen that up close. Read more Ep 21: How DEI fuels business success with Iveta Bukane Why DEI isn't just a moral imperative—it’s a business necessity. Read more Ep 20: Driving tangible sustainability outcomes with Freja Landewall Discover how ESG goes far beyond the environment, encompassing people, governance, and the long-term resilience of business. Read more Ep 19: Future-proofing public services in Sweden with Marie Ceder Between demographic changes, the rise in AI, and digitalisation, the public sector is at a pivotal moment. Read more Ep 18: Making inclusion part of our everyday work with Ida Algotsson What does inclusion truly mean at Visma – not just as values, but as everyday actions? Read more Ep 17: Sustainability at the heart of business with Robin Åkerberg Honouring our responsibility goes well beyond the numbers – it starts with a shared purpose and values. Read more Ep 16: Innovation for the public good with Kasper Lyhr Serving the public sector goes way beyond software – it’s about shaping the future of society as a whole. Read more Ep 15: Leading with transparency and vulnerability with Ellen Sano What does it mean to be a “firestarter” in business? Read more Ep 14: Women, innovation, and the future of Visma with Merete Hverven Our CEO, Merete, knows that great leadership takes more than just hard work – it takes vision. Read more Ep 13: Building partnerships beyond software with Daniel Ognøy Kaspersen What does it look like when an accounting software company delivers more than just great software? Read more Ep 12: AI in the accounting sphere with Joris Joppe Artificial intelligence is changing industries across the board, and accounting is no exception. But in such a highly specialised field, what does change actually look like? Read more Ep 11: From Founder to Segment Director with Ari-Pekka Salovaara Ari-Pekka is a serial entrepreneur who joined Visma when his company was acquired in 2010. He now leads the small business segment. Read more Ep 10: When brave choices can save a company with Charlotte von Sydow What’s it like stepping in as the Managing Director for a company in decline? Read more Ep 09: Revolutionising tax tech in Italy with Enrico Mattiazzi and Vito Lomele Take one look at their product, their customer reviews, or their workplace awards, and it’s clear why Fiscozen leads Italy’s tax tech scene. Read more Ep 08: Navigating the waters of entrepreneurship with Steffen Torp When it comes to being an entrepreneur, the journey is as personal as it is unpredictable. Read more Ep 07: The untold stories of Visma with Øystein Moan What did Visma look like in its early days? Are there any decisions our former CEO would have made differently? Read more Ep 06: Measure what matters: Employee engagement with Vibeke Müller Research shows that having engaged, happy employees is so important for building a great company culture and performing better financially. Read more Ep 05: Our Team Visma | Lease a Bike sponsorship with Anne-Grethe Thomle Karlsen It’s one thing to sponsor the world’s best cycling team; it’s a whole other thing to provide software and expertise that helps them do what they do best. Read more Ep 04: “How do you make people care about security?” with Joakim Tauren With over 700 applications across the Visma Group (and counting!), cybersecurity is make-or-break for us. Read more Ep 03: The human side of enterprise with Yvette Hoogewerf As a software company, our products are central to our business… but that’s only one part of the equation. Read more Ep 02: From Management Trainee to CFO with Stian Grindheim How does someone work their way up from Management Trainee to CFO by the age of 30? And balance fatherhood alongside it all? Read more Ep 01: An optimistic look at the future of AI with Jacob Nyman We’re all-too familiar with the fears surrounding artificial intelligence. So today, Jacob and Johan are flipping the script. Read more (Trailer) Introducing: Voice of Visma These are the stories that shape us... and the reason Visma is unlike anywhere else. Read more Visma Software International AS Organisation number: 980858073 MVA (Foretaksregisteret/The Register of Business Enterprises) Main office Karenslyst allé 56 0277 Oslo Norway Postal address PO box 733, Skøyen 0214 Oslo Norway visma@visma.com Visma on LinkedIn Who we are About us Technology at Visma Sustainability Become a Visma company Our sponsorship Contact us What we offer For small businesses For accounting offices For medium businesses For public sector For partners e-invoicing Digital signature For investors Overview Financials Governance Events Careers Careers at Visma Open positions Hubs Resources Blog Trust Centre Community News Press ©️ 2026 Visma Privacy policy Cookie policy Whistleblowing Cookies settings Transparency Act Change country | 2026-01-13T09:30:35 |
https://docs.aws.amazon.com/es_es/AmazonCloudFront/latest/DeveloperGuide/lambda-examples.html#lambda-examples-normalize-query-string-parameters | Funciones de ejemplo de Lambda@Edge - Amazon CloudFront Funciones de ejemplo de Lambda@Edge - Amazon CloudFront Documentación Amazon CloudFront Guía para desarrolladores Ejemplos generales Generación de respuestas: ejemplos Cadenas de consulta: ejemplos Personalización de contenido por encabezados de tipo de dispositivo o país: ejemplos Selección de origen dinámico basada en contenido: ejemplos Actualización de estados de error: ejemplos Acceso al cuerpo de la solicitud: ejemplos Funciones de ejemplo de Lambda@Edge Consulte los ejemplos siguientes para usar funciones de Lambda con Amazon CloudFront. nota Si elige el tiempo de ejecución Node.js 18 o una versión posterior para la función Lambda@Edge, se creará automáticamente un archivo index.mjs . Para usar los siguientes ejemplos de código, cambie el nombre del archivo index.mjs a index.js . Temas Ejemplos generales Generación de respuestas: ejemplos Cadenas de consulta: ejemplos Personalización de contenido por encabezados de tipo de dispositivo o país: ejemplos Selección de origen dinámico basada en contenido: ejemplos Actualización de estados de error: ejemplos Acceso al cuerpo de la solicitud: ejemplos Ejemplos generales Los ejemplos siguientes muestran formas habituales de usar Lambda@Edge en CloudFront. Temas Ejemplo: prueba A/B Ejemplo: Sobrescritura de un encabezado de respuesta Ejemplo: prueba A/B Puede utilizar el siguiente ejemplo para probar dos versiones diferentes de una imagen sin crear redirecciones ni cambiar la dirección URL. En este ejemplo se leen las cookies de la solicitud del lector y se modifica la URL de la solicitud en consecuencia. Si el espectador no envía una cookie con uno de los valores esperados, el ejemplo asigna aleatoriamente al espectador una de las URL. 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; } 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; } } 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" ''' experimentUri = "" 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 Ejemplo: Sobrescritura de un encabezado de respuesta En el ejemplo siguiente, se muestra cómo cambiar el valor de un encabezado de respuesta según el valor de otro encabezado. Node.js export const handler = async (event) => { 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()] = [ { key: headerNameDst, value: headers[headerNameSrc.toLowerCase()][0].value, }]; console.log(`Response header "$ { headerNameDst}" was set to ` + `"$ { headers[headerNameDst.toLowerCase()][0].value}"`); } return response; }; Python import json def lambda_handler(event, context): response = event['Records'][0]['cf']['response'] headers = response['headers'] header_name_src = 'X-Amz-Meta-Last-Modified' header_name_dst = 'Last-Modified' if headers.get(header_name_src.lower()): headers[header_name_dst.lower()] = [ { 'key': header_name_dst, 'value': headers[header_name_src.lower()][0]['value'] }] print(f'Response header " { header_name_dst}" was set to ' f'" { headers[header_name_dst.lower()][0]["value"]}"') return response Generación de respuestas: ejemplos En los ejemplos siguientes se muestra cómo puede usar Lambda@Edge para generar respuestas. Temas Ejemplo: Envío de contenido estático (respuesta generada) Ejemplo: Generación de un redireccionamiento HTTP (respuesta generada) Ejemplo: Envío de contenido estático (respuesta generada) En el siguiente ejemplo se muestra cómo utilizar una función de Lambda para enviar contenido de sitio web estático, lo que reduce la carga en el servidor de origen y la latencia total. nota Puede generar respuestas HTTP para los eventos de solicitud del espectador y al origen. Para obtener más información, consulte Generación de respuestas HTTP en los desencadenadores de solicitud . También puede sustituir o quitar el cuerpo de la respuesta HTTP en eventos de respuesta de origen. Para obtener más información, consulte Actualización de respuestas HTTP en desencadenadores de respuesta de origen . 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' }] }, 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 } return response Ejemplo: Generación de un redireccionamiento HTTP (respuesta generada) En el siguiente ejemplo se muestra cómo generar una redirección HTTP. nota Puede generar respuestas HTTP para los eventos de solicitud del espectador y al origen. Para obtener más información, consulte Generación de respuestas HTTP en los desencadenadores de solicitud . 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. response = { 'status': '302', 'statusDescription': 'Found', 'headers': { 'location': [ { 'key': 'Location', 'value': 'https://docs.aws.amazon.com/lambda/latest/dg/lambda-edge.html' }] } } return response Cadenas de consulta: ejemplos En los ejemplos siguientes se muestran formas de usar Lambda@Edge con cadenas de consulta. Temas Ejemplo: Adición de un encabezado en función de un parámetro de la cadena de consulta Ejemplo: Normalización de parámetros de cadenas de consulta para mejorar la tasa de aciertos de caché Ejemplo: Redireccionamiento de los usuarios no autenticados a una página de inicio de sesión Ejemplo: Adición de un encabezado en función de un parámetro de la cadena de consulta El siguiente ejemplo muestra cómo obtener el par clave-valor de un parámetro de la cadena de consulta y, a continuación, añadir un encabezado en función de dichos valores. 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. * 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 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'] # Update request querystring request['querystring'] = urlencode(params) return request Ejemplo: Normalización de parámetros de cadenas de consulta para mejorar la tasa de aciertos de caché El siguiente ejemplo muestra cómo mejorar la tasa de acceso a la caché haciendo los siguientes cambios en las cadenas de consulta antes de que CloudFront reenvíe las solicitudes a su origen: Alfabetizar los pares de clave-valor por el nombre del parámetro. Cambiar a minúsculas el modelo de mayúsculas y minúsculas de los pares de clave-valor. Para obtener más información, consulte Almacenamiento en caché de contenido en función de parámetros de cadenas de consulta . 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 */ 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 request['querystring'] = urlencode(sortedParams) return request Ejemplo: Redireccionamiento de los usuarios no autenticados a una página de inicio de sesión El siguiente ejemplo muestra cómo redirigir a los usuarios una página de inicio de sesión si no ha introducido sus credenciales. 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; } /* 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 params. ''' # Check for session-id in cookie, if present, then proceed with request parsedCookies = parseCookies(headers) 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 Personalización de contenido por encabezados de tipo de dispositivo o país: ejemplos En los ejemplos siguientes se muestra cómo puede usar Lambda@Edge para personalizar el comportamiento en función de la ubicación o el tipo de dispositivo que usa el lector. Temas Ejemplo: Redireccionamiento de solicitudes de espectadores a una URL específica de un país Ejemplo: Envío de distintas versiones de un objeto en función del dispositivo Ejemplo: Redireccionamiento de solicitudes de espectadores a una URL específica de un país El siguiente ejemplo muestra cómo generar una respuesta de redireccionamiento HTTP con una URL específica del país y devolver la respuesta al espectador. Esto resulta útil cuando se quiere proporcionar respuestas específicas del país. Por ejemplo: Si tiene subdominios específicos de un país, como us.ejemplo.com y tw.ejemplo.com, puede generar una respuesta de redireccionamiento cuando un espectador solicite ejemplo.com. Si está haciendo streaming de video, pero no tiene derechos para transmitir el contenido en un país determinado, puede redirigir a los usuarios de dicho país a una página en la que se explica por qué no pueden ver el video. Tenga en cuenta lo siguiente: Debe configurar la distribución para almacenar en la caché en función del encabezado CloudFront-Viewer-Country . Para obtener más información, consulte Caché en función de encabezados de solicitud seleccionados . CloudFront agrega el encabezado CloudFront-Viewer-Country después del evento de solicitud del lector. Para utilizar este ejemplo, debe crear un activador para el evento de solicitud al origen. 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 = { 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', 'statusDescription': 'Found', 'headers': { 'location': [ { 'key': 'Location', 'value': url }] } } return response Ejemplo: Envío de distintas versiones de un objeto en función del dispositivo El siguiente ejemplo muestra cómo ofrecer distintas versiones de un objeto en función del tipo de dispositivo que el usuario está utilizando; por ejemplo, un dispositivo móvil o una tablet. Tenga en cuenta lo siguiente: Debe configurar la distribución para almacenar en la caché en función de los encabezados CloudFront-Is-*-Viewer . Para obtener más información, consulte Caché en función de encabezados de solicitud seleccionados . CloudFront agrega los encabezados CloudFront-Is-*-Viewer después del evento de solicitud del lector. Para utilizar este ejemplo, debe crear un activador para el evento de solicitud al origen. 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 * 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. ''' desktopPath = '/desktop'; mobilePath = '/mobile'; tabletPath = '/tablet'; smarttvPath = '/smarttv'; 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 Selección de origen dinámico basada en contenido: ejemplos En los ejemplos siguientes se muestra cómo puede usar Lambda@Edge para el direccionamiento a diferentes orígenes en función de la información de la solicitud. Temas Ejemplo: Uso de un desencadenador de solicitud de origen para cambiar desde un origen personalizado a un origen de Amazon S3 Ejemplo: Uso de un desencadenador de solicitud de origen para cambiar la región de origen de Amazon S3 Ejemplo: Uso de un desencadenador de solicitud de origen para cambiar desde un origen de Amazon S3 a un origen personalizado Ejemplo: Uso de un desencadenador de solicitud al origen para transferir gradualmente el tráfico desde un bucket de Amazon S3 a otro Ejemplo: Uso de un desencadenador de solicitud de origen para cambiar el nombre del dominio de origen en función del encabezado de país Ejemplo: Uso de un desencadenador de solicitud de origen para cambiar desde un origen personalizado a un origen de Amazon S3 Esta función demuestra cómo utilizar un desencadenador de solicitud al origen para cambiar desde un origen personalizado a un origen de Amazon S3 desde el que recuperar el contenido, en función de las propiedades de la solicitud. 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: 'origin-access-identity', path: '', customHeaders: { } } }; request.headers['host'] = [ { key: 'host', value: s3DomainName}]; } } 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 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': 'origin-access-identity', 'path': '', 'customHeaders': { } } } request['headers']['host'] = [ { 'key': 'host', 'value': s3DomainName}] return request Ejemplo: Uso de un desencadenador de solicitud de origen para cambiar la región de origen de Amazon S3 Esta función demuestra cómo utilizar un desencadenador de solicitud al origen para cambiar el origen de Amazon S3 desde el que se recupera el contenido, en función de las propiedades de la solicitud. En este ejemplo, utilizamos el valor del encabezado CloudFront-Viewer-Country para actualizar el nombre de dominio del bucket de S3 por un bucket de una región que está más cerca del lector. Esto puede resultar útil de varias maneras: Reduce las latencias cuando la región especificada está más cerca del país del lector. Proporciona soberanía de los datos, al asegurarse de que los datos se distribuyen desde un origen que está en el país del que provino la solicitud. Para utilizar este ejemplo, debe hacer lo siguiente: Configure la distribución para almacenar en la caché en función del encabezado CloudFront-Viewer-Country . Para obtener más información, consulte Caché en función de encabezados de solicitud seleccionados . Crear un disparador para esta función en el evento de solicitud al origen. CloudFront agrega el encabezado CloudFront-Viewer-Country después del evento de solicitud del lector; por lo tanto, para utilizar este ejemplo, debe asegurarse de que la función ejecuta una solicitud de origen. nota El siguiente código de ejemplo usa la misma identidad de acceso de origen (OAI) para todos los buckets de S3 que usa para el origen. Para obtener más información, consulte Identidad de acceso de origen . 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 * 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); }; Python 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: 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: ''' 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 Ejemplo: Uso de un desencadenador de solicitud de origen para cambiar desde un origen de Amazon S3 a un origen personalizado Esta función demuestra cómo utilizar un disparador de solicitud al origen para cambiar el origen personalizado desde el que se recupera el contenido, en función de las propiedades de la solicitud. 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: { 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': { } } } request['headers']['host'] = [ { 'key': 'host', 'value': 'www.example.com'}] return request Ejemplo: Uso de un desencadenador de solicitud al origen para transferir gradualmente el tráfico desde un bucket de Amazon S3 a otro Esta función demuestra cómo transferir gradualmente el tráfico desde un bucket de Amazon S3 a otro de forma controlada. 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}]; } 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 Ejemplo: Uso de un desencadenador de solicitud de origen para cambiar el nombre del dominio de origen en función del encabezado de país Esta función demuestra cómo cambiar el nombre del dominio de origen en función del encabezado CloudFront-Viewer-Country , de forma que el contenido se distribuya desde un origen más cercano al país del lector. La implementación de esta funcionalidad para su distribución puede tener ventajas como las siguientes: Reducir las latencias cuando la región especificada está más cerca del país del lector Proporcionar soberanía de los datos, al asegurarse de que los datos se distribuyen desde un origen que está en el país del que provino la solicitud Tenga en cuenta que para habilitar esta funcionalidad, debe configurar su distribución para almacenar en la caché en función del encabezado CloudFront-Viewer-Country . Para obtener más información, consulte Caché en función de encabezados de solicitud seleccionados . 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 request['headers']['host'] = [ { 'key': 'host', 'value': domainName}] return request Actualización de estados de error: ejemplos En los ejemplos siguientes se proporciona orientación acerca de cómo puede usar Lambda@Edge para cambiar el estado de error que se devuelve a los usuarios. Temas Ejemplo: Uso de un desencadenador de respuesta de origen para actualizar el código de estado de error a 200 Ejemplo: Uso de un desencadenador de respuesta de origen para actualizar el código de estado de error a 302 Ejemplo: Uso de un desencadenador de respuesta de origen para actualizar el código de estado de error a 200 Esta función demuestra cómo actualizar el estado de la respuesta a 200 y generar un cuerpo con contenido estático para devolverlo al espectador en la siguiente situación: La función se desencadena en una respuesta del origen. El estado de la respuesta del servidor de origen es un código de estado de error (4xx o 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'; } callback(null, response); }; Python 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 Ejemplo: Uso de un desencadenador de respuesta de origen para actualizar el código de estado de error a 302 Esta función demuestra cómo actualizar el código de estado HTTP a 302 para la redirección a otra ruta (comportamiento de la caché) en la que se ha configurado un origen diferente. Tenga en cuenta lo siguiente: La función se desencadena en una respuesta del origen. El estado de la respuesta del servidor de origen es un código de estado de error (4xx o 5xx). Node.js 'use strict'; exports.handler = (event, context, callback) => { const response = event.Records[0].cf.response; const 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 (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 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 Acceso al cuerpo de la solicitud: ejemplos En los ejemplos siguientes se muestra cómo puede usar Lambda@Edge para trabajar con las solicitudes POST. nota Para utilizar estos ejemplos, debe habilitar la opción incluir cuerpo en la asociación de funciones Lambda de la distribución. No está habilitada de forma predeterminada. Para habilitar esta configuración en la consola de CloudFront, seleccione la casilla de verificación Incluir cuerpo en la Asociación de funciones Lambda . Para habilitar esta configuración en la API de CloudFront o con CloudFormation, establezca el campo IncludeBody en true en LambdaFunctionAssociation . Temas Ejemplo: Uso de un desencadenador de solicitud para leer un formulario HTML Ejemplo: Uso de un desencadenador de solicitud para modificar un formulario HTML Ejemplo: Uso de un desencadenador de solicitud para leer un formulario HTML Esta función ilustra cómo puede procesar el cuerpo de una solicitud POST generada por un formulario HTML (formulario web), como por ejemplo un formulario tipo "póngase en contacto con nosotros". Por ejemplo, es posible que tenga un formulario HTML como el siguiente: <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> Para la función de ejemplo que se indica a continuación, la función se debe desencadenar en una solicitud al origen o del lector de CloudFront. 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 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 Ejemplo: Uso de un desencadenador de solicitud para modificar un formulario HTML Esta función ilustra cómo puede modificar el cuerpo de una solicitud POST generada por un formulario HTML (formulario web). La función se activa en una solicitud al origen o del lector de CloudFront. 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. * * 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'] | 2026-01-13T09:30:35 |
https://www.php.net/x-myracloud-5958a2bbbed300a9b9ac631223924e0b/1768296245.42 | PHP update page now Downloads Documentation Get Involved Help Search docs Getting Started Introduction A simple tutorial Language Reference Basic syntax Types Variables Constants Expressions Operators Control Structures Functions Classes and Objects Namespaces Enumerations Errors Exceptions Fibers Generators Attributes References Explained Predefined Variables Predefined Exceptions Predefined Interfaces and Classes Predefined Attributes Context options and parameters Supported Protocols and Wrappers Security Introduction General considerations Installed as CGI binary Installed as an Apache module Session Security Filesystem Security Database Security Error Reporting User Submitted Data Hiding PHP Keeping Current Features HTTP authentication with PHP Cookies Sessions Handling file uploads Using remote files Connection handling Persistent Database Connections Command line usage Garbage Collection DTrace Dynamic Tracing Function Reference Affecting PHP's Behaviour Audio Formats Manipulation Authentication Services Command Line Specific Extensions Compression and Archive Extensions Cryptography Extensions Database Extensions Date and Time Related Extensions File System Related Extensions Human Language and Character Encoding Support Image Processing and Generation Mail Related Extensions Mathematical Extensions Non-Text MIME Output Process Control Extensions Other Basic Extensions Other Services Search Engine Extensions Server Specific Extensions Session Extensions Text Processing Variable and Type Related Extensions Web Services Windows Only Extensions XML Manipulation GUI Extensions Keyboard Shortcuts ? This help j Next menu item k Previous menu item g p Previous man page g n Next man page G Scroll to bottom g g Scroll to top g h Goto homepage g s Goto search (current page) / Focus search box A popular general-purpose scripting language that is especially suited to web development. Fast, flexible and pragmatic, PHP powers everything from your blog to the most popular websites in the world. What's new in 8.5 Download 8.5.1 · Changelog · Upgrading 8.4.16 · Changelog · Upgrading 8.3.29 · Changelog · Upgrading 8.2.30 · Changelog · Upgrading 18 Dec 2025 PHP 8.1.34 Released! The PHP development team announces the immediate availability of PHP 8.1.34. This is a security release. All PHP 8.1 users are encouraged to upgrade to this version. For source downloads of PHP 8.1.34 please visit our downloads page , Windows source and binaries can also be found there . The list of changes is recorded in the ChangeLog . 18 Dec 2025 PHP 8.4.16 Released! The PHP development team announces the immediate availability of PHP 8.4.16. This is a security release. All PHP 8.4 users are encouraged to upgrade to this version. For source downloads of PHP 8.4.16 please visit our downloads page , Windows source and binaries can also be found there . The list of changes is recorded in the ChangeLog . 18 Dec 2025 PHP 8.2.30 Released! The PHP development team announces the immediate availability of PHP 8.2.30. This is a security release. All PHP 8.2 users are encouraged to upgrade to this version. For source downloads of PHP 8.2.30 please visit our downloads page , Windows source and binaries can also be found there . The list of changes is recorded in the ChangeLog . 18 Dec 2025 PHP 8.3.29 Released! The PHP development team announces the immediate availability of PHP 8.3.29. This is a security release. All PHP 8.3 users are encouraged to upgrade to this version. For source downloads of PHP 8.3.29 please visit our downloads page , Windows source and binaries can also be found there . The list of changes is recorded in the ChangeLog . 18 Dec 2025 PHP 8.5.1 Released! The PHP development team announces the immediate availability of PHP 8.5.1. This is a security release. All PHP 8.5 users are encouraged to upgrade to this version. For source downloads of PHP 8.5.1 please visit our downloads page , Windows source and binaries can also be found there . The list of changes is recorded in the ChangeLog . 20 Nov 2025 PHP 8.5.0 Released! The PHP development team announces the immediate availability of PHP 8.5.0. This release marks the latest minor release of the PHP language. PHP 8.5 comes with numerous improvements and new features such as: New "URI" extension New pipe operator (|>) Clone With New #[\NoDiscard] attribute Support for closures, casts, and first class callables in constant expressions And much much more... For source downloads of PHP 8.5.0 please visit our downloads page , Windows source and binaries can also be found there . The list of changes is recorded in the ChangeLog . The migration guide is available in the PHP Manual. Please consult it for the detailed list of new features and backward incompatible changes. Kudos to all the contributors and supporters! 20 Nov 2025 PHP 8.4.15 Released! The PHP development team announces the immediate availability of PHP 8.4.15. This is a bug fix release. All PHP 8.4 users are encouraged to upgrade to this version. For source downloads of PHP 8.4.15 please visit our downloads page , Windows source and binaries can also be found there . The list of changes is recorded in the ChangeLog . 20 Nov 2025 PHP 8.3.28 Released! The PHP development team announces the immediate availability of PHP 8.3.28. This is a bug fix release. All PHP 8.3 users are encouraged to upgrade to this version. For source downloads of PHP 8.3.28 please visit our downloads page , Windows source and binaries can also be found there . The list of changes is recorded in the ChangeLog . 13 Nov 2025 PHP 8.5.0 RC 5 available for testing The PHP team is pleased to announce the fifth release candidate of PHP 8.5.0, RC 5. This continues the PHP 8.5 release cycle, the rough outline of which is specified in the PHP Wiki . For source downloads of PHP 8.5.0 RC5, please visit the download page . Please carefully test this version and report any issues found on GitHub . Please DO NOT use this version in production, it is a test version. For more information on the new features and other changes, you can read the NEWS file, or the UPGRADING file for a complete list of upgrading notes. These files can also be found in the release archive. The next release will be the GA release of PHP 8.5.0, planned for 20 Nov 2025. The signatures for the release can be found in the manifest or on the Release Candidates page . Thank you for helping us make PHP better. 06 Nov 2025 PHP 8.5.0 RC4 available for testing The PHP team is pleased to announce the final planned release candidate of PHP 8.5.0, RC 4. This continues the PHP 8.5 release cycle, the rough outline of which is specified in the PHP Wiki . For source downloads of PHP 8.5.0 RC4, please visit the download page . Please carefully test this version and report any issues found on GitHub . Please DO NOT use this version in production, it is a test version. For more information on the new features and other changes, you can read the NEWS file, or the UPGRADING file for a complete list of upgrading notes. These files can also be found in the release archive. The next release will be the GA release of PHP 8.5.0, planned for 20 Nov 2025. The signatures for the release can be found in the manifest or on the Release Candidates page . Thank you for helping us make PHP better. 23 Oct 2025 PHP 8.3.27 Released! The PHP development team announces the immediate availability of PHP 8.3.27. This is a bug fix release. All PHP 8.3 users are encouraged to upgrade to this version. For source downloads of PHP 8.3.27 please visit our downloads page , Windows source and binaries can be found on windows.php.net/download/ . The list of changes is recorded in the ChangeLog . 23 Oct 2025 PHP 8.4.14 Released! The PHP development team announces the immediate availability of PHP 8.4.14. This is a bug fix release. All PHP 8.4 users are encouraged to upgrade to this version. For source downloads of PHP 8.4.14 please visit our downloads page , Windows source and binaries can be found on windows.php.net/download/ . The list of changes is recorded in the ChangeLog . 23 Oct 2025 PHP 8.5.0 RC 3 available for testing The PHP team is pleased to announce the third release candidate of PHP 8.5.0, RC 3. This continues the PHP 8.5 release cycle, the rough outline of which is specified in the PHP Wiki . For source downloads of PHP 8.5.0 RC3, please visit the download page . Please carefully test this version and report any issues found on GitHub . Please DO NOT use this version in production, it is an early test version. For more information on the new features and other changes, you can read the NEWS file, or the UPGRADING file for a complete list of upgrading notes. These files can also be found in the release archive. The next release will be RC4, planned for 6 Nov 2025. The signatures for the release can be found in the manifest or on the Release Candidates page . Thank you for helping us make PHP better. 09 Oct 2025 PHP 8.5.0 RC 2 available for testing The PHP team is pleased to announce the second release candidate of PHP 8.5.0, RC 2. This continues the PHP 8.5 release cycle, the rough outline of which is specified in the PHP Wiki . For source downloads of PHP 8.5.0 RC2, please visit the download page . Please carefully test this version and report any issues found on GitHub . Please DO NOT use this version in production, it is an early test version. For more information on the new features and other changes, you can read the NEWS file, or the UPGRADING file for a complete list of upgrading notes. These files can also be found in the release archive. The next release will be RC3, planned for 23 Oct 2025. The signatures for the release can be found in the manifest or on the Release Candidates page . Thank you for helping us make PHP better. 25 Sep 2025 PHP 8.5.0 RC 1 available for testing The PHP team is pleased to announce the first release candidate of PHP 8.5.0, RC 1. This continues the PHP 8.5 release cycle, the rough outline of which is specified in the PHP Wiki . For source downloads of PHP 8.5.0 RC1, please visit the download page . Please carefully test this version and report any issues found on GitHub . Please DO NOT use this version in production, it is an early test version. For more information on the new features and other changes, you can read the NEWS file, or the UPGRADING file for a complete list of upgrading notes. These files can also be found in the release archive. The next release will be RC2, planned for 9 Oct 2025. The signatures for the release can be found in the manifest or on the Release Candidates page . Thank you for helping us make PHP better. 25 Sep 2025 PHP 8.3.26 Released! The PHP development team announces the immediate availability of PHP 8.3.26. This is a bug fix release. All PHP 8.3 users are encouraged to upgrade to this version. For source downloads of PHP 8.3.26 please visit our downloads page , Windows source and binaries can be found on windows.php.net/download/ . The list of changes is recorded in the ChangeLog . 25 Sep 2025 PHP 8.4.13 Released! The PHP development team announces the immediate availability of PHP 8.4.13. This is a bug fix release. All PHP 8.4 users are encouraged to upgrade to this version. For source downloads of PHP 8.4.13 please visit our downloads page , Windows source and binaries can be found on windows.php.net/download/ . The list of changes is recorded in the ChangeLog . 11 Sep 2025 PHP 8.5.0 Beta 3 available for testing The PHP team is pleased to announce the third beta release of PHP 8.5.0, Beta 3. This continues the PHP 8.5 release cycle, the rough outline of which is specified in the PHP Wiki . For source downloads of PHP 8.5.0 Beta 3, please visit the download page . Please carefully test this version and report any issues found on GitHub . Please DO NOT use this version in production, it is an early test version. For more information on the new features and other changes, you can read the NEWS file, or the UPGRADING file for a complete list of upgrading notes. These files can also be found in the release archive. The next release will be RC1, planned for 25 Sep 2025. The signatures for the release can be found in the manifest or on the Release Candidates page . Thank you for helping us make PHP better. 28 Aug 2025 PHP 8.5.0 Beta 2 available for testing The PHP team is pleased to announce the second beta release of PHP 8.5.0, Beta 2. This continues the PHP 8.5 release cycle, the rough outline of which is specified in the PHP Wiki . For source downloads of PHP 8.5.0 Beta 2 please visit the download page . Please carefully test this version and report any issues found on GitHub . Please DO NOT use this version in production, it is an early test version. For more information on the new features and other changes, you can read the NEWS file, or the UPGRADING file for a complete list of upgrading notes. These files can also be found in the release archive. The next release will be Beta 3, planned for 11 Sep 2025. The signatures for the release can be found in the manifest or on the Release Candidates page . Thank you for helping us make PHP better. 28 Aug 2025 PHP 8.3.25 Released! The PHP development team announces the immediate availability of PHP 8.3.25. This is a bug fix release. All PHP 8.3 users are encouraged to upgrade to this version. For source downloads of PHP 8.3.25 please visit our downloads page , Windows source and binaries can be found on windows.php.net/download/ . The list of changes is recorded in the ChangeLog . 28 Aug 2025 PHP 8.4.12 Released! The PHP development team announces the immediate availability of PHP 8.4.12. This is a bug fix release. All PHP 8.4 users are encouraged to upgrade to this version. For source downloads of PHP 8.4.12 please visit our downloads page , Windows source and binaries can be found on windows.php.net/download/ . The list of changes is recorded in the ChangeLog . 14 Aug 2025 PHP 8.5.0 Beta 1 available for testing The PHP team is pleased to announce the first beta release of PHP 8.5.0, Beta 1. This continues the PHP 8.5 release cycle, the rough outline of which is specified in the PHP Wiki . For source downloads of PHP 8.5.0 Beta 1 please visit the download page . Please carefully test this version and report any issues found on GitHub . Please DO NOT use this version in production, it is an early test version. For more information on the new features and other changes, you can read the NEWS file, or the UPGRADING file for a complete list of upgrading notes. These files can also be found in the release archive. The next release will be Beta 2, planned for 28 Aug 2025. The signatures for the release can be found in the manifest or on the Release Candidates page . Thank you for helping us make PHP better. 01 Aug 2025 PHP 8.5.0 Alpha 4 available for testing The PHP team is pleased to announce the third testing release of PHP 8.5.0, Alpha 4. This continues the PHP 8.5 release cycle, the rough outline of which is specified in the PHP Wiki . For source downloads of PHP 8.5.0 Alpha 4 please visit the download page . Please carefully test this version and report any issues found on GitHub . Please DO NOT use this version in production, it is an early test version. For more information on the new features and other changes, you can read the NEWS file, or the UPGRADING file for a complete list of upgrading notes. These files can also be found in the release archive. The next release will be Beta 1, planned for 14 Aug 2025. The signatures for the release can be found in the manifest or on the Release Candidates page . Thank you for helping us make PHP better. 31 Jul 2025 PHP 8.4.11 Released! The PHP development team announces the immediate availability of PHP 8.4.11. This is a bug fix release. All PHP 8.4 users are encouraged to upgrade to this version. For source downloads of PHP 8.4.11 please visit our downloads page , Windows source and binaries can be found on windows.php.net/download/ . The list of changes is recorded in the ChangeLog . 31 Jul 2025 PHP 8.3.24 Released! The PHP development team announces the immediate availability of PHP 8.3.24. This is a bug fix release. All PHP 8.3 users are encouraged to upgrade to this version. For source downloads of PHP 8.3.24 please visit our downloads page , Windows source and binaries can be found on windows.php.net/download/ . The list of changes is recorded in the ChangeLog . Older News Entries The PHP Foundation The PHP Foundation is a collective of people and organizations, united in the mission to ensure the long-term prosperity of the PHP language. Donate Upcoming conferences International PHP Conference Berlin 2026 Laravel Live Japan Conferences calling for papers Dutch PHP Conference 2026 User Group Events Special Thanks Social media @official_php @php@fosstodon.org @phpnet Copyright © 2001-2026 The PHP Group My PHP.net Contact Other PHP.net sites Privacy policy View Source ↑ and ↓ to navigate • Enter to select • Esc to close • / to open Press Enter without selection to search using Google | 2026-01-13T09:30:35 |
https://support.microsoft.com/ko-kr/windows/microsoft-edge%EC%97%90%EC%84%9C-%EC%BF%A0%ED%82%A4-%EA%B4%80%EB%A6%AC-%EB%B3%B4%EA%B8%B0-%ED%97%88%EC%9A%A9-%EC%B0%A8%EB%8B%A8-%EC%82%AD%EC%A0%9C-%EB%B0%8F-%EC%82%AC%EC%9A%A9-168dab11-0753-043d-7c16-ede5947fc64d | Microsoft Edge에서 쿠키 관리: 보기, 허용, 차단, 삭제 및 사용 - Microsoft 지원 관련 주제 × Windows 보안, 안전 및 개인 정보 개요 보안, 안전 및 개인 정보 개요 Windows 보안 Windows 보안에 대한 도움말 보기 Windows 보안으로 보호 유지 Xbox 또는 Windows PC 재활용, 판매 또는 선물하기 전에 Windows PC에서 맬웨어 제거 Windows 안전 Windows 안전에 대한 도움말 보기 Microsoft Edge에서 브라우저 기록 보기 및 삭제 쿠키 삭제 및 관리 Windows를 다시 설치할 때 중요한 콘텐츠를 안전하게 제거 분실한 Windows 장치 찾기 및 잠금 Windows 개인 정보 보호 Windows 개인 정보 보호에 대한 도움말 보기 앱에서 사용하는 Windows 개인 정보 설정 개인 정보 대시보드에서 사용자 데이터 보기 주 콘텐츠로 건너뛰기 Microsoft 고객 지원 고객 지원 고객 지원 홈 Microsoft 365 Office 제품 Microsoft 365 Outlook Microsoft Teams OneDrive Microsoft Copilot OneNote Windows 기타... 장치 Surface PC 액세서리 Xbox PC 게임 HoloLens Surface Hub 하드웨어 보증 계정 및 청구 계정 Microsoft Store & 청구 리소스 새로운 기능 커뮤니티 포럼 Microsoft 365 관리자 소규모 비즈니스 포털 개발자 교육 지원 사기 보고 제품 안전 자세히 Microsoft 365 구입 Microsoft 전체 Global Microsoft 365 Teams Copilot Windows Surface Xbox 세일 지원 소프트웨어 소프트웨어 Windows 앱 AI OneDrive Outlook Skype에서 Teams로 이동 중 OneNote Microsoft Teams PC 및 장치 PC 및 장치 Xbox 쇼핑 주변 기기 엔터테인먼트 엔터테인먼트 Xbox Game Pass Ultimate Xbox 및 게임 PC 게임 기업 고객용 기업 고객용 Microsoft Security Azure Dynamics 365 비즈니스용 Microsoft 365 Microsoft Industry Microsoft Power Platform Windows 365 개발자 및 IT 개발자 및 IT Microsoft 개발자 Microsoft Learn AI 마켓플레이스 앱 지원 Microsoft Tech 커뮤니티 Microsoft Marketplace Visual Studio Marketplace Rewards 기타 기타 무료 다운로드 및 보안 교육 볼륨 라이선싱 사이트맵 보기 검색 도움말 검색 결과 없음 취소 로그인 Microsoft로 로그인 로그인하거나 계정을 만듭니다. 안녕하세요. 다른 계정을 선택합니다. 계정이 여러 개 있음 로그인할 계정을 선택합니다. 관련 주제 Windows 보안, 안전 및 개인 정보 개요 보안, 안전 및 개인 정보 개요 Windows 보안 Windows 보안에 대한 도움말 보기 Windows 보안으로 보호 유지 Xbox 또는 Windows PC 재활용, 판매 또는 선물하기 전에 Windows PC에서 맬웨어 제거 Windows 안전 Windows 안전에 대한 도움말 보기 Microsoft Edge에서 브라우저 기록 보기 및 삭제 쿠키 삭제 및 관리 Windows를 다시 설치할 때 중요한 콘텐츠를 안전하게 제거 분실한 Windows 장치 찾기 및 잠금 Windows 개인 정보 보호 Windows 개인 정보 보호에 대한 도움말 보기 앱에서 사용하는 Windows 개인 정보 설정 개인 정보 대시보드에서 사용자 데이터 보기 Microsoft Edge에서 쿠키 관리: 보기, 허용, 차단, 삭제 및 사용 적용 대상 Windows 10 Windows 11 Microsoft Edge 쿠키는 방문하는 웹 사이트에서 디바이스에 저장된 작은 데이터 조각입니다. 로그인 자격 증명 기억, 사이트 기본 설정, 사용자 동작 추적 등 다양한 용도로 사용됩니다. 그러나 개인 정보 보호를 위해 쿠키를 삭제하거나 검색 문제를 resolve 수 있습니다. 이 문서에서는 다음 방법에 대한 지침을 제공합니다. 모든 쿠키 보기 모든 쿠키 허용 특정 웹 사이트에서 쿠키 허용 타사 쿠키 차단 모든 쿠키 차단은 특정 사이트에서 쿠키 차단 모든 쿠키 삭제 특정 사이트에서 쿠키 삭제 브라우저를 닫을 때마다 쿠키 삭제 쿠키를 사용하여 더 빠른 검색을 위해 페이지를 미리 로드합니다. 모든 쿠키 보기 Edge 브라우저를 열고 브라우저 창의 오른쪽 위 모서리에서 설정 등을 선택합니다. 설정 > 개인 정보, 검색 및 서비스를 선택합니다. 쿠키를 선택한 다음 모든 쿠키 및 사이트 데이터 보기를 클릭하여 저장된 모든 쿠키 및 관련 사이트 정보를 확인합니다. 모든 쿠키 허용 쿠키를 허용하면 웹 사이트에서 브라우저에서 데이터를 저장하고 검색할 수 있으므로 기본 설정 및 로그인 정보를 기억하여 검색 환경을 향상시킬 수 있습니다. Edge 브라우저를 열고 브라우저 창의 오른쪽 위 모서리에서 설정 등을 선택합니다. 설정 > 개인 정보, 검색 및 서비스를 선택합니다. 쿠키를 선택하고 모든 쿠키를 허용 하도록 사이트에서 쿠키 데이터를 저장하고 읽을 수 있도록 허용(권장) 토글을 사용하도록 설정합니다. 특정 사이트에서 쿠키 허용 쿠키를 허용하면 웹 사이트에서 브라우저에서 데이터를 저장하고 검색할 수 있으므로 기본 설정 및 로그인 정보를 기억하여 검색 환경을 향상시킬 수 있습니다. Edge 브라우저를 열고 브라우저 창의 오른쪽 위 모서리에서 설정 등을 선택합니다. 설정 > 개인 정보, 검색 및 서비스를 선택합니다. 쿠키를 선택하고 허용됨으로 이동하여 쿠키를 저장합니다. 사이트 추가 를 선택하여 사이트의 URL을 입력하여 사이트별로 쿠키를 허용합니다. 타사 쿠키 차단 타사 사이트에서 PC에 쿠키를 저장하지 않으려면 쿠키를 차단할 수 있습니다. 그러나 쿠키를 차단하면 일부 페이지가 올바르게 표시되지 않거나 사이트를 보려면 쿠키를 허용해야 한다는 메시지가 표시될 수 있습니다. Edge 브라우저를 열고 브라우저 창의 오른쪽 위 모서리에서 설정 등을 선택합니다. 설정 > 개인 정보, 검색 및 서비스를 선택합니다. 쿠키를 선택하고 타사 쿠키 차단 토글을 사용하도록 설정합니다. 모든 쿠키 차단은 타사 사이트에서 PC에 쿠키를 저장하지 않으려면 쿠키를 차단할 수 있습니다. 그러나 쿠키를 차단하면 일부 페이지가 올바르게 표시되지 않거나 사이트를 보려면 쿠키를 허용해야 한다는 메시지가 표시될 수 있습니다. Edge 브라우저를 열고 브라우저 창의 오른쪽 위 모서리에서 설정 등을 선택합니다. 설정 > 개인 정보, 검색 및 서비스를 선택합니다. 쿠키를 선택하고 사이트에서 쿠키 데이터를 저장하고 읽을 수 있도록 허용(권장) 을 사용하지 않도록 설정하여 모든 쿠키를 차단합니다. 특정 사이트에서 쿠키 차단 Microsoft Edge를 사용하면 특정 사이트의 쿠키를 차단할 수 있지만 이렇게 하면 일부 페이지가 올바르게 표시되지 않거나 쿠키가 해당 사이트를 볼 수 있도록 허용해야 한다는 메시지가 사이트에서 수신될 수 있습니다. 특정 사이트에서 쿠키를 차단하려면 다음을 수행합니다. Edge 브라우저를 열고 브라우저 창의 오른쪽 위 모서리에서 설정 등을 선택합니다. 설정 > 개인 정보, 검색 및 서비스를 선택합니다. 쿠키를 선택하고 쿠키를 저장하고 읽을 수 없음으로 이동합니다. 사이트 추가 를 선택하여 사이트의 URL을 입력하여 사이트별로 쿠키를 차단합니다. 모든 쿠키 삭제 Edge 브라우저를 열고 브라우저 창의 오른쪽 위 모서리에서 설정 등을 선택합니다. 설정 > 개인 정보, 검색 및 서비스 를 선택합니다. 검색 데이터 지우기를 선택한 다음, 지금 검색 데이터 지우 기 옆에 있는 선택을 선택합니다 . 시간 범위 의 목록에서 시간 범위를 선택합니다. 쿠키 및 기타 사이트 데이터 를 선택한 다음 지금 지우기 를 선택합니다. 참고: 또는 Ctrl + Shift + DELETE 를 함께 누 른 다음 4단계와 5단계를 진행하여 쿠키를 삭제할 수 있습니다. 이제 선택한 시간 범위에 대한 모든 쿠키 및 기타 사이트 데이터가 삭제됩니다. 대부분의 사이트에서 로그아웃됩니다. 특정 사이트에서 쿠키 삭제 Edge 브라우저를 열고 설정 및 기타 > 설정 > 개인 정보, 검색 및 서비스를 선택합니다. 쿠키를 선택한 다음 모든 쿠키 및 사이트 데이터 보기를 클릭하고 쿠키를 삭제하려는 사이트를 검색합니다. 삭제하려는 쿠키가 있는 사이트 오른쪽에 있는 아래쪽 화살표 를 선택하고 삭제 를 선택합니다. 선택한 사이트의 쿠키는 이제 삭제됩니다. 쿠키를 삭제하려는 모든 사이트에 대해 이 단계를 반복합니다. 브라우저를 닫을 때마다 쿠키 삭제 Edge 브라우저를 열고 설정 및 기타 > 설정 > 개인 정보, 검색 및 서비스를 선택합니다. 검색 데이터 지우기를 선택한 다음 브라우저를 닫을 때마다 지울 항목 선택을 선택합니다. 쿠키 및 기타 사이트 데이터 토글을 켭니다. 이 기능이 켜지면 Edge 브라우저를 닫을 때마다 모든 쿠키 및 기타 사이트 데이터가 삭제됩니다. 대부분의 사이트에서 로그아웃됩니다. 쿠키를 사용하여 더 빠른 검색을 위해 페이지를 미리 로드합니다. Edge 브라우저를 열고 브라우저 창의 오른쪽 위 모서리에서 설정 등을 선택합니다. 설정 > 개인 정보, 검색 및 서비스 를 선택합니다. 쿠키를 선택하고 빠른 검색 및 검색을 위해 페이지 미리 로드 토글을 사용하도록 설정합니다. RSS 피드 구독 도움이 더 필요하세요? 더 많은 옵션을 원하세요? 검색 커뮤니티 문의 구독 혜택을 살펴보고, 교육 과정을 찾아보고, 디바이스를 보호하는 방법 등을 알아봅니다. Microsoft 365 구독 혜택 Microsoft 365 교육 Microsoft 보안 접근성 센터 커뮤니티를 통해 질문하고 답변하고, 피드백을 제공하고, 풍부한 지식을 갖춘 전문가의 의견을 들을 수 있습니다. Microsoft 커뮤니티에 질문하기 Microsoft Tech Community Windows 참가자 Microsoft 365 참가자 일반적인 문제에 대한 해결 방법을 찾거나 지원 에이전트로부터 도움을 받으세요. 온라인 지원 이 정보가 유용한가요? 예 아니요 감사합니다. Microsoft에 대한 피드백이 더 있으신가요? 사용자 환경 개선에 도움을 주시겠어요? (Microsoft에 피드백을 보내 주시면 도움을 드리겠습니다.) 언어 품질에 얼마나 만족하시나요? 사용 경험에 어떠한 영향을 주었나요? 문제가 해결됨 지침이 명확함 이해하기 쉬움 전문 용어가 없음 그림이 도움이 됨 번역 품질 내 화면과 일치하지 않음 지침이 잘못됨 너무 기술적임 정보가 부족함 그림이 부족함 번역 품질 추가 피드백이 있으신가요? (선택 사항) 피드백 제출 제출을 누르면 피드백이 Microsoft 제품과 서비스를 개선하는 데 사용됩니다. IT 관리자는 이 데이터를 수집할 수 있습니다. 개인정보처리방침 의견 주셔서 감사합니다! × 새로운 기능 Surface Pro Surface Laptop 조직용 Copilot 개인 사용자용 Copilot Microsoft 365 Microsoft 제품 살펴보기 Windows 11 앱 Microsoft Store 계정 프로필 다운로드 센터 Microsoft Store 지원 반품/환불 주문 조회 교육 Microsoft Education 교육용 장치 교육용 Microsoft Teams Microsoft 365 Education Office Education 교육자 트레이닝 및 개발 학생 및 학부모용 특가 혜택 Azure for students 기업 고객 Microsoft Security Azure Dynamics 365 Microsoft 365 Microsoft Advertising Microsoft 365 Copilot Microsoft Teams 개발자 및 IT Microsoft 개발자 Microsoft Learn AI 마켓플레이스 앱 지원 Microsoft Tech 커뮤니티 Microsoft Marketplace Microsoft Power Platform Marketplace Rewards Visual Studio 회사 채용 정보 Microsoft 정보 회사 뉴스 Microsoft 개인 정보 보호 투자자 지속 가능성 한국어(대한민국) 개인정보처리방침 선택 옵트아웃 아이콘 개인 정보 선택 사항 개인정보처리방침 선택 옵트아웃 아이콘 개인 정보 선택 사항 소비자 상태 개인정보처리방침 Microsoft에 문의 개인정보처리방침 및 위치정보이용약관 쿠키 관리 사용약관 상표 광고 정보 © Microsoft 2026 한국마이크로소프트(유) 대표이사: 조원우 주소: (우)110-150 서울 종로구 종로1길 50 더 케이트윈타워 A동 12층 전화번호: 02-531-4500, 메일: ms-korea@microsoft.com 사업자등록번호: 120-81-05948 사업자정보확인 호스팅서비스 제공자: Microsoft Corporation 통신판매신고: 제2013-서울종로-1009호 사이버몰의 이용약관: Microsoft Store 판매 약관 | 2026-01-13T09:30:35 |
https://aws.amazon.com/eventbridge/resources/#Documentation | Amazon EventBridge Resources | Event Bus | Amazon Web Services Skip to main content Filter: All English Contact us AWS Marketplace Support My account Search Filter: All Sign in to console Create account Application Integration › Amazon EventBridge › Resources Amazon EventBridge resources Webinars How to use Amazon EventBridge to build decoupled, event-driven architectures | Video series In this learning path, you will get an overview of EventBridge, the basics of event-driven architectures, a deeper dive into EventBridge capabilities, and how best to use it in your serverless applications. Watch the video Amazon EventBridge Deep Dive | (50:22) In this webinar, we'll cover all things EventBridge, including how events flow from internal and external applications through EventBridge, and how you can use rules and policies to route, transform, and control access to these events. Watch the video Amazon EventBridge Overview Features Pricing Resources FAQs More Videos How To Get Started With Amazon EventBridge (8:58) Play How To Set Up A Custom Event Bus With Amazon EventBridge (7:42) Play How to Use Amazon EventBridge Schema Registry (11:24) Play Amazon EventBridge: Integrating with Zendesk (11:01) Play Amazon EventBridge: Integrating with Auth0 (7:09) Play Amazon EventBridge: Integrating with PagerDuty (7:34) Play AWS New York Summit 2019: Intro to Event-driven Architectures and Amazon EventBridge (51:38) Play Documentation User Guide Key concepts, tutorials, and instructions for using features Learn more Amazon EventBridge section of AWS CLI Reference How to use EventBridge from the AWS CLI Learn more API Reference How to use the EventBridge API, including actions and data types Learn more What's new Loading Loading Loading Loading Loading Featured blog Amazon EventBridge – Event-Driven AWS Integration for your SaaS Applications Jeff Barr | July 11, 2019 Learn more Other blogs Loading Loading Loading Loading Loading Customer testimonials Hudson In late 2019, Hudson , a leader in recruitment and talent management, announced the release of JobAccelerator. JobAccelerator is an SaaS application, built using contemporary event-driven architectures powered by AWS serverless and data lake technologies ( Amazon EventBridge , AWS Step Functions orchestration, AWS Lambda , Amazon Simple Storage Service (Amazon S3), AWS Glue , and Amazon Athena ). Amazon EventBridge, the backbone of JobAccelerator, drives microservice communication between AWS services and integrates seamlessly with third-party products, such as authentication and messaging services. Through the adoption of Amazon EventBridge, JobAccelerator was able to scale ten-fold in a short period of time—going from an average of 5,000 events per month in late 2019 to an average of 50,000 events in early 2021 in a highly cost effective manner—resulting in hundreds of thousands of dollars saved annually. Through low-code development, Amazon EventBridge has also enabled the JobAccelerator development team to deliver new features in a timely fashion to a highly competitive market. JobAccelerator is currently trusted by many Fortune 500 companies in Asia Pacific and Oceania regions, empowering tens of thousands of outplaced employees to secure their next roles through coaching and job-seeking experiences. "By using services such as Amazon EventBridge, Hudson has created a highly scalable and cost effective technology that helps job seekers build their perfect resume, refine their job search, track their job activity, get better job recommendations, and secure their next role quicker. It has allowed us to bring a product to market that services both ASX100 companies and individuals in under three months." Dino Talic, Co-Founder and CPO, JobAccelerator, Hudson Get started FAQs Visit the Amazon EventBridge FAQs page Learn more Console Get started building with Amazon EventBridge in the AWS Management Console Sign in Documentation Get a deeper understanding of Amazon EventBridge in the Developer Guide Learn more Did you find what you were looking for today? Let us know so we can improve the quality of the content on our pages Yes No Create an AWS account Learn What Is AWS? What Is Cloud Computing? What Is Agentic AI? Cloud Computing Concepts Hub AWS Cloud Security What's New Blogs Press Releases Resources Getting Started Training AWS Trust Center AWS Solutions Library Architecture Center Product and Technical FAQs Analyst Reports AWS Partners Developers Builder Center SDKs & Tools .NET on AWS Python on AWS Java on AWS PHP on AWS JavaScript on AWS Help Contact Us File a Support Ticket AWS re:Post Knowledge Center AWS Support Overview Get Expert Help AWS Accessibility Legal English Back to top Amazon is an Equal Opportunity Employer: Minority / Women / Disability / Veteran / Gender Identity / Sexual Orientation / Age. x facebook linkedin instagram twitch youtube podcasts email Privacy Site terms Cookie Preferences © 2026, Amazon Web Services, Inc. or its affiliates. All rights reserved. | 2026-01-13T09:30:35 |
https://www.php.net/manual/it/book.bc.php | PHP: BC Math - Manual update page now Downloads Documentation Get Involved Help Search docs Getting Started Introduction A simple tutorial Language Reference Basic syntax Types Variables Constants Expressions Operators Control Structures Functions Classes and Objects Namespaces Enumerations Errors Exceptions Fibers Generators Attributes References Explained Predefined Variables Predefined Exceptions Predefined Interfaces and Classes Predefined Attributes Context options and parameters Supported Protocols and Wrappers Security Introduction General considerations Installed as CGI binary Installed as an Apache module Session Security Filesystem Security Database Security Error Reporting User Submitted Data Hiding PHP Keeping Current Features HTTP authentication with PHP Cookies Sessions Handling file uploads Using remote files Connection handling Persistent Database Connections Command line usage Garbage Collection DTrace Dynamic Tracing Function Reference Affecting PHP's Behaviour Audio Formats Manipulation Authentication Services Command Line Specific Extensions Compression and Archive Extensions Cryptography Extensions Database Extensions Date and Time Related Extensions File System Related Extensions Human Language and Character Encoding Support Image Processing and Generation Mail Related Extensions Mathematical Extensions Non-Text MIME Output Process Control Extensions Other Basic Extensions Other Services Search Engine Extensions Server Specific Extensions Session Extensions Text Processing Variable and Type Related Extensions Web Services Windows Only Extensions XML Manipulation GUI Extensions Keyboard Shortcuts ? This help j Next menu item k Previous menu item g p Previous man page g n Next man page G Scroll to bottom g g Scroll to top g h Goto homepage g s Goto search (current page) / Focus search box Introduzione » « Estensioni matematiche Manuale PHP Guida Funzioni Estensioni matematiche Change language: English German Spanish French Italian Japanese Brazilian Portuguese Russian Turkish Ukrainian Chinese (Simplified) Other Matematica di Precisione Arbitraria BCMath Introduzione Installazione/Configurazione Requisiti Installazione Configurazione di Runtime Tipi di risorse Costanti predefinite Funzioni BC Math bcadd — Somma due numeri a precisione arbitraria bcceil — Round up arbitrary precision number bccomp — Confronta due numeri a precisione arbitraria bcdiv — Divide due numeri a precisione arbitraria bcdivmod — Get the quotient and modulus of an arbitrary precision number bcfloor — Round down arbitrary precision number bcmod — Ricava il modulo di un numero a precisione arbitraria bcmul — Moltiplica due numeri a precisione arbitraria bcpow — Effettua l'elevamento a potenza bcpowmod — Effettua l'elevamento a potenza, applicando quindi il modulo bcround — Round arbitrary precision number bcscale — Imposta il valore di precisione di default per tutte le funzioni matematich BCMath bcsqrt — Ottiene la radice quadrata di un numero a precisione arbitraria bcsub — Sottrae un numero a precisione arbitraria da un altro Found A Problem? Learn How To Improve This Page • Submit a Pull Request • Report a Bug + add a note User Contributed Notes 3 notes up down 75 Hayley Watson ¶ 10 years ago This extension is an interface to the GNU implementation as a library of the Basic Calculator utility by Philip Nelson; hence the name. up down 22 volek at adamv dot cz ¶ 10 years ago Note that when you use implementation of factorial that ClaudiuS made, you get results even if you try to calculate factorial of number that you normally can't, e.g. 2.5, -2, etc. Here is safer implementation: <?php /** * Calculates a factorial of given number. * @param string|int $num * @throws InvalidArgumentException * @return string */ function bcfact ( $num ) { if (! filter_var ( $num , FILTER_VALIDATE_INT ) || $num <= 0 ) { throw new InvalidArgumentException ( sprintf ( 'Argument must be natural number, "%s" given.' , $num )); } for ( $result = '1' ; $num > 0 ; $num --) { $result = bcmul ( $result , $num ); } return $result ; } ?> up down 20 ClaudiuS ¶ 12 years ago Needed to compute some permutations and found the BC extension great but poor on functions, so untill this gets implemented here's the factorial function: <?php /* BC FACTORIAL * n! = n * (n-1) * (n-2) .. 1 [eg. 5! = 5 * 4 * 3 * 2 * 1 = 120] */ function bcfact ( $n ){ $factorial = $n ; while (-- $n > 1 ) $factorial = bcmul ( $factorial , $n ); return $factorial ; } print bcfact ( 50 ); //30414093201713378043612608166064768844377641568960512000000000000 ?> + add a note Estensioni matematiche BC Math GMP Math Statistics Trader Copyright © 2001-2026 The PHP Documentation Group My PHP.net Contact Other PHP.net sites Privacy policy ↑ and ↓ to navigate • Enter to select • Esc to close • / to open Press Enter without selection to search using Google | 2026-01-13T09:30:35 |
https://www.php.net/manual/it/function.mailparse-uudecode-all.php | PHP: mailparse_uudecode_all - Manual update page now Downloads Documentation Get Involved Help Search docs Getting Started Introduction A simple tutorial Language Reference Basic syntax Types Variables Constants Expressions Operators Control Structures Functions Classes and Objects Namespaces Enumerations Errors Exceptions Fibers Generators Attributes References Explained Predefined Variables Predefined Exceptions Predefined Interfaces and Classes Predefined Attributes Context options and parameters Supported Protocols and Wrappers Security Introduction General considerations Installed as CGI binary Installed as an Apache module Session Security Filesystem Security Database Security Error Reporting User Submitted Data Hiding PHP Keeping Current Features HTTP authentication with PHP Cookies Sessions Handling file uploads Using remote files Connection handling Persistent Database Connections Command line usage Garbage Collection DTrace Dynamic Tracing Function Reference Affecting PHP's Behaviour Audio Formats Manipulation Authentication Services Command Line Specific Extensions Compression and Archive Extensions Cryptography Extensions Database Extensions Date and Time Related Extensions File System Related Extensions Human Language and Character Encoding Support Image Processing and Generation Mail Related Extensions Mathematical Extensions Non-Text MIME Output Process Control Extensions Other Basic Extensions Other Services Search Engine Extensions Server Specific Extensions Session Extensions Text Processing Variable and Type Related Extensions Web Services Windows Only Extensions XML Manipulation GUI Extensions Keyboard Shortcuts ? This help j Next menu item k Previous menu item g p Previous man page g n Next man page G Scroll to bottom g g Scroll to top g h Goto homepage g s Goto search (current page) / Focus search box Estensioni matematiche » « mailparse_stream_encode Manuale PHP Guida Funzioni Estensioni correlate alle email Mailparse Mailparse Funzioni Change language: English German Spanish French Italian Japanese Brazilian Portuguese Russian Turkish Ukrainian Chinese (Simplified) Other mailparse_uudecode_all (PECL mailparse >= 0.9.0) mailparse_uudecode_all — Scans the data from fp and extract each embedded uuencoded file Descrizione mailparse_uudecode_all ( resource $fp ): array Scans the data from the given file pointer and extract each embedded uuencoded file into a temporary file. Elenco dei parametri fp A valid file pointer. Valori restituiti Returns an array of associative arrays listing filename information. filename Path to the temporary file name created origfilename The original filename, for uuencoded parts only The first filename entry is the message body. The next entries are the decoded uuencoded files. Esempi Example #1 mailparse_uudecode_all() example <?php $text = <<<EOD To: fred@example.com hello, this is some text hello. blah blah blah. begin 644 test.txt /=&AI<R!I<R!A('1E<W0* ` end EOD; $fp = tmpfile (); fwrite ( $fp , $text ); $data = mailparse_uudecode_all ( $fp ); echo "BODY\n" ; readfile ( $data [ 0 ][ "filename" ]); echo "UUE ( { $data [ 1 ][ 'origfilename' ]} )\n" ; readfile ( $data [ 1 ][ "filename" ]); // Clean up unlink ( $data [ 0 ][ "filename" ]); unlink ( $data [ 1 ][ "filename" ]); ?> Il precedente esempio visualizzerà: BODY To: fred@example.com hello, this is some text hello. blah blah blah. UUE (test.txt) this is a test Found A Problem? Learn How To Improve This Page • Submit a Pull Request • Report a Bug + add a note User Contributed Notes 1 note up down 0 mat at phpconsulting dot com ¶ 22 years ago As an alternative, uudecode() can be called as static function as follows: $file =& Mail_mimeDecode::uudecode($some_text); This will return the following arrays: @param string Input body to look for attachments in @return array Decoded bodies, filenames and permissions + add a note Mailparse Funzioni mailparse_​determine_​best_​xfer_​encoding mailparse_​msg_​create mailparse_​msg_​extract_​part mailparse_​msg_​extract_​part_​file mailparse_​msg_​extract_​whole_​part_​file mailparse_​msg_​free mailparse_​msg_​get_​part mailparse_​msg_​get_​part_​data mailparse_​msg_​get_​structure mailparse_​msg_​parse mailparse_​msg_​parse_​file mailparse_​rfc822_​parse_​addresses mailparse_​stream_​encode mailparse_​uudecode_​all Copyright © 2001-2026 The PHP Documentation Group My PHP.net Contact Other PHP.net sites Privacy policy ↑ and ↓ to navigate • Enter to select • Esc to close • / to open Press Enter without selection to search using Google | 2026-01-13T09:30:35 |
https://l.facebook.com/l.php?u=https%3A%2F%2Fwww.instagram.com%2F&h=AT2B6hlfBwhpVZ6oGkL26j4sRjtmWslT7rSwaGbGjedWHeuKB5-tFGZzoJwiSrNoOwNyVemmif118qs24S5WsB5J7g5s5eAylFEgZgV0zqYmAGmLIlRWmmQ7JuNgfc-Wc6lpKAa3pPSRFy2j | Facebook Facebook 이메일 또는 휴대폰 비밀번호 계정을 잊으셨나요? 새 계정 만들기 일시적으로 차단됨 일시적으로 차단됨 회원님의 이 기능 사용 속도가 너무 빠른 것 같습니다. 이 기능 사용에서 일시적으로 차단되었습니다. Back 한국어 English (US) Tiếng Việt Bahasa Indonesia ภาษาไทย Español 中文(简体) 日本語 Português (Brasil) Français (France) Deutsch 가입하기 로그인 Messenger Facebook Lite 동영상 Meta Pay Meta 스토어 Meta Quest Ray-Ban Meta Meta AI Meta AI 콘텐츠 더 보기 Instagram Threads 투표 정보 센터 개인정보처리방침 개인정보 보호 센터 정보 광고 만들기 페이지 만들기 개발자 채용 정보 쿠키 AdChoices 이용 약관 고객 센터 연락처 업로드 및 비사용자 설정 활동 로그 Meta © 2026 | 2026-01-13T09:30:35 |
https://l.facebook.com/l.php?u=https%3A%2F%2Fwww.instagram.com%2F&h=AT0FTKKvQ9_A8LTUwABQgo3SzjZr4ns6cWZR_3Hdxt3cj1nySJ5-hWNUtHJ_-wO7b9ZSn09d2Aq1NMhMc1p8SzdNBiVhSLLdIzybz8PZ3p1Yd5lWNLlmZbL6oL0fk6dNXg95uyI3C5coXz0B | Facebook Facebook 이메일 또는 휴대폰 비밀번호 계정을 잊으셨나요? 새 계정 만들기 일시적으로 차단됨 일시적으로 차단됨 회원님의 이 기능 사용 속도가 너무 빠른 것 같습니다. 이 기능 사용에서 일시적으로 차단되었습니다. Back 한국어 English (US) Tiếng Việt Bahasa Indonesia ภาษาไทย Español 中文(简体) 日本語 Português (Brasil) Français (France) Deutsch 가입하기 로그인 Messenger Facebook Lite 동영상 Meta Pay Meta 스토어 Meta Quest Ray-Ban Meta Meta AI Meta AI 콘텐츠 더 보기 Instagram Threads 투표 정보 센터 개인정보처리방침 개인정보 보호 센터 정보 광고 만들기 페이지 만들기 개발자 채용 정보 쿠키 AdChoices 이용 약관 고객 센터 연락처 업로드 및 비사용자 설정 활동 로그 Meta © 2026 | 2026-01-13T09:30:35 |
https://l.facebook.com/l.php?u=https%3A%2F%2Fwww.instagram.com%2F&h=AT1vlas0l0Ur2D8vaIWf9Wp40M4iO1rFh2IKCJpq37kqN3pDfM5MLiCf3JITkAKbTaEbkSXYARLeS29o8fFlS9PZnhlQks1ksGBkG4NBcBtGJj7OCl_gP2NVKw2QMOe6RTA0B90i_e0z8ohF | Facebook Facebook 이메일 또는 휴대폰 비밀번호 계정을 잊으셨나요? 새 계정 만들기 일시적으로 차단됨 일시적으로 차단됨 회원님의 이 기능 사용 속도가 너무 빠른 것 같습니다. 이 기능 사용에서 일시적으로 차단되었습니다. Back 한국어 English (US) Tiếng Việt Bahasa Indonesia ภาษาไทย Español 中文(简体) 日本語 Português (Brasil) Français (France) Deutsch 가입하기 로그인 Messenger Facebook Lite 동영상 Meta Pay Meta 스토어 Meta Quest Ray-Ban Meta Meta AI Meta AI 콘텐츠 더 보기 Instagram Threads 투표 정보 센터 개인정보처리방침 개인정보 보호 센터 정보 광고 만들기 페이지 만들기 개발자 채용 정보 쿠키 AdChoices 이용 약관 고객 센터 연락처 업로드 및 비사용자 설정 활동 로그 Meta © 2026 | 2026-01-13T09:30:35 |
https://phproundtable.com/show/behind-the-scenes-of-two-years-of-the-php-roundtable | PHPRoundtable PHPRoundtable The PHP podcast where everyone has a seat. Guests Library Sponsors About Us 52: Behind the scenes of two years of the PHP Roundtable Panelists: Chris Tankersley Jeremy Mikola Cal Evans Davey Shafik August 25 2016 Today the PHP Roundtable celebrates 2 years of generating nerdy discussions! We take a look behind the scenes of the PHP Roundtable podcast and chat with some nerds about what's going on the world of PHP. About Us Sponsors © 2026 PHPRoundtable Proud member of the php[architect] family | 2026-01-13T09:30:35 |
https://phproundtable.com/show/being-a-woman-in-the-php-community | PHPRoundtable PHPRoundtable The PHP podcast where everyone has a seat. Guests Library Sponsors About Us 29: Being A Woman In The PHP Community Panelists: Beth Tucker Long Eryn O’Neil Samantha Quiñones August 25 2015 Inspired by a panel discussion at Midwest PHP 2015 , we discuss what barriers exist for women in the PHP community and what we can all do to remove gender bias. About Us Sponsors © 2026 PHPRoundtable Proud member of the php[architect] family | 2026-01-13T09:30:35 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.