Warm tip: This article is reproduced from serverfault.com, please click

"gcloud command not found" when run via crontab

发布于 2018-11-20 14:24:21

So I installed the google cloud sdk by downloading the archive as follows:

$ wget https://dl.google.com/dl/cloudsdk/channels/rapid/downloads/google-cloud-sdk-225.0.0-linux-x86_64.tar.gz
$ tar -xvzf google-cloud-sdk-225.0.0-linux-x86_64.tar.gz

The above creates google-cloud-sdk directory with relavent files and I run install.sh which installs gcloud.

When I access gcloud from the shell, it behaves as expected. But when I try to access it via crontab, I get the error as stated in the title.

Any reason why could be the case??

P.S My intention is to use gcloud to perform firestore backups every 24hrs.

EDIT:
As Doug suggested, I referenced gcloud by its full path and was greeted with the following:

    Traceback (most recent call last):
  File "/home/ec2-user/google-cloud-sdk/lib/gcloud.py", line 95, in <module>
    main()
  File "/home/ec2-user/google-cloud-sdk/lib/gcloud.py", line 54, in main
    from googlecloudsdk.core.util import encoding
  File "/home/ec2-user/google-cloud-sdk/lib/googlecloudsdk/core/util/encoding.py", line 202
    for k, v in six.iteritems(env)}
      ^
SyntaxError: invalid syntax

I have set CLOUDSDK_PYTHON to /usr/bin/python2.7 (python 2.7.13) still the error persists. But the strange this is, this error doesn't happen when I run the command directly via the shell.

Answer: ok this is the behaviour of crontab which I wasn't aware of. It doesn't access the environment variables set. More info in this answer

Questioner
Adarsh
Viewed
0
community wiki 2020-12-08 12:30:01

Adding solution from the comments as community wiki answer

Crontab does not have access to the environment variables. By adding gcloud to the PATH environment variable used to run the scripts can resolve this issue. Also, crontab wont use shell login settings it is reccomended to change the entry of crontab from:

path_to_script.sh >> path_to_log_file 2>&1

to export:

CLOUDSDK_PYTHON=/usr/bin/python2.7; path_to_script.sh >> path_to_log_file 2>&1