3

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.

luator
  • 4,769
  • 3
  • 30
  • 51

1 Answers1

1

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.

tsnowlan
  • 3,472
  • 10
  • 15
  • This seems to have the same problem as the `%environment` section: It is indeed sourced when opening the container (I verified by adding an `echo`) but the alias created there is not present in the actual shell that is opened. – luator Oct 14 '19 at 07:09
  • Ah, that's right. The shell is launched with `exec` to takes over the PID but using only the exported environment. Aliases are never inherited by subshells. You can use functions instead of aliases and export those with `export -f func_name`. However, debian-based images will still have problems in that `/bin/sh` is symlinks to `/bin/dash`, which does not support `export -f`. – tsnowlan Oct 14 '19 at 14:21