Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Extract region name from Cloud Run metadata server response #1546

Merged
merged 2 commits into from
Jan 4, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 12 additions & 1 deletion detectors/gcp/cloud-run.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import (
"context"
"fmt"
"os"
"strings"

"cloud.google.com/go/compute/metadata"

Expand Down Expand Up @@ -56,6 +57,16 @@ func NewCloudRun() *CloudRun {
}
}

func (c *CloudRun) cloudRegion(ctx context.Context) (string, error) {
region, err := c.mc.Get("instance/region")
if err != nil {
return "", err
}
// Region from the metadata server is in the format /projects/123/regions/r.
// https://cloud.google.com/run/docs/reference/container-contract#metadata-server
return region[strings.LastIndex(region, "/")+1:], nil
}

// Detect detects associated resources when running on Cloud Run hosts.
// NOTE: the service.namespace attribute is currently hardcoded to be
// "cloud-run-managed". This may change in the future, please do not rely on
Expand All @@ -80,7 +91,7 @@ func (c *CloudRun) Detect(ctx context.Context) (*resource.Resource, error) {
attributes = append(attributes, semconv.CloudAccountIDKey.String(projectID))
}

if region, err := c.mc.Get("instance/region"); hasProblem(err) {
if region, err := c.cloudRegion(ctx); hasProblem(err) {
errInfo = append(errInfo, err.Error())
} else if region != "" {
attributes = append(attributes, semconv.CloudRegionKey.String(region))
Expand Down
2 changes: 1 addition & 1 deletion detectors/gcp/cloud-run_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ func TestCloudRunDetectorExpectSuccess(t *testing.T) {
metadata := map[string]string{
"project/project-id": "foo",
"instance/id": "bar",
"instance/region": "utopia",
"instance/region": "/projects/123/regions/utopia",
}
envvars := map[string]string{
"K_SERVICE": "x-service",
Expand Down