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

Add the "google_project" datasource #699

Closed
wants to merge 4 commits into from
Closed
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
100 changes: 100 additions & 0 deletions google/data_source_google_project.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
package google

import (
"fmt"
"log"
"sort"
"strconv"
"time"

"github.com/hashicorp/terraform/helper/schema"
"google.golang.org/api/cloudresourcemanager/v1"
)

func dataSourceGoogleProject() *schema.Resource {
return &schema.Resource{
Read: dataSourceGoogleProjectRead,

Schema: map[string]*schema.Schema{
"name": &schema.Schema{
Type: schema.TypeString,
Required: true,
},

"project_id": &schema.Schema{
Type: schema.TypeString,
Computed: true,
},

"number": &schema.Schema{
Type: schema.TypeString,
Computed: true,
},
},
}
}

func dataSourceGoogleProjectRead(d *schema.ResourceData, meta interface{}) error {
config := meta.(*Config)

filter := fmt.Sprintf("name:%s", d.Get("name").(string))
firstCall := config.clientResourceManager.Projects.List().Filter(filter)

resp, err := firstCall.Do()
if err != nil {
return fmt.Errorf("Error reading Project: %s", err)
}

if len(resp.Projects) < 1 {
// The project doesn't exist
return fmt.Errorf("Project Not Found")
}

var activeProjects []*cloudresourcemanager.Project

// filter any project that is not in "ACTIVE" state
for _, project := range resp.Projects {
if project.LifecycleState == "ACTIVE" {
activeProjects = append(activeProjects, project)
}
}

// fetch the entire projects collection but only append those which are active
nextToken := resp.NextPageToken

for nextToken != "" {
call := firstCall.PageToken(nextToken)

resp, err := call.Do()
if err != nil {
return fmt.Errorf("Error reading Project: %s", err)
}

for _, project := range resp.Projects {
if project.LifecycleState == "ACTIVE" {
activeProjects = append(activeProjects, project)
}
}

nextToken = resp.NextPageToken
}

// sort by ascending order of creation
sort.Slice(activeProjects, func(i, j int) bool {
iCreateTime, _ := time.Parse(time.RFC3339, activeProjects[i].CreateTime)
jCreateTime, _ := time.Parse(time.RFC3339, activeProjects[j].CreateTime)

return iCreateTime.Before(jCreateTime)
})

// the last element is the most recent one
lastActiveProject := activeProjects[len(activeProjects)-1]

log.Printf("[DEBUG] Google project found: %q", lastActiveProject)

d.Set("project_id", lastActiveProject.ProjectId)
d.Set("number", strconv.FormatInt(int64(lastActiveProject.ProjectNumber), 10))
d.SetId(lastActiveProject.ProjectId)

return nil
}
86 changes: 86 additions & 0 deletions google/data_source_google_project_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
package google

import (
"fmt"
"testing"

"github.com/hashicorp/terraform/helper/acctest"
"github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/terraform"
)

func TestAccDataSourceGoogleProject(t *testing.T) {
t.Parallel()

skipIfEnvNotSet(t,
[]string{
"GOOGLE_ORG",
}...,
)

name := "foobar"
randSuffix := acctest.RandString(10)
pid := fmt.Sprintf("%s-%s", name, randSuffix)

resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
Steps: []resource.TestStep{
{
Config: testAccDataSourceGoogleProjectConfig(pid, name, org),
Check: resource.ComposeTestCheckFunc(
testAccDataSourceGoogleProjectCheck("data.google_project.my_project", "google_project.foobar"),
),
},
},
})
}

func testAccDataSourceGoogleProjectCheck(data_source_name string, resource_name string) resource.TestCheckFunc {
return func(s *terraform.State) error {
ds, ok := s.RootModule().Resources[data_source_name]
if !ok {
return fmt.Errorf("root module has no resource called %s", data_source_name)
}

rs, ok := s.RootModule().Resources[resource_name]
if !ok {
return fmt.Errorf("can't find %s in state", resource_name)
}

ds_attr := ds.Primary.Attributes
rs_attr := rs.Primary.Attributes

project_attrs_to_test := []string{
"project_id",
"number",
"name",
}

for _, attr_to_check := range project_attrs_to_test {
if ds_attr[attr_to_check] != rs_attr[attr_to_check] {
return fmt.Errorf(
"%s is %s; want %s",
attr_to_check,
ds_attr[attr_to_check],
rs_attr[attr_to_check],
)
}
}

return nil
}
}

func testAccDataSourceGoogleProjectConfig(pid string, name string, org string) string {
return fmt.Sprintf(`
resource "google_project" "foobar" {
project_id = "%s"
name = "%s"
org_id = "%s"
}

data "google_project" "my_project" {
name = "${google_project.foobar.name}"
}`, pid, name, org)
}
1 change: 1 addition & 0 deletions google/provider.go
Original file line number Diff line number Diff line change
@@ -58,6 +58,7 @@ func Provider() terraform.ResourceProvider {
"google_compute_instance_group": dataSourceGoogleComputeInstanceGroup(),
"google_container_engine_versions": dataSourceGoogleContainerEngineVersions(),
"google_iam_policy": dataSourceGoogleIamPolicy(),
"google_project": dataSourceGoogleProject(),
"google_storage_object_signed_url": dataSourceGoogleSignedUrl(),
},

40 changes: 40 additions & 0 deletions website/docs/d/google_project.html.markdown
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
---
layout: "google"
page_title: "Google: google_project"
sidebar_current: "docs-google-datasource-project"
description: |-
Provides the Google Project details based on a name
---

# google\_project

Provides access to the latest available Google Project details based a given name.
See more about [project details](https://cloud.google.com/resource-manager/docs/cloud-platform-resource-hierarchy#projects) in the upstream docs.

```
data "google_project" "foo" {
name = "foobar"
}

resource "google_project_services" "project" {
project = "${data.google_project.foo.project_id}"
services = ["iam.googleapis.com", "cloudresourcemanager.googleapis.com"]
}
```

## Argument Reference

The following arguments are supported:

* `name` - (Required) The display name of the project.

## Attributes Reference

The following attribute is exported:

In addition to the arguments listed above, the following computed attributes are
exported:

* `project_id` - The project ID.

* `number` - The numeric identifier of the project.