Skip to content

Commit

Permalink
Gcr resource (#3073) (#1725)
Browse files Browse the repository at this point in the history
* First pass at registry bucket creation

* Add docs

* PR feedback

Signed-off-by: Modular Magician <magic-modules@google.com>
  • Loading branch information
modular-magician authored Feb 5, 2020
1 parent 826b1c3 commit 229072b
Show file tree
Hide file tree
Showing 5 changed files with 235 additions and 0 deletions.
1 change: 1 addition & 0 deletions google-beta/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -752,6 +752,7 @@ func ResourceMapWithErrors() (map[string]*schema.Resource, error) {
"google_compute_target_pool": resourceComputeTargetPool(),
"google_container_cluster": resourceContainerCluster(),
"google_container_node_pool": resourceContainerNodePool(),
"google_container_registry": resourceContainerRegistry(),
"google_dataflow_job": resourceDataflowJob(),
"google_dataproc_cluster": resourceDataprocCluster(),
"google_dataproc_cluster_iam_binding": ResourceIamBinding(IamDataprocClusterSchema, NewDataprocClusterUpdater, DataprocClusterIdParseFunc),
Expand Down
103 changes: 103 additions & 0 deletions google-beta/resource_container_registry.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
package google

import (
"fmt"
"log"
"strings"

"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)

func resourceContainerRegistry() *schema.Resource {
return &schema.Resource{
Create: resourceContainerRegistryCreate,
Read: resourceContainerRegistryRead,
Delete: resourceContainerRegistryDelete,

Schema: map[string]*schema.Schema{
"location": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
StateFunc: func(s interface{}) string {
return strings.ToUpper(s.(string))
},
},

"project": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
},

"bucket_self_link": {
Type: schema.TypeString,
Computed: true,
},
},
}
}

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

project, err := getProject(d, config)
if err != nil {
return err
}
log.Printf("[DEBUG] Project: %s", project)

location := d.Get("location").(string)
log.Printf("[DEBUG] location: %s", location)
urlBase := "https://gcr.io/v2/token"
if location != "" {
urlBase = fmt.Sprintf("https://%s.gcr.io/v2/token", strings.ToLower(location))
}

// Performing a token handshake with the GCR API causes the backing bucket to create if it hasn't already.
url, err := replaceVars(d, config, fmt.Sprintf("%s?service=gcr.io&scope=repository:{{project}}/my-repo:push,pull", urlBase))
if err != nil {
return err
}

_, err = sendRequestWithTimeout(config, "GET", project, url, nil, d.Timeout(schema.TimeoutCreate))

if err != nil {
return err
}
return resourceContainerRegistryRead(d, meta)
}

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

location := d.Get("location").(string)
project, err := getProject(d, config)
if err != nil {
return err
}
name := ""
if location != "" {
name = fmt.Sprintf("%s.artifacts.%s.appspot.com", strings.ToLower(location), project)
} else {
name = fmt.Sprintf("artifacts.%s.appspot.com", project)
}

res, err := config.clientStorage.Buckets.Get(name).Do()
if err != nil {
return handleNotFoundError(err, d, fmt.Sprintf("Container Registry Storage Bucket %q", name))
}
log.Printf("[DEBUG] Read bucket %v at location %v\n\n", res.Name, res.SelfLink)

// Update the ID according to the bucket ID
d.Set("bucket_self_link", res.SelfLink)

d.SetId(res.Id)
return nil
}

func resourceContainerRegistryDelete(d *schema.ResourceData, meta interface{}) error {
// Don't delete the backing bucket as this is not a supported GCR action
return nil
}
65 changes: 65 additions & 0 deletions google-beta/resource_container_registry_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
package google

import (
"fmt"
"testing"

"github.com/hashicorp/terraform-plugin-sdk/helper/acctest"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
)

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

resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
Steps: []resource.TestStep{
{
Config: testAccContainerRegistry_basic(),
},
},
})
}

func TestAccContainerRegistry_iam(t *testing.T) {
t.Parallel()
account := acctest.RandString(10)

resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
Steps: []resource.TestStep{
{
Config: testAccContainerRegistry_iam(account),
},
},
})
}

func testAccContainerRegistry_basic() string {
return `
resource "google_container_registry" "foobar" {
location = "EU"
}
`
}

func testAccContainerRegistry_iam(account string) string {
return fmt.Sprintf(`
resource "google_container_registry" "foobar" {
location = "EU"
}
resource "google_service_account" "test-account-1" {
account_id = "acct-%s-1"
display_name = "Container Registry Iam Testing Account"
}
resource "google_storage_bucket_iam_member" "viewer" {
bucket = google_container_registry.foobar.id
role = "roles/storage.objectViewer"
member = "serviceAccount:${google_service_account.test-account-1.email}"
}
`, account)
}
57 changes: 57 additions & 0 deletions website/docs/r/container_registry.html.markdown
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
---
subcategory: "Container Registry"
layout: "google"
page_title: "Google: google_container_registry"
sidebar_current: "docs-google-container-registry"
description: |-
Ensures the GCS bucket backing Google Container Registry exists.
---

# google_container_registry

Ensures that the Google Cloud Storage bucket that backs Google Container Registry exists. Creating this resource will create the backing bucket if it does not exist, or do nothing if the bucket already exists. Destroying this resource does *NOT* destroy the backing bucket. For more information see [the official documentation](https://cloud.google.com/container-registry/docs/overview)

This resource can be used to ensure that the GCS bucket exists prior to assigning permissions. For more information see the [access control page](https://cloud.google.com/container-registry/docs/access-control) for GCR.


## Example Usage

```hcl
resource "google_container_registry" "registry" {
project = "my-project"
location = "EU"
}
```

The `id` field of the `google_container_registry` is the identifier of the storage bucket that backs GCR and can be used to assign permissions to the bucket.

```hcl
resource "google_container_registry" "registry" {
project = "my-project"
location = "EU"
}
resource "google_storage_bucket_iam_member" "viewer" {
bucket = google_container_registry.registry.id
role = "roles/storage.objectViewer"
member = "user:jane@example.com"
}
```

## Argument Reference

The following arguments are supported:

* `location` - (Optional) The location of the registry. One of `ASIA`, `EU`, `US` or not specified. See [the official documentation](https://cloud.google.com/container-registry/docs/pushing-and-pulling#pushing_an_image_to_a_registry) for more information on registry locations.

* `project` - (Optional) The ID of the project in which the resource belongs. If it is not provided, the provider project is used.


## Attributes Reference

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

* `bucket_self_link` - The URI of the created resource.

* `id` - The name of the bucket that supports the Container Registry. In the form of `artifacts.{project}.appspot.com` or `{location}.artifacts.{project}.appspot.com` if location is specified.
9 changes: 9 additions & 0 deletions website/google.erb
Original file line number Diff line number Diff line change
Expand Up @@ -834,6 +834,15 @@
</ul>
</li>

<li<%= sidebar_current("docs-google-container-registry") %>>
<a href="#">Google Container Registry Resources</a>
<ul class="nav nav-visible">
<li<%= sidebar_current("docs-google-container-registry") %>>
<a href="/docs/providers/google/r/container_registry.html">google_container_registry</a>
</li>
</ul>
</li>

<li<%= sidebar_current("docs-google-container") %>>
<a href="#">Google Kubernetes (Container) Engine Resources</a>
<ul class="nav nav-visible">
Expand Down

0 comments on commit 229072b

Please sign in to comment.