Building Linux AMIs on aarch darwin

A little while ago I posted this thread asking for help cross compiling a linux ami.

After a bit more experience with Nix I realized that emulation is currently required to do this and after even more trial and error I managed to get it working. Build and Deploy Linux Systems from macOS ends with no solution for handling the different architectures and reminded me to make a post.

Below is a dockerfile and script that allowed me to build a x86_64 linux ami on my M1 macbook pro.

As a note the dockerfile effectively lies to nix about the environment and hopes the environment doesn’t try to use those features. Hopefully this works for your purposes, so far it has been working for mine.

FROM nixos/nix

# disable filtering of syscalls and enable nix-command and flakes
RUN echo "filter-syscalls = false" >> /etc/nix/nix.conf 
RUN echo "experimental-features = nix-command flakes" >> /etc/nix/nix.conf
RUN echo "sandbox = false" >> /etc/nix/nix.conf
RUN echo "system-features = kvm" >> /etc/nix/nix.conf
#!/usr/bin/env zx

// build the docker image
await $`docker buildx build . -t homelab-ami-builder --file ./builder.dockerfile --platform=linux/amd64`.stdio('inherit', 'pipe', 'pipe');

// run the image using linux/amd64 as the platform and run the build in it
await $`docker run --platform linux/amd64 -v builder-nix-store:/nix/store -v $(pwd):/bootstrap -w /bootstrap -it homelab-ami-builder nix build .#homelab-ami --out-link homelab-ami && cp -l homelab-ami ./build/homelab-ami`.stdio('inherit', 'pipe', 'pipe');

This strategy is important to me as I only own an aarch64-darwin machine.

3 Likes