github.com/GoogleCloudPlatform/terraformer@v0.8.18/terraformutils/terraformoutput/bucket.go (about) 1 // Copyright 2018 The Terraformer Authors. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 package terraformoutput 15 16 import ( 17 "context" 18 "log" 19 "strings" 20 21 "cloud.google.com/go/storage" 22 ) 23 24 type BucketState struct { 25 Name string 26 } 27 28 func (b BucketState) BucketGetTfData(path string) interface{} { 29 name := strings.ReplaceAll(b.Name, "gs://", "") 30 bucketStateData := map[string]interface{}{ 31 "terraform": map[string]interface{}{ 32 "backend": []map[string]interface{}{ 33 { 34 "gcs": map[string]interface{}{ 35 "bucket": name, 36 "prefix": b.BucketPrefix(path), 37 }, 38 }, 39 }, 40 }, 41 } 42 return bucketStateData 43 } 44 45 func (b BucketState) BucketPrefix(path string) string { 46 return strings.TrimSuffix(path, "/") 47 } 48 49 func (b BucketState) BucketUpload(path string, file []byte) error { 50 ctx := context.Background() 51 client, err := storage.NewClient(ctx) 52 if err != nil { 53 log.Fatalf("Failed to create client: %v", err) 54 } 55 name := strings.ReplaceAll(b.Name, "gs://", "") 56 wc := client.Bucket(name).Object(b.BucketPrefix(path) + "/default.tfstate").NewWriter(ctx) 57 if _, err = wc.Write(file); err != nil { 58 return err 59 } 60 if err := wc.Close(); err != nil { 61 return err 62 } 63 return nil 64 }