6

The answer to Can I configure Linux swap space on AWS Elastic Beanstalk? (from 2016) shows how to configure Linux swap space for an AWS Elastic Beanstalk environment using .ebextensions configuration files.

However, the AWS docs Customizing software on Linux servers has this note for the newer Amazon Linux 2 platforms:

On Amazon Linux 2 platforms, instead of providing files and commands in .ebextensions configuration files, we highly recommend that you use Buildfile. Procfile, and platform hooks whenever possible to configure and run custom code on your environment instances during instance provisioning.

How do I configure swap space using this more modern configuration approach?

Aaron Brager
  • 65,323
  • 19
  • 161
  • 287

2 Answers2

7

Buildfile and Procfile are not suited for that. They serve different purposes - running short and long running commands.

I would use the platform hooks for that. Specifically, prebuild:

Files here run after the Elastic Beanstalk platform engine downloads and extracts the application source bundle, and before it sets up and configures the application and web server.

The rationale is that it's better to create swap now, before the application starts configuring. If the swap creation operation fails, you get notified fast, rather then after you setup your application.

From the SO link, you could put 01_add-swap-space.sh into .platform/hooks/prebuild/ folder. Please make sure that 01_add-swap-space.sh is executable (chmod +x) before you package your appliaction into a zip.

Dario Seidl
  • 4,140
  • 1
  • 39
  • 55
Marcin
  • 215,873
  • 14
  • 235
  • 294
  • 4
    So it's basically the same, but the script goes in a different place, and I don't need `.ebextensions/swap.config` since the script will be executed at the right time based on its location in the file system. Awesome. – Aaron Brager Jun 29 '20 at 03:08
  • 2
    @AaronBrager Yes. Amazon Linux 2 hooks introduced a lot of new things, such as these hooks. – Marcin Jun 29 '20 at 03:16
1

The simplest solution is to place the following script in .platform/hooks/predeploy/ in your deploy zip file. If not already done, it will create a swap file of 1G (1024 x 1M) and make sure it is initialized whenever the instance is rebooted.

#!/bin/bash
echo "************************"
echo "Handling swap file"
echo $(date)
echo "************************"
# if /etc/fstab doesn't contains swapfile command
if ! grep -q "swap" /etc/fstab; then
    sudo /bin/dd if=/dev/zero of=/var/swap.1 bs=1M count=1024
    sudo /sbin/mkswap /var/swap.1
    sudo chmod 600 /var/swap.1
    sudo /sbin/swapon /var/swap.1
    sudo /sbin/swapon -s
    touch .swapmem
    echo "************************"
    echo "Adding swapfile to /etc/fstab"
    echo $(date)
    echo "************************"
    echo '/var/swap.1 swap swap defaults 0 0' | sudo tee -a /etc/fstab
fi
Shahar Hajdu
  • 315
  • 2
  • 4