How to create EC2 AMI images with multiple nitro-based volumes attached correctly

Solution 1:

On your script you have one step that creates the file system with mkfs and another step to add it on fstab file.

Before add it on fstab get the UUID from device you just formatted.
Use this UUID to add mount instructions to fstab, instead of device path.

This is how you can change your code.

  commands:
    - sudo mkdir /data
    - sudo mkfs -t xfs /dev/nvme1n1
    - echo "$(blkid /dev/nvme1n1 | awk '{print $2}')  /data  xfs  defaults,nofail  0  2" | sudo tee -a /etc/fstab

See this other answer about UUID usage:

https://stackoverflow.com/questions/64568780/aws-nvme-mounted-to-different-directory-after-reboot/67453438?noredirect=1#comment119235037_67453438


Update

Your concept about AMI and when volumes are related to it is not correct.
Volumes are attached exactly when you generate AMI, doesn't matter which mechanism you use to generate it.
When you generated your AMI using image builder, it will attach volumes on it and will run the commands you added to format your device (see note). Exactly at the moment you create AMI. Not when you create instance.
So, filesystem is already there with UUID, fstab is already configured.

Every instance you create later from this AMI, will be exactly the same as this AMI.

See this example, I create one instance, formatted device with xfs, mounted it via fstab, stopped it and generated an AMI.
Then I launched a new instance from this AMI, see that all devices UUID are the same, even the one from root volume.

Before generate AMI, instance name ip-172-31-12-219:

[root@ip-172-31-12-219 ~]# lsblk -f
NAME          FSTYPE LABEL UUID                                 MOUNTPOINT
nvme1n1
└─nvme1n1p1   xfs          e24884d7-26a2-457d-bf51-875907986bf0 /mnt/disk10
nvme0n1
├─nvme0n1p1   xfs    /     7b355c6b-f82b-4810-94b9-4f3af651f629 /
└─nvme0n1p128

Another instance from AMI above, instance name ip-172-31-8-239:

[root@ip-172-31-8-239 ~]# lsblk -f
NAME          FSTYPE LABEL UUID                                 MOUNTPOINT
nvme1n1
└─nvme1n1p1   xfs          e24884d7-26a2-457d-bf51-875907986bf0 /mnt/disk10
nvme0n1
├─nvme0n1p1   xfs    /     7b355c6b-f82b-4810-94b9-4f3af651f629 /
└─nvme0n1p128

When you generate AMI from console you can see this message.

During the image creation process, Amazon EC2 creates a snapshot of each of the above volumes.

Which means when you create an instance from this AMI, all volumes are a "restore" from these snapshots. Every bit and byte are the same.

I hope I have clarified your doubts here.


Note

Totally out of topic, you are creating a filesystem on your disk instead of a partition. It is okay, it is supported. But it is not recommended.
You can search more about each option. One advantage is partition alignment, which is very helpful with SSD.