Rebuild initrd Image (Linux)

Sometimes kernel fails to boot due to improperly created initrd image, i.e. trying to mount /dev/VolGroup00/LogVol00 to /sysroot when using root volume on LVM.

Three lines of nash code can sometimes save you hours of Dexter. 

The Quick Way

This article assumes the initrd file we want to modify is /boot/initrd.img-3.4.89.

Copy and Extract initrd Image

# IMG=initrd.img-3.4.89
# cp -v /boot/"$IMG" /tmp/"$IMG".gz && gunzip /tmp/"$IMG".gz
# mkdir /tmp/"$IMG"_dir && cd /tmp/"$IMG"_dir && cpio -i < ../"$IMG"

Modify the initrd image as needed.

Create a New Image

# find ./ | cpio -H newc -o > /tmp/"$IMG".cpio
# gzip /tmp/"$IMG".cpio && mv -v /tmp/"$IMG".cpio.gz /boot/"$IMG"-new
# cd ~ && rm /tmp/"$IMG"* -Rf

Don’t forget to update Grub configuration to use the new initrd file (ignore this line if you overwrote the old initrd file).

The Long Way

Copy and Extract initrd Image

Initrd image is normally a gzip compressed cpio archive.

# file -b /boot/initrd.img-3.4.89
gzip compressed data, from Unix, last modified: Mon May 12 15:09:33 2014

Copy the initrd image file and expand it:

# cp /boot/initrd.img-3.4.89 /tmp/initrd.img-3.4.89.gz
# gunzip /tmp/initrd.img-3.4.89.gz

The expanded file is a cpio archive:

# file -b /tmp/initrd.img-3.4.89
ASCII cpio archive (SVR4 with no CRC)

Create a temp directory to work in:

# mkdir /tmp/1 && cd /tmp/1

Extract the initrd archive:

# cpio -i < ../initrd.img-3.4.89
908760 blocks

The old initrd archive file is no longer needed, delete it:

# rm ../initrd.img-3.4.89

Modify the initrd image.

Create initrd Image

Create a new cpio archive and compress it:

# find ./ | cpio -H newc -o > /tmp/initrd.img-3.4.89.cpio
# gzip /tmp/initrd.img-3.4.89.cpio
# file -b  /tmp/initrd.img-3.4.89.cpio.gz
gzip compressed data, was "initrd.img-3.4.89.cpio", from Unix, last modified: Tue Jul  8 18:21:05 2014

Move the new initrd image to /boot folder:

# mv /tmp/initrd.img-3.4.89.cpio.gz /boot/initrd.img-3.4.89-new

Make sure you update your Grub config appropriatelly.