luator
luator

Reputation: 5017

Automatically source configuration when running Singularity container with "shell" command

I use a Singularity/Apptainer container (build from a definition file) to build the code of my project. The way I use it is to run the container with singularity shell my_container.sif such that my workspace is mounted in the container and then run the command for building there.

For the build to work, I first need to source a configuration file which sets up the environment, creates some aliases, etc. This configuration file is part of the container. So currently inside the container I do the following:

> source /setup.bash
> build_command

I am wondering if there is a way to make Singularity/Apptainer automatically source that /setup.bash file when I run the container with singularity shell. I tried with the %environment section in the definition file but it does not seem possible to create aliases there.

Upvotes: 3

Views: 1444

Answers (1)

tsnowlan
tsnowlan

Reputation: 3772

Aliases don't get inherited between subshells, so it's not currently possible to pass those through $SINGULARITY_ENVIRONMENT or %environment.

One option is to convert the aliases to functions:

From:

alias build_command='pushd build_dir && ./configure && make && make install && popd'

To:

build_command() { pushd build_dir && ./configure && make && make install && popd ; }
export -f build_command

However, Singularity uses /bin/sh by default for the initial environment processing and Debian-based systems have /bin/sh symlinked to /bin/dash and dash does not support export functions to subshells that I have found. You might be stuck manually sourcing a file with the aliases/functions if using an OS in the Debian family.


In the %post section of your definition, you can echo into $SINGULARITY_ENVIRONMENT.

From the docs:

%post
    apt-get update && apt-get install -y netcat
    NOW=`date`
    echo "export NOW=\"${NOW}\"" >> $SINGULARITY_ENVIRONMENT

In your case, you would do echo "alias something='something else' >> $SINGULARITY_ENVIRONMENT. It is important to do the append redirect >>, as you don't want to clobber the existing environment file.

Upvotes: 1

Related Questions