'How to add arguments to Python script entrypoint based on conditions

I have an entry point like so:

ENTRYPOINT [ "python" ,"/usr/local/bin/script.py" ]

I want to be able to add multiple arguments to script.py if a particular container has "MY_ENV_VAR" set to TRUE.

So for instance if:

MY_ENV_VAR = true
MY_ENV_VAR2 = true
MY_ENV_VAR3 = false (or anything other than true)

I want to run /usr/local/bin/script.py --my-env-var --my-env-var2

I can't find a good working example of how to accomplish this



Solution 1:[1]

You will not be able to conditionally do this within the Dockerfile, but you can achieve the desired behavior by configuring the Python script script.py as follows:

import argparse
import os

def main():
    parser = argparse.ArgumentParser("Arguments")

    if os.environ.get("MY_ENV_VAR") is not None:
        parser.add_argument("--my-env-var", required=True, action="store_true")
    
    if os.environ.get("MY_ENV_VAR2") is not None:
        parser.add_argument("--my-env-var2", required=True, action="store_true")
    
    parser.parse_args()

if __name__ == "__main__":
    main()

The logic is that if MY_ENV_VAR or MY_ENV_VAR2, then a required argparse argument is set.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1