Before deploy functions to lambda@edge, we have to meet some prerequisites as below:
- S3 bucket with public website hosting and set
index.htmlas base path. - Cloudfront distribution to server content for lambda@edge.
- Setup webserver on EC2 instance.
- Create lambda function.
- Setup lambda@edge trigger.
- Validation.
- Create S3 bucket and add enable static website hosting.
- Add below bucket policy
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "PublicReadGetObject",
"Effect": "Allow",
"Principal": "*",
"Action": "s3:GetObject",
"Resource": "arn:aws:s3:::<bucket_name>/*"
}
]
}
- Now upload
index.htmlandwordDoc.doc.htmlto s3. - Update static website hosting base path to
index.html
- Create cloudfront distrution with above create s3 as origin. keep other setting as default
- Check by entering distrubution url if it returns s3
index.htmlpage
- Create EC2 instance with ubuntu 18.04 and public ip.
- Login to EC2 instance using public ip and private key.
- Install nginx using below command
# sudo -i
# apt-get update
# apt-get install -y nginx
# systemctl start nginx.service
# systemctl enable nginx.service
# touch /var/www/html/index.html
# echo "Sample Page from EC2 nginx webserver" > /var/www/html/index.html
- Allow port
80and443instance security group.
- Create lambda function with runtime
python 3.7. - Update code from file
lambda_handler.py - Create role as
lambda-edgewith below policy
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"logs:CreateLogGroup",
"logs:CreateLogStream",
"logs:PutLogEvents"
],
"Resource": [
"arn:aws:logs:*:*:*"
]
}
]
}
- Attach above created role to lambda function.
- Update
EC2 public ipinsidelambda_handler.py. - IAM Role
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Service": [
"lambda.amazonaws.com",
"edgelambda.amazonaws.com"
]
},
"Action": "sts:AssumeRole"
}
]
}
- Publish new version of lambda.
- On new publish version
Add trigger --> Choose cloud front --> Deploy to Lambda@Edge --> select distribution --> choose event
viwer request--> confirm
- Open in browser
<cloud_front_distrinution_url>/webPage.aspxit should open page from EC2. <cloud_front_distrinution_url>/wordDoc.docit should open page from S3 bucket.<cloud_front_distrinution_url>/it should get 503 Error