Use IAM Conditions

MySQL  |  PostgreSQL  |  SQL Server

IAM Conditions allows you to define and enforce conditional,attribute-based access control forGoogle Cloud resources, including Cloud SQL instances. For moreinformation about IAM Conditions, see theOverview ofIAM Conditions page.

Introduction

In Cloud SQL, you can enforce conditional access based on the followingattributes:

  • Date/time attributes: Used to set temporary (expiring), scheduled, orlimited-duration access to Cloud SQL resources. For example, you canallow a user to access a database instance until a specified date. You canuse date/time attributes at any level of the resource hierarchy. For moreinformation, seeConfiguring temporary access.
  • Resource attributes: Used to configure conditional access based on a tag,resource name, resource type, or resource service attribute. InCloud SQL, you can use attributes of database instances toconfigure conditional access. For example, you can allow a user to only accessinstances with a specific tag. For more information, seeConfiguring resource-based access.

Use cases include:

  • Allowing users to connect to specific instances.

  • Allowing users to create instances with specific prefixes or suffixes(for example, "test").

  • Limiting access to backup operations for test instances

  • Allowing users to delete development and test instances, but not productioninstances.

  • Allowing users to perform administrative operations on certain dates orat certain times.

Allow users to connect to specific instances

Suppose you want to let a user or service account have permission toconnect to one specific Cloud SQL instance only. You can include anIAM Condition in the IAM policy binding thatgrants that account the permissions of a Cloud SQL role.

By default, the predefined Cloud SQL Client role(roles/cloudsql.client), which contains thecloudsql.instances.connectpermission, authorizes its member to connect toall Cloud SQL instances in a project. By introducing an IAMCondition into the policy binding, you can grant permission to just the namedinstance.

Console

This example shows how to modify the existing IAM binding for the project to give a service account a Cloud SQL Client role for a specific instance.

This example uses the following variables:

  • PROJECT_ID: Your Google Cloud project.
  • INSTANCE_ID: The name of the instance you want to grant access to.

  1. In the Google Cloud console, go to theService accounts page.

    Go to IAM

  2. ClickAdd.
  3. In theNew Members input box, enter the service account email.
  4. Click theRole dropdown list and select theCloud SQL Client role.
  5. ClickAdd condition.
  6. Enter a title and description.
  7. Select theCondition editor tab.
  8. In theCondition builder section:
    • ForCondition type - Resource - Name, enterprojects/PROJECT_ID/instances/INSTANCE_ID
    • Ensure that theAND conditional is selected.
    • ForCondition type - Resource - Service, selectsqladmin.googleapis.com.
  9. ClickSave to save the condition.
  10. ClickSave to save the policy.

gcloud

This example shows how to modify the existing IAM policy binding for the project to give a specific service account the Cloud SQL Client role, but only for a specific instance.

This example uses the following variables:

  • PROJECT_ID: Your Google Cloud project.
  • INSTANCE_ID: The name of the instance you want to grant access to.
  • SERVICE_ACCOUNT_EMAIL: The complete email address of the service account whose access you want to modify.

  1. Get the existing IAM policy bindings and output it to the filebindings.json:
  2. gcloudprojectsget-iam-policyPROJECT_ID--format=json>bindings.json
  3. Add the following conditional role binding to thebindings.json file:
    {"bindings":[{"role":"roles/cloudsql.client","members":["serviceAccount:SERVICE_ACCOUNT_EMAIL"],"condition":{"expression":"resource.name == 'projects/PROJECT_ID/instances/INSTANCE_ID'          && resource.service == 'sqladmin.googleapis.com'"}}],"etag":"BwWKmjvelug=","version":3}
  4. Update the IAM policy with the newbindings.json file.
    gcloudprojectsset-iam-policyPROJECT_IDbindings.json

Terraform

To allow users to connect to specific instances, use aTerraformgoogle_iam_policy data resource and agoogle_project_iam_policy Terraform resource.

Caution: If you create agoogle_project_iam_policy resource, then you override both the existing policy and all access in your Google Cloud project.

If you delete this resource, then anyone who doesn't have organization-level access to your Google Cloud project is locked out of the project. As a result, they can't access any resources associated with the project.

Use the resource only for Google Cloud projects that are fully managed by Terraform. If you use the resource, we strongly recommend that you import the policy before deleting it. This way, if any issues occur, you can reinstate the policy.

data "google_iam_policy" "sql_iam_policy" {  binding {    role = "roles/cloudsql.client"    members = [      "serviceAccount:${google_project_service_identity.gcp_sa_cloud_sql.email}",    ]    condition {      expression  = "resource.name == 'projects/${data.google_project.project.project_id}/instances/${google_sql_database_instance.default.name}' && resource.type == 'sqladmin.googleapis.com/Instance'"      title       = "created"      description = "Cloud SQL instance creation"    }  }}resource "google_project_iam_policy" "project" {  project     = data.google_project.project.project_id  policy_data = data.google_iam_policy.sql_iam_policy.policy_data}

Apply the changes

To apply your Terraform configuration in a Google Cloud project, complete the steps in the following sections.

Prepare Cloud Shell

  1. LaunchCloud Shell.
  2. Set the default Google Cloud project where you want to apply your Terraform configurations.

    You only need to run this command once per project, and you can run it in any directory.

    export GOOGLE_CLOUD_PROJECT=PROJECT_ID

    Environment variables are overridden if you set explicit values in the Terraform configuration file.

Prepare the directory

Each Terraform configuration file must have its own directory (alsocalled aroot module).

  1. InCloud Shell, create a directory and a new file within that directory. The filename must have the.tf extension—for examplemain.tf. In this tutorial, the file is referred to asmain.tf.
    mkdirDIRECTORY && cdDIRECTORY && touch main.tf
  2. If you are following a tutorial, you can copy the sample code in each section or step.

    Copy the sample code into the newly createdmain.tf.

    Optionally, copy the code from GitHub. This is recommended when the Terraform snippet is part of an end-to-end solution.

  3. Review and modify the sample parameters to apply to your environment.
  4. Save your changes.
  5. Initialize Terraform. You only need to do this once per directory.
    terraform init

    Optionally, to use the latest Google provider version, include the-upgrade option:

    terraform init -upgrade

Apply the changes

  1. Review the configuration and verify that the resources that Terraform is going to create or update match your expectations:
    terraform plan

    Make corrections to the configuration as necessary.

  2. Apply the Terraform configuration by running the following command and enteringyes at the prompt:
    terraform apply

    Wait until Terraform displays the "Apply complete!" message.

  3. Open your Google Cloud project to view the results. In the Google Cloud console, navigate to your resources in the UI to make sure that Terraform has created or updated them.
Note: Terraform samples typically assume that the required APIs are enabled in your Google Cloud project.

Delete the changes

To delete your changes, do the following:

  1. To disable deletion protection, in your Terraform configuration file set thedeletion_protection argument tofalse.
    deletion_protection =  "false"
  2. Apply the updated Terraform configuration by running the following command and enteringyes at the prompt:
    terraform apply
  1. Remove resources previously applied with your Terraform configuration by running the following command and enteringyes at the prompt:

    terraform destroy

Limit access to backup operations for test instances

Suppose your service's topology is configured so that all test instances have a prefix oftest (for example,test-instance-1), and all production instances have a prefix ofprod (for example,prod-instance-1).

You can limit access to backup operations to your test instances for a user or a service account. Limiting access includes restrictingCREATE,GET,LIST, orDELETE operations to backups for your test instances.

Console

  1. In the Google Cloud console, go to theService accounts page.

    Go to IAM

  2. Click thePRINCIPALS tab.
  3. Locate the user's email address or service account (principal) to which you want to restrict access.
  4. Click theEdit principal icon to the right of the principal. This icon appears as a pencil.
  5. In theEdit permissions dialog box, clickADD ANOTHER ROLE.
  6. In theFilter field of the subsequent dialog box, enterCloud SQL Admin. Then, select theCloud SQL Admin role that appears.

    TheEdit permissions dialog box is active, and theCloud SQL Admin role now appears in the dialog box.

  7. To the right of theCloud SQL Admin role, click theAdd condition link.
  8. In theEdit condition dialog box, supply the following information:
    1. In theTitle field, enter a name for the condition that you're adding to limit access to backup operations for test instances. For example, you can enterLimit access to backup operations.
    2. Click theCONDITION EDITOR tab, and then add the following condition:

      resource.type=="sqladmin.googleapis.com/BackupRun"&&resource.name.startsWith("projects/PROJECT_ID/instances/test")

      This condition limits the scope of the Cloud SQL Admin role for the principal that you selected to those resources that have resource names that start withprojects/PROJECT_ID/instances/test. Also, replace thePROJECT_ID placeholder variable with the name of your Google Cloud project.

  9. ClickSAVE.
  10. In theEdit permissions dialog box, clickSAVE.

gcloud

This example uses the following variables:


  1. Limit the scope of thecloudsql.admin role for a user who has an email address ofUSER_EMAIL.

    The scope of the role is limited to those resources that have resource names that start withprojects/PROJECT_ID/instances/test.

    gcloudprojectsadd-iam-policy-bindingPROJECT_ID\--member=user:USER_EMAIL\--role=roles/cloudsql.admin\--condition=expression="resource.type == \"sqladmin.googleapis.com/BackupRun\" && resource.name.startsWith(\"projects/PROJECT_ID/instances/test-instance-1\")",title="test"
  2. OR

  3. Limit the scope of thecloudsql.admin role for a user who's logged in with a service account ofSERVICE_ACCOUNT_EMAIL.

    gcloudprojectsadd-iam-policy-bindingPROJECT_ID\--member=serviceAccount:SERVICE_ACCOUNT_EMAIL\--role=roles/cloudsql.admin\--condition=expression="resource.type == \"sqladmin.googleapis.com/BackupRun\" && resource.name.startsWith(\"projects/PROJECT_ID/instances/test-instance-1\")",title="test"
Note:The same conditions in this section apply tofinal backups. If you restrict access to final backups only for instances that have thetest prefix, then you can see the final backups only for instances with this prefix. All IAM conditions that exist for theBackupRuns resource in the format of either theBackupRun URI (projects/PROJECT_ID/instances/INSTANCE_ID/backupRuns) or theInstance resource (projects/PROJECT_ID/instances/var>INSTANCE_ID) also apply to final backups. We don't support conditions for thebackup URI.

Allow users to delete test instances, but not production instances

Suppose you want to allow a service account to delete testinstances, but not production instances. You can dothis by using tags, and by adding the following two policy bindings for the service account:

  • A Cloud SQL Editor role on the resource where you granted therole, and its descendants. If granted on the project the role applies to allof the instances in the project. The Cloud SQL Editor roledoes not contain thecloudsql.instances.delete permission.
  • A Cloud SQL Admin role on instances with thetest tag.

Console

  1. In the Google Cloud console, go to theService accounts page.

    Go to IAM

  2. ClickAdd.
  3. In theNew Members field, enter the service account email.
  4. Click theRole dropdown list and select theCloud SQL Editor role. Add nothing further for this role.
  5. ClickSave to save the condition.
  6. Click theRole menu for the same account and select theCloud Cloud SQL Admin role.
  7. ClickAdd condition.
  8. Enter a title and description.
  9. Select theCondition editor tab.
  10. In theCondition builder section:
    • ForCondition type - Resource - Name, enter a name for the condition.
    • ForCondition type - Resource - Service, selectsqladmin.googleapis.com.
    • ForCondition type - Resource - Tag, enter the Tag key namespaced name. For this example, theOperator ismatches and the value is815471563813/env/test.
  11. ClickSave to save the condition.
  12. ClickSave to save the policy.

gcloud

This example uses the following variables:

  • PROJECT_ID: Your Google Cloud project.
  • INSTANCE_ID: Your Cloud SQL instance.
  • REGION: The region your Cloud SQL instance is in.
  • ORGANIZATION_ID: The ID of the organization to be the parent resource to this tag key; for example: 12345678901. To learn how to get your organization ID, seeCreating and managing organizations.
  • SERVICE_ACCOUNT_EMAIL:The complete email address of the service account whose access you want to modify.

  1. Create a tag key named `env` with tag values `prod` and `test`. For more information, see Creating and defining a new tag.
    gcloudalpharesource-managertagskeyscreateenv\--parent=organizations/ORGANIZATION_IDgcloudalpharesource-managertagsvaluescreateprod\--parent=envgcloudalpharesource-managertagsvaluescreatetest\--parent=env
  2. Attach the `env` tag with value `test` to your test environment Cloud SQL instances. For more information, see the Cloud SQL tags page.
  3. gcloudalpharesource-managertagsbindingscreate\--tag-value=test\--parent=//sqladmin.googleapis.com/projects/PROJECT_ID/instances/INSTANCE_ID\--location=REGION
  4. Get the existing IAM policy bindings and output it to the filebindings.json:
    gcloudprojectsget-iam-policyPROJECT_ID--format=json>>bindings.json
  5. Add the following conditional bindings to thebindings.json file:
    {"bindings":[{"role":"roles/cloudsql.editor","members":["serviceAccount:SERVICE_ACCOUNT_EMAIL"]},{"role":"roles/cloudsql.admin","members":["serviceAccount:SERVICE_ACCOUNT_EMAIL"],"condition":{"expression":"resource.matchTag('ORGANIZATION_ID/env', 'test')"}}],"etag":"BwWKmjvelug=""version":3}
  6. Update the IAM policy bindings with the newbindings.json file.
    gcloudprojectsset-iam-policyPROJECT_IDbindings.json

Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Last updated 2025-12-17 UTC.