KeyError for environmental variable in EC2 when using Crontab

Viewed 42

I am trying to use Crontab to schedule a python function, which I have tested directly from the command line (and works fine), however when I put it into a Cronjob:

*/5 * * * * /usr/bin/python3 /home/ubuntu/Python/function.py args >> /var/log/logfile.log 2>&1

I receive the error:

KeyError: 'GOOGLE_APPLICATION_CREDENTIALS'

I have included

import os
SERVICE_ACCOUNT_JSON = os.environ['GOOGLE_APPLICATION_CREDENTIALS']

in my function code, and set the path to the json file in the ~/.bashrc file as I don't want to explicitly state the variable path in the function.

export GOOGLE_APPLICATION_CREDENTIALS="/home/ubuntu/.hiddendirectory/keyfile.json"

I'm aware that this is typically because the path to the variable is different when run from Cron as opposed to the command prompt, but I'm not sure what changes to make so that the script can find the variable without stating the path in the script directly. This is also the case for all other environment variables such as my AWS credentials - they are all treated as if they don't exist:

botocore.exceptions.NoCredentialsError: Unable to locate credentials

Any suggestions would be appreciated, thanks

1 Answers

The cron job might be executing the script as a different user, and therefore it is looking in a different home directory for credentials.

Run a script via cron and have it execute the whoami command to see the user under which the script is running.

If it is a different user, you will need to put a credentials file in that user's home directory.

Related