Rifiutare l'accesso alle risorse

Questa pagina spiega come negare l'accesso alle entità impedendo loro di utilizzare autorizzazioni Identity and Access Management (IAM) specifiche.

In IAM, neghi l'accesso con i criteri di negazione. Ogni policy di negazione è collegata a un'organizzazione, una cartella o un progetto Google Cloud . Un criterio di negazione contiene regole di negazione, che identificano le entità ed elencano le autorizzazioni che le entità non possono utilizzare.

I criteri di negazione sono separati dai criteri di autorizzazione, noti anche come criteri IAM. Un criterio di autorizzazione fornisce l'accesso alle risorse concedendo ruoli IAM alle entità.

Puoi gestire le policy di negazione con la console Google Cloud , Google Cloud CLI o l'API REST v2 IAM.

Prima di iniziare

  • Enable the IAM API.

    Enable the API

  • Configurare l'autenticazione.

    Select the tab for how you plan to use the samples on this page:

    Console

    When you use the Google Cloud console to access Google Cloud services and APIs, you don't need to set up authentication.

    gcloud

      In the Google Cloud console, activate Cloud Shell.

      Activate Cloud Shell

      At the bottom of the Google Cloud console, a Cloud Shell session starts and displays a command-line prompt. Cloud Shell is a shell environment with the Google Cloud CLI already installed and with values already set for your current project. It can take a few seconds for the session to initialize.

      Terraform

      Per utilizzare gli esempi di Terraform in questa pagina in un ambiente di sviluppo locale, installa e inizializza gcloud CLI, quindi configura le Credenziali predefinite dell'applicazione con le tue credenziali utente.

      1. Install the Google Cloud CLI.

      2. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

      3. To initialize the gcloud CLI, run the following command:

        gcloud init
      4. If you're using a local shell, then create local authentication credentials for your user account:

        gcloud auth application-default login

        You don't need to do this if you're using Cloud Shell.

        If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.

      Per saperne di più, consulta Configura ADC per un ambiente di sviluppo locale nella documentazione sull'autenticazione Google Cloud .

      Vai

      Per utilizzare gli esempi di Go questa pagina in un ambiente di sviluppo locale, installa e inizializza gcloud CLI, quindi configura le Credenziali predefinite dell'applicazione con le tue credenziali utente.

      1. Install the Google Cloud CLI.

      2. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

      3. To initialize the gcloud CLI, run the following command:

        gcloud init
      4. If you're using a local shell, then create local authentication credentials for your user account:

        gcloud auth application-default login

        You don't need to do this if you're using Cloud Shell.

        If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.

      Per saperne di più, consulta Configura ADC per un ambiente di sviluppo locale nella documentazione sull'autenticazione Google Cloud .

      Java

      Per utilizzare gli esempi di Java questa pagina in un ambiente di sviluppo locale, installa e inizializza gcloud CLI, quindi configura le Credenziali predefinite dell'applicazione con le tue credenziali utente.

      1. Install the Google Cloud CLI.

      2. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

      3. To initialize the gcloud CLI, run the following command:

        gcloud init
      4. If you're using a local shell, then create local authentication credentials for your user account:

        gcloud auth application-default login

        You don't need to do this if you're using Cloud Shell.

        If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.

      Per saperne di più, consulta Configura ADC per un ambiente di sviluppo locale nella documentazione sull'autenticazione Google Cloud .

      Node.js

      Per utilizzare gli esempi di Node.js questa pagina in un ambiente di sviluppo locale, installa e inizializza gcloud CLI, quindi configura le Credenziali predefinite dell'applicazione con le tue credenziali utente.

      1. Install the Google Cloud CLI.

      2. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

      3. To initialize the gcloud CLI, run the following command:

        gcloud init
      4. If you're using a local shell, then create local authentication credentials for your user account:

        gcloud auth application-default login

        You don't need to do this if you're using Cloud Shell.

        If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.

      Per saperne di più, consulta Configura ADC per un ambiente di sviluppo locale nella documentazione sull'autenticazione Google Cloud .

      Python

      Per utilizzare gli esempi di Python questa pagina in un ambiente di sviluppo locale, installa e inizializza gcloud CLI, quindi configura le Credenziali predefinite dell'applicazione con le tue credenziali utente.

      1. Install the Google Cloud CLI.

      2. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

      3. To initialize the gcloud CLI, run the following command:

        gcloud init
      4. If you're using a local shell, then create local authentication credentials for your user account:

        gcloud auth application-default login

        You don't need to do this if you're using Cloud Shell.

        If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.

      Per saperne di più, consulta Configura ADC per un ambiente di sviluppo locale nella documentazione sull'autenticazione Google Cloud .

      REST

      Per utilizzare gli esempi di API REST in questa pagina in un ambiente di sviluppo locale, utilizzi le credenziali che fornisci a gcloud CLI.

        After installing the Google Cloud CLI, initialize it by running the following command:

        gcloud init

        If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

      Per saperne di più, consulta la sezione Autenticarsi per l'utilizzo di REST nella documentazione sull'autenticazione di Google Cloud .

    1. Leggi la panoramica delle policy di negazione.

Ruoli obbligatori

Per ottenere le autorizzazioni necessarie per gestire le policy di negazione, chiedi all'amministratore di concederti i seguenti ruoli IAM nell'organizzazione:

  • Per visualizzare le policy di negazione: Deny Reviewer (roles/iam.denyReviewer)
  • Per visualizzare, creare, aggiornare ed eliminare le policy di negazione: Deny Admin (roles/iam.denyAdmin)

Per saperne di più sulla concessione dei ruoli, consulta Gestisci l'accesso a progetti, cartelle e organizzazioni.

Questi ruoli predefiniti contengono le autorizzazioni necessarie per gestire i criteri di negazione. Per vedere quali sono esattamente le autorizzazioni richieste, espandi la sezione Autorizzazioni obbligatorie:

Autorizzazioni obbligatorie

Per gestire le policy di negazione sono necessarie le seguenti autorizzazioni:

  • Per visualizzare le policy di negazione:
    • iam.denypolicies.get
    • iam.denypolicies.list
  • Per creare, aggiornare ed eliminare le policy di negazione:
    • iam.denypolicies.create
    • iam.denypolicies.delete
    • iam.denypolicies.get
    • iam.denypolicies.update

Potresti anche ottenere queste autorizzazioni con ruoli personalizzati o altri ruoli predefiniti.

Identificare le autorizzazioni da negare

Prima di creare una policy di negazione, devi decidere quali autorizzazioni vuoi negare e a quali entità devono essere negate queste autorizzazioni.

Solo alcune autorizzazioni possono essere negate. Per un elenco delle autorizzazioni che puoi negare, consulta Autorizzazioni supportate nelle policy di negazione.

In alcuni casi, puoi utilizzare i gruppi di autorizzazioni anche per negare insiemi di autorizzazioni. Per ulteriori informazioni, vedi Gruppi di autorizzazioni.

Gestisci i criteri di negazione con l'API REST v2, che richiede un formato speciale per i nomi delle autorizzazioni. Ad esempio, l'autorizzazione per creare un ruolo personalizzato IAM è denominata nel seguente modo:

  • API v1: iam.roles.create
  • API v2: iam.googleapis.com/roles.create

Crea una policy di negazione

Puoi aggiungere policy di negazione a organizzazioni, cartelle e progetti. Ogni risorsa può avere fino a 500 criteri di negazione.

Le policy di negazione contengono regole di negazione, che specificano quanto segue:

  • Le autorizzazioni da negare.
  • Le entità a cui sono negate queste autorizzazioni.
  • (Facoltativo) Entità esenti dal rifiuto delle autorizzazioni.

    Ad esempio, puoi negare un'autorizzazione a un gruppo, ma esentare utenti specifici che appartengono a quel gruppo.

  • (Facoltativo) Un'espressione di condizione che specifica quando le entità non possono utilizzare le autorizzazioni. Nelle policy di negazione, le espressioni condizionali possono utilizzare solo funzioni per i tag delle risorse. Altre funzioni e operatori non sono supportati.

Ogni risorsa può avere fino a 500 regole di negazione in tutte le relative policy di negazione associate.

I criteri di negazione vengono ereditati tramite la gerarchia delle risorse. Ad esempio, se neghi un'autorizzazione a livello di organizzazione, questa verrà negata anche per le cartelle e i progetti all'interno dell'organizzazione e per le risorse specifiche del servizio all'interno di ogni progetto.

I criteri di negazione sostituiscono i criteri di autorizzazione. Se a un'entità viene concesso un ruolo che contiene un'autorizzazione specifica, ma un criterio di negazione afferma che l'entità non può utilizzare questa autorizzazione, l'entità non può utilizzare l'autorizzazione.

Console

  1. Nella console Google Cloud , vai alla scheda Nega nella pagina IAM.

    Vai a IAM

  2. Seleziona un progetto, una cartella o un'organizzazione.

  3. Fai clic su Crea policy di negazione.

  4. Nella sezione Nome criterio, definisci l'ID criterio in uno dei seguenti modi:

    • Nel campo Nome visualizzato, inserisci un nome visualizzato per il criterio. La compilazione di questo campo compila automaticamente il campo ID. Se vuoi modificare l'ID della norma, aggiorna il testo nel campo ID.
    • Nel campo ID, inserisci un ID per la norma.
  5. Nella sezione Regole di negazione, definisci le regole di negazione del criterio. Ogni policy di negazione deve avere almeno una regola di negazione. Per aggiungere altre regole di negazione, fai clic su Aggiungi regola di negazione.

    Per ogni regola di negazione:

    1. Nel campo Entità negate, aggiungi una o più entità a cui vuoi impedire di utilizzare le autorizzazioni specificate. L'entità può essere uno qualsiasi dei tipi di entità negli identificatori di entità per le norme di negazione, ad eccezione delle entità i cui ID iniziano con deleted:.
    2. (Facoltativo) Nel campo Entità eccezione, aggiungi le entità che vuoi che possano utilizzare le autorizzazioni specificate, anche se queste entità sono incluse nella sezione Entità negate. Ad esempio, puoi utilizzare questo campo per creare un'eccezione per utenti specifici che appartengono a un gruppo negato.

    3. Nelle sezioni Autorizzazioni negate, aggiungi le autorizzazioni che vuoi negare. Le autorizzazioni devono essere supportate nelle norme di negazione.

      In alcuni casi, puoi anche utilizzare i gruppi di autorizzazioni per negare insiemi di autorizzazioni. Per ulteriori informazioni, vedi Gruppi di autorizzazioni.

    4. (Facoltativo) Aggiungi autorizzazioni di eccezione. Le autorizzazioni di eccezione sono autorizzazioni che non vuoi che questa regola di negazione neghi, anche se sono incluse nell'elenco delle autorizzazioni negate. Ad esempio, puoi utilizzare questo campo per creare eccezioni per autorizzazioni specifiche in un gruppo di autorizzazioni.

      Per aggiungere autorizzazioni di eccezione, fai clic su Autorizzazioni di eccezione, poi su Aggiungi un'altra autorizzazione e inserisci l'autorizzazione nel campo Autorizzazione 1. Continua ad aggiungere autorizzazioni finché non avrai aggiunto tutte quelle che vuoi esentare dalla policy di negazione.

    5. (Facoltativo) Aggiungi una condizione di negazione per specificare quando le entità non possono utilizzare l'autorizzazione. Per aggiungere una condizione di negazione, fai clic su Aggiungi condizione di negazione e poi definisci i seguenti campi:

      • Titolo: facoltativo. Un breve riepilogo dello scopo della condizione.
      • (Facoltativo) Descrizione. Una descrizione più lunga della condizione.
      • Espressione condizionale: puoi aggiungere un'espressione condizionale utilizzando il Generatore di condizioni o l'Editor di condizioni. Il generatore di condizioni fornisce un'interfaccia interattiva per selezionare il tipo di condizione, l'operatore e altri dettagli applicabili dell'espressione. L'editor delle condizioni fornisce un'interfaccia basata su testo per inserire manualmente un'espressione utilizzando la sintassi CEL (Common Expression Language).

        Le condizioni di negazione devono basarsi sui tag delle risorse. Altre funzioni e operatori non sono supportati.

  6. Fai clic su Crea.

gcloud

Per creare una policy di negazione per una risorsa, inizia creando un file JSON che contenga la policy. Un criterio di negazione utilizza il seguente formato:

{
  "displayName": "POLICY_NAME",
  "rules": [
    {
      "denyRule": DENY_RULE_1
    },
    {
      "denyRule": DENY_RULE_2
    },
    {
      "denyRule": DENY_RULE_N
    }
  ]
}

Fornisci i seguenti valori:

  • POLICY_NAME: Il nome visualizzato per la policy di negazione.
  • DENY_RULE_1, DENY_RULE_2, ...DENY_RULE_N: le regole di negazione nei criteri. Ogni regola di negazione può contenere i seguenti campi:

    • deniedPermissions: un elenco di autorizzazioni che le entità specificate non possono utilizzare. Le autorizzazioni devono essere supportate nelle policy di negazione.

      In alcuni casi, puoi utilizzare i gruppi di autorizzazioni anche per negare insiemi di autorizzazioni. Per ulteriori informazioni, vedi Gruppi di autorizzazioni.

    • exceptionPermissions: un elenco di autorizzazioni che le entità specificate possono utilizzare, anche se queste autorizzazioni sono incluse in deniedPermissions. Ad esempio, puoi utilizzare questo campo per creare eccezioni per autorizzazioni specifiche in un gruppo di autorizzazioni.
    • deniedPrincipals: un elenco di entità che non possono utilizzare le autorizzazioni specificate. Per scoprire come formattare gli identificatori principal, consulta Identificatori principal per le policy di negazione.
    • exceptionPrincipals: (Facoltativo). Un elenco di entità che possono utilizzare le autorizzazioni specificate, anche se sono incluse in deniedPrincipals. Ad esempio, puoi utilizzare questo campo per creare un'eccezione per utenti specifici che appartengono a un gruppo negato. Per scoprire come formattare gli identificatori principal, consulta Identificatori principal per le policy di negazione.

    • denialCondition: (Facoltativo). Un'espressione di condizione che specifica quando le entità non possono utilizzare le autorizzazioni. Contiene i seguenti campi:

    Per esempi di regole di negazione, vedi Casi d'uso comuni.

Ad esempio, la seguente policy di negazione contiene una regola di negazione, che nega un'autorizzazione a Lucian:

{
  "displayName": "My deny policy.",
  "rules": [
    {
      "denyRule": {
        "deniedPrincipals": [
          "principal://goog/subject/lucian@example.com"
        ],
        "deniedPermissions": [
          "iam.googleapis.com/roles.create"
        ]
      }
    }
  ]
}

Successivamente, esegui il comando gcloud iam policies create:

gcloud iam policies create POLICY_ID \
    --attachment-point=ATTACHMENT_POINT \
    --kind=denypolicies \
    --policy-file=POLICY_FILE

Fornisci i seguenti valori:

  • POLICY_ID: l'identificatore della policy di negazione.

  • ATTACHMENT_POINT: un identificatore della risorsa a cui è associato il criterio di negazione. Per scoprire come formattare questo valore, consulta Punto di attacco.

  • POLICY_FILE: il percorso del file JSON che contiene la policy di negazione.

Per impostazione predefinita, se questo comando ha esito positivo, non stampa alcun output. Per stampare una risposta dettagliata, aggiungi il flag --format=json al comando.

Ad esempio, il seguente comando crea un criterio di negazione denominato my-deny-policy per il progetto my-project, utilizzando un file denominato policy.json:

gcloud iam policies create my-deny-policy \
    --attachment-point=cloudresourcemanager.googleapis.com/projects/my-project \
    --kind=denypolicies \
    --policy-file=policy.json

Terraform

Per scoprire come applicare o rimuovere una configurazione Terraform, consulta Comandi Terraform di base. Per saperne di più, consulta la documentazione di riferimento del fornitore Terraform.

data "google_project" "default" {
}

# Create a service account
resource "google_service_account" "default" {
  display_name = "IAM Deny Example - Service Account"
  account_id   = "example-sa"
  project      = data.google_project.default.project_id
}

# Create an IAM deny policy that denies a permission for the service account
resource "google_iam_deny_policy" "default" {
  provider     = google-beta
  parent       = urlencode("cloudresourcemanager.googleapis.com/projects/${data.google_project.default.project_id}")
  name         = "my-deny-policy"
  display_name = "My deny policy."
  rules {
    deny_rule {
      denied_principals  = ["principal://iam.googleapis.com/projects/-/serviceAccounts/${google_service_account.default.email}"]
      denied_permissions = ["iam.googleapis.com/roles.create"]
    }
  }
}

Go

Per scoprire come installare e utilizzare la libreria client per IAM, consulta Librerie client IAM. Per ulteriori informazioni, consulta la documentazione di riferimento dell'API IAM Go.

Per autenticarti in IAM, configura le Credenziali predefinite dell'applicazione. Per ulteriori informazioni, consulta Prima di iniziare.

import (
	"context"
	"fmt"
	"io"

	iam "cloud.google.com/go/iam/apiv2"
	"cloud.google.com/go/iam/apiv2/iampb"

	"google.golang.org/genproto/googleapis/type/expr"
)

// createDenyPolicy creates a deny policy.
func createDenyPolicy(w io.Writer, projectID, policyID string) error {
	// You can add deny policies to organizations, folders, and projects.
	// Each of these resources can have up to 5 deny policies.
	// Deny policies contain deny rules, which specify the following:
	// 1. The permissions to deny and/or exempt.
	// 2. The principals that are denied, or exempted from denial.
	// 3. An optional condition on when to enforce the deny rules.

	// projectID := "your_project_id"
	// policyID := "your_policy_id"

	ctx := context.Background()
	policiesClient, err := iam.NewPoliciesClient(ctx)
	if err != nil {
		return fmt.Errorf("NewPoliciesClient: %w", err)
	}
	defer policiesClient.Close()

	// Each deny policy is attached to an organization, folder, or project.
	// To work with deny policies, specify the attachment point.
	//
	// Its format can be one of the following:
	// 1. cloudresourcemanager.googleapis.com/organizations/ORG_ID
	// 2. cloudresourcemanager.googleapis.com/folders/FOLDER_ID
	// 3. cloudresourcemanager.googleapis.com/projects/PROJECT_ID
	//
	// The attachment point is identified by its URL-encoded resource name. Hence, replace
	// the "/" with "%%2F".
	attachmentPoint := fmt.Sprintf(
		"cloudresourcemanager.googleapis.com%%2Fprojects%%2F%s",
		projectID,
	)

	denyRule := &iampb.DenyRule{
		// Add one or more principals who should be denied the permissions specified in this rule.
		// For more information on allowed values,
		// see: https://cloud.google.com/iam/help/deny/principal-identifiers
		DeniedPrincipals: []string{"principalSet://goog/public:all"},
		// Optionally, set the principals who should be exempted from the
		// list of denied principals. For example, if you want to deny certain permissions
		// to a group but exempt a few principals, then add those here.
		// ExceptionPrincipals: []string{"principalSet://goog/group/project-admins@example.com"},
		//
		// Set the permissions to deny.
		// The permission value is of the format: service_fqdn/resource.action
		// For the list of supported permissions,
		// see: https://cloud.google.com/iam/help/deny/supported-permissions
		DeniedPermissions: []string{"cloudresourcemanager.googleapis.com/projects.delete"},
		// Optionally, add the permissions to be exempted from this rule.
		// Meaning, the deny rule will not be applicable to these permissions.
		// ExceptionPermissions: []string{"cloudresourcemanager.googleapis.com/projects.create"},
		//
		// Set the condition which will enforce the deny rule.
		// If this condition is true, the deny rule will be applicable.
		// Else, the rule will not be enforced.
		// The expression uses Common Expression Language syntax (CEL).
		// Here we block access based on tags.
		//
		// Here, we create a deny rule that denies the
		// cloudresourcemanager.googleapis.com/projects.delete permission
		// to everyone except project-admins@example.com for resources that are tagged test.
		// A tag is a key-value pair that can be attached to an organization, folder, or project.
		// For more info, see: https://cloud.google.com/iam/docs/deny-access#create-deny-policy
		DenialCondition: &expr.Expr{
			Expression: "!resource.matchTag('12345678/env', 'test')",
		},
	}

	// Add the deny rule and a description for it.
	policyRule := &iampb.PolicyRule{
		Description: "block all principals from deleting projects, unless the principal is a member of project-admins@example.com and the project being deleted has a tag with the value test",
		Kind: &iampb.PolicyRule_DenyRule{
			DenyRule: denyRule,
		},
	}

	policy := &iampb.Policy{
		DisplayName: "Restrict project deletion access",
		Rules:       [](*iampb.PolicyRule){policyRule},
	}

	req := &iampb.CreatePolicyRequest{
		// Construct the full path of the resource's deny policies.
		// Its format is: "policies/ATTACHMENT_POINT/denypolicies"
		Parent:   fmt.Sprintf("policies/%s/denypolicies", attachmentPoint),
		Policy:   policy,
		PolicyId: policyID,
	}
	op, err := policiesClient.CreatePolicy(ctx, req)
	if err != nil {
		return fmt.Errorf("unable to create policy: %w", err)
	}

	policy, err = op.Wait(ctx)
	if err != nil {
		return fmt.Errorf("unable to wait for the operation: %w", err)
	}

	fmt.Fprintf(w, "Policy %s created\n", policy.GetName())

	return nil
}

Java

Per scoprire come installare e utilizzare la libreria client per IAM, consulta Librerie client IAM. Per ulteriori informazioni, consulta la documentazione di riferimento dell'API IAM Java.

Per autenticarti in IAM, configura le Credenziali predefinite dell'applicazione. Per ulteriori informazioni, consulta Prima di iniziare.


import com.google.iam.v2.CreatePolicyRequest;
import com.google.iam.v2.DenyRule;
import com.google.iam.v2.PoliciesClient;
import com.google.iam.v2.Policy;
import com.google.iam.v2.PolicyRule;
import com.google.longrunning.Operation;
import com.google.type.Expr;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class CreateDenyPolicy {

  public static void main(String[] args)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // TODO(developer): Replace these variables before running the sample.
    // ID or number of the Google Cloud project you want to use.
    String projectId = "your-google-cloud-project-id";

    // Specify the id of the Deny policy you want to create.
    String policyId = "deny-policy-id";

    createDenyPolicy(projectId, policyId);
  }

  // Create a deny policy.
  // You can add deny policies to organizations, folders, and projects.
  // Each of these resources can have up to 5 deny policies.
  //
  // Deny policies contain deny rules, which specify the following:
  // 1. The permissions to deny and/or exempt.
  // 2. The principals that are denied, or exempted from denial.
  // 3. An optional condition on when to enforce the deny rules.
  public static void createDenyPolicy(String projectId, String policyId)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {

    try (PoliciesClient policiesClient = PoliciesClient.create()) {
      // Each deny policy is attached to an organization, folder, or project.
      // To work with deny policies, specify the attachment point.
      //
      // Its format can be one of the following:
      // 1. cloudresourcemanager.googleapis.com/organizations/ORG_ID
      // 2. cloudresourcemanager.googleapis.com/folders/FOLDER_ID
      // 3. cloudresourcemanager.googleapis.com/projects/PROJECT_ID
      //
      // The attachment point is identified by its URL-encoded resource name.
      String urlEncodedResource =
          URLEncoder.encode(
              "cloudresourcemanager.googleapis.com/projects/", StandardCharsets.UTF_8);
      String attachmentPoint = String.format("%s%s", urlEncodedResource, projectId);

      // Construct the full path of the resource to which the policy is attached.
      // Its format is: "policies/{attachmentPoint}/denypolicies/{policyId}"
      String policyParent = String.format("policies/%s/denypolicies", attachmentPoint);

      DenyRule denyRule =
          DenyRule.newBuilder()
              // Add one or more principals who should be denied the permissions specified in this
              // rule.
              // For more information on allowed values, see:
              // https://cloud.google.com/iam/docs/principal-identifiers
              .addDeniedPrincipals("principalSet://goog/public:all")

              // Optionally, set the principals who should be exempted from the
              // list of denied principals. For example, if you want to deny certain permissions
              // to a group but exempt a few principals, then add those here.
              // .addExceptionPrincipals(
              //     "principalSet://goog/group/project-admins@example.com")

              // Set the permissions to deny.
              // The permission value is of the format: service_fqdn/resource.action
              // For the list of supported permissions, see:
              // https://cloud.google.com/iam/help/deny/supported-permissions
              .addDeniedPermissions("cloudresourcemanager.googleapis.com/projects.delete")

              // Optionally, add the permissions to be exempted from this rule.
              // Meaning, the deny rule will not be applicable to these permissions.
              // .addExceptionPermissions("cloudresourcemanager.googleapis.com/projects.create")

              // Set the condition which will enforce the deny rule. If this condition is true,
              // the deny rule will be applicable. Else, the rule will not be enforced.
              .setDenialCondition(
                  Expr.newBuilder()
                      // The expression uses Common Expression Language syntax (CEL).
                      // Here we block access based on tags.
                      //
                      // A tag is a key-value pair that can be attached to an organization, folder,
                      // or project. You can use deny policies to deny permissions based on tags
                      // without adding an IAM Condition to every role grant.
                      // For example, imagine that you tag all of your projects as dev, test, or
                      // prod. You want only members of project-admins@example.com to be able to
                      // perform operations on projects that are tagged prod.
                      // To solve this problem, you create a deny rule that denies the
                      // cloudresourcemanager.googleapis.com/projects.delete permission to everyone
                      // except project-admins@example.com for resources that are tagged test.
                      .setExpression("!resource.matchTag('12345678/env', 'test')")
                      .setTitle("Only for test projects")
                      .build())
              .build();

      // Add the deny rule and a description for it.
      Policy policy =
          Policy.newBuilder()
              // Set the deny rule.
              .addRules(
                  PolicyRule.newBuilder()
                      // Set a description for the rule.
                      .setDescription(
                          "block all principals from deleting projects, unless the principal"
                              + " is a member of project-admins@example.com and the project"
                              + " being deleted has a tag with the value test")
                      .setDenyRule(denyRule)
                      .build())
              .build();

      // Set the policy resource path, policy rules and a unique ID for the policy.
      CreatePolicyRequest createPolicyRequest =
          CreatePolicyRequest.newBuilder()
              .setParent(policyParent)
              .setPolicy(policy)
              .setPolicyId(policyId)
              .build();

      // Build the create policy request.
      Operation operation =
          policiesClient
              .createPolicyCallable()
              .futureCall(createPolicyRequest)
              .get(3, TimeUnit.MINUTES);

      // Wait for the operation to complete.
      if (operation.hasError()) {
        System.out.println("Error in creating the policy " + operation.getError());
        return;
      }

      // Retrieve the policy name.
      Policy response = policiesClient.getPolicy(String.format("%s/%s", policyParent, policyId));
      String policyName = response.getName();
      System.out.println(
          "Created the deny policy: " + policyName.substring(policyName.lastIndexOf("/") + 1));
    }
  }
}

Node.js

Per scoprire come installare e utilizzare la libreria client per IAM, consulta Librerie client IAM. Per ulteriori informazioni, consulta la documentazione di riferimento dell'API IAM Node.js.

Per autenticarti in IAM, configura le Credenziali predefinite dell'applicazione. Per ulteriori informazioni, consulta Prima di iniziare.

/**
 * TODO(developer): Uncomment and replace these variables before running the sample.
 */
// const projectId = 'YOUR_PROJECT_ID';
// const policyID = 'YOUR_POLICY_ID';

const {PoliciesClient} = require('@google-cloud/iam').v2;

const iamClient = new PoliciesClient();

// Each deny policy is attached to an organization, folder, or project.
// To work with deny policies, specify the attachment point.
//
// Its format can be one of the following:
// 1. cloudresourcemanager.googleapis.com/organizations/ORG_ID
// 2. cloudresourcemanager.googleapis.com/folders/FOLDER_ID
// 3. cloudresourcemanager.googleapis.com/projects/PROJECT_ID
//
// The attachment point is identified by its URL-encoded resource name. Hence, replace
// the "/" with "%2F".
const attachmentPoint = `cloudresourcemanager.googleapis.com%2Fprojects%2F${projectId}`;

const denyRule = {
  // Add one or more principals who should be denied the permissions specified in this rule.
  // For more information on allowed values, see: https://cloud.google.com/iam/help/deny/principal-identifiers
  deniedPrincipals: ['principalSet://goog/public:all'],
  // Optionally, set the principals who should be exempted from the
  // list of denied principals. For example, if you want to deny certain permissions
  // to a group but exempt a few principals, then add those here.
  // exceptionPrincipals: ['principalSet://goog/group/project-admins@example.com'],
  // Set the permissions to deny.
  // The permission value is of the format: service_fqdn/resource.action
  // For the list of supported permissions, see: https://cloud.google.com/iam/help/deny/supported-permissions
  deniedPermissions: ['cloudresourcemanager.googleapis.com/projects.delete'],
  // Optionally, add the permissions to be exempted from this rule.
  // Meaning, the deny rule will not be applicable to these permissions.
  // exceptionPermissions: ['cloudresourcemanager.googleapis.com/projects.create']
  //
  // Set the condition which will enforce the deny rule.
  // If this condition is true, the deny rule will be applicable. Else, the rule will not be enforced.
  // The expression uses Common Expression Language syntax (CEL).
  // Here we block access based on tags.
  //
  // Here, we create a deny rule that denies the cloudresourcemanager.googleapis.com/projects.delete permission to everyone except project-admins@example.com for resources that are tagged test.
  // A tag is a key-value pair that can be attached to an organization, folder, or project.
  // For more info, see: https://cloud.google.com/iam/docs/deny-access#create-deny-policy
  denialCondition: {
    expression: '!resource.matchTag("12345678/env", "test")',
  },
};

async function createDenyPolicy() {
  const request = {
    parent: `policies/${attachmentPoint}/denypolicies`,
    policy: {
      displayName: 'Restrict project deletion access',
      rules: [
        {
          description:
            'block all principals from deleting projects, unless the principal is a member of project-admins@example.com and the project being deleted has a tag with the value test',
          denyRule,
        },
      ],
    },
    policyId,
  };

  const [operation] = await iamClient.createPolicy(request);
  const [policy] = await operation.promise();

  console.log(`Created the deny policy: ${policy.name}`);
}

createDenyPolicy();

Python

Per scoprire come installare e utilizzare la libreria client per IAM, consulta Librerie client IAM. Per ulteriori informazioni, consulta la documentazione di riferimento dell'API IAM Python.

Per autenticarti in IAM, configura le Credenziali predefinite dell'applicazione. Per ulteriori informazioni, consulta Prima di iniziare.

def create_deny_policy(project_id: str, policy_id: str) -> None:
    """Create a deny policy.

    You can add deny policies to organizations, folders, and projects.
    Each of these resources can have up to 5 deny policies.

    Deny policies contain deny rules, which specify the following:
    1. The permissions to deny and/or exempt.
    2. The principals that are denied, or exempted from denial.
    3. An optional condition on when to enforce the deny rules.

    Params:
    project_id: ID or number of the Google Cloud project you want to use.
    policy_id: Specify the ID of the deny policy you want to create.
    """

    from google.cloud import iam_v2
    from google.cloud.iam_v2 import types

    policies_client = iam_v2.PoliciesClient()

    # Each deny policy is attached to an organization, folder, or project.
    # To work with deny policies, specify the attachment point.
    #
    # Its format can be one of the following:
    # 1. cloudresourcemanager.googleapis.com/organizations/ORG_ID
    # 2. cloudresourcemanager.googleapis.com/folders/FOLDER_ID
    # 3. cloudresourcemanager.googleapis.com/projects/PROJECT_ID
    #
    # The attachment point is identified by its URL-encoded resource name. Hence, replace
    # the "/" with "%2F".
    attachment_point = f"cloudresourcemanager.googleapis.com%2Fprojects%2F{project_id}"

    deny_rule = types.DenyRule()
    # Add one or more principals who should be denied the permissions specified in this rule.
    # For more information on allowed values, see: https://cloud.google.com/iam/help/deny/principal-identifiers
    deny_rule.denied_principals = ["principalSet://goog/public:all"]

    # Optionally, set the principals who should be exempted from the
    # list of denied principals. For example, if you want to deny certain permissions
    # to a group but exempt a few principals, then add those here.
    # deny_rule.exception_principals = ["principalSet://goog/group/project-admins@example.com"]

    # Set the permissions to deny.
    # The permission value is of the format: service_fqdn/resource.action
    # For the list of supported permissions, see: https://cloud.google.com/iam/help/deny/supported-permissions
    deny_rule.denied_permissions = [
        "cloudresourcemanager.googleapis.com/projects.delete"
    ]

    # Optionally, add the permissions to be exempted from this rule.
    # Meaning, the deny rule will not be applicable to these permissions.
    # deny_rule.exception_permissions = ["cloudresourcemanager.googleapis.com/projects.create"]

    # Set the condition which will enforce the deny rule.
    # If this condition is true, the deny rule will be applicable. Else, the rule will not be enforced.
    # The expression uses Common Expression Language syntax (CEL).
    # Here we block access based on tags.
    #
    # Here, we create a deny rule that denies the cloudresourcemanager.googleapis.com/projects.delete permission to everyone except project-admins@example.com for resources that are tagged test.
    # A tag is a key-value pair that can be attached to an organization, folder, or project.
    # For more info, see: https://cloud.google.com/iam/docs/deny-access#create-deny-policy
    deny_rule.denial_condition = {
        "expression": "!resource.matchTag('12345678/env', 'test')"
    }

    # Add the deny rule and a description for it.
    policy_rule = types.PolicyRule()
    policy_rule.description = "block all principals from deleting projects, unless the principal is a member of project-admins@example.com and the project being deleted has a tag with the value test"
    policy_rule.deny_rule = deny_rule

    policy = types.Policy()
    policy.display_name = "Restrict project deletion access"
    policy.rules = [policy_rule]

    # Set the policy resource path, policy rules and a unique ID for the policy.
    request = types.CreatePolicyRequest()
    # Construct the full path of the resource's deny policies.
    # Its format is: "policies/{attachmentPoint}/denypolicies"
    request.parent = f"policies/{attachment_point}/denypolicies"
    request.policy = policy
    request.policy_id = policy_id

    # Build the create policy request and wait for the operation to complete.
    result = policies_client.create_policy(request=request).result()
    print(f"Created the deny policy: {result.name.rsplit('/')[-1]}")


if __name__ == "__main__":
    import uuid

    # Your Google Cloud project ID.
    PROJECT_ID = os.getenv("GOOGLE_CLOUD_PROJECT", "your-google-cloud-project-id")

    # Any unique ID (0 to 63 chars) starting with a lowercase letter.
    policy_id = f"deny-{uuid.uuid4()}"

    # Test the policy lifecycle.
    create_deny_policy(PROJECT_ID, policy_id)

REST

Il metodo policies.createPolicy crea un criterio di negazione per una risorsa.

Prima di utilizzare i dati della richiesta, apporta le seguenti sostituzioni:

  • ENCODED_ATTACHMENT_POINT: un identificatore codificato come URL per la risorsa a cui è associata la policy di negazione. Per scoprire come formattare questo valore, consulta Punto di attacco.

  • POLICY_ID: un identificatore per la policy di negazione.
  • POLICY_NAME: il nome visualizzato per il criterio di negazione.
  • DENY_RULE_1, DENY_RULE_2, ...DENY_RULE_N: le regole di negazione nei criteri. Ogni regola di negazione può contenere i seguenti campi:

    • deniedPermissions: un elenco di autorizzazioni che le entità specificate non possono utilizzare. Le autorizzazioni devono essere supportate nelle policy di negazione.

      In alcuni casi, puoi utilizzare i gruppi di autorizzazioni anche per negare insiemi di autorizzazioni. Per ulteriori informazioni, vedi Gruppi di autorizzazioni.

    • exceptionPermissions: un elenco di autorizzazioni che le entità specificate possono utilizzare, anche se queste autorizzazioni sono incluse in deniedPermissions. Ad esempio, puoi utilizzare questo campo per creare eccezioni per autorizzazioni specifiche in un gruppo di autorizzazioni.
    • deniedPrincipals: un elenco di entità che non possono utilizzare le autorizzazioni specificate. Per scoprire come formattare gli identificatori principal, consulta Identificatori principal per le policy di negazione.
    • exceptionPrincipals: (Facoltativo). Un elenco di entità che possono utilizzare le autorizzazioni specificate, anche se sono incluse in deniedPrincipals. Ad esempio, puoi utilizzare questo campo per creare un'eccezione per utenti specifici che appartengono a un gruppo negato. Per scoprire come formattare gli identificatori principal, consulta Identificatori principal per le policy di negazione.

    • denialCondition: (Facoltativo). Un'espressione di condizione che specifica quando le entità non possono utilizzare le autorizzazioni. Contiene i seguenti campi:

    Per esempi di regole di negazione, vedi Casi d'uso comuni.

Metodo HTTP e URL:

POST https://iam.googleapis.com/v2/policies/ENCODED_ATTACHMENT_POINT/denypolicies?policyId=POLICY_ID

Corpo JSON della richiesta:

{
  "displayName": "POLICY_NAME",
  "rules": [
    {
      "denyRule": DENY_RULE_1
    },
    {
      "denyRule": DENY_RULE_2
    },

    {
      "denyRule": DENY_RULE_N
    }
  ]
}

Per inviare la richiesta, espandi una di queste opzioni:

Dovresti ricevere una risposta JSON simile alla seguente:

{
  "name": "policies/cloudresourcemanager.googleapis.com%2Fprojects%2F1234567890123/denypolicies/my-policy/operations/89cb3e508bf1ff01",
  "metadata": {
    "@type": "type.googleapis.com/google.iam.v2.PolicyOperationMetadata",
    "createTime": "2022-06-28T19:06:12.455151Z"
  },
  "response": {
    "@type": "type.googleapis.com/google.iam.v2.Policy",
    "name": "policies/cloudresourcemanager.googleapis.com%2Fprojects%2F1234567890123/denypolicies/my-policy",
    "uid": "6665c437-a3b2-a018-6934-54dd16d3426e",
    "kind": "DenyPolicy",
    "displayName": "My deny policy.",
    "etag": "MTc3NDU4MjM4OTY0MzU5MjQ5OTI=",
    "createTime": "2022-06-28T19:06:12.455151Z",
    "updateTime": "2022-06-28T22:26:21.968687Z"
    "rules": [
      {
        "denyRule": {
          "deniedPrincipals": [
            "principal://goog/subject/lucian@example.com"
          ],
          "deniedPermissions": [
            "iam.googleapis.com/roles.create"
          ]
        }
      }
    ]
  }
}

La risposta identifica un'operazione a lunga esecuzione. Puoi monitorare lo stato dell'operazione a lunga esecuzione per scoprire quando è stata completata. Per maggiori dettagli, vedi Controllare lo stato di un'operazione di lunga durata in questa pagina.

Elenca i criteri di negazione

Una risorsa può avere più policy di rifiuto. Puoi elencare tutti i criteri di negazione associati a una risorsa e poi visualizzare ogni criterio di negazione per vedere le regole di negazione in ogni criterio.

Console

  1. Nella console Google Cloud , vai alla scheda Nega nella pagina IAM.

    Vai a IAM

  2. Seleziona un progetto, una cartella o un'organizzazione.

    La console Google Cloud elenca tutte le policy di negazione che si applicano a quel progetto, a quella cartella o a quell'organizzazione. Sono incluse le policy di negazione ereditate da altre risorse. Per saperne di più sull'ereditarietà dei criteri di negazione, consulta Ereditarietà dei criteri di negazione.

gcloud

Per elencare le policy di negazione per una risorsa, esegui il comando gcloud iam policies list:

gcloud iam policies list \
    --attachment-point=ATTACHMENT_POINT \
    --kind=denypolicies \
    --format=json

Fornisci il seguente valore:

  • ATTACHMENT_POINT: un identificatore della risorsa a cui è associato il criterio di negazione. Per scoprire come formattare questo valore, consulta Punto di attacco.

Ad esempio, il seguente comando elenca le policy di negazione associate a un'organizzazione il cui ID numerico è 123456789012:

gcloud iam policies list \
    --attachment-point=cloudresourcemanager.googleapis.com/organizations/123456789012 \
    --kind=denypolicies \
    --format=json

Go

Per scoprire come installare e utilizzare la libreria client per IAM, consulta Librerie client IAM. Per ulteriori informazioni, consulta la documentazione di riferimento dell'API IAM Go.

Per autenticarti in IAM, configura le Credenziali predefinite dell'applicazione. Per ulteriori informazioni, consulta Prima di iniziare.

import (
	"context"
	"fmt"
	"io"

	iam "cloud.google.com/go/iam/apiv2"
	"cloud.google.com/go/iam/apiv2/iampb"
	"google.golang.org/api/iterator"
)

// listDenyPolicies lists all the deny policies that are attached to a resource.
// A resource can have up to 5 deny policies.
func listDenyPolicies(w io.Writer, projectID string) error {
	// projectID := "your_project_id"

	ctx := context.Background()
	policiesClient, err := iam.NewPoliciesClient(ctx)
	if err != nil {
		return fmt.Errorf("NewPoliciesClient: %w", err)
	}
	defer policiesClient.Close()

	// Each deny policy is attached to an organization, folder, or project.
	// To work with deny policies, specify the attachment point.
	//
	// Its format can be one of the following:
	// 1. cloudresourcemanager.googleapis.com/organizations/ORG_ID
	// 2. cloudresourcemanager.googleapis.com/folders/FOLDER_ID
	// 3. cloudresourcemanager.googleapis.com/projects/PROJECT_ID
	//
	// The attachment point is identified by its URL-encoded resource name. Hence, replace
	// the "/" with "%%2F".
	attachmentPoint := fmt.Sprintf(
		"cloudresourcemanager.googleapis.com%%2Fprojects%%2F%s",
		projectID,
	)

	req := &iampb.ListPoliciesRequest{
		// Construct the full path of the resource's deny policies.
		// Its format is: "policies/ATTACHMENT_POINT/denypolicies"
		Parent: fmt.Sprintf("policies/%s/denypolicies", attachmentPoint),
	}
	it := policiesClient.ListPolicies(ctx, req)
	fmt.Fprintf(w, "Policies found in project %s:\n", projectID)

	for {
		policy, err := it.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			return err
		}
		fmt.Fprintf(w, "- %s\n", policy.GetName())
	}
	return nil
}

Java

Per scoprire come installare e utilizzare la libreria client per IAM, consulta Librerie client IAM. Per ulteriori informazioni, consulta la documentazione di riferimento dell'API IAM Java.

Per autenticarti in IAM, configura le Credenziali predefinite dell'applicazione. Per ulteriori informazioni, consulta Prima di iniziare.


import com.google.iam.v2.PoliciesClient;
import com.google.iam.v2.Policy;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

public class ListDenyPolicies {

  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    // ID or number of the Google Cloud project you want to use.
    String projectId = "your-google-cloud-project-id";

    listDenyPolicies(projectId);
  }

  // List all the deny policies that are attached to a resource.
  // A resource can have up to 5 deny policies.
  public static void listDenyPolicies(String projectId) throws IOException {
    // Initialize the Policies client.
    try (PoliciesClient policiesClient = PoliciesClient.create()) {

      // Each deny policy is attached to an organization, folder, or project.
      // To work with deny policies, specify the attachment point.
      //
      // Its format can be one of the following:
      // 1. cloudresourcemanager.googleapis.com/organizations/ORG_ID
      // 2. cloudresourcemanager.googleapis.com/folders/FOLDER_ID
      // 3. cloudresourcemanager.googleapis.com/projects/PROJECT_ID
      //
      // The attachment point is identified by its URL-encoded resource name.
      String urlEncodedResource =
          URLEncoder.encode(
              "cloudresourcemanager.googleapis.com/projects/", StandardCharsets.UTF_8);
      String attachmentPoint = String.format("%s%s", urlEncodedResource, projectId);

      // Construct the full path of the resource to which the policy is attached.
      // Its format is: "policies/{attachmentPoint}/denypolicies"
      String policyParent = String.format("policies/%s/denypolicies", attachmentPoint);

      // Create a list request and iterate over the returned policies.
      for (Policy policy : policiesClient.listPolicies(policyParent).iterateAll()) {
        System.out.println(policy.getName());
      }
      System.out.println("Listed all deny policies");
    }
  }
}

Node.js

Per scoprire come installare e utilizzare la libreria client per IAM, consulta Librerie client IAM. Per ulteriori informazioni, consulta la documentazione di riferimento dell'API IAM Node.js.

Per autenticarti in IAM, configura le Credenziali predefinite dell'applicazione. Per ulteriori informazioni, consulta Prima di iniziare.

/**
 * TODO(developer): Uncomment and replace these variables before running the sample.
 */
// const projectId = 'YOUR_PROJECT_ID';

const {PoliciesClient} = require('@google-cloud/iam').v2;

const iamClient = new PoliciesClient();

// Each deny policy is attached to an organization, folder, or project.
// To work with deny policies, specify the attachment point.
//
// Its format can be one of the following:
// 1. cloudresourcemanager.googleapis.com/organizations/ORG_ID
// 2. cloudresourcemanager.googleapis.com/folders/FOLDER_ID
// 3. cloudresourcemanager.googleapis.com/projects/PROJECT_ID
//
// The attachment point is identified by its URL-encoded resource name. Hence, replace
// the "/" with "%2F".
const attachmentPoint = `cloudresourcemanager.googleapis.com%2Fprojects%2F${projectId}`;

async function listDenyPolicies() {
  const request = {
    parent: `policies/${attachmentPoint}/denypolicies`,
  };

  const policies = await iamClient.listPoliciesAsync(request);
  for await (const policy of policies) {
    console.log(`- ${policy.name}`);
  }
}

listDenyPolicies();

Python

Per scoprire come installare e utilizzare la libreria client per IAM, consulta Librerie client IAM. Per ulteriori informazioni, consulta la documentazione di riferimento dell'API IAM Python.

Per autenticarti in IAM, configura le Credenziali predefinite dell'applicazione. Per ulteriori informazioni, consulta Prima di iniziare.

def list_deny_policy(project_id: str) -> None:
    """List all the deny policies that are attached to a resource.

    A resource can have up to 5 deny policies.

    project_id: ID or number of the Google Cloud project you want to use.
    """

    from google.cloud import iam_v2
    from google.cloud.iam_v2 import types

    policies_client = iam_v2.PoliciesClient()

    # Each deny policy is attached to an organization, folder, or project.
    # To work with deny policies, specify the attachment point.
    #
    # Its format can be one of the following:
    # 1. cloudresourcemanager.googleapis.com/organizations/ORG_ID
    # 2. cloudresourcemanager.googleapis.com/folders/FOLDER_ID
    # 3. cloudresourcemanager.googleapis.com/projects/PROJECT_ID
    #
    # The attachment point is identified by its URL-encoded resource name. Hence, replace
    # the "/" with "%2F".
    attachment_point = f"cloudresourcemanager.googleapis.com%2Fprojects%2F{project_id}"

    request = types.ListPoliciesRequest()
    # Construct the full path of the resource's deny policies.
    # Its format is: "policies/{attachmentPoint}/denypolicies"
    request.parent = f"policies/{attachment_point}/denypolicies"

    # Create a list request and iterate over the returned policies.
    policies = policies_client.list_policies(request=request)

    for policy in policies:
        print(policy.name)
    print("Listed all deny policies")


if __name__ == "__main__":
    # Your Google Cloud project ID.
    PROJECT_ID = os.getenv("GOOGLE_CLOUD_PROJECT", "your-google-cloud-project-id")

    # Any unique ID (0 to 63 chars) starting with a lowercase letter.
    policy_id = f"deny-{uuid.uuid4()}"

    list_deny_policy(PROJECT_ID)

REST

Il metodo policies.listPolicies elenca i criteri di negazione per una risorsa.

Prima di utilizzare i dati della richiesta, apporta le seguenti sostituzioni:

  • ENCODED_ATTACHMENT_POINT: un identificatore codificato come URL per la risorsa a cui è associata la policy di negazione. Per scoprire come formattare questo valore, consulta Punto di attacco.

Metodo HTTP e URL:

GET https://iam.googleapis.com/v2/policies/ENCODED_ATTACHMENT_POINT/denypolicies

Per inviare la richiesta, espandi una di queste opzioni:

Dovresti ricevere una risposta JSON simile alla seguente:

{
  "policies": [
    {
      "name": "policies/cloudresourcemanager.googleapis.com%2Fprojects%2F1067607927478/denypolicies/test-policy",
      "uid": "6665c437-a3b2-a018-6934-54dd16d3426e",
      "kind": "DenyPolicy",
      "displayName": "My deny policy.",
      "createTime": "2022-06-28T19:06:12.455151Z",
      "updateTime": "2022-06-28T22:26:21.968687Z"
    },
    {
      "name": "policies/cloudresourcemanager.googleapis.com%2Fprojects%2F1067607927478/denypolicies/test-policy-2",
      "uid": "8465d710-ea20-0a08-d92c-b2a3ebf766ab",
      "kind": "DenyPolicy",
      "displayName": "My second deny policy.",
      "createTime": "2022-06-05T19:21:53.595455Z",
      "updateTime": "2022-06-05T19:21:53.595455Z"
    },
    {
      "name": "policies/cloudresourcemanager.googleapis.com%2Fprojects%2F1067607927478/denypolicies/test-policy-3",
      "uid": "ee9f7c2f-7e8c-b05c-d4e5-e03bfb2954e0",
      "kind": "DenyPolicy",
      "displayName": "My third deny policy.",
      "createTime": "2022-06-05T19:22:26.770543Z",
      "updateTime": "2022-06-05T19:22:26.770543Z"
    }
  ]
}

Visualizzare una policy di negazione

Puoi visualizzare una policy di negazione per vedere le regole di negazione che contiene, incluse le autorizzazioni negate e le entità che non possono utilizzare queste autorizzazioni.

Console

  1. Nella console Google Cloud , vai alla scheda Nega nella pagina IAM.

    Vai a IAM

  2. Seleziona un progetto, una cartella o un'organizzazione.

  3. Nella colonna ID norma, fai clic sull'ID della norma che vuoi visualizzare.

    La console Google Cloud mostra i dettagli della policy di rifiuto, tra cui l'ID policy, la data di creazione e le regole di rifiuto nella policy di rifiuto.

gcloud

Per ottenere la policy di negazione per una risorsa, esegui il comando gcloud iam policies get:

gcloud iam policies get POLICY_ID \
    --attachment-point=ATTACHMENT_POINT \
    --kind=denypolicies \
    --format=json

Fornisci i seguenti valori:

  • POLICY_ID: l'identificatore della policy di negazione.

  • ATTACHMENT_POINT: un identificatore della risorsa a cui è associato il criterio di negazione. Per scoprire come formattare questo valore, consulta Punto di attacco.

Ad esempio, il seguente comando recupera il criterio di negazione denominato my-deny-policy per il progetto my-project e lo salva in un file denominato policy.json:

gcloud iam policies get my-deny-policy \
    --attachment-point=cloudresourcemanager.googleapis.com/projects/my-project \
    --kind=denypolicies \
    --format=json \
    > ./policy.json

Go

Per scoprire come installare e utilizzare la libreria client per IAM, consulta Librerie client IAM. Per ulteriori informazioni, consulta la documentazione di riferimento dell'API IAM Go.

Per autenticarti in IAM, configura le Credenziali predefinite dell'applicazione. Per ulteriori informazioni, consulta Prima di iniziare.

import (
	"context"
	"fmt"
	"io"

	iam "cloud.google.com/go/iam/apiv2"
	"cloud.google.com/go/iam/apiv2/iampb"
)

// getDenyPolicy retrieves the deny policy given the project ID and policy ID.
func getDenyPolicy(w io.Writer, projectID, policyID string) error {
	// projectID := "your_project_id"
	// policyID := "your_policy_id"

	ctx := context.Background()
	policiesClient, err := iam.NewPoliciesClient(ctx)
	if err != nil {
		return fmt.Errorf("NewPoliciesClient: %w", err)
	}
	defer policiesClient.Close()

	// Each deny policy is attached to an organization, folder, or project.
	// To work with deny policies, specify the attachment point.
	//
	// Its format can be one of the following:
	// 1. cloudresourcemanager.googleapis.com/organizations/ORG_ID
	// 2. cloudresourcemanager.googleapis.com/folders/FOLDER_ID
	// 3. cloudresourcemanager.googleapis.com/projects/PROJECT_ID
	//
	// The attachment point is identified by its URL-encoded resource name. Hence, replace
	// the "/" with "%%2F".
	attachmentPoint := fmt.Sprintf(
		"cloudresourcemanager.googleapis.com%%2Fprojects%%2F%s",
		projectID,
	)

	req := &iampb.GetPolicyRequest{
		// Construct the full path of the policy.
		// Its format is: "policies/ATTACHMENT_POINT/denypolicies/POLICY_ID"
		Name: fmt.Sprintf("policies/%s/denypolicies/%s", attachmentPoint, policyID),
	}
	policy, err := policiesClient.GetPolicy(ctx, req)
	if err != nil {
		return fmt.Errorf("unable to get policy: %w", err)
	}

	fmt.Fprintf(w, "Policy %s retrieved\n", policy.GetName())

	return nil
}

Java

Per scoprire come installare e utilizzare la libreria client per IAM, consulta Librerie client IAM. Per ulteriori informazioni, consulta la documentazione di riferimento dell'API IAM Java.

Per autenticarti in IAM, configura le Credenziali predefinite dell'applicazione. Per ulteriori informazioni, consulta Prima di iniziare.


import com.google.iam.v2.GetPolicyRequest;
import com.google.iam.v2.PoliciesClient;
import com.google.iam.v2.Policy;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

public class GetDenyPolicy {

  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.

    // ID or number of the Google Cloud project you want to use.
    String projectId = "your-google-cloud-project-id";

    // Specify the ID of the deny policy you want to retrieve.
    String policyId = "deny-policy-id";

    getDenyPolicy(projectId, policyId);
  }

  // Retrieve the deny policy given the project ID and policy ID.
  public static void getDenyPolicy(String projectId, String policyId) throws IOException {
    // Create the IAM Policies client.
    try (PoliciesClient policiesClient = PoliciesClient.create()) {

      // Each deny policy is attached to an organization, folder, or project.
      // To work with deny policies, specify the attachment point.
      //
      // Its format can be one of the following:
      // 1. cloudresourcemanager.googleapis.com/organizations/ORG_ID
      // 2. cloudresourcemanager.googleapis.com/folders/FOLDER_ID
      // 3. cloudresourcemanager.googleapis.com/projects/PROJECT_ID
      //
      // The attachment point is identified by its URL-encoded resource name.
      String urlEncodedResource =
          URLEncoder.encode(
              "cloudresourcemanager.googleapis.com/projects/", StandardCharsets.UTF_8);
      String attachmentPoint = String.format("%s%s", urlEncodedResource, projectId);

      // Construct the full path of the resource to which the policy is attached.
      // Its format is: "policies/{attachmentPoint}/denypolicies/{policyId}"
      String policyParent = String.format("policies/%s/denypolicies/%s", attachmentPoint, policyId);

      // Specify the policyParent and execute the GetPolicy request.
      GetPolicyRequest getPolicyRequest =
          GetPolicyRequest.newBuilder().setName(policyParent).build();

      Policy policy = policiesClient.getPolicy(getPolicyRequest);
      System.out.printf("Retrieved the deny policy: %s : %s%n", policyId, policy);
    }
  }
}

Node.js

Per scoprire come installare e utilizzare la libreria client per IAM, consulta Librerie client IAM. Per ulteriori informazioni, consulta la documentazione di riferimento dell'API IAM Node.js.

Per autenticarti in IAM, configura le Credenziali predefinite dell'applicazione. Per ulteriori informazioni, consulta Prima di iniziare.

/**
 * TODO(developer): Uncomment and replace these variables before running the sample.
 */
// const projectId = 'YOUR_PROJECT_ID';
// const policyID = 'YOUR_POLICY_ID';

const {PoliciesClient} = require('@google-cloud/iam').v2;

const iamClient = new PoliciesClient();

// Each deny policy is attached to an organization, folder, or project.
// To work with deny policies, specify the attachment point.
//
// Its format can be one of the following:
// 1. cloudresourcemanager.googleapis.com/organizations/ORG_ID
// 2. cloudresourcemanager.googleapis.com/folders/FOLDER_ID
// 3. cloudresourcemanager.googleapis.com/projects/PROJECT_ID
//
// The attachment point is identified by its URL-encoded resource name. Hence, replace
// the "/" with "%2F".
const attachmentPoint = `cloudresourcemanager.googleapis.com%2Fprojects%2F${projectId}`;

async function getDenyPolicy() {
  const request = {
    name: `policies/${attachmentPoint}/denypolicies/${policyId}`,
  };

  const [policy] = await iamClient.getPolicy(request);

  console.log(`Retrieved the deny policy: ${policy.name}`);
}

getDenyPolicy();

Python

Per scoprire come installare e utilizzare la libreria client per IAM, consulta Librerie client IAM. Per ulteriori informazioni, consulta la documentazione di riferimento dell'API IAM Python.

Per autenticarti in IAM, configura le Credenziali predefinite dell'applicazione. Per ulteriori informazioni, consulta Prima di iniziare.

from google.cloud import iam_v2
from google.cloud.iam_v2 import Policy, types


def get_deny_policy(project_id: str, policy_id: str) -> Policy:
    """Retrieve the deny policy given the project ID and policy ID.

    project_id: ID or number of the Google Cloud project you want to use.
    policy_id: The ID of the deny policy you want to retrieve.
    """
    policies_client = iam_v2.PoliciesClient()

    # Each deny policy is attached to an organization, folder, or project.
    # To work with deny policies, specify the attachment point.
    #
    # Its format can be one of the following:
    # 1. cloudresourcemanager.googleapis.com/organizations/ORG_ID
    # 2. cloudresourcemanager.googleapis.com/folders/FOLDER_ID
    # 3. cloudresourcemanager.googleapis.com/projects/PROJECT_ID
    #
    # The attachment point is identified by its URL-encoded resource name. Hence, replace
    # the "/" with "%2F".
    attachment_point = f"cloudresourcemanager.googleapis.com%2Fprojects%2F{project_id}"

    request = types.GetPolicyRequest()
    # Construct the full path of the policy.
    # Its format is: "policies/{attachmentPoint}/denypolicies/{policyId}"
    request.name = f"policies/{attachment_point}/denypolicies/{policy_id}"

    # Execute the GetPolicy request.
    policy = policies_client.get_policy(request=request)
    print(f"Retrieved the deny policy: {policy_id} : {policy}")
    return policy


if __name__ == "__main__":
    # Your Google Cloud project ID.
    PROJECT_ID = os.getenv("GOOGLE_CLOUD_PROJECT", "your-google-cloud-project-id")

    # Any unique ID (0 to 63 chars) starting with a lowercase letter.
    policy_id = f"deny-{uuid.uuid4()}"

    policy = get_deny_policy(PROJECT_ID, policy_id)

REST

Il metodo policies.get recupera un criterio di negazione per una risorsa.

Prima di utilizzare i dati della richiesta, apporta le seguenti sostituzioni:

  • ENCODED_ATTACHMENT_POINT: un identificatore codificato come URL per la risorsa a cui è associata la policy di negazione. Per scoprire come formattare questo valore, consulta Punto di attacco.

  • POLICY_ID: un identificatore per la policy di negazione.

Metodo HTTP e URL:

GET https://iam.googleapis.com/v2/policies/ENCODED_ATTACHMENT_POINT/denypolicies/POLICY_ID

Per inviare la richiesta, espandi una di queste opzioni:

Dovresti ricevere una risposta JSON simile alla seguente:

{
  "name": "policies/cloudresourcemanager.googleapis.com%2Fprojects%2F1234567890123/denypolicies/my-policy",
  "uid": "6665c437-a3b2-a018-6934-54dd16d3426e",
  "kind": "DenyPolicy",
  "displayName": "My deny policy.",
  "etag": "MTc3NDU4MjM4OTY0MzU5MjQ5OTI=",
  "createTime": "2022-06-05T19:22:26.770543Z",
  "updateTime": "2022-06-05T19:22:26.770543Z",
  "rules": [
    {
      "denyRule": {
        "deniedPrincipals": [
          "principal://goog/subject/lucian@example.com"
        ],
        "deniedPermissions": [
          "iam.googleapis.com/roles.create"
        ]
      }
    }
  ]
}

Aggiorna una policy di negazione

Dopo aver creato una policy di negazione, puoi aggiornare le regole di negazione che contiene, nonché il nome visualizzato.

Puoi aggiornare un criterio di negazione utilizzando la console Google Cloud o uno dei seguenti metodi programmatici:

  • gcloud CLI
  • API REST
  • Librerie client IAM

Aggiorna una policy di negazione utilizzando la console Google Cloud

  1. Nella console Google Cloud , vai alla scheda Nega nella pagina IAM.

    Vai a IAM

  2. Seleziona un progetto, una cartella o un'organizzazione.

  3. Nella colonna ID criterio, fai clic sull'ID del criterio che vuoi modificare.

  4. Fai clic su Modifica.

  5. Aggiorna la policy di negazione:

    • Per modificare il nome visualizzato della policy, modifica il campo Nome visualizzato.
    • Per modificare una regola di negazione esistente, fai clic sulla regola di negazione e poi modifica le entità della regola, le entità di eccezione, le autorizzazioni negate, le autorizzazioni di eccezione o la condizione di negazione.
    • Per rimuovere una regola di negazione, trova la regola di negazione che vuoi eliminare e fai clic su Elimina nella riga.
    • Per aggiungere una regola di negazione, fai clic su Aggiungi regola di negazione e poi crea una regola di negazione come quando crei un criterio di negazione.
  6. Al termine dell'aggiornamento della norma di negazione, fai clic su Salva.

Aggiornare una policy di negazione in modo programmatico

Per aggiornare un criterio di negazione utilizzando gcloud CLI, l'API REST o le librerie client IAM, utilizza il pattern read-modify-write:

  1. Leggi la versione attuale delle norme.
  2. Modifica le informazioni nella norma in base alle esigenze.
  3. Scrivi le norme aggiornate.

Leggi il criterio di negazione

gcloud

Per ottenere la policy di negazione per una risorsa, esegui il comando gcloud iam policies get:

gcloud iam policies get POLICY_ID \
    --attachment-point=ATTACHMENT_POINT \
    --kind=denypolicies \
    --format=json

Fornisci i seguenti valori:

  • POLICY_ID: l'identificatore della policy di negazione.

  • ATTACHMENT_POINT: un identificatore della risorsa a cui è associato il criterio di negazione. Per scoprire come formattare questo valore, consulta Punto di attacco.

Ad esempio, il seguente comando recupera il criterio di negazione denominato my-deny-policy per il progetto my-project e lo salva in un file denominato policy.json:

gcloud iam policies get my-deny-policy \
    --attachment-point=cloudresourcemanager.googleapis.com/projects/my-project \
    --kind=denypolicies \
    --format=json \
    > ./policy.json

Go

Per scoprire come installare e utilizzare la libreria client per IAM, consulta Librerie client IAM. Per ulteriori informazioni, consulta la documentazione di riferimento dell'API IAM Go.

Per autenticarti in IAM, configura le Credenziali predefinite dell'applicazione. Per ulteriori informazioni, consulta Prima di iniziare.

import (
	"context"
	"fmt"
	"io"

	iam "cloud.google.com/go/iam/apiv2"
	"cloud.google.com/go/iam/apiv2/iampb"
)

// getDenyPolicy retrieves the deny policy given the project ID and policy ID.
func getDenyPolicy(w io.Writer, projectID, policyID string) error {
	// projectID := "your_project_id"
	// policyID := "your_policy_id"

	ctx := context.Background()
	policiesClient, err := iam.NewPoliciesClient(ctx)
	if err != nil {
		return fmt.Errorf("NewPoliciesClient: %w", err)
	}
	defer policiesClient.Close()

	// Each deny policy is attached to an organization, folder, or project.
	// To work with deny policies, specify the attachment point.
	//
	// Its format can be one of the following:
	// 1. cloudresourcemanager.googleapis.com/organizations/ORG_ID
	// 2. cloudresourcemanager.googleapis.com/folders/FOLDER_ID
	// 3. cloudresourcemanager.googleapis.com/projects/PROJECT_ID
	//
	// The attachment point is identified by its URL-encoded resource name. Hence, replace
	// the "/" with "%%2F".
	attachmentPoint := fmt.Sprintf(
		"cloudresourcemanager.googleapis.com%%2Fprojects%%2F%s",
		projectID,
	)

	req := &iampb.GetPolicyRequest{
		// Construct the full path of the policy.
		// Its format is: "policies/ATTACHMENT_POINT/denypolicies/POLICY_ID"
		Name: fmt.Sprintf("policies/%s/denypolicies/%s", attachmentPoint, policyID),
	}
	policy, err := policiesClient.GetPolicy(ctx, req)
	if err != nil {
		return fmt.Errorf("unable to get policy: %w", err)
	}

	fmt.Fprintf(w, "Policy %s retrieved\n", policy.GetName())

	return nil
}

Java

Per scoprire come installare e utilizzare la libreria client per IAM, consulta Librerie client IAM. Per ulteriori informazioni, consulta la documentazione di riferimento dell'API IAM Java.

Per autenticarti in IAM, configura le Credenziali predefinite dell'applicazione. Per ulteriori informazioni, consulta Prima di iniziare.


import com.google.iam.v2.GetPolicyRequest;
import com.google.iam.v2.PoliciesClient;
import com.google.iam.v2.Policy;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

public class GetDenyPolicy {

  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.

    // ID or number of the Google Cloud project you want to use.
    String projectId = "your-google-cloud-project-id";

    // Specify the ID of the deny policy you want to retrieve.
    String policyId = "deny-policy-id";

    getDenyPolicy(projectId, policyId);
  }

  // Retrieve the deny policy given the project ID and policy ID.
  public static void getDenyPolicy(String projectId, String policyId) throws IOException {
    // Create the IAM Policies client.
    try (PoliciesClient policiesClient = PoliciesClient.create()) {

      // Each deny policy is attached to an organization, folder, or project.
      // To work with deny policies, specify the attachment point.
      //
      // Its format can be one of the following:
      // 1. cloudresourcemanager.googleapis.com/organizations/ORG_ID
      // 2. cloudresourcemanager.googleapis.com/folders/FOLDER_ID
      // 3. cloudresourcemanager.googleapis.com/projects/PROJECT_ID
      //
      // The attachment point is identified by its URL-encoded resource name.
      String urlEncodedResource =
          URLEncoder.encode(
              "cloudresourcemanager.googleapis.com/projects/", StandardCharsets.UTF_8);
      String attachmentPoint = String.format("%s%s", urlEncodedResource, projectId);

      // Construct the full path of the resource to which the policy is attached.
      // Its format is: "policies/{attachmentPoint}/denypolicies/{policyId}"
      String policyParent = String.format("policies/%s/denypolicies/%s", attachmentPoint, policyId);

      // Specify the policyParent and execute the GetPolicy request.
      GetPolicyRequest getPolicyRequest =
          GetPolicyRequest.newBuilder().setName(policyParent).build();

      Policy policy = policiesClient.getPolicy(getPolicyRequest);
      System.out.printf("Retrieved the deny policy: %s : %s%n", policyId, policy);
    }
  }
}

Node.js

Per scoprire come installare e utilizzare la libreria client per IAM, consulta Librerie client IAM. Per ulteriori informazioni, consulta la documentazione di riferimento dell'API IAM Node.js.

Per autenticarti in IAM, configura le Credenziali predefinite dell'applicazione. Per ulteriori informazioni, consulta Prima di iniziare.

/**
 * TODO(developer): Uncomment and replace these variables before running the sample.
 */
// const projectId = 'YOUR_PROJECT_ID';
// const policyID = 'YOUR_POLICY_ID';

const {PoliciesClient} = require('@google-cloud/iam').v2;

const iamClient = new PoliciesClient();

// Each deny policy is attached to an organization, folder, or project.
// To work with deny policies, specify the attachment point.
//
// Its format can be one of the following:
// 1. cloudresourcemanager.googleapis.com/organizations/ORG_ID
// 2. cloudresourcemanager.googleapis.com/folders/FOLDER_ID
// 3. cloudresourcemanager.googleapis.com/projects/PROJECT_ID
//
// The attachment point is identified by its URL-encoded resource name. Hence, replace
// the "/" with "%2F".
const attachmentPoint = `cloudresourcemanager.googleapis.com%2Fprojects%2F${projectId}`;

async function getDenyPolicy() {
  const request = {
    name: `policies/${attachmentPoint}/denypolicies/${policyId}`,
  };

  const [policy] = await iamClient.getPolicy(request);

  console.log(`Retrieved the deny policy: ${policy.name}`);
}

getDenyPolicy();

Python

Per scoprire come installare e utilizzare la libreria client per IAM, consulta Librerie client IAM. Per ulteriori informazioni, consulta la documentazione di riferimento dell'API IAM Python.

Per autenticarti in IAM, configura le Credenziali predefinite dell'applicazione. Per ulteriori informazioni, consulta Prima di iniziare.

from google.cloud import iam_v2
from google.cloud.iam_v2 import Policy, types


def get_deny_policy(project_id: str, policy_id: str) -> Policy:
    """Retrieve the deny policy given the project ID and policy ID.

    project_id: ID or number of the Google Cloud project you want to use.
    policy_id: The ID of the deny policy you want to retrieve.
    """
    policies_client = iam_v2.PoliciesClient()

    # Each deny policy is attached to an organization, folder, or project.
    # To work with deny policies, specify the attachment point.
    #
    # Its format can be one of the following:
    # 1. cloudresourcemanager.googleapis.com/organizations/ORG_ID
    # 2. cloudresourcemanager.googleapis.com/folders/FOLDER_ID
    # 3. cloudresourcemanager.googleapis.com/projects/PROJECT_ID
    #
    # The attachment point is identified by its URL-encoded resource name. Hence, replace
    # the "/" with "%2F".
    attachment_point = f"cloudresourcemanager.googleapis.com%2Fprojects%2F{project_id}"

    request = types.GetPolicyRequest()
    # Construct the full path of the policy.
    # Its format is: "policies/{attachmentPoint}/denypolicies/{policyId}"
    request.name = f"policies/{attachment_point}/denypolicies/{policy_id}"

    # Execute the GetPolicy request.
    policy = policies_client.get_policy(request=request)
    print(f"Retrieved the deny policy: {policy_id} : {policy}")
    return policy


if __name__ == "__main__":
    # Your Google Cloud project ID.
    PROJECT_ID = os.getenv("GOOGLE_CLOUD_PROJECT", "your-google-cloud-project-id")

    # Any unique ID (0 to 63 chars) starting with a lowercase letter.
    policy_id = f"deny-{uuid.uuid4()}"

    policy = get_deny_policy(PROJECT_ID, policy_id)

REST

Il metodo policies.get recupera un criterio di negazione per una risorsa.

Prima di utilizzare i dati della richiesta, apporta le seguenti sostituzioni:

  • ENCODED_ATTACHMENT_POINT: un identificatore codificato come URL per la risorsa a cui è associata la policy di negazione. Per scoprire come formattare questo valore, consulta Punto di attacco.

  • POLICY_ID: un identificatore per la policy di negazione.

Metodo HTTP e URL:

GET https://iam.googleapis.com/v2/policies/ENCODED_ATTACHMENT_POINT/denypolicies/POLICY_ID

Per inviare la richiesta, espandi una di queste opzioni:

Dovresti ricevere una risposta JSON simile alla seguente:

{
  "name": "policies/cloudresourcemanager.googleapis.com%2Fprojects%2F1234567890123/denypolicies/my-policy",
  "uid": "6665c437-a3b2-a018-6934-54dd16d3426e",
  "kind": "DenyPolicy",
  "displayName": "My deny policy.",
  "etag": "MTc3NDU4MjM4OTY0MzU5MjQ5OTI=",
  "createTime": "2022-06-05T19:22:26.770543Z",
  "updateTime": "2022-06-05T19:22:26.770543Z",
  "rules": [
    {
      "denyRule": {
        "deniedPrincipals": [
          "principal://goog/subject/lucian@example.com"
        ],
        "deniedPermissions": [
          "iam.googleapis.com/roles.create"
        ]
      }
    }
  ]
}

Modifica la policy di negazione

Per modificare la policy di negazione, devi apportare modifiche alla copia della policy che hai letto in precedenza da IAM. Puoi aggiornare il nome visualizzato oppure aggiungere, modificare o rimuovere le regole di negazione. Le modifiche non entrano in vigore finché non scrivi le norme aggiornate.

Ad esempio, puoi aggiungere un'autorizzazione a una regola di negazione esistente:

{
  "name": "policies/cloudresourcemanager.googleapis.com%2Fprojects%2F1234567890123/denypolicies/my-policy",
  "uid": "6665c437-a3b2-a018-6934-54dd16d3426e",
  "kind": "DenyPolicy",
  "displayName": "My deny policy.",
  "etag": "MTc3NDU4MjM4OTY0MzU5MjQ5OTI=",
  "createTime": "2021-10-05T19:22:26.770543Z",
  "updateTime": "2021-10-05T19:22:26.770543Z",
  "rules": [
    {
      "denyRule": {
        "deniedPrincipals": [
          "principal://goog/subject/lucian@example.com"
        ],
        "deniedPermissions": [
          "iam.googleapis.com/roles.create",
          "iam.googleapis.com/roles.delete"
        ]
      }
    }
  ]
}

Scrivi la policy di negazione aggiornata

Dopo aver modificato localmente la policy di negazione, devi scrivere la policy di negazione aggiornata in IAM.

Ogni policy di negazione contiene un campo etag che identifica la versione della policy. Il valore di etag cambia ogni volta che aggiorni il criterio. Quando scrivi la policy aggiornata, il etag nella tua richiesta deve corrispondere al etag corrente memorizzato in IAM. Se i valori non corrispondono, la richiesta non va a buon fine. Questa funzionalità consente di evitare che le modifiche simultanee si sovrascrivano a vicenda.

gcloud

Per aggiornare la policy di negazione per una risorsa, esegui il comando gcloud iam policies update:

gcloud iam policies update POLICY_ID \
    --attachment-point=ATTACHMENT_POINT \
    --kind=denypolicies \
    --policy-file=POLICY_FILE

Fornisci i seguenti valori:

  • POLICY_ID: l'identificatore della policy di negazione.

  • ATTACHMENT_POINT: un identificatore della risorsa a cui è associato il criterio di negazione. Per scoprire come formattare questo valore, consulta Punto di attacco.

  • POLICY_FILE: il percorso del file JSON che contiene la policy di negazione.

Per impostazione predefinita, se questo comando ha esito positivo, non stampa alcun output. Per stampare una risposta dettagliata, aggiungi il flag --format=json al comando.

Ad esempio, il seguente comando aggiorna una policy di negazione denominata my-deny-policy per il progetto my-project, utilizzando un file denominato policy.json:

gcloud iam policies update my-deny-policy \
    --attachment-point=cloudresourcemanager.googleapis.com/projects/my-project \
    --kind=denypolicies \
    --policy-file=policy.json

Go

Per scoprire come installare e utilizzare la libreria client per IAM, consulta Librerie client IAM. Per ulteriori informazioni, consulta la documentazione di riferimento dell'API IAM Go.

Per autenticarti in IAM, configura le Credenziali predefinite dell'applicazione. Per ulteriori informazioni, consulta Prima di iniziare.

import (
	"context"
	"fmt"
	"io"

	iam "cloud.google.com/go/iam/apiv2"

	"cloud.google.com/go/iam/apiv2/iampb"
	"google.golang.org/genproto/googleapis/type/expr"
)

// updateDenyPolicy updates the deny rules and/ or its display name after policy creation.
func updateDenyPolicy(w io.Writer, projectID, policyID, etag string) error {
	// projectID := "your_project_id"
	// policyID := "your_policy_id"
	// etag := "your_etag"

	ctx := context.Background()
	policiesClient, err := iam.NewPoliciesClient(ctx)
	if err != nil {
		return fmt.Errorf("NewPoliciesClient: %w", err)
	}
	defer policiesClient.Close()

	// Each deny policy is attached to an organization, folder, or project.
	// To work with deny policies, specify the attachment point.
	//
	// Its format can be one of the following:
	// 1. cloudresourcemanager.googleapis.com/organizations/ORG_ID
	// 2. cloudresourcemanager.googleapis.com/folders/FOLDER_ID
	// 3. cloudresourcemanager.googleapis.com/projects/PROJECT_ID
	//
	// The attachment point is identified by its URL-encoded resource name. Hence, replace
	// the "/" with "%%2F".
	attachmentPoint := fmt.Sprintf(
		"cloudresourcemanager.googleapis.com%%2Fprojects%%2F%s",
		projectID,
	)

	denyRule := &iampb.DenyRule{
		// Add one or more principals who should be denied the permissions specified in this rule.
		// For more information on allowed values,
		// see: https://cloud.google.com/iam/help/deny/principal-identifiers
		DeniedPrincipals: []string{"principalSet://goog/public:all"},
		// Optionally, set the principals who should be exempted from the
		// list of denied principals. For example, if you want to deny certain permissions
		// to a group but exempt a few principals, then add those here.
		// ExceptionPrincipals: []string{"principalSet://goog/group/project-admins@example.com"},
		//
		// Set the permissions to deny.
		// The permission value is of the format: service_fqdn/resource.action
		// For the list of supported permissions,
		// see: https://cloud.google.com/iam/help/deny/supported-permissions
		DeniedPermissions: []string{"cloudresourcemanager.googleapis.com/projects.delete"},
		// Optionally, add the permissions to be exempted from this rule.
		// Meaning, the deny rule will not be applicable to these permissions.
		// ExceptionPermissions: []string{"cloudresourcemanager.googleapis.com/projects.create"},
		//
		// Set the condition which will enforce the deny rule.
		// If this condition is true, the deny rule will be applicable.
		// Else, the rule will not be enforced.
		// The expression uses Common Expression Language syntax (CEL).
		// Here we block access based on tags.
		//
		// Here, we create a deny rule that denies the
		// cloudresourcemanager.googleapis.com/projects.delete permission
		// to everyone except project-admins@example.com for resources that are tagged prod.
		// A tag is a key-value pair that can be attached to an organization, folder, or project.
		// For more info, see: https://cloud.google.com/iam/docs/deny-access#create-deny-policy
		DenialCondition: &expr.Expr{
			Expression: "!resource.matchTag('12345678/env', 'prod')",
		},
	}

	// Set the rule description and deny rule to update.
	policyRule := &iampb.PolicyRule{
		Description: "block all principals from deleting projects, unless the principal is a member of project-admins@example.com and the project being deleted has a tag with the value prod",
		Kind: &iampb.PolicyRule_DenyRule{
			DenyRule: denyRule,
		},
	}

	// Set the policy resource path, version (etag) and the updated deny rules.
	policy := &iampb.Policy{
		// Construct the full path of the policy.
		// Its format is: "policies/ATTACHMENT_POINT/denypolicies/POLICY_ID"
		Name:  fmt.Sprintf("policies/%s/denypolicies/%s", attachmentPoint, policyID),
		Etag:  etag,
		Rules: [](*iampb.PolicyRule){policyRule},
	}

	// Create the update policy request.
	req := &iampb.UpdatePolicyRequest{
		Policy: policy,
	}
	op, err := policiesClient.UpdatePolicy(ctx, req)
	if err != nil {
		return fmt.Errorf("unable to update policy: %w", err)
	}

	policy, err = op.Wait(ctx)
	if err != nil {
		return fmt.Errorf("unable to wait for the operation: %w", err)
	}

	fmt.Fprintf(w, "Policy %s updated\n", policy.GetName())

	return nil
}

Java

Per scoprire come installare e utilizzare la libreria client per IAM, consulta Librerie client IAM. Per ulteriori informazioni, consulta la documentazione di riferimento dell'API IAM Java.

Per autenticarti in IAM, configura le Credenziali predefinite dell'applicazione. Per ulteriori informazioni, consulta Prima di iniziare.


import com.google.iam.v2.DenyRule;
import com.google.iam.v2.PoliciesClient;
import com.google.iam.v2.Policy;
import com.google.iam.v2.PolicyRule;
import com.google.iam.v2.UpdatePolicyRequest;
import com.google.longrunning.Operation;
import com.google.type.Expr;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class UpdateDenyPolicy {

  public static void main(String[] args)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // TODO(developer): Replace these variables before running the sample.

    // ID or number of the Google Cloud project you want to use.
    String projectId = "your-google-cloud-project-id";

    // Specify the ID of the Deny policy you want to retrieve.
    String policyId = "deny-policy-id";

    // Etag field that identifies the policy version. The etag changes each time
    // you update the policy. Get the etag of an existing policy by performing a GetPolicy request.
    String etag = "policy_etag";

    updateDenyPolicy(projectId, policyId, etag);
  }

  // Update the deny rules and/ or its display name after policy creation.
  public static void updateDenyPolicy(String projectId, String policyId, String etag)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {

    try (PoliciesClient policiesClient = PoliciesClient.create()) {

      // Each deny policy is attached to an organization, folder, or project.
      // To work with deny policies, specify the attachment point.
      //
      // Its format can be one of the following:
      // 1. cloudresourcemanager.googleapis.com/organizations/ORG_ID
      // 2. cloudresourcemanager.googleapis.com/folders/FOLDER_ID
      // 3. cloudresourcemanager.googleapis.com/projects/PROJECT_ID
      //
      // The attachment point is identified by its URL-encoded resource name.
      String urlEncodedResource =
          URLEncoder.encode(
              "cloudresourcemanager.googleapis.com/projects/", StandardCharsets.UTF_8);
      String attachmentPoint = String.format("%s%s", urlEncodedResource, projectId);

      // Construct the full path of the resource to which the policy is attached to.
      // Its format is: "policies/{attachmentPoint}/denypolicies/{policyId}"
      String policyParent = String.format("policies/%s/denypolicies/%s", attachmentPoint, policyId);

      DenyRule denyRule =
          DenyRule.newBuilder()
              // Add one or more principals who should be denied the permissions specified in this
              // rule.
              // For more information on allowed values, see:
              // https://cloud.google.com/iam/docs/principal-identifiers
              .addDeniedPrincipals("principalSet://goog/public:all")

              // Optionally, set the principals who should be exempted from the list of principals
              // added in "DeniedPrincipals".
              // Example, if you want to deny certain permissions to a group but exempt a few
              // principals, then add those here.
              // .addExceptionPrincipals(
              //     "principalSet://goog/group/project-admins@example.com")

              // Set the permissions to deny.
              // The permission value is of the format: service_fqdn/resource.action
              // For the list of supported permissions, see:
              // https://cloud.google.com/iam/help/deny/supported-permissions
              .addDeniedPermissions("cloudresourcemanager.googleapis.com/projects.delete")

              // Add the permissions to be exempted from this rule.
              // Meaning, the deny rule will not be applicable to these permissions.
              // .addExceptionPermissions("cloudresourcemanager.googleapis.com/projects.get")

              // Set the condition which will enforce the deny rule.
              // If this condition is true, the deny rule will be applicable. Else, the rule will
              // not be enforced.
              .setDenialCondition(
                  Expr.newBuilder()
                      // The expression uses Common Expression Language syntax (CEL). Here we block
                      // access based on tags.
                      //
                      // A tag is a key-value pair that can be attached to an organization, folder,
                      // or project. You can use deny policies to deny permissions based on tags
                      // without adding an IAM Condition to every role grant.
                      // For example, imagine that you tag all of your projects as dev, test, or
                      // prod. You want only members of project-admins@example.com to be able to
                      // perform operations on projects that are tagged prod.
                      // To solve this problem, you create a deny rule that denies the
                      // cloudresourcemanager.googleapis.com/projects.delete permission to everyone
                      // except project-admins@example.com for resources that are tagged prod.
                      .setExpression("!resource.matchTag('12345678/env', 'prod')")
                      .setTitle("Only for prod projects")
                      .build())
              .build();

      // Set the policy resource path, version (etag) and the updated deny rules.
      Policy policy =
          Policy.newBuilder()
              .setName(policyParent)
              .setEtag(etag)
              .addRules(
                  PolicyRule.newBuilder()
                      // Set the rule description to update.
                      .setDescription(
                          "Block all principals from deleting projects, unless the principal"
                              + " is a member of project-admins@example.com and the project"
                              + "being deleted has a tag with the value prod")
                      // Set the deny rule to update.
                      .setDenyRule(denyRule)
                      .build())
              .build();

      // Create the update policy request.
      UpdatePolicyRequest updatePolicyRequest =
          UpdatePolicyRequest.newBuilder().setPolicy(policy).build();

      // Wait for the operation to complete.
      Operation operation =
          policiesClient
              .updatePolicyCallable()
              .futureCall(updatePolicyRequest)
              .get(3, TimeUnit.MINUTES);

      if (operation.hasError()) {
        System.out.println("Error in updating the policy " + operation.getError());
        return;
      }

      System.out.println("Updated the deny policy: " + policyId);
    }
  }
}

Node.js

Per scoprire come installare e utilizzare la libreria client per IAM, consulta Librerie client IAM. Per ulteriori informazioni, consulta la documentazione di riferimento dell'API IAM Node.js.

Per autenticarti in IAM, configura le Credenziali predefinite dell'applicazione. Per ulteriori informazioni, consulta Prima di iniziare.

/**
 * TODO(developer): Uncomment and replace these variables before running the sample.
 */
// const projectId = 'YOUR_PROJECT_ID';
// const policyID = 'YOUR_POLICY_ID';
// const etag = 'YOUR_ETAG';

const {PoliciesClient} = require('@google-cloud/iam').v2;

const iamClient = new PoliciesClient();

// Each deny policy is attached to an organization, folder, or project.
// To work with deny policies, specify the attachment point.
//
// Its format can be one of the following:
// 1. cloudresourcemanager.googleapis.com/organizations/ORG_ID
// 2. cloudresourcemanager.googleapis.com/folders/FOLDER_ID
// 3. cloudresourcemanager.googleapis.com/projects/PROJECT_ID
//
// The attachment point is identified by its URL-encoded resource name. Hence, replace
// the "/" with "%2F".
const attachmentPoint = `cloudresourcemanager.googleapis.com%2Fprojects%2F${projectId}`;

const denyRule = {
  // Add one or more principals who should be denied the permissions specified in this rule.
  // For more information on allowed values, see: https://cloud.google.com/iam/help/deny/principal-identifiers
  deniedPrincipals: ['principalSet://goog/public:all'],
  // Optionally, set the principals who should be exempted from the
  // list of denied principals. For example, if you want to deny certain permissions
  // to a group but exempt a few principals, then add those here.
  // exceptionPrincipals: ['principalSet://goog/group/project-admins@example.com'],
  // Set the permissions to deny.
  // The permission value is of the format: service_fqdn/resource.action
  // For the list of supported permissions, see: https://cloud.google.com/iam/help/deny/supported-permissions
  deniedPermissions: ['cloudresourcemanager.googleapis.com/projects.delete'],
  // Optionally, add the permissions to be exempted from this rule.
  // Meaning, the deny rule will not be applicable to these permissions.
  // exceptionPermissions: ['cloudresourcemanager.googleapis.com/projects.create']
  //
  // Set the condition which will enforce the deny rule.
  // If this condition is true, the deny rule will be applicable. Else, the rule will not be enforced.
  // The expression uses Common Expression Language syntax (CEL).
  // Here we block access based on tags.
  //
  // Here, we create a deny rule that denies the cloudresourcemanager.googleapis.com/projects.delete permission to everyone except project-admins@example.com for resources that are tagged test.
  // A tag is a key-value pair that can be attached to an organization, folder, or project.
  // For more info, see: https://cloud.google.com/iam/docs/deny-access#create-deny-policy
  denialCondition: {
    expression: '!resource.matchTag("12345678/env", "prod")',
  },
};

async function updateDenyPolicy() {
  const request = {
    policy: {
      name: `policies/${attachmentPoint}/denypolicies/${policyId}`,
      etag,
      rules: [
        {
          description:
            'block all principals from deleting projects, unless the principal is a member of project-admins@example.com and the project being deleted has a tag with the value prod',
          denyRule,
        },
      ],
    },
    policyId,
  };

  const [operation] = await iamClient.updatePolicy(request);
  const [policy] = await operation.promise();

  console.log(`Updated the deny policy: ${policy.name}`);
}

updateDenyPolicy();

Python

Per scoprire come installare e utilizzare la libreria client per IAM, consulta Librerie client IAM. Per ulteriori informazioni, consulta la documentazione di riferimento dell'API IAM Python.

Per autenticarti in IAM, configura le Credenziali predefinite dell'applicazione. Per ulteriori informazioni, consulta Prima di iniziare.

def update_deny_policy(project_id: str, policy_id: str, etag: str) -> None:
    """Update the deny rules and/ or its display name after policy creation.

    project_id: ID or number of the Google Cloud project you want to use.

    policy_id: The ID of the deny policy you want to retrieve.

    etag: Etag field that identifies the policy version. The etag changes each time
    you update the policy. Get the etag of an existing policy by performing a GetPolicy request.
    """

    from google.cloud import iam_v2
    from google.cloud.iam_v2 import types

    policies_client = iam_v2.PoliciesClient()

    # Each deny policy is attached to an organization, folder, or project.
    # To work with deny policies, specify the attachment point.
    #
    # Its format can be one of the following:
    # 1. cloudresourcemanager.googleapis.com/organizations/ORG_ID
    # 2. cloudresourcemanager.googleapis.com/folders/FOLDER_ID
    # 3. cloudresourcemanager.googleapis.com/projects/PROJECT_ID
    #
    # The attachment point is identified by its URL-encoded resource name.
    # Hence, replace the "/" with "%2F".
    attachment_point = f"cloudresourcemanager.googleapis.com%2Fprojects%2F{project_id}"

    deny_rule = types.DenyRule()

    # Add one or more principals who should be denied the permissions
    # specified in this rule.
    # For more information on allowed values, see:
    # https://cloud.google.com/iam/help/deny/principal-identifiers
    deny_rule.denied_principals = ["principalSet://goog/public:all"]

    # Optionally, set the principals who should be exempted
    # from the list of principals added in "DeniedPrincipals".
    # Example, if you want to deny certain permissions to a group
    # but exempt a few principals, then add those here.
    # deny_rule.exception_principals = ["principalSet://goog/group/project-admins@example.com"]

    # Set the permissions to deny.
    # The permission value is of the format: service_fqdn/resource.action
    # For the list of supported permissions, see:
    # https://cloud.google.com/iam/help/deny/supported-permissions
    deny_rule.denied_permissions = [
        "cloudresourcemanager.googleapis.com/projects.delete"
    ]

    # Add the permissions to be exempted from this rule.
    # Meaning, the deny rule will not be applicable to these permissions.
    # deny_rule.exception_permissions = ["cloudresourcemanager.googleapis.com/projects.get"]

    # Set the condition which will enforce the deny rule.
    # If this condition is true, the deny rule will be applicable.
    # Else, the rule will not be enforced.
    #
    # The expression uses Common Expression Language syntax (CEL).
    # Here we block access based on tags.
    #
    # Here, we create a deny rule that denies the
    # cloudresourcemanager.googleapis.com/projects.delete permission to everyone
    # except project-admins@example.com for resources that are tagged prod.
    # A tag is a key-value pair that can be attached
    # to an organization, folder, or project.
    # For more info, see:
    # https://cloud.google.com/iam/docs/deny-access#create-deny-policy
    deny_rule.denial_condition = {
        "expression": "!resource.matchTag('12345678/env', 'prod')"
    }

    # Set the rule description and deny rule to update.
    policy_rule = types.PolicyRule()
    policy_rule.description = "block all principals from deleting projects, unless the principal is a member of project-admins@example.com and the project being deleted has a tag with the value prod"
    policy_rule.deny_rule = deny_rule

    # Set the policy resource path, version (etag) and the updated deny rules.
    policy = types.Policy()
    # Construct the full path of the policy.
    # Its format is: "policies/{attachmentPoint}/denypolicies/{policyId}"
    policy.name = f"policies/{attachment_point}/denypolicies/{policy_id}"
    policy.etag = etag
    policy.rules = [policy_rule]

    # Create the update policy request.
    request = types.UpdatePolicyRequest()
    request.policy = policy

    result = policies_client.update_policy(request=request).result()
    print(f"Updated the deny policy: {result.name.rsplit('/')[-1]}")


if __name__ == "__main__":
    # Your Google Cloud project ID.
    PROJECT_ID = os.getenv("GOOGLE_CLOUD_PROJECT", "your-google-cloud-project-id")

    # Any unique ID (0 to 63 chars) starting with a lowercase letter.
    policy_id = f"deny-{uuid.uuid4()}"
    # Get the etag by performing a Get policy request.
    etag = "etag"

    update_deny_policy(PROJECT_ID, policy_id, etag)

REST

Il metodo policies.update aggiorna una policy di negazione.

Prima di utilizzare i dati della richiesta, apporta le seguenti sostituzioni:

  • ENCODED_ATTACHMENT_POINT: un identificatore codificato come URL per la risorsa a cui è associata la policy di negazione. Per scoprire come formattare questo valore, consulta Punto di attacco.

  • POLICY_ID: un identificatore per la policy di negazione.
  • POLICY: la policy di negazione aggiornata.

    Ad esempio, per aggiungere un'autorizzazione alla norma mostrata nel passaggio precedente, sostituisci POLICY con quanto segue:

    {
      "name": "policies/cloudresourcemanager.googleapis.com%2Fprojects%2F1234567890123/denypolicies/my-policy",
      "uid": "6665c437-a3b2-a018-6934-54dd16d3426e",
      "kind": "DenyPolicy",
      "displayName": "My deny policy.",
      "etag": "MTc3NDU4MjM4OTY0MzU5MjQ5OTI=",
      "createTime": "2022-06-05T19:22:26.770543Z",
      "updateTime": "2022-06-05T19:22:26.770543Z",
      "rules": [
        {
          "denyRule": {
            "deniedPrincipals": [
              "principal://goog/subject/lucian@example.com"
            ],
            "deniedPermissions": [
              "iam.googleapis.com/roles.create",
              "iam.googleapis.com/roles.delete"
            ]
          }
        }
      ]
    }

Metodo HTTP e URL:

PUT https://iam.googleapis.com/v2/policies/ENCODED_ATTACHMENT_POINT/denypolicies/POLICY_ID

Corpo JSON della richiesta:

POLICY

Per inviare la richiesta, espandi una di queste opzioni:

Dovresti ricevere una risposta JSON simile alla seguente:

{
  "name": "policies/cloudresourcemanager.googleapis.com%2Fprojects%2F1234567890123/denypolicies/my-policy/operations/8b2d0ab2daf1ff01",
  "metadata": {
    "@type": "type.googleapis.com/google.iam.v2.PolicyOperationMetadata",
    "createTime": "2021-10-05T22:26:21.968687Z"
  },
  "response": {
    "@type": "type.googleapis.com/google.iam.v2.Policy",
    "name": "policies/cloudresourcemanager.googleapis.com%2Fprojects%2F1234567890123/denypolicies/my-policy",
    "uid": "6665c437-a3b2-a018-6934-54dd16d3426e",
    "kind": "DenyPolicy",
    "displayName": "My deny policy.",
    "etag": "MTgxNTIxNDE3NTYxNjQxODYxMTI=",
    "createTime": "2022-06-05T19:22:26.770543Z",
    "updateTime": "2022-06-05T22:26:21.968687Z",
    "rules": [
      {
        "denyRule": {
          "deniedPrincipals": [
            "principal://goog/subject/lucian@example.com"
          ],
          "deniedPermissions": [
            "iam.googleapis.com/roles.create",
            "iam.googleapis.com/roles.delete"
          ]
        }
      }
    ]
  }
}

La risposta identifica un'operazione a lunga esecuzione. Puoi monitorare lo stato dell'operazione a lunga esecuzione per scoprire quando è stata completata. Per maggiori dettagli, vedi Controllare lo stato di un'operazione di lunga durata in questa pagina.

Eliminare una policy di negazione

Se non vuoi più applicare le regole in un criterio di negazione, puoi eliminarlo.

(Facoltativo) Puoi specificare etag per la versione della policy che stai eliminando. Se specifichi etag, questo deve corrispondere all'etag corrente archiviato da IAM. Se i valori non corrispondono, la richiesta non va a buon fine. Puoi utilizzare questa funzionalità per assicurarti di eliminare la policy che ti interessa, anziché una versione aggiornata.

Se ometti etag dalla richiesta, IAM elimina la policy in modo incondizionato.

Console

  1. Nella console Google Cloud , vai alla scheda Nega nella pagina IAM.

    Vai a IAM

  2. Seleziona un progetto, una cartella o un'organizzazione.

  3. Nella colonna ID norma, fai clic sull'ID della norma che vuoi eliminare.

  4. Fai clic su Elimina. Nella finestra di dialogo di conferma, fai clic su Conferma.

gcloud

Per eliminare una policy di negazione da una risorsa, esegui il comando gcloud iam policies delete:

gcloud iam policies delete POLICY_ID \
    --attachment-point=ATTACHMENT_POINT \
    --kind=denypolicies

Fornisci i seguenti valori:

  • POLICY_ID: l'identificatore della policy di negazione.

  • ATTACHMENT_POINT: un identificatore della risorsa a cui è associato il criterio di negazione. Per scoprire come formattare questo valore, consulta Punto di attacco.

Se vuoi, puoi aggiungere il flag --etag=ETAG. Sostituisci ETAG con il valore etag corrente per il criterio di negazione.

Per impostazione predefinita, se questo comando ha esito positivo, non stampa alcun output. Per stampare una risposta dettagliata, aggiungi il flag --format=json al comando.

Ad esempio, il seguente comando elimina un criterio di negazione denominato my-deny-policy dal progetto my-project:

gcloud iam policies delete my-deny-policy \
    --attachment-point=cloudresourcemanager.googleapis.com/projects/my-project \
    --kind=denypolicies

Go

Per scoprire come installare e utilizzare la libreria client per IAM, consulta Librerie client IAM. Per ulteriori informazioni, consulta la documentazione di riferimento dell'API IAM Go.

Per autenticarti in IAM, configura le Credenziali predefinite dell'applicazione. Per ulteriori informazioni, consulta Prima di iniziare.

import (
	"context"
	"fmt"
	"io"

	iam "cloud.google.com/go/iam/apiv2"

	"cloud.google.com/go/iam/apiv2/iampb"
)

// deleteDenyPolicy deletes the policy if you no longer want to enforce the rules in a deny policy.
func deleteDenyPolicy(w io.Writer, projectID, policyID string) error {
	// projectID := "your_project_id"
	// policyID := "your_policy_id"

	ctx := context.Background()
	policiesClient, err := iam.NewPoliciesClient(ctx)
	if err != nil {
		return fmt.Errorf("NewPoliciesClient: %w", err)
	}
	defer policiesClient.Close()

	// Each deny policy is attached to an organization, folder, or project.
	// To work with deny policies, specify the attachment point.
	//
	// Its format can be one of the following:
	// 1. cloudresourcemanager.googleapis.com/organizations/ORG_ID
	// 2. cloudresourcemanager.googleapis.com/folders/FOLDER_ID
	// 3. cloudresourcemanager.googleapis.com/projects/PROJECT_ID
	//
	// The attachment point is identified by its URL-encoded resource name. Hence, replace
	// the "/" with "%%2F".
	attachmentPoint := fmt.Sprintf(
		"cloudresourcemanager.googleapis.com%%2Fprojects%%2F%s",
		projectID,
	)

	req := &iampb.DeletePolicyRequest{
		// Construct the full path of the policy.
		// Its format is: "policies/ATTACHMENT_POINT/denypolicies/POLICY_ID"
		Name: fmt.Sprintf("policies/%s/denypolicies/%s", attachmentPoint, policyID),
	}
	op, err := policiesClient.DeletePolicy(ctx, req)
	if err != nil {
		return fmt.Errorf("unable to delete policy: %w", err)
	}

	policy, err := op.Wait(ctx)
	if err != nil {
		return fmt.Errorf("unable to wait for the operation: %w", err)
	}

	fmt.Fprintf(w, "Policy %s deleted\n", policy.GetName())

	return nil
}

Java

Per scoprire come installare e utilizzare la libreria client per IAM, consulta Librerie client IAM. Per ulteriori informazioni, consulta la documentazione di riferimento dell'API IAM Java.

Per autenticarti in IAM, configura le Credenziali predefinite dell'applicazione. Per ulteriori informazioni, consulta Prima di iniziare.


import com.google.iam.v2.DeletePolicyRequest;
import com.google.iam.v2.PoliciesClient;
import com.google.longrunning.Operation;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class DeleteDenyPolicy {

  public static void main(String[] args)
      throws IOException, InterruptedException, ExecutionException, TimeoutException {
    // TODO(developer): Replace these variables before running the sample.

    // ID or number of the Google Cloud project you want to use.
    String projectId = "your-google-cloud-project-id";

    // Specify the ID of the deny policy you want to retrieve.
    String policyId = "deny-policy-id";

    deleteDenyPolicy(projectId, policyId);
  }

  // Delete the policy if you no longer want to enforce the rules in a deny policy.
  public static void deleteDenyPolicy(String projectId, String policyId)
      throws IOException, InterruptedException, ExecutionException, TimeoutException {
    try (PoliciesClient policiesClient = PoliciesClient.create()) {

      // Each deny policy is attached to an organization, folder, or project.
      // To work with deny policies, specify the attachment point.
      //
      // Its format can be one of the following:
      // 1. cloudresourcemanager.googleapis.com/organizations/ORG_ID
      // 2. cloudresourcemanager.googleapis.com/folders/FOLDER_ID
      // 3. cloudresourcemanager.googleapis.com/projects/PROJECT_ID
      //
      // The attachment point is identified by its URL-encoded resource name.
      String urlEncodedResource =
          URLEncoder.encode(
              "cloudresourcemanager.googleapis.com/projects/", StandardCharsets.UTF_8);
      String attachmentPoint = String.format("%s%s", urlEncodedResource, projectId);

      // Construct the full path of the resource to which the policy is attached.
      // Its format is: "policies/{attachmentPoint}/denypolicies/{policyId}"
      String policyParent = String.format("policies/%s/denypolicies/%s", attachmentPoint, policyId);

      // Create the DeletePolicy request.
      DeletePolicyRequest deletePolicyRequest =
          DeletePolicyRequest.newBuilder().setName(policyParent).build();

      // Delete the policy and wait for the operation to complete.
      Operation operation =
          policiesClient
              .deletePolicyCallable()
              .futureCall(deletePolicyRequest)
              .get(3, TimeUnit.MINUTES);

      if (operation.hasError()) {
        System.out.println("Error in deleting the policy " + operation.getError());
        return;
      }

      System.out.println("Deleted the deny policy: " + policyId);
    }
  }
}

Node.js

Per scoprire come installare e utilizzare la libreria client per IAM, consulta Librerie client IAM. Per ulteriori informazioni, consulta la documentazione di riferimento dell'API IAM Node.js.

Per autenticarti in IAM, configura le Credenziali predefinite dell'applicazione. Per ulteriori informazioni, consulta Prima di iniziare.

/**
 * TODO(developer): Uncomment and replace these variables before running the sample.
 */
// const projectId = 'YOUR_PROJECT_ID';
// const policyID = 'YOUR_POLICY_ID';

const {PoliciesClient} = require('@google-cloud/iam').v2;

const iamClient = new PoliciesClient();

// Each deny policy is attached to an organization, folder, or project.
// To work with deny policies, specify the attachment point.
//
// Its format can be one of the following:
// 1. cloudresourcemanager.googleapis.com/organizations/ORG_ID
// 2. cloudresourcemanager.googleapis.com/folders/FOLDER_ID
// 3. cloudresourcemanager.googleapis.com/projects/PROJECT_ID
//
// The attachment point is identified by its URL-encoded resource name. Hence, replace
// the "/" with "%2F".
const attachmentPoint = `cloudresourcemanager.googleapis.com%2Fprojects%2F${projectId}`;

async function deleteDenyPolicy() {
  const request = {
    name: `policies/${attachmentPoint}/denypolicies/${policyId}`,
  };

  const [operation] = await iamClient.deletePolicy(request);
  const [policy] = await operation.promise();

  console.log(`Deleted the deny policy: ${policy.name}`);
}

deleteDenyPolicy();

Python

Per scoprire come installare e utilizzare la libreria client per IAM, consulta Librerie client IAM. Per ulteriori informazioni, consulta la documentazione di riferimento dell'API IAM Python.

Per autenticarti in IAM, configura le Credenziali predefinite dell'applicazione. Per ulteriori informazioni, consulta Prima di iniziare.

def delete_deny_policy(project_id: str, policy_id: str) -> None:
    """Delete the policy if you no longer want to enforce the rules in a deny policy.

    project_id: ID or number of the Google Cloud project you want to use.
    policy_id: The ID of the deny policy you want to retrieve.
    """

    from google.cloud import iam_v2
    from google.cloud.iam_v2 import types

    policies_client = iam_v2.PoliciesClient()

    # Each deny policy is attached to an organization, folder, or project.
    # To work with deny policies, specify the attachment point.
    #
    # Its format can be one of the following:
    # 1. cloudresourcemanager.googleapis.com/organizations/ORG_ID
    # 2. cloudresourcemanager.googleapis.com/folders/FOLDER_ID
    # 3. cloudresourcemanager.googleapis.com/projects/PROJECT_ID
    #
    # The attachment point is identified by its URL-encoded resource name. Hence, replace
    # the "/" with "%2F".
    attachment_point = f"cloudresourcemanager.googleapis.com%2Fprojects%2F{project_id}"

    request = types.DeletePolicyRequest()
    # Construct the full path of the policy.
    # Its format is: "policies/{attachmentPoint}/denypolicies/{policyId}"
    request.name = f"policies/{attachment_point}/denypolicies/{policy_id}"

    # Create the DeletePolicy request.
    result = policies_client.delete_policy(request=request).result()
    print(f"Deleted the deny policy: {result.name.rsplit('/')[-1]}")


if __name__ == "__main__":
    import uuid

    # Your Google Cloud project ID.
    PROJECT_ID = os.getenv("GOOGLE_CLOUD_PROJECT", "your-google-cloud-project-id")

    # Any unique ID (0 to 63 chars) starting with a lowercase letter.
    policy_id = f"deny-{uuid.uuid4()}"

    delete_deny_policy(PROJECT_ID, policy_id)

REST

Il metodo policies.delete elimina una policy di negazione da una risorsa.

Prima di utilizzare i dati della richiesta, apporta le seguenti sostituzioni:

  • ENCODED_ATTACHMENT_POINT: un identificatore codificato come URL per la risorsa a cui è associata la policy di negazione. Per scoprire come formattare questo valore, consulta Punto di attacco.

  • POLICY_ID: un identificatore per la policy di negazione.
  • ETAG: (Facoltativo). Un identificatore per la versione del criterio. Se presente, questo valore deve corrispondere al valore etag corrente per le norme.

Metodo HTTP e URL:

DELETE https://iam.googleapis.com/v2/policies/ENCODED_ATTACHMENT_POINT/denypolicies/POLICY_ID?etag=ETAG

Per inviare la richiesta, espandi una di queste opzioni:

Dovresti ricevere una risposta JSON simile alla seguente:

{
  "name": "policies/cloudresourcemanager.googleapis.com%2Fprojects%2F1234567890123/denypolicies/my-policy/operations/8223fe308bf1ff01",
  "metadata": {
    "@type": "type.googleapis.com/google.iam.v2.PolicyOperationMetadata",
    "createTime": "2021-10-05T19:45:00.133311Z"
  },
  "response": {
    "@type": "type.googleapis.com/google.iam.v2.Policy",
    "name": "policies/cloudresourcemanager.googleapis.com%2Fprojects%2F1234567890123/denypolicies/my-policy",
    "kind": "DenyPolicy",
    "displayName": "My deny policy.",
    "etag": "MTc3NDU4MjM4OTY0MzU5MjQ5OTI=",
    "createTime": "2022-06-28T19:06:12.455151Z",
    "updateTime": "2022-07-05T19:45:00.133311Z",
    "deleteTime": "2022-07-05T19:45:00.133311Z",
    "rules": [
      {
        "denyRule": {
          "deniedPrincipals": [
            "principal://goog/subject/lucian@example.com"
          ],
          "deniedPermissions": [
            "iam.googleapis.com/roles.create"
          ]
        }
      }
    ]
  }
}

La risposta identifica un'operazione a lunga esecuzione. Puoi monitorare lo stato dell'operazione a lunga esecuzione per scoprire quando è stata completata. Per maggiori dettagli, vedi Controllare lo stato di un'operazione di lunga durata in questa pagina.

Controllare lo stato di un'operazione a lunga esecuzione

Quando utilizzi l'API REST o le librerie client, qualsiasi metodo che modifica una policy di negazione restituisce un&#39operazione a lunga esecuzionea (LRO). L'operazione a lunga esecuzione monitora lo stato della richiesta e indica se la modifica alla norma è stata completata.

Go

Gli esempi di codice in questa pagina mostrano come attendere il completamento di un'operazione a lunga esecuzione e poi accedere al relativo risultato.

Java

Gli esempi di codice in questa pagina mostrano come attendere il completamento di un'operazione a lunga esecuzione e poi accedere al relativo risultato.

Node.js

Gli esempi di codice in questa pagina mostrano come attendere il completamento di un'operazione a lunga esecuzione e poi accedere al relativo risultato.

Python

Gli esempi di codice in questa pagina mostrano come attendere il completamento di un'operazione a lunga esecuzione e poi accedere al relativo risultato.

REST

Il metodo policies.operations.get restituisce lo stato di un'operazione a lunga esecuzione.

Prima di utilizzare i dati della richiesta, apporta le seguenti sostituzioni:

  • ENCODED_ATTACHMENT_POINT: un identificatore codificato come URL per la risorsa a cui è associata la policy di negazione. Per scoprire come formattare questo valore, consulta Punto di attacco.

  • OPERATION_ID: l'identificatore dell'operazione. Ricevi questo identificatore nella risposta alla tua richiesta originale, come parte del nome dell'operazione. Utilizza il valore esadecimale alla fine del nome dell'operazione. Ad esempio, 89cb3e508bf1ff01.

Metodo HTTP e URL:

GET https://iam.googleapis.com/v2/policies/ENCODED_ATTACHMENT_POINT/operations/OPERATION_ID

Per inviare la richiesta, espandi una di queste opzioni:

Dovresti ricevere una risposta JSON simile alla seguente:

{
  "name": "policies/cloudresourcemanager.googleapis.com%2Fprojects%2F1234567890123/denypolicies/my-policy/operations/89cb3e508bf1ff01",
  "done": true
}

Se il campo done dell'operazione non è presente, continua a monitorare il suo stato recuperando ripetutamente l'operazione. Utilizza il backoff esponenziale troncato per introdurre un ritardo tra ogni richiesta. Quando il campo done è impostato su true, l'operazione è completata e puoi interrompere la ricezione dell'operazione.

Passaggi successivi