Skip to content

Instantly share code, notes, and snippets.

@martingehrke
Last active August 29, 2015 14:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save martingehrke/3e8012ff205044ab6795 to your computer and use it in GitHub Desktop.
Save martingehrke/3e8012ff205044ab6795 to your computer and use it in GitHub Desktop.
Reading a file in cfengine can be expensive. The code below shows how do it right.
#this requires cfengine 3.7 for the if and unless
vars:
"file" string => "/full/path/to/file.json";
classname:: #always gate file reads as tightly as possible
"data" data => readjson("$(file)", inf),
if => fileexists("$(file)"), #don't try to read if file is missing
unless => isvariable("$(this.promiser)"); #don't read file more than once
#you can't do all that in pre 3.7 but you can do some
# sometimes I prefer an error if the file is missing
vars:
"file" string => "/full/path/to/file.json";
classname:: #same as above
"data" data => readjson("$(file)", inf),
ifvarclass => not(isvariable("$(this.promiser)")); # unless == if not
@martingehrke
Copy link
Author

  1. only read if the file exists
  2. only read if you haven't already read it
  3. always gate a file read as tightly as possible. vars (and classes) are always evaluated if the file is read. This means you may not be calling the bundle, but the vars and classes are eval'd. By gating them you prevent that.
    #1 is up for discussion. Sometimes I prefer to see an error if the file is absent. It is easier to troubleshoot

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment