nickp
nickp

Reputation: 25

capture returncode of python script running within the container

I'm creating a make-release script where the full application is prepared for deployment on the machine where it is needed. It should be able to be build on a standard linux build machine (with docker) The thing is that I struggle to find a way to make a single python script independed from the build machine.

"""Return hash of the key, used for prometheus web-portal access configuration"""

import sys
try:
    import bcrypt
except ImportError as e:
    print(e)
    sys.exit(1)

args = sys.argv

if len(args) == 2:
    try:
        PASSWORD = str(args[1])
        hashed_password = bcrypt.hashpw(PASSWORD.encode("utf-8"), bcrypt.gensalt())
        print(hashed_password.decode())
        sys.exit(0)
    except (IndexError, SystemError, ValueError, RuntimeError, UnicodeError) as e:
        print(e)
        sys.exit(1)

else:
    print('not enough arguments given')
    sys.exit(1)

Depending on the return code the print is either a hash or an error code. It is therefor important to have the return code to handle the script different.

# get hashed key for prometheus
HASHED_SECRET=$(python3 src/generate_prometheus_passhash.py ${PROMETHEUS_WEB_PASS})
RETURN_CODE=$?

if [ ${RETURN_CODE} == 0 ]; then
  <Use hash>
else
  echo "error: ${HASHED_SECRET}"
  exit 1;
fi

Does anyone have a good solution for this?

EDIT: In summary. The python script has to run in a docker container to prevent library dependencies on the host machine. I want to get both the return code (1 or 0 from the script) as the print (stdout) out of the docker container where the python script runs in. The calls should be done via bash.

Upvotes: 0

Views: 128

Answers (1)

totok
totok

Reputation: 1500

You could use the || logic to set a bad hash in HASH if the return code is not 0, and check for the value of $HASH with a if statement:

script.py

#!/usr/bin/env python3
import sys

args = sys.argv

if (len(args) < 2):
    exit(1)
else:
    print("ABCDEFG")
    exit(0)

test.sh

#!/bin/sh

echo "Trying something that will fail"
HASH=$(python3 script.py || echo "BAD-HASH")
echo "HASH: $HASH"

echo "Trying something that will work"
HASH=$(python3 script.py a b c || echo "BAD-HASH")
echo "HASH: $HASH"

Output

$ ./test.sh
Trying something that will fail
HASH: BAD-HASH
Trying something that will work
HASH: ABCDEFG

Upvotes: 1

Related Questions