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 support for lifecycle ignore_changes #35

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
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
44 changes: 28 additions & 16 deletions local/resource_local_file.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"crypto/sha1"
"encoding/base64"
"encoding/hex"
"fmt"
"io/ioutil"
"os"
"path"
Expand All @@ -14,10 +15,16 @@ import (

func resourceLocalFile() *schema.Resource {
return &schema.Resource{
Create: resourceLocalFileCreate,
Read: resourceLocalFileRead,
Create: resourceLocalFileCreate,
Delete: resourceLocalFileDelete,

Update: nil,
Exists: func(d *schema.ResourceData, meta interface{}) (bool, error) {
if _, err := os.Stat(d.Get("filename").(string)); os.IsNotExist(err) {
return false, nil
}
return true, nil
},
Schema: map[string]*schema.Schema{
"content": {
Type: schema.TypeString,
Expand Down Expand Up @@ -65,25 +72,30 @@ func resourceLocalFile() *schema.Resource {
}

func resourceLocalFileRead(d *schema.ResourceData, _ interface{}) error {
// If the output file doesn't exist, mark the resource for creation.
outputPath := d.Get("filename").(string)
if _, err := os.Stat(outputPath); os.IsNotExist(err) {
d.SetId("")
return nil
// Get actual content from file.
filePath := d.Get("filename").(string)
byteContent, err := ioutil.ReadFile(filePath)
if err != nil {
return err
}

// Verify that the content of the destination file matches the content we
// expect. Otherwise, the file might have been modified externally and we
// must reconcile.
outputContent, err := ioutil.ReadFile(outputPath)
if err != nil {
var setErr error

// Set file_permission to match what is on disk.
stat, _ := os.Stat(filePath)
setErr = d.Set("file_permission", fmt.Sprintf("%04o", stat.Mode().Perm()))
if setErr != nil {
return err
}

outputChecksum := sha1.Sum([]byte(outputContent))
if hex.EncodeToString(outputChecksum[:]) != d.Id() {
d.SetId("")
return nil
// Set `content` or `content_base64` to match current value on disk.
if _, exists := d.GetOkExists("content"); exists {
setErr = d.Set("content", string(byteContent))
} else if _, exists := d.GetOkExists("content_base64"); exists {
setErr = d.Set("content_base64", base64.StdEncoding.EncodeToString(byteContent))
}
if setErr != nil {
return err
}

return nil
Expand Down