Skip to content

Commit

Permalink
Firebase Hosting site Terraform provider (#6598) (#4846)
Browse files Browse the repository at this point in the history
* Firebase Hosting site Terraform provider

* Add sweeper to Firebase Hosting Site

* Add a basic hosting site without app

* Move app_id to test_vars_overrides to avoid adding random_suffix

* Add defaultUrl. Shorten base_url. Add sites/site-id import

* Create new web app as part of hosting site test

* Fix tab vs spaces

* Separate basic and full test for firebasehosting

* Add update test for google_firebase_hosting_site

* Use immediate delete for test web app

* Use deletion_policy = DELETE for handwritten update test

* Address feedack on site_id name

* Use specific Firebase Hosting docs

Signed-off-by: Modular Magician <magic-modules@google.com>

Signed-off-by: Modular Magician <magic-modules@google.com>
  • Loading branch information
modular-magician authored Nov 7, 2022
1 parent 1d11969 commit 0efb108
Show file tree
Hide file tree
Showing 8 changed files with 808 additions and 2 deletions.
3 changes: 3 additions & 0 deletions .changelog/6598.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
```release-note:new-resource
`google_firebase_hosting_site`
```
4 changes: 4 additions & 0 deletions google-beta/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -218,6 +218,7 @@ type Config struct {
EssentialContactsBasePath string
FilestoreBasePath string
FirebaseBasePath string
FirebaseHostingBasePath string
FirestoreBasePath string
GameServicesBasePath string
GKEHubBasePath string
Expand Down Expand Up @@ -326,6 +327,7 @@ const DocumentAIBasePathKey = "DocumentAI"
const EssentialContactsBasePathKey = "EssentialContacts"
const FilestoreBasePathKey = "Filestore"
const FirebaseBasePathKey = "Firebase"
const FirebaseHostingBasePathKey = "FirebaseHosting"
const FirestoreBasePathKey = "Firestore"
const GameServicesBasePathKey = "GameServices"
const GKEHubBasePathKey = "GKEHub"
Expand Down Expand Up @@ -428,6 +430,7 @@ var DefaultBasePaths = map[string]string{
EssentialContactsBasePathKey: "https://essentialcontacts.googleapis.com/v1/",
FilestoreBasePathKey: "https://file.googleapis.com/v1beta1/",
FirebaseBasePathKey: "https://firebase.googleapis.com/v1beta1/",
FirebaseHostingBasePathKey: "https://firebasehosting.googleapis.com/v1beta1/",
FirestoreBasePathKey: "https://firestore.googleapis.com/v1/",
GameServicesBasePathKey: "https://gameservices.googleapis.com/v1beta/",
GKEHubBasePathKey: "https://gkehub.googleapis.com/v1beta1/",
Expand Down Expand Up @@ -1306,6 +1309,7 @@ func ConfigureBasePaths(c *Config) {
c.EssentialContactsBasePath = DefaultBasePaths[EssentialContactsBasePathKey]
c.FilestoreBasePath = DefaultBasePaths[FilestoreBasePathKey]
c.FirebaseBasePath = DefaultBasePaths[FirebaseBasePathKey]
c.FirebaseHostingBasePath = DefaultBasePaths[FirebaseHostingBasePathKey]
c.FirestoreBasePath = DefaultBasePaths[FirestoreBasePathKey]
c.GameServicesBasePath = DefaultBasePaths[GameServicesBasePathKey]
c.GKEHubBasePath = DefaultBasePaths[GKEHubBasePathKey]
Expand Down
14 changes: 12 additions & 2 deletions google-beta/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -517,6 +517,14 @@ func Provider() *schema.Provider {
"GOOGLE_FIREBASE_CUSTOM_ENDPOINT",
}, DefaultBasePaths[FirebaseBasePathKey]),
},
"firebase_hosting_custom_endpoint": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validateCustomEndpoint,
DefaultFunc: schema.MultiEnvDefaultFunc([]string{
"GOOGLE_FIREBASE_HOSTING_CUSTOM_ENDPOINT",
}, DefaultBasePaths[FirebaseHostingBasePathKey]),
},
"firestore_custom_endpoint": {
Type: schema.TypeString,
Optional: true,
Expand Down Expand Up @@ -1013,9 +1021,9 @@ func Provider() *schema.Provider {
return provider
}

// Generated resources: 277
// Generated resources: 278
// Generated IAM resources: 183
// Total generated resources: 460
// Total generated resources: 461
func ResourceMap() map[string]*schema.Resource {
resourceMap, _ := ResourceMapWithErrors()
return resourceMap
Expand Down Expand Up @@ -1306,6 +1314,7 @@ func ResourceMapWithErrors() (map[string]*schema.Resource, error) {
"google_firebase_project_location": resourceFirebaseProjectLocation(),
"google_firebase_web_app": resourceFirebaseWebApp(),
"google_firebase_android_app": resourceFirebaseAndroidApp(),
"google_firebase_hosting_site": resourceFirebaseHostingSite(),
"google_firestore_index": resourceFirestoreIndex(),
"google_firestore_document": resourceFirestoreDocument(),
"google_game_services_realm": resourceGameServicesRealm(),
Expand Down Expand Up @@ -1758,6 +1767,7 @@ func providerConfigure(ctx context.Context, d *schema.ResourceData, p *schema.Pr
config.EssentialContactsBasePath = d.Get("essential_contacts_custom_endpoint").(string)
config.FilestoreBasePath = d.Get("filestore_custom_endpoint").(string)
config.FirebaseBasePath = d.Get("firebase_custom_endpoint").(string)
config.FirebaseHostingBasePath = d.Get("firebase_hosting_custom_endpoint").(string)
config.FirestoreBasePath = d.Get("firestore_custom_endpoint").(string)
config.GameServicesBasePath = d.Get("game_services_custom_endpoint").(string)
config.GKEHubBasePath = d.Get("gke_hub_custom_endpoint").(string)
Expand Down
316 changes: 316 additions & 0 deletions google-beta/resource_firebase_hosting_site.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,316 @@
// ----------------------------------------------------------------------------
//
// *** AUTO GENERATED CODE *** Type: MMv1 ***
//
// ----------------------------------------------------------------------------
//
// This file is automatically generated by Magic Modules and manual
// changes will be clobbered when the file is regenerated.
//
// Please read more about how to change this file in
// .github/CONTRIBUTING.md.
//
// ----------------------------------------------------------------------------

package google

import (
"fmt"
"log"
"reflect"
"strings"
"time"

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

func resourceFirebaseHostingSite() *schema.Resource {
return &schema.Resource{
Create: resourceFirebaseHostingSiteCreate,
Read: resourceFirebaseHostingSiteRead,
Update: resourceFirebaseHostingSiteUpdate,
Delete: resourceFirebaseHostingSiteDelete,

Importer: &schema.ResourceImporter{
State: resourceFirebaseHostingSiteImport,
},

Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(20 * time.Minute),
Update: schema.DefaultTimeout(20 * time.Minute),
Delete: schema.DefaultTimeout(20 * time.Minute),
},

Schema: map[string]*schema.Schema{
"app_id": {
Type: schema.TypeString,
Optional: true,
Description: `Optional. The [ID of a Web App](https://firebase.google.com/docs/projects/api/reference/rest/v1beta1/projects.webApps#WebApp.FIELDS.app_id)
associated with the Hosting site.`,
},
"site_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Description: `Required. Immutable. A globally unique identifier for the Hosting site. This identifier is
used to construct the Firebase-provisioned subdomains for the site, so it must also be a valid
domain name label.`,
},
"default_url": {
Type: schema.TypeString,
Computed: true,
Description: `The default URL for the site in the form of https://{name}.web.app`,
},
"name": {
Type: schema.TypeString,
Computed: true,
Description: `Output only. The fully-qualified resource name of the Hosting site, in the
format: projects/PROJECT_IDENTIFIER/sites/SITE_ID PROJECT_IDENTIFIER: the
Firebase project's
['ProjectNumber'](https://firebase.google.com/docs/projects/api/reference/rest/v1beta1/projects#FirebaseProject.FIELDS.project_number) ***(recommended)*** or its
['ProjectId'](https://firebase.google.com/docs/projects/api/reference/rest/v1beta1/projects#FirebaseProject.FIELDS.project_id).
Learn more about using project identifiers in Google's
[AIP 2510 standard](https://google.aip.dev/cloud/2510).`,
},
"project": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
},
},
UseJSONNumber: true,
}
}

func resourceFirebaseHostingSiteCreate(d *schema.ResourceData, meta interface{}) error {
config := meta.(*Config)
userAgent, err := generateUserAgentString(d, config.userAgent)
if err != nil {
return err
}

obj := make(map[string]interface{})
appIdProp, err := expandFirebaseHostingSiteAppId(d.Get("app_id"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("app_id"); !isEmptyValue(reflect.ValueOf(appIdProp)) && (ok || !reflect.DeepEqual(v, appIdProp)) {
obj["appId"] = appIdProp
}

url, err := replaceVars(d, config, "{{FirebaseHostingBasePath}}projects/{{project}}/sites?siteId={{site_id}}")
if err != nil {
return err
}

log.Printf("[DEBUG] Creating new Site: %#v", obj)
billingProject := ""

project, err := getProject(d, config)
if err != nil {
return fmt.Errorf("Error fetching project for Site: %s", err)
}
billingProject = project

// err == nil indicates that the billing_project value was found
if bp, err := getBillingProject(d, config); err == nil {
billingProject = bp
}

res, err := sendRequestWithTimeout(config, "POST", billingProject, url, userAgent, obj, d.Timeout(schema.TimeoutCreate))
if err != nil {
return fmt.Errorf("Error creating Site: %s", err)
}
if err := d.Set("name", flattenFirebaseHostingSiteName(res["name"], d, config)); err != nil {
return fmt.Errorf(`Error setting computed identity field "name": %s`, err)
}

// Store the ID now
id, err := replaceVars(d, config, "projects/{{project}}/sites/{{site_id}}")
if err != nil {
return fmt.Errorf("Error constructing id: %s", err)
}
d.SetId(id)

log.Printf("[DEBUG] Finished creating Site %q: %#v", d.Id(), res)

return resourceFirebaseHostingSiteRead(d, meta)
}

func resourceFirebaseHostingSiteRead(d *schema.ResourceData, meta interface{}) error {
config := meta.(*Config)
userAgent, err := generateUserAgentString(d, config.userAgent)
if err != nil {
return err
}

url, err := replaceVars(d, config, "{{FirebaseHostingBasePath}}projects/{{project}}/sites/{{site_id}}")
if err != nil {
return err
}

billingProject := ""

project, err := getProject(d, config)
if err != nil {
return fmt.Errorf("Error fetching project for Site: %s", err)
}
billingProject = project

// err == nil indicates that the billing_project value was found
if bp, err := getBillingProject(d, config); err == nil {
billingProject = bp
}

res, err := sendRequest(config, "GET", billingProject, url, userAgent, nil)
if err != nil {
return handleNotFoundError(err, d, fmt.Sprintf("FirebaseHostingSite %q", d.Id()))
}

if err := d.Set("project", project); err != nil {
return fmt.Errorf("Error reading Site: %s", err)
}

if err := d.Set("name", flattenFirebaseHostingSiteName(res["name"], d, config)); err != nil {
return fmt.Errorf("Error reading Site: %s", err)
}
if err := d.Set("app_id", flattenFirebaseHostingSiteAppId(res["appId"], d, config)); err != nil {
return fmt.Errorf("Error reading Site: %s", err)
}
if err := d.Set("default_url", flattenFirebaseHostingSiteDefaultUrl(res["defaultUrl"], d, config)); err != nil {
return fmt.Errorf("Error reading Site: %s", err)
}

return nil
}

func resourceFirebaseHostingSiteUpdate(d *schema.ResourceData, meta interface{}) error {
config := meta.(*Config)
userAgent, err := generateUserAgentString(d, config.userAgent)
if err != nil {
return err
}

billingProject := ""

project, err := getProject(d, config)
if err != nil {
return fmt.Errorf("Error fetching project for Site: %s", err)
}
billingProject = project

obj := make(map[string]interface{})
appIdProp, err := expandFirebaseHostingSiteAppId(d.Get("app_id"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("app_id"); !isEmptyValue(reflect.ValueOf(v)) && (ok || !reflect.DeepEqual(v, appIdProp)) {
obj["appId"] = appIdProp
}

url, err := replaceVars(d, config, "{{FirebaseHostingBasePath}}projects/{{project}}/sites/{{site_id}}")
if err != nil {
return err
}

log.Printf("[DEBUG] Updating Site %q: %#v", d.Id(), obj)
updateMask := []string{}

if d.HasChange("app_id") {
updateMask = append(updateMask, "appId")
}
// updateMask is a URL parameter but not present in the schema, so replaceVars
// won't set it
url, err = addQueryParams(url, map[string]string{"updateMask": strings.Join(updateMask, ",")})
if err != nil {
return err
}

// err == nil indicates that the billing_project value was found
if bp, err := getBillingProject(d, config); err == nil {
billingProject = bp
}

res, err := sendRequestWithTimeout(config, "PATCH", billingProject, url, userAgent, obj, d.Timeout(schema.TimeoutUpdate))

if err != nil {
return fmt.Errorf("Error updating Site %q: %s", d.Id(), err)
} else {
log.Printf("[DEBUG] Finished updating Site %q: %#v", d.Id(), res)
}

return resourceFirebaseHostingSiteRead(d, meta)
}

func resourceFirebaseHostingSiteDelete(d *schema.ResourceData, meta interface{}) error {
config := meta.(*Config)
userAgent, err := generateUserAgentString(d, config.userAgent)
if err != nil {
return err
}

billingProject := ""

project, err := getProject(d, config)
if err != nil {
return fmt.Errorf("Error fetching project for Site: %s", err)
}
billingProject = project

url, err := replaceVars(d, config, "{{FirebaseHostingBasePath}}projects/{{project}}/sites/{{site_id}}")
if err != nil {
return err
}

var obj map[string]interface{}
log.Printf("[DEBUG] Deleting Site %q", d.Id())

// err == nil indicates that the billing_project value was found
if bp, err := getBillingProject(d, config); err == nil {
billingProject = bp
}

res, err := sendRequestWithTimeout(config, "DELETE", billingProject, url, userAgent, obj, d.Timeout(schema.TimeoutDelete))
if err != nil {
return handleNotFoundError(err, d, "Site")
}

log.Printf("[DEBUG] Finished deleting Site %q: %#v", d.Id(), res)
return nil
}

func resourceFirebaseHostingSiteImport(d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) {
config := meta.(*Config)
if err := parseImportId([]string{
"projects/(?P<project>[^/]+)/sites/(?P<site_id>[^/]+)",
"(?P<project>[^/]+)/(?P<site_id>[^/]+)",
"sites/(?P<site_id>[^/]+)",
"(?P<site_id>[^/]+)",
}, d, config); err != nil {
return nil, err
}

// Replace import id for the resource id
id, err := replaceVars(d, config, "projects/{{project}}/sites/{{site_id}}")
if err != nil {
return nil, fmt.Errorf("Error constructing id: %s", err)
}
d.SetId(id)

return []*schema.ResourceData{d}, nil
}

func flattenFirebaseHostingSiteName(v interface{}, d *schema.ResourceData, config *Config) interface{} {
return v
}

func flattenFirebaseHostingSiteAppId(v interface{}, d *schema.ResourceData, config *Config) interface{} {
return v
}

func flattenFirebaseHostingSiteDefaultUrl(v interface{}, d *schema.ResourceData, config *Config) interface{} {
return v
}

func expandFirebaseHostingSiteAppId(v interface{}, d TerraformResourceData, config *Config) (interface{}, error) {
return v, nil
}
Loading

0 comments on commit 0efb108

Please sign in to comment.