Issue
I am writing a script to automatically create SWAP on an AWS ephemeral volume. Part of that process requires the script to 'sense' which nvme to apply swap to since AWS Linux can reorder the nvme names at stop/start.
I am using Terraform to run a 'start-up' script which does a ton of stuff to the instance. One of them is inserting the script into /opt/scripts and then adding the crontab which will run this auto-swap script @reboot.
However, when I run the Terraform start up script, it replaces my cat EOT with results of my logic rather than the actual script I want inside /opt/scripts/swap.sh.
Here is the part of my start up script with the EOT:
# Create auto-swap script
mkdir /opt/scripts
cat <<EOT >> /opt/scripts/swap.sh
#!/bin/bash
exec 3>&1 4>&2
trap 'exec 2>&4 1>&3' 0 1 2 3
exec 1>/opt/scripts/swap.log 2>&1
# Create SWAP partition
sudo mkswap $(lsblk | grep "279.4G" | cut -d " " -f1 | perl -ne 'print "/dev/$_"')
sudo swapon $(lsblk | grep "279.4G" | cut -d " " -f1 | perl -ne 'print "/dev/$_"')
swapon -s
EOT
Here is what is inside of /opt/scripts/swap.sh after I run my Terraform:
#!/bin/bash
exec 3>&1 4>&2
trap 'exec 2>&4 1>&3' 0 1 2 3
exec 1>/opt/scripts/swap.log 2>&1
# Create SWAP partition
sudo mkswap /dev/nvme1n1
sudo swapon /dev/nvme1n1
swapon -s
I need the cat EOT to create EXACTLY what I have shown in the script into /opt/scripts/swap.sh not the /dev/nvme1n1 that it figured out on it's own. How do I do this?
Desired contents of /opt/scripts/swap.sh:
#!/bin/bash
exec 3>&1 4>&2
trap 'exec 2>&4 1>&3' 0 1 2 3
exec 1>/opt/scripts/swap.log 2>&1
# Create SWAP partition
sudo mkswap $(lsblk | grep "279.4G" | cut -d " " -f1 | perl -ne 'print "/dev/$_"')
sudo swapon $(lsblk | grep "279.4G" | cut -d " " -f1 | perl -ne 'print "/dev/$_"')
swapon -s
Solution
You need to quote the delimiter; right now, the here document is treated like a double-quoted string, so the command substitutions are evaluated immediately.
# Create auto-swap script
mkdir /opt/scripts
cat <<'EOT' >> /opt/scripts/swap.sh
#!/bin/bash
exec 3>&1 4>&2
trap 'exec 2>&4 1>&3' 0 1 2 3
exec 1>/opt/scripts/swap.log 2>&1
# Create SWAP partition
sudo mkswap $(lsblk | grep "279.4G" | cut -d " " -f1 | perl -ne 'print "/dev/$_"')
sudo swapon $(lsblk | grep "279.4G" | cut -d " " -f1 | perl -ne 'print "/dev/$_"')
swapon -s
EOT
Answered By - chepner Answer Checked By - Senaida (WPSolving Volunteer)