github.com/nathanielks/terraform@v0.6.1-0.20170509030759-13e1a62319dc/builtin/providers/local/resource_local_file.go (about) 1 package local 2 3 import ( 4 "crypto/sha1" 5 "encoding/hex" 6 "io/ioutil" 7 "os" 8 "path" 9 10 "github.com/hashicorp/terraform/helper/schema" 11 ) 12 13 func resourceLocalFile() *schema.Resource { 14 return &schema.Resource{ 15 Create: resourceLocalFileCreate, 16 Read: resourceLocalFileRead, 17 Delete: resourceLocalFileDelete, 18 19 Schema: map[string]*schema.Schema{ 20 "content": { 21 Type: schema.TypeString, 22 Required: true, 23 ForceNew: true, 24 }, 25 "filename": { 26 Type: schema.TypeString, 27 Description: "Path to the output file", 28 Required: true, 29 ForceNew: true, 30 }, 31 }, 32 } 33 } 34 35 func resourceLocalFileRead(d *schema.ResourceData, _ interface{}) error { 36 // If the output file doesn't exist, mark the resource for creation. 37 outputPath := d.Get("filename").(string) 38 if _, err := os.Stat(outputPath); os.IsNotExist(err) { 39 d.SetId("") 40 return nil 41 } 42 43 // Verify that the content of the destination file matches the content we 44 // expect. Otherwise, the file might have been modified externally and we 45 // must reconcile. 46 outputContent, err := ioutil.ReadFile(outputPath) 47 if err != nil { 48 return err 49 } 50 51 outputChecksum := sha1.Sum([]byte(outputContent)) 52 if hex.EncodeToString(outputChecksum[:]) != d.Id() { 53 d.SetId("") 54 return nil 55 } 56 57 return nil 58 } 59 60 func resourceLocalFileCreate(d *schema.ResourceData, _ interface{}) error { 61 content := d.Get("content").(string) 62 destination := d.Get("filename").(string) 63 64 destinationDir := path.Dir(destination) 65 if _, err := os.Stat(destinationDir); err != nil { 66 if err := os.MkdirAll(destinationDir, 0777); err != nil { 67 return err 68 } 69 } 70 71 if err := ioutil.WriteFile(destination, []byte(content), 0777); err != nil { 72 return err 73 } 74 75 checksum := sha1.Sum([]byte(content)) 76 d.SetId(hex.EncodeToString(checksum[:])) 77 78 return nil 79 } 80 81 func resourceLocalFileDelete(d *schema.ResourceData, _ interface{}) error { 82 os.Remove(d.Get("filename").(string)) 83 return nil 84 }