Deniega el acceso a los recursos

En esta página, se explica cómo denegar el acceso de las principales evitando que usen permisos específicos de Identity and Access Management (IAM).

En IAM, deniegas el acceso con políticas de denegación. Cada política de denegación está vinculada a una organización, una carpeta o un proyecto de Google Cloud. Una política de denegación contiene reglas de denegación, que identifican las principales y enumeran los permisos que las principales no pueden usar.

Las políticas de denegación son independientes de las políticas de permiso, también conocidas como políticas de IAM. Una política de permiso proporciona acceso a los recursos mediante la asignación de funciones de IAM a las principales.

Puedes administrar las políticas de denegación con Google Cloud CLI o la API de REST v2 de IAM.

Antes de comenzar

  • Habilita IAM API.

    Habilita la API

  • Configura la autenticación.

    Selecciona la pestaña para saber cómo planeas usar las muestras en esta página:

    gcloud

    Puedes usar las muestras de gcloud CLI en esta página desde cualquiera de los siguientes entornos de desarrollo:

    • Cloud Shell: Para usar una terminal en línea con la CLI de gcloud ya configurada, activa Cloud Shell.

      En la parte inferior de esta página, se inicia una sesión de Cloud Shell y se muestra una ventana de línea de comandos. La sesión puede tardar unos segundos en inicializarse.

    • Shell local: Para usar la CLI de gcloud en un entorno de desarrollo local, instala e inicializa la CLI de gcloud.

    Terraform

    Para usar las muestras de Terraform de esta página desde un entorno de desarrollo local, instala e inicializa la CLI de gcloud y, luego, configura las credenciales predeterminadas de la aplicación con tus credenciales de usuario.

    1. Instala Google Cloud CLI.
    2. Para inicializar la CLI de gcloud, ejecuta el siguiente comando:

      gcloud init
    3. Crea credenciales de autenticación locales para tu Cuenta de Google:

      gcloud auth application-default login

    Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local en la documentación de autenticación de Google Cloud.

    Go

    Para usar las muestras de Go de esta página desde un entorno de desarrollo local, instala e inicializa la CLI de gcloud y, luego, configura las credenciales predeterminadas de la aplicación con tus credenciales de usuario.

    1. Instala Google Cloud CLI.
    2. Para inicializar la CLI de gcloud, ejecuta el siguiente comando:

      gcloud init
    3. Crea credenciales de autenticación locales para tu Cuenta de Google:

      gcloud auth application-default login

    Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local en la documentación de autenticación de Google Cloud.

    Java

    Para usar las muestras de Java de esta página desde un entorno de desarrollo local, instala e inicializa la CLI de gcloud y, luego, configura las credenciales predeterminadas de la aplicación con tus credenciales de usuario.

    1. Instala Google Cloud CLI.
    2. Para inicializar la CLI de gcloud, ejecuta el siguiente comando:

      gcloud init
    3. Crea credenciales de autenticación locales para tu Cuenta de Google:

      gcloud auth application-default login

    Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local en la documentación de autenticación de Google Cloud.

    Node.js

    Para usar las muestras de Node.js de esta página desde un entorno de desarrollo local, instala e inicializa la CLI de gcloud y, luego, configura las credenciales predeterminadas de la aplicación con tus credenciales de usuario.

    1. Instala Google Cloud CLI.
    2. Para inicializar la CLI de gcloud, ejecuta el siguiente comando:

      gcloud init
    3. Crea credenciales de autenticación locales para tu Cuenta de Google:

      gcloud auth application-default login

    Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local en la documentación de autenticación de Google Cloud.

    Python

    Para usar las muestras de Python de esta página desde un entorno de desarrollo local, instala e inicializa la CLI de gcloud y, luego, configura las credenciales predeterminadas de la aplicación con tus credenciales de usuario.

    1. Instala Google Cloud CLI.
    2. Para inicializar la CLI de gcloud, ejecuta el siguiente comando:

      gcloud init
    3. Crea credenciales de autenticación locales para tu Cuenta de Google:

      gcloud auth application-default login

    Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local en la documentación de autenticación de Google Cloud.

    REST

    Para usar las muestras de la API de REST en esta página en un entorno de desarrollo local, debes usar las credenciales que proporcionas a la CLI de gcloud.

      Instala Google Cloud CLI y, luego, inicializa la ejecución del siguiente comando:

      gcloud init

  • Lee la descripción general de las políticas de denegación.

Roles obligatorios

Si deseas obtener los permisos que necesitas para administrar las políticas de denegación, pídele al administrador que te otorgue los siguientes roles de IAM en la organización:

Si quieres obtener más información para otorgar roles, consulta Administra el acceso.

Estas funciones predefinidas contienen los permisos necesarios para administrar las políticas de denegación. Para ver los permisos exactos que son necesarios, expande la sección Permisos requeridos:

Permisos necesarios

Se requieren los siguientes permisos para administrar las políticas de denegación:

  • Para ver las políticas de denegación, haz lo siguiente:
    • iam.denypolicies.get
    • iam.denypolicies.list
  • Para crear, actualizar y borrar políticas de denegación, otorga:
    • iam.denypolicies.create
    • iam.denypolicies.delete
    • iam.denypolicies.get
    • iam.denypolicies.update

También puedes obtener estos permisos con roles personalizados o con otros roles predefinidos.

Identifica los permisos para denegar

Antes de crear una política de denegación, debes decidir qué permisos deseas denegar y a qué principales deben denegarse.

Solo se pueden denegar algunos permisos. Para obtener una lista de los permisos que puedes denegar, consulta Permisos admitidos en las políticas de denegación.

En algunos casos, también puedes usar grupos de permisos para denegar conjuntos de permisos. Para obtener más información, consulta Grupos de permisos.

Las políticas de denegación se administran con la API de REST v2, que requiere un formato especial para los nombres de los permisos. Por ejemplo, el permiso para crear un rol personalizada de IAM tiene el siguiente nombre:

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

Identifica el punto de conexión

Cada política de denegación se adjunta a una organización, carpeta o proyecto. Cuando se adjuntan a uno de estos recursos, todos los recursos de nivel inferior de ese proyecto, carpeta u organización heredan las políticas de denegación. Para trabajar con políticas de denegación, necesitas un identificador del recurso al que se adjunta la política de denegación, que se denomina punto de conexión. Este identificador usa uno de los siguientes formatos:

Formato de punto de conexión
Organización

cloudresourcemanager.googleapis.com/organizations/ORG_ID
Reemplaza ORG_ID por el ID numérico de la organización. Para la API de REST, codifica todo el valor en URL.

Ejemplo de la CLI de gcloud:
cloudresourcemanager.googleapis.com/organizations/123456789012

Ejemplo de la API de REST:
cloudresourcemanager.googleapis.com%2Forganizations%2F123456789012

Carpeta

cloudresourcemanager.googleapis.com/folders/FOLDER_ID
Reemplaza FOLDER_ID por el ID de la carpeta numérica. Para la API de REST, codifica todo el valor en URL.

Ejemplo de la CLI de gcloud:
cloudresourcemanager.googleapis.com/folders/987654321098

Ejemplo de la API de REST:
cloudresourcemanager.googleapis.com%2Ffolders%2F987654321098

Proyecto

cloudresourcemanager.googleapis.com/projects/PROJECT_ID
Reemplaza PROJECT_ID por el ID del proyecto alfanumérico o numérico. Para la API de REST, codifica todo el valor en URL.

Ejemplo de la CLI de gcloud:
cloudresourcemanager.googleapis.com/projects/my-project

Ejemplo de la API de REST:
cloudresourcemanager.googleapis.com%2Fprojects%2Fmy-project

Crea una política de denegación

Puedes agregar políticas de denegación a organizaciones, carpetas y proyectos. Cada recurso puede tener hasta 500 políticas de denegación.

Las políticas de denegación contienen reglas de denegación, que especifican lo siguiente:

  • Los permisos que se deben denegar.
  • Las principales que a las que se deniegan esos permisos.
  • Opcional: Principales que están exentas de la denegación de permisos.

    Por ejemplo, puedes denegar un permiso a un grupo, pero eximir a usuarios específicos que pertenecen a ese grupo.

  • Es una expresión de condición que especifica cuándo las principales no pueden usar los permisos. En las políticas de denegación, las expresiones de condiciones solo pueden usar funciones para etiquetas de recursos. No se admiten otras funciones ni operadores.

Cada recurso puede tener hasta 500 reglas de denegación en todas sus políticas de denegación adjuntas.

Las políticas de denegación se heredan a través de la jerarquía de recursos. Por ejemplo, si deniegas un permiso a nivel de la organización, ese permiso también se denegará en las carpetas y proyectos de esa organización y en los recursos específicos del servicio dentro de cada proyecto.

Las políticas de denegación anulan las políticas de permiso. Si a una principal se le otorga un rol que contiene un permiso específico, pero una política de denegación indica que la principal no puede usar ese permiso, la principal no puede usar el permiso.

gcloud

A fin de crear una política de denegación para un recurso, primero crea un archivo JSON que contenga la política. Una política de denegación usa el siguiente formato:

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

Ingresa los siguientes valores:

  • POLICY_NAME: Es el nombre visible de la política de denegación.
  • DENY_RULE_1, DENY_RULE_2, ...DENY_RULE_N: Son las reglas de denegación de la política. Cada regla de denegación puede contener estos campos:

    Para ver ejemplos de reglas de denegación, consulta Casos de uso comunes.

Por ejemplo, la siguiente política de denegación contiene una regla de denegación, que niega un permiso al usuario lucian@example.com:

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

A continuación, ejecuta el comando gcloud iam policies create:

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

Ingresa los siguientes valores:

  • POLICY_ID: Es el identificador de la política de denegación.

  • ATTACHMENT_POINT: un identificador para el recurso al que se adjunta la política de denegación. Para obtener información sobre cómo dar formato a este valor, consulta Identifica el punto de conexión en esta página.

  • POLICY_FILE: Es la ruta del archivo JSON que contiene la política de denegación.

De forma predeterminada, si este comando tiene éxito, no imprime ningún resultado. Para imprimir una respuesta detallada, agrega la marca --format=json al comando.

Por ejemplo, el siguiente comando crea una política de denegación llamada my-deny-policy para el proyecto my-project, mediante un archivo llamado policy.json:

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

Terraform

Si deseas obtener más información para aplicar o quitar una configuración de Terraform, consulta los comandos básicos de Terraform. Para obtener más información, consulta la documentación de referencia del proveedor de 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

Para obtener más obtener información sobre cómo instalar y usar la biblioteca cliente de IAM, consulta Bibliotecas cliente de IAM. Para obtener más información, consulta la documentación de referencia de la API de IAM Go.

Para autenticarte en IAM, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta Antes de comenzar.

import (
	"context"
	"fmt"
	"io"

	iam "cloud.google.com/go/iam/apiv2"
	iampb "google.golang.org/genproto/googleapis/iam/v2"

	"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

Para obtener más obtener información sobre cómo instalar y usar la biblioteca cliente de IAM, consulta Bibliotecas cliente de IAM. Para obtener más información, consulta la documentación de referencia de la API de IAM Java.

Para autenticarte en IAM, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta Antes de comenzar.


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

Para obtener más obtener información sobre cómo instalar y usar la biblioteca cliente de IAM, consulta Bibliotecas cliente de IAM. Para obtener más información, consulta la documentación de referencia de la API de IAM Node.js.

Para autenticarte en IAM, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta Antes de comenzar.

/**
 * 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

Para obtener más obtener información sobre cómo instalar y usar la biblioteca cliente de IAM, consulta Bibliotecas cliente de IAM. Para obtener más información, consulta la documentación de referencia de la API de IAM Python.

Para autenticarte en IAM, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta Antes de comenzar.



def create_deny_policy(project_id: str, policy_id: str) -> None:
    from google.cloud import iam_v2
    from google.cloud.iam_v2 import types

    """
      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.
    """
    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 = "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

El método policies.createPolicy crea una política de denegación para un recurso.

Antes de usar cualquiera de los datos de solicitud a continuación, realiza los siguientes reemplazos:

  • ENCODED_ATTACHMENT_POINT: un identificador codificado en URL para el recurso al que se adjunta la política de denegación. Para obtener información sobre cómo dar formato a este valor, consulta Identifica el punto de conexión en esta página.

  • POLICY_ID: Es un identificador para la política de denegación.
  • POLICY_NAME: Es el nombre visible de la política de denegación.
  • DENY_RULE_1, DENY_RULE_2, ...DENY_RULE_N: Son las reglas de denegación de la política. Cada regla de denegación puede contener estos campos:

    Para ver ejemplos de reglas de denegación, consulta Casos de uso comunes.

Método HTTP y URL:

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

Cuerpo JSON de la solicitud:

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

    {
      "denyRule": DENY_RULE_N
    }
  ]
}

Para enviar tu solicitud, expande una de estas opciones:

Deberías recibir una respuesta JSON similar a la que se muestra a continuación:

{
  "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 respuesta identifica una operación de larga duración. Puedes supervisar el estado de la operación de larga duración para saber cuándo se completa. Para obtener más información, consulta Revisa el estado de una operación de larga duración en esta página.

Enumera las políticas de denegación

Un recurso puede tener varias políticas de denegación. Puedes enumerar todas las políticas de denegación que están conectadas a un recurso y, luego, ver cada política de denegación para ver las reglas de denegación de cada política.

gcloud

Para enumerar las políticas de denegación de un recurso, ejecuta el comando gcloud iam policies list:

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

Ingresa el siguiente valor:

  • ATTACHMENT_POINT: un identificador para el recurso al que se adjunta la política de denegación. Para obtener información sobre cómo dar formato a este valor, consulta Identifica el punto de conexión en esta página.

Por ejemplo, con el siguiente comando, se enumeran las políticas de denegación adjuntas a una organización cuyo ID numérico es 123456789012:

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

Go

Para obtener más obtener información sobre cómo instalar y usar la biblioteca cliente de IAM, consulta Bibliotecas cliente de IAM. Para obtener más información, consulta la documentación de referencia de la API de IAM Go.

Para autenticarte en IAM, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta Antes de comenzar.

import (
	"context"
	"fmt"
	"io"

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

// 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

Para obtener más obtener información sobre cómo instalar y usar la biblioteca cliente de IAM, consulta Bibliotecas cliente de IAM. Para obtener más información, consulta la documentación de referencia de la API de IAM Java.

Para autenticarte en IAM, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta Antes de comenzar.


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

Para obtener más obtener información sobre cómo instalar y usar la biblioteca cliente de IAM, consulta Bibliotecas cliente de IAM. Para obtener más información, consulta la documentación de referencia de la API de IAM Node.js.

Para autenticarte en IAM, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta Antes de comenzar.

/**
 * 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

Para obtener más obtener información sobre cómo instalar y usar la biblioteca cliente de IAM, consulta Bibliotecas cliente de IAM. Para obtener más información, consulta la documentación de referencia de la API de IAM Python.

Para autenticarte en IAM, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta Antes de comenzar.

def list_deny_policy(project_id: str) -> None:
    from google.cloud import iam_v2
    from google.cloud.iam_v2 import types

    """
    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.
    """
    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__":
    import uuid

    # Your Google Cloud project ID.
    project_id = "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

El método policies.listPolicies permite enumerar las políticas de denegación de un recurso.

Antes de usar cualquiera de los datos de solicitud a continuación, realiza los siguientes reemplazos:

  • ENCODED_ATTACHMENT_POINT: un identificador codificado en URL para el recurso al que se adjunta la política de denegación. Para obtener información sobre cómo dar formato a este valor, consulta Identifica el punto de conexión en esta página.

Método HTTP y URL:

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

Para enviar tu solicitud, expande una de estas opciones:

Deberías recibir una respuesta JSON similar a la que se muestra a continuación:

{
  "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"
    }
  ]
}

Visualiza una política de denegación

Puedes ver una política de denegación para ver las reglas de denegación que contiene, incluidos los permisos denegados y las principales que no pueden usar esos permisos.

gcloud

Para obtener la política de denegación de un recurso, ejecuta el comando gcloud iam policies get:

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

Ingresa los siguientes valores:

  • POLICY_ID: Es el identificador de la política de denegación.

  • ATTACHMENT_POINT: un identificador para el recurso al que se adjunta la política de denegación. Para obtener información sobre cómo dar formato a este valor, consulta Identifica el punto de conexión en esta página.

Por ejemplo, con el siguiente comando, se obtiene la política de denegación my-deny-policy para el proyecto my-project y se guarda en un archivo llamado policy.json:

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

Go

Para obtener más obtener información sobre cómo instalar y usar la biblioteca cliente de IAM, consulta Bibliotecas cliente de IAM. Para obtener más información, consulta la documentación de referencia de la API de IAM Go.

Para autenticarte en IAM, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta Antes de comenzar.

import (
	"context"
	"fmt"
	"io"

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

// 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

Para obtener más obtener información sobre cómo instalar y usar la biblioteca cliente de IAM, consulta Bibliotecas cliente de IAM. Para obtener más información, consulta la documentación de referencia de la API de IAM Java.

Para autenticarte en IAM, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta Antes de comenzar.


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

Para obtener más obtener información sobre cómo instalar y usar la biblioteca cliente de IAM, consulta Bibliotecas cliente de IAM. Para obtener más información, consulta la documentación de referencia de la API de IAM Node.js.

Para autenticarte en IAM, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta Antes de comenzar.

/**
 * 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

Para obtener más obtener información sobre cómo instalar y usar la biblioteca cliente de IAM, consulta Bibliotecas cliente de IAM. Para obtener más información, consulta la documentación de referencia de la API de IAM Python.

Para autenticarte en IAM, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta Antes de comenzar.

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__":
    import uuid

    # Your Google Cloud project ID.
    project_id = "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

El método policies.get obtiene una política de denegación para un recurso.

Antes de usar cualquiera de los datos de solicitud a continuación, realiza los siguientes reemplazos:

  • ENCODED_ATTACHMENT_POINT: un identificador codificado en URL para el recurso al que se adjunta la política de denegación. Para obtener información sobre cómo dar formato a este valor, consulta Identifica el punto de conexión en esta página.

  • POLICY_ID: Es un identificador para la política de denegación.

Método HTTP y URL:

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

Para enviar tu solicitud, expande una de estas opciones:

Deberías recibir una respuesta JSON similar a la que se muestra a continuación:

{
  "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"
        ]
      }
    }
  ]
}

Actualiza una política de denegación

Después de crear una política de denegación, puedes actualizar las reglas de denegación que contiene y su nombre visible.

Para actualizar una política de denegación, usa el patrón read-modify-write:

  1. Lee la versión actual de la política.
  2. Modifica la información en la política según sea necesario.
  3. Escribe la política actualizada:

Lee la política de denegación

gcloud

Para obtener la política de denegación de un recurso, ejecuta el comando gcloud iam policies get:

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

Ingresa los siguientes valores:

  • POLICY_ID: Es el identificador de la política de denegación.

  • ATTACHMENT_POINT: un identificador para el recurso al que se adjunta la política de denegación. Para obtener información sobre cómo dar formato a este valor, consulta Identifica el punto de conexión en esta página.

Por ejemplo, con el siguiente comando, se obtiene la política de denegación my-deny-policy para el proyecto my-project y se guarda en un archivo llamado policy.json:

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

Go

Para obtener más obtener información sobre cómo instalar y usar la biblioteca cliente de IAM, consulta Bibliotecas cliente de IAM. Para obtener más información, consulta la documentación de referencia de la API de IAM Go.

Para autenticarte en IAM, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta Antes de comenzar.

import (
	"context"
	"fmt"
	"io"

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

// 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

Para obtener más obtener información sobre cómo instalar y usar la biblioteca cliente de IAM, consulta Bibliotecas cliente de IAM. Para obtener más información, consulta la documentación de referencia de la API de IAM Java.

Para autenticarte en IAM, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta Antes de comenzar.


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

Para obtener más obtener información sobre cómo instalar y usar la biblioteca cliente de IAM, consulta Bibliotecas cliente de IAM. Para obtener más información, consulta la documentación de referencia de la API de IAM Node.js.

Para autenticarte en IAM, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta Antes de comenzar.

/**
 * 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

Para obtener más obtener información sobre cómo instalar y usar la biblioteca cliente de IAM, consulta Bibliotecas cliente de IAM. Para obtener más información, consulta la documentación de referencia de la API de IAM Python.

Para autenticarte en IAM, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta Antes de comenzar.

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__":
    import uuid

    # Your Google Cloud project ID.
    project_id = "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

El método policies.get obtiene una política de denegación para un recurso.

Antes de usar cualquiera de los datos de solicitud a continuación, realiza los siguientes reemplazos:

  • ENCODED_ATTACHMENT_POINT: un identificador codificado en URL para el recurso al que se adjunta la política de denegación. Para obtener información sobre cómo dar formato a este valor, consulta Identifica el punto de conexión en esta página.

  • POLICY_ID: Es un identificador para la política de denegación.

Método HTTP y URL:

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

Para enviar tu solicitud, expande una de estas opciones:

Deberías recibir una respuesta JSON similar a la que se muestra a continuación:

{
  "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 política de denegación

Para modificar la política de denegación, realiza cambios en la copia de la política que leíste desde IAM. Puedes actualizar el nombre visible o agregar, cambiar o quitar reglas de denegación. Los cambios no se aplicarán hasta que escribas la política actualizada.

Por ejemplo, puedes agregar un permiso a una regla de denegación existente:

{
  "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"
        ]
      }
    }
  ]
}

Escribe la política de denegación actualizada

Después de modificar la política de denegación de forma local, debes escribir la política de denegación actualizada en IAM.

Cada política de denegación contiene un campo etag que identifica la versión de la política. El etag cambia cada vez que actualizas la política. Cuando escribes la política actualizada, el etag en tu solicitud debe coincidir con el etag actual almacenado en IAM. Si los valores no coinciden, la solicitud falla. Esta característica ayuda a evitar que los cambios simultáneos se reemplacen entre sí.

gcloud

Para actualizar la política de denegación de un recurso, ejecuta el comando gcloud iam policies update:

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

Ingresa los siguientes valores:

  • POLICY_ID: Es el identificador de la política de denegación.

  • ATTACHMENT_POINT: un identificador para el recurso al que se adjunta la política de denegación. Para obtener información sobre cómo dar formato a este valor, consulta Identifica el punto de conexión en esta página.

  • POLICY_FILE: Es la ruta del archivo JSON que contiene la política de denegación.

De forma predeterminada, si este comando tiene éxito, no imprime ningún resultado. Para imprimir una respuesta detallada, agrega la marca --format=json al comando.

Por ejemplo, con el siguiente comando, se actualiza una política de denegación llamada my-deny-policy para el proyecto my-project, mediante un archivo llamado policy.json:

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

Go

Para obtener más obtener información sobre cómo instalar y usar la biblioteca cliente de IAM, consulta Bibliotecas cliente de IAM. Para obtener más información, consulta la documentación de referencia de la API de IAM Go.

Para autenticarte en IAM, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta Antes de comenzar.

import (
	"context"
	"fmt"
	"io"

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

	iampb "google.golang.org/genproto/googleapis/iam/v2"
	"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

Para obtener más obtener información sobre cómo instalar y usar la biblioteca cliente de IAM, consulta Bibliotecas cliente de IAM. Para obtener más información, consulta la documentación de referencia de la API de IAM Java.

Para autenticarte en IAM, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta Antes de comenzar.


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

Para obtener más obtener información sobre cómo instalar y usar la biblioteca cliente de IAM, consulta Bibliotecas cliente de IAM. Para obtener más información, consulta la documentación de referencia de la API de IAM Node.js.

Para autenticarte en IAM, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta Antes de comenzar.

/**
 * 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

Para obtener más obtener información sobre cómo instalar y usar la biblioteca cliente de IAM, consulta Bibliotecas cliente de IAM. Para obtener más información, consulta la documentación de referencia de la API de IAM Python.

Para autenticarte en IAM, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta Antes de comenzar.

def update_deny_policy(project_id: str, policy_id: str, etag: str) -> None:
    from google.cloud import iam_v2
    from google.cloud.iam_v2 import types

    """
    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.
    """
    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__":
    import uuid

    # Your Google Cloud project ID.
    project_id = "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

El método policies.update actualiza una política de denegación.

Antes de usar cualquiera de los datos de solicitud a continuación, realiza los siguientes reemplazos:

  • ENCODED_ATTACHMENT_POINT: un identificador codificado en URL para el recurso al que se adjunta la política de denegación. Para obtener información sobre cómo dar formato a este valor, consulta Identifica el punto de conexión en esta página.

  • POLICY_ID: Es un identificador para la política de denegación.
  • POLICY: Es la política de denegación actualizada.

    Por ejemplo, para agregar un permiso a la política que se muestra en el paso anterior, reemplaza POLICY por lo siguiente:

    {
      "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"
            ]
          }
        }
      ]
    }

Método HTTP y URL:

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

Cuerpo JSON de la solicitud:

POLICY

Para enviar tu solicitud, expande una de estas opciones:

Deberías recibir una respuesta JSON similar a la que se muestra a continuación:

{
  "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 respuesta identifica una operación de larga duración. Puedes supervisar el estado de la operación de larga duración para saber cuándo se completa. Para obtener más información, consulta Revisa el estado de una operación de larga duración en esta página.

Borra una política de denegación

Si ya no deseas aplicar las reglas en una política de denegación, puedes borrar la política.

De manera opcional, puedes especificar el etag para la versión de la política que estás borrando. Si especificas etag, este debe coincidir con el etag actual que almacena IAM. Si los valores no coinciden, la solicitud falla. Puedes usar esta función para asegurarte de borrar la política deseada, en lugar de una versión actualizada de esa política.

Si omites el etag de la solicitud, IAM borra la política de forma incondicional.

gcloud

Para borrar una política de denegación de un recurso, ejecuta el comando gcloud iam policies delete:

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

Ingresa los siguientes valores:

  • POLICY_ID: Es el identificador de la política de denegación.

  • ATTACHMENT_POINT: un identificador para el recurso al que se adjunta la política de denegación. Para obtener información sobre cómo dar formato a este valor, consulta Identifica el punto de conexión en esta página.

También puedes agregar la marca --etag=ETAG. Reemplaza ETAG con el valor etag actual para la política de denegación.

De forma predeterminada, si este comando tiene éxito, no imprime ningún resultado. Para imprimir una respuesta detallada, agrega la marca --format=json al comando.

Por ejemplo, el siguiente comando borra una política de denegación llamada my-deny-policy del proyecto my-project:

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

Go

Para obtener más obtener información sobre cómo instalar y usar la biblioteca cliente de IAM, consulta Bibliotecas cliente de IAM. Para obtener más información, consulta la documentación de referencia de la API de IAM Go.

Para autenticarte en IAM, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta Antes de comenzar.

import (
	"context"
	"fmt"
	"io"

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

	iampb "google.golang.org/genproto/googleapis/iam/v2"
)

// 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

Para obtener más obtener información sobre cómo instalar y usar la biblioteca cliente de IAM, consulta Bibliotecas cliente de IAM. Para obtener más información, consulta la documentación de referencia de la API de IAM Java.

Para autenticarte en IAM, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta Antes de comenzar.


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

Para obtener más obtener información sobre cómo instalar y usar la biblioteca cliente de IAM, consulta Bibliotecas cliente de IAM. Para obtener más información, consulta la documentación de referencia de la API de IAM Node.js.

Para autenticarte en IAM, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta Antes de comenzar.

/**
 * 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

Para obtener más obtener información sobre cómo instalar y usar la biblioteca cliente de IAM, consulta Bibliotecas cliente de IAM. Para obtener más información, consulta la documentación de referencia de la API de IAM Python.

Para autenticarte en IAM, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta Antes de comenzar.

def delete_deny_policy(project_id: str, policy_id: str) -> None:
    from google.cloud import iam_v2
    from google.cloud.iam_v2 import types

    """
    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.
    """
    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 = "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

Mediante el método policies.delete, se borra una política de denegación de un recurso.

Antes de usar cualquiera de los datos de solicitud a continuación, realiza los siguientes reemplazos:

  • ENCODED_ATTACHMENT_POINT: un identificador codificado en URL para el recurso al que se adjunta la política de denegación. Para obtener información sobre cómo dar formato a este valor, consulta Identifica el punto de conexión en esta página.

  • POLICY_ID: Es un identificador para la política de denegación.
  • ETAG: Opcional Es un identificador para la versión de la política. Si está presente, este valor debe coincidir con el valor etag actual para la política.

Método HTTP y URL:

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

Para enviar tu solicitud, expande una de estas opciones:

Deberías recibir una respuesta JSON similar a la que se muestra a continuación:

{
  "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 respuesta identifica una operación de larga duración. Puedes supervisar el estado de la operación de larga duración para saber cuándo se completa. Para obtener más información, consulta Revisa el estado de una operación de larga duración en esta página.

Revisa el estado de una operación de larga duración

Cuando usas la API de REST o las bibliotecas cliente, cualquier método que cambie una política de denegación mostrará una operación de larga duración o LRO. La operación de larga duración realiza un seguimiento del estado de la solicitud y también indica si se completó el cambio en la política.

Go

En las muestras de código de esta página, se muestra cómo esperar a que finalice una operación de larga duración y, luego, acceder a su resultado.

Java

En las muestras de código de esta página, se muestra cómo esperar a que finalice una operación de larga duración y, luego, acceder a su resultado.

Node.js

En las muestras de código de esta página, se muestra cómo esperar a que finalice una operación de larga duración y, luego, acceder a su resultado.

Python

En las muestras de código de esta página, se muestra cómo esperar a que finalice una operación de larga duración y, luego, acceder a su resultado.

REST

El método policies.operations.get muestra el estado de una operación de larga duración.

Antes de usar cualquiera de los datos de solicitud a continuación, realiza los siguientes reemplazos:

  • ENCODED_ATTACHMENT_POINT: un identificador codificado en URL para el recurso al que se adjunta la política de denegación. Para obtener información sobre cómo dar formato a este valor, consulta Identifica el punto de conexión en esta página.

  • OPERATION_ID: Es el identificador para la operación. Recibirás este identificador en la respuesta a tu solicitud original, como parte del nombre de la operación. Usa el valor hexadecimal al final del nombre de la operación. Por ejemplo, 89cb3e508bf1ff01

Método HTTP y URL:

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

Para enviar tu solicitud, expande una de estas opciones:

Deberías recibir una respuesta JSON similar a la que se muestra a continuación:

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

Si el campo done de la operación no está presente, continúa supervisando su estado mediante la obtención de la operación repetidas veces. Usa la retirada exponencial truncada para ingresar una demora entre cada solicitud. Cuando el campo done se establece como true, la operación está completa, y puedes dejar de obtener la operación.

¿Qué sigue?