'Script to create swap partition fails when running automatically
I am creating a cluster of machines in AWS (Amazon Linux 2) using terraform by utilizing the user_data
argument under the aws_instance
resource. Part of the script is the creation of a swap partition. The commands in my script work perfectly if I execute them manually in the instance.
I have tried the following in my script. It creates the partition successfully, but it does not seem to finish up creating the swap as confirmed in more /proc/swaps
. It successfully executes the lines of code below everything I have showed that I omitted from my post. So it must be failing at the partprobe
, mkswap /dev/nvme1n1p2
, or swapon /dev/nvme1n1p2
. It runs the echo "/dev/nvme1n1p2 swap swap defaults 0 0" >> /etc/fstab
. I'm not sure how to tell where it is not executing.
# Create SWAP partition
fdisk /dev/nvme1n1 <<EOF
n
p
2
+48G
w
EOF
partprobe
mkswap /dev/nvme1n1p2
swapon /dev/nvme1n1p2
echo "/dev/nvme1n1p2 swap swap defaults 0 0" >> /etc/fstab
The results intended are to create swap partition as confirmed by running more /proc/swaps
. The partition is created, but not the actual swap.
UPDATE: Here is the contents of the log file:
mkswap: cannot open /dev/nvme1n1p2: No such file or directory
swapon: cannot open /dev/nvme1n1p2: No such file or directory
However that device is listed when running lsblk
and the command works if I run it manually.
Solution 1:[1]
Solution from the comments by @thatotherguy:
I'm guessing it's a race condition with partprobe
. If you run manually, there will be several seconds between each command so udev
will have plenty of time to create device node asynchronously. When you run them in a script, it doesn't. You could try adding sleep 5
after partprobe
.
This solved the OP's error, and I can also report success using this fix.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |