Search code examples
google-compute-engine

Can we use cron job to start the Compute engine at particular time?


Need a crop job script to start or stop the Compute Engine virtual machines at particular time.


Solution

  • You can use instance schedule: you create a resource policy detailing the start and stop behavior, and then attach the policy to one or more VM instances.

    Example with terraform:

    resource "google_compute_resource_policy" "start_stop" {
      name        = "start-stop-policy"
      description = "Start Stop instances"
      instance_schedule_policy {
        vm_start_schedule {
          schedule = "10 8 * * 1-5"
        }
        vm_stop_schedule {
          schedule = "30 18 * * *"
        }
        time_zone = "Europe/Paris"
      }
    }
    
    # attach resource_policy to instance
    resource "google_compute_instance" "my_instance" {
       ...
       resource_policies = [google_compute_resource_policy.start_stop.self_link]
       ...
    }
    

    This solution is totally free and simple.

    If you want another solution you can see this documentation: https://cloud.google.com/scheduler/docs/start-and-stop-compute-engine-instances-on-a-schedule, so you will create:

    • Cloud Scheduler jobs to make calls on a set schedule to start and stop the instance
    • Pub/Sub messages sent and received for each start and stop event.
    • Cloud Run functions to start and stop the instance we want to schedule.