Google cloud SDK code to execute via cron

不问归期 提交于 2021-02-07 20:57:20

问题


I am trying to implement an automated code to shut down and start VM Instances in my Google Cloud account via Crontab. The OS is Ubuntu 12 lts and is installed with Google service account so it can handle read/write on my Google cloud account.

My actual code is in this file /home/ubu12lts/cronfiles/resetvm.sh

#!/bin/bash
echo Y | gcloud compute instances stop my-vm-name --zone us-central1-a
sleep 120s
gcloud compute instances start my-vm-name --zone us-central1-a
echo "completed"

When I call the above file like this,

$ bash /home/ubu12lts/cronfiles/resetvm.sh

It works perfect and does the job.

Now I wanted to set this up in cron so it would do automatically every hour. So I did

$ sudo crontab -e

And added this code in cron

0 * * * *  /bin/sh /home/ubu12lts/cronfiles/resetvm.sh >>/home/ubu12lts/cron.log

And made script executable

chmod +x /home/ubu12lts/cronfiles/resetvm.sh

I also tested the crontab by adding a sample command of creating .txt file with a sample message and it worked perfect.

But the above code for gcloud SDK doesn't work through cron. The VM doesn't stop neither starts in my GC compute engine.

Anyone can help please?

Thank you so much.


回答1:


You have added the entry to root's crontab, while your Cloud SDK installation is setup for a different user (I am guessing ubu121lts).

You should add the entry in ubu121lts's crontab using:

crontab -u ubu121lts -e

Additionally your entry is currently scheduled to run on the 0th minute every hour. Is that what you intended?




回答2:


I have run into a similar issue before. I fixed it by forcing the profile in my script.sh,loading the gcloud environment variables with it. Example below:

#!/bin/bash

source /etc/profile

echo Y | gcloud compute instances stop my-vm-name --zone us-central1-a sleep 120s gcloud compute instances start my-vm-name --zone us-central1-a echo "completed"

This also helped me resize node count in GKE.



来源:https://stackoverflow.com/questions/30823604/google-cloud-sdk-code-to-execute-via-cron

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!