Search code examples
pythongoogle-secret-manager

Python create_secret in Google Secrets: How can I select the Secret Manager location 'europe-north1'?


I have this code to create a secret:

from google.cloud import secretmanager


def create_secret(secret_id):
    # Create the Secret Manager client.
    client = secretmanager.SecretManagerServiceClient()

    # Build the resource name of the parent project.
    PROJECT_ID = "123456789"
    parent = f"projects/{PROJECT_ID}"

    # Build a dict of settings for the secret
    secret = {'replication': {'automatic': {}}}

    # Create the secret
    response = client.create_secret(secret_id=secret_id, parent=parent, secret=secret)

    # Print the new secret name.
    print(f'Created secret: {response.name}')

When I run it I get this error:

Constraint constraints/gcp.resourceLocations violated for [orgpolicy:projects/123456789] attempting to create a secret in [global]

The entire traceback:

Traceback (most recent call last):
  File "C:\Users\bruker\Code\auto\venv\lib\site-packages\google\api_core\grpc_helpers.py", line 72, in error_remapped_callable
    return callable_(*args, **kwargs)
  File "C:\Users\bruker\Code\auto\venv\lib\site-packages\grpc\_channel.py", line 946, in __call__
    return _end_unary_response_blocking(state, call, False, None)
  File "C:\Users\bruker\Code\auto\venv\lib\site-packages\grpc\_channel.py", line 849, in _end_unary_response_blocking
    raise _InactiveRpcError(state)
grpc._channel._InactiveRpcError: <_InactiveRpcError of RPC that terminated with:
    status = StatusCode.FAILED_PRECONDITION
    details = "Constraint constraints/gcp.resourceLocations violated for [orgpolicy:projects/123456789] attempting to create a secret in [global]. For more information, see https://cloud.google.com/resource-manager/docs/organization-policy/defining-locations."
    debug_error_string = "UNKNOWN:Error received from peer ipv4:1.2.3.4:443 {created_time:"2022-12-02T12:16:38.059799917+00:00", grpc_status:9, grpc_message:"Constraint constraints/gcp.resourceLocations violated for [orgpolicy:projects/123456789] attempting to create a secret in [global]. For more information, see https://cloud.google.com/resource-manager/docs/organization-policy/defining-locations."}"
>

So I belive that my Google Cloud Administrator has set a constraint so that we only can store secrets in Findland / europe-north1. How can I set this when I create a secret?

The code is originaly from here: https://codelabs.developers.google.com/codelabs/secret-manager-python#5


Solution

  • The nesting always get's me but this is the soulution for setting the location. Hope it helps!

    secret = {"replication":
                  {'user_managed':
                       {"replicas":
                            [
                                {"location": "europe-west1"}
                            ]
                       }
                  }
    }