singularity-container

How to set a shell variable in a Singularity definition file so that it is seen by several sections


I need to set a version string for an app that I am packaging in a Singularity container. This version string is used in several places in the definition file (*.def).

I know that I can set a shell variable in the %post section like this:

%post
...
VERSION="x.y"
cp /path/$VERSION /otherpath
...

but these settings are valid only within the %post section (which actually makes sense).

I also know that I can define environment variables in the %environment section but these settings are only when the container is run and will not be "seen" during image build time.

What I would like to have is a mechanism whereby I could say VERSION="x.y" somewhere in the definition file and then I could refer to its contents as $VERSION in several sections, e.g. in %post and then in %test, %labels etc.

Any help would be much appreciated.


Solution

  • I found the solution: the %arguments section, introduced in Apptainer 1.2. Works similarly to the Dockerfile ARG keyword in that the value defined under %arguments can be overridden by setting the --build-arg command line argument when executing apptainer build.

    In my use case, the definition file would look like this:

    %arguments
      VERSION=x.y
    ...
    %post
      ...
      cp /path/{{ VERSION }} /otherpath
      ...
    %labels
      Author Joe Bloggs
      Version {{ VERSION }}
    ...
    

    If you use Singularity, the feature is available since Version 4.0CE.

    NOTE that the %arguments section is not supported in earlier Apptainer or Singularity versions.