Vinod Bellikoth
Vinod Bellikoth

Reputation: 21

In GCP, can I prevent deletion of a VM, created by me, by another user?

In a given GCP project, all team members have access to create and delete VMs. We need a solution to avoid one member deleting a VM created by another member. How can we restrict members from accidentally deleting each other's VMs within a project?

Upvotes: 2

Views: 850

Answers (1)

Martin Zeitler
Martin Zeitler

Reputation: 76769

Such fine-grained permissions can be defined by IAM policies for Compute Engine resources:

Grant users access to a specific subset of resources.
Suppose Alice should manage a subset of instances in a project. With instance-level IAM policies, you grant her the compute.instanceAdmin.v1 role on only those instances. If you granted Alice the same role on the project, then she would have permission to modify all instances in the project.


Cloud IAM doesn't directly support scripting, but the gcloud CLI can be automated.

When a text file called mappings.txt provides the mappings:

instance-1 [email protected]
instance-2 [email protected]
instance-3 [email protected]

Then one can process that config file with a shell script:

#!/bin/bash
PROJECT_ID=$(gcloud config get-value project)

while read LINE; do

    INSTANCE=${LINE% *}
    USER=${LINE#* }

    # update project policy
    gcloud projects remove-iam-policy-binding $PROJECT_ID \
        --member="user:${USER}" \
        --role="roles/compute.instanceAdmin.v1"

    # update instance policy
    gcloud compute instances add-iam-policy-binding $INSTANCE \
        --member="user:${USER}" \
        --role="roles/compute.instanceAdmin.v1"

done < ./mappings.txt

Removing roles/compute.instanceAdmin.v1 also prevents them from creating new instances, but there seems to be no other way to prevent them from administering another user's instance. This loop might well be suitable to setup instances for a whole team or classroom - and it could create them, as well. With many users and instances, "combing through" is the most effective.


Or when wanting to apply --deletion-protection to all instances of the current project:

#!/bin/bash
for INSTANCE in `gcloud compute instances list --format="value(name)"`; do
    gcloud compute instances update $INSTANCE \
        --deletion-protection 
done

There would also be the possibility, to clone roles/compute.instanceAdmin.v1 as a custom role and then taking away all of the delete permissions (which not only do exist for VM instances):

gcloud iam roles describe roles/compute.instanceAdmin.v1 | grep delete
gcloud iam roles describe roles/compute.admin | grep delete

I'd rather ask, if roles/compute.admin or roles/compute.instanceAdmin.v1 is even required for what they're doing? It's usually enough, when there's someone or a small team responsible for that; IAM also supports setting up groups, which makes this easier to handle.

Upvotes: 1

Related Questions