This post is from reproducing a customer issue. To solve the customer’s problem, I tried to install Selenium Chromedriver and BeautifulSoup, package them into a Lambda Layer, and build a Lambda based on that layer, but kept getting a “Chromedriver file not found” error. After pit after pit of troubleshooting, this savior suddenly appeared: https://stackoverflow.com/questions/69047401/selenium-docker-container-runs-on-ec2-but-not-on-aws-lambda. Based on this article and the corresponding GitHub https://github.com/rchauhan9/image-scraper-lambda-container/tree/master, it mainly builds the Lambda via a container image, but before doing so you first package the needed packages and environment into an image.
But since the company Mac can’t install Docker, I first spun up an EC2 for most of the work.
The examples and the knowledge needed to build this post all reference the AWS official docs.
sudo yum update -y sudo amazon-linux-extras install docker sudo service docker start sudo usermod -a -G docker ec2-user # log back into the terminal at this point docker info
from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC
Go to Lambda Console > Create Function > Container Image
1 2
Function Name: ScrappingfromImage Container image URI: 125657041963.dkr.ecr.us-east-1.amazonaws.com/cx-lambda:latest
Configuring Lambda network access
If you want the Lambda function to connect to the external network, unlike EC2, you need to attach the Lambda to your own VPC, put the Lambda in a private subnet, and that private subnet’s route table must have its default route set to a NAT Gateway. Because when Lambda connects to a VPC it creates an ENI, and that ENI by default only takes a private IP, so a NAT Gateway is needed to translate between public and private IPs, and it connects to the NAT Gateway via a feature called V2N.
flowchart LR
subgraph Custom VPC
direction LR
c1(Lambda) ---> a2(NATGateway)
subgraph Public Subnet
direction LR
a2(NATGateway)
end
subgraph Private Subnet
direction LR
c1(Lambda)
end
end
private route
Configuring Lambda permissions
Remember to add the VPCAccessExecutionRole permission to the Lambda.
Then test the code.
But first go to Configuration > General Configuration > Timeout and raise the timeout.