0
votes

so I am trying to deploy a cloud function to shutdown all VM's in different projects on GCP.

I have added the functionality to a single project using this guide: https://cloud.google.com/scheduler/docs/start-and-stop-compute-engine-instances-on-a-schedule

It shutdowns / starts VM's with the correct tag.

Now I want to extend this to all VM's across projects, so I was thinking i need another service account that I Can add under the cloud Function.

I have gotten a service account from the cloud Admin that has access to all projects, and added that under IAM, and given role as owner. But the issue is that I cannot assign the service account to the function.

Is there something I am missing? Or is there an easier way of doing what I am trying to accomplish?

1

1 Answers

3
votes

The easiest way is to give the service account used by that Cloud Function access to the other projects. You just need to go to your other projects and add this service account in the IAM section and give it the permissions it needs, for example compute.admin in this case.

Note that by default, Cloud Functions uses the App Engine default service account, which may not be convenient for you since the App Engine app in your Cloud Function's project would also be granted the compute.admin role in the other projects.

I'd recommend to create a dedicated service account for this use case (in the same project than your Function) and assign it to the Function and then add it as member of the other projects.

Then, in your Cloud Function, you'll need to run your code for each project you'd like to act upon. You can create a separate client object for each specifying the project Id as constructor option, like so:

const compute = new Compute({
    projectId: 'your-project-id'
});

So far you only loop through the VMs in the current project where the Function runs in.

Another option would be to have such a function defined in each project you'd like to act upon. You'd have a "master" function that you'd call, it'd act on the VMs in its project and call the other functions in the other project to act on theirs.