Skip to content

Commit

Permalink
Extract region name from Cloud Run metadata server response (#1546)
Browse files Browse the repository at this point in the history
Previously this was returning a full string like /projects/123/regions/r, which does not match up with what the semvconv.CloudRegionKey value is supposed to be.

Co-authored-by: Tyler Yahn <MrAlias@users.noreply.github.com>
  • Loading branch information
nikklassen and MrAlias authored Jan 4, 2022
1 parent 49ea9ed commit 02a2d07
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 2 deletions.
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

0 comments on commit 02a2d07

Please sign in to comment.