Skip to content

Conversation

@khilan-crest
Copy link

Adding tags samples

Fixes #

Note: Before submitting a pull request, please open an issue for discussion if you are not associated with Google.

Checklist

@product-auto-label product-auto-label bot added api: secretmanager Issues related to the Secret Manager API. samples Issues that are directly related to samples. labels Jan 15, 2026
@gemini-code-assist
Copy link
Contributor

Summary of Changes

Hello @khilan-crest, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request expands the Google Cloud Secret Manager Python samples by adding new code examples for managing resource tags. Specifically, it provides utilities to detach existing tag bindings from secrets and to list all tags currently associated with a secret. These new samples cater to both global and regional secret configurations, offering developers clear guidance on how to programmatically interact with the tagging features of Secret Manager.

Highlights

  • New Tag Management Samples: Introduces new Python samples for managing tags on Google Cloud Secret Manager secrets, including operations to detach and list tag bindings.
  • Global and Regional Support: The new samples provide functionality for both globally available secrets and regionally managed secrets, ensuring comprehensive coverage.
  • Python Client Library Integration: Demonstrates the use of google.cloud.resourcemanager_v3 and google.cloud.secretmanager client libraries for interacting with the respective Google Cloud APIs.
  • Enhanced Test Coverage: Adds new unit tests for the tag detachment and listing functionalities in both global and regional contexts, ensuring the reliability of the new samples.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces new samples for managing tags on secrets in Secret Manager, for both global and regional secrets. The changes include scripts for listing and detaching tag bindings, along with corresponding tests. My review focuses on improving code clarity, correctness of documentation, and consistency in testing. I've suggested refactoring some loops to be more idiomatic, correcting misleading docstrings, and enhancing a test case to be more robust.

Comment on lines 30 to 39
location_id (str): Region where the secret should be stored (e.g., "us-central1")
secret_id (str): ID of the secret to create
Example:
# Create a regional secret with a customer-managed encryption key
list_regional_secret_tag_bindings(
"my-project",
"my-regional-secret-with-cmek",
"us-central1",
)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

The docstring contains several inaccuracies that could confuse users:

  1. The description for location_id implies creation (should be stored), but the function is for listing.
  2. The description for secret_id says ID of the secret to create, which is incorrect.
  3. The example comment is misleadingly about creating a secret.
  4. The arguments in the example call for location_id and secret_id are swapped.

This suggestion corrects these issues.

Suggested change
location_id (str): Region where the secret should be stored (e.g., "us-central1")
secret_id (str): ID of the secret to create
Example:
# Create a regional secret with a customer-managed encryption key
list_regional_secret_tag_bindings(
"my-project",
"my-regional-secret-with-cmek",
"us-central1",
)
location_id (str): Region where the secret is stored (e.g., "us-central1")
secret_id (str): ID of the secret to list tag bindings for
Example:
# List tag bindings for a regional secret
list_regional_secret_tag_bindings(
"my-project",
"us-central1",
"my-regional-secret",
)

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done

Comment on lines 44 to 50
binding_name = None
request = resourcemanager_v3.ListTagBindingsRequest(parent=parent)

for binding in client.list_tag_bindings(request=request):
if binding.tag_value == tag_value:
binding_name = binding.name
break
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The loop to find the binding name can be made more concise and idiomatic by using a generator expression with next().

    request = resourcemanager_v3.ListTagBindingsRequest(parent=parent)
    binding_name = next(
        (b.name for b in client.list_tag_bindings(request=request) if b.tag_value == tag_value),
        None,
    )

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For loop version is more readable to user.

parent = f"//secretmanager.googleapis.com/{secret_name}"

# List all tag bindings.
tag_bindings = []
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The tag_bindings list is initialized but its value is never used. It can be removed to simplify the code.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done

print(f"Tag bindings for {secret_name}:")
for binding in bindings:
print(f"- Tag Value: {binding.tag_value}")
tag_bindings.append(binding)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Since the tag_bindings list is not used, this append operation is unnecessary and can be removed.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done

Comment on lines +60 to +67
binding_name = None
request = resourcemanager_v3.ListTagBindingsRequest(parent=parent)
tag_bindings = tag_bindings_client.list_tag_bindings(request=request)

for binding in tag_bindings:
if binding.tag_value == tag_value:
binding_name = binding.name
break
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

This loop to find the binding name can be simplified and made more Pythonic by using a generator expression with next().

    request = resourcemanager_v3.ListTagBindingsRequest(parent=parent)
    tag_bindings = tag_bindings_client.list_tag_bindings(request=request)
    binding_name = next(
        (binding.name for binding in tag_bindings if binding.tag_value == tag_value),
        None,
    )

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For loop version is more readable to user.

Comment on lines 56 to 69
print(f"Tag bindings for {name}:")
count = 0

# Use the list_tag_bindings method to get all tag bindings
request = resourcemanager_v3.ListTagBindingsRequest(parent=parent)
tag_bindings = tag_bindings_client.list_tag_bindings(request=request)

# Iterate through the results
for binding in tag_bindings:
print(f"- Tag Value: {binding.tag_value}")
count += 1

if count == 0:
print(f"No tag bindings found for {name}.")
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The header Tag bindings for {name}: is printed even if no bindings are found. It would provide a better user experience to only print the header when there are bindings to display.

Suggested change
print(f"Tag bindings for {name}:")
count = 0
# Use the list_tag_bindings method to get all tag bindings
request = resourcemanager_v3.ListTagBindingsRequest(parent=parent)
tag_bindings = tag_bindings_client.list_tag_bindings(request=request)
# Iterate through the results
for binding in tag_bindings:
print(f"- Tag Value: {binding.tag_value}")
count += 1
if count == 0:
print(f"No tag bindings found for {name}.")
count = 0
# Use the list_tag_bindings method to get all tag bindings
request = resourcemanager_v3.ListTagBindingsRequest(parent=parent)
tag_bindings = tag_bindings_client.list_tag_bindings(request=request)
# Iterate through the results
for binding in tag_bindings:
if count == 0:
print(f"Tag bindings for {name}:")
print(f"- Tag Value: {binding.tag_value}")
count += 1
if count == 0:
print(f"No tag bindings found for {name}.")

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It is good to print and display empty tag values instead of printing None.

Comment on lines 777 to 809
def test_detach_tag(
project_id: str,
tag_key_and_tag_value: Tuple[str, str],
secret_id: str,
) -> None:
"""Test detaching a tag from a secret."""
# Get the tag value from the fixture

_, tag_value = tag_key_and_tag_value

# First bind the tag to the secret

bind_tags_to_secret(project_id, secret_id, tag_value)
secret_name = f"projects/{project_id}/secrets/{secret_id}"

# Now detach the tag

detach_tag(project_id, secret_id, tag_value)

client = resourcemanager_v3.TagBindingsClient()
parent = f"//secretmanager.googleapis.com/{secret_name}"
request = resourcemanager_v3.ListTagBindingsRequest(parent=parent)

# Check that none of the bindings contain our tag value

tag_found = False
for binding in client.list_tag_bindings(request=request):
if binding.tag_value == tag_value:
tag_found = True
break
assert (
not tag_found
), f"Tag value {tag_value} should have been detached but was found"
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

For consistency with test_detach_regional_tag, this test should also verify the output message from the detach_tag function. This requires adding the capsys fixture to the test function and asserting that the success message is present in the output.

def test_detach_tag(
    capsys: pytest.LogCaptureFixture,
    project_id: str,
    tag_key_and_tag_value: Tuple[str, str],
    secret_id: str,
) -> None:
    """Test detaching a tag from a secret."""
    # Get the tag value from the fixture

    _, tag_value = tag_key_and_tag_value

    # First bind the tag to the secret

    bind_tags_to_secret(project_id, secret_id, tag_value)
    secret_name = f"projects/{project_id}/secrets/{secret_id}"

    # Now detach the tag

    detach_tag(project_id, secret_id, tag_value)

    out, _ = capsys.readouterr()
    assert "Detached tag value" in out

    client = resourcemanager_v3.TagBindingsClient()
    parent = f"//secretmanager.googleapis.com/{secret_name}"
    request = resourcemanager_v3.ListTagBindingsRequest(parent=parent)

    # Check that none of the bindings contain our tag value

    tag_found = False
    for binding in client.list_tag_bindings(request=request):
        if binding.tag_value == tag_value:
            tag_found = True
            break
    assert (
        not tag_found
    ), f"Tag value {tag_value} should have been detached but was found"

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

api: secretmanager Issues related to the Secret Manager API. samples Issues that are directly related to samples.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant