推敲していない雑なコードの記事です。すみません。
LambdaでCapybaraやplaywrightするためにchrome入れないといけないですが、Amazon Linux 2023にいれる方法がなかなかなく、さらにRubyでnokogiriとcapybaraで動かすのに苦労したので備忘録です。
結構調べて試行錯誤しないといけなかったので共有です。
実際は使わなかったので細かい調整はおまかせします。確実に不要な部分があります。
Dockerfile
FROM public.ecr.aws/lambda/ruby:3.3
# google-chome
ADD google-chrome.repo /etc/yum.repos.d/google-chrome.repo
RUN rpm --import https://dl.google.com/linux/linux_signing_key.pub
RUN dnf install -y google-chrome-stable
RUN dnf install -y make automake gcc gcc-c++ kernel-devel
RUN dnf install -y libxml2 libxml2-devel libxslt libxslt-devel zlib-devel xz patch
RUN dnf install -y tar
# Copy Gemfile and Gemfile.lock
COPY Gemfile Gemfile.lock ${LAMBDA_TASK_ROOT}/
# Install Bundler and the specified gems
RUN gem install bundler:2.5.18 && \
bundle config set --local path 'vendor/bundle' && \
bundle install
# Copy function code
COPY lambda_function.rb ${LAMBDA_TASK_ROOT}/
# Set the CMD to your handler (could also be done as a parameter override outside of the Dockerfile)
CMD [ "lambda_function.LambdaFunction::Handler.process" ]
lambda_function.rb
require 'selenium-webdriver'
require 'capybara'
module LambdaFunction
class Handler
def self.process(event:,context:)
options = Selenium::WebDriver::Chrome::Options.new
options.add_argument("--user-data-dir=/tmp/abc")
options.add_argument('--headless=new')
options.add_argument('--disable-site-isolation-trials')
options.add_argument('--window-size=1920,1080')
options.add_argument('--no-sandbox')
options.add_argument('--disable-extensions')
options.add_argument('--disable-notifications')
options.add_argument('--disable-popup-blocking')
options.add_argument('--disable-web-security')
options.add_argument('--disable-dev-shm-usage')
options.add_argument('--disable-site-isolation-trials')
options.add_argument('--disable-features=Translate')
options.add_argument('--restore-last-session')
Capybara.register_driver :app_selenium_chrome_headless do |app|
Capybara::Selenium::Driver.new(app, browser: :chrome, options: options)
end
session = Capybara::Session.new(:app_selenium_chrome_headless)
session.visit "https://example.com"
puts session.html
session.save_screenshot("screenshot.png")
session.quit
"Hello from Lambda!" + session.html
end
end
end
Gemfile
source 'https://rubygems.org'
gem 'aws-sdk-lambda'
gem 'aws_lambda_ric'
gem 'capybara'
gem 'selenium-webdriver'
gem 'nokogiri', force_ruby_platform: true
google-chrome.repo
[google-chrome]
name=google-chrome
baseurl=http://dl.google.com/linux/chrome/rpm/stable/$basearch
enabled=1
gpgcheck=1
gpgkey=https://dl-ssl.google.com/linux/linux_signing_key.pub
実行手順は元記事を参照してください。
ローカル実行までしか試していません。
https://docs.aws.amazon.com/ja_jp/lambda/latest/dg/ruby-image.html#ruby-image-clients