Promise types
Within a bundle, the promise types are executed in a round-robin fashion in thefollowingnormal ordering. Which promise types are availabledepends on thebundle type:
| Promise type | common | agent | server | monitor |
|---|---|---|---|---|
| defaults - a default value for bundle parameters | x | x | x | x |
| classes - a class, representing a state of the system | x | x | x | x |
| meta - information about promise bundles | x | x | x | x |
| reports - report a message | x | x | x | x |
| vars - a variable, representing a value | x | x | x | x |
| commands - execute a command | x | |||
| databases - configure a database | x | |||
| files - configure a file | x | |||
| packages - install a package | x | |||
| guest_environments | x | |||
| methods - take on a whole bundle of other promises | x | |||
| processes - start or terminate processes | x | |||
| services - manage services or define new abstractions | x | |||
| storage - verify attached storage | x | |||
| users - add or remove users | x | |||
| access - grant or deny access to file objects | x | |||
| roles - allow certain users to activate certain classes | x | |||
| measurements - measure or sample data from the system | x |
See each promise type's reference documentation for detailed lists of availableattributes.
Common promise attributes
The following attributes are available to all promise types.
action
Type:body action
Theaction settings allow general transaction control to be implemented onpromise verification. Action bodies place limits on how often to verify thepromise and what classes to raise in the case that the promise can or cannot bekept.
action_policy
Description: Determines whether to repair or report about non-kept promises
Type: (menu option)
Allowed input range:
fixmakes changes to move toward the desired statewarndoes not make changes, emits a warning level log message about non-compliance, raise repair_failed (not-kept)nopalias for warn
Default value:fix
Example:
Policy:
bodyfilecontrol{# Include the stdlib for local_dcp, policy, delete_linesinputs=>{"$(sys.libdir)/stdlib.cf"};}bundleagentexample_action_policy{files:# We make sure there is some files to operate on, so we simply make a copy# of ourselves"$(this.promise_filename).nop"copy_from=>local_dcp($(this.promise_filename));"$(this.promise_filename).warn"copy_from=>local_dcp($(this.promise_filename));"$(this.promise_filename).fix"copy_from=>local_dcp($(this.promise_filename));# We exercise each valid value of action_policy (nop, fix, warn) defining# classes named for the action_policy"$(this.promise_filename).nop"handle=>"delete_lines_action_nop",edit_line=>delete_lines_matching(".*"),action=>policy("nop"),classes=>results("namespace","MY_files_promise_nop");"$(this.promise_filename).warn"handle=>"delete_lines_action_warn",edit_line=>delete_lines_matching(".*"),action=>policy("warn"),classes=>results("namespace","MY_files_promise_warn");"$(this.promise_filename).fix"handle=>"delete_lines_action_fix",edit_line=>delete_lines_matching(".*"),action=>policy("fix"),classes=>results("namespace","MY_files_promise_fix");commands:"/bin/echo Running Command nop"handle=>"command_nop",action=>policy("nop"),classes=>results("namespace","MY_commands_promise_nop");"/bin/echo Running Command warn"handle=>"command_warn",action=>policy("warn"),classes=>results("namespace","MY_commands_promise_warn");"/bin/echo Running Command fix"handle=>"command_fix",action=>policy("fix"),classes=>results("namespace","MY_commands_promise_fix");reports:"MY classes:$(const.n)$(const.t)$(with)"with=>join("$(const.n)$(const.t)",sort(classesmatching("MY_.*"),"lex"));}bundleagent__main__{methods:"example_action_policy";}This policy can be found in/var/cfengine/share/doc/examples/action_policy.cfand downloaded directly fromgithub.
Output:
warning: Should edit file '/tmp/action_policy.cf.nop' but only a warning promised warning: Should edit file '/tmp/action_policy.cf.warn' but only a warning promised warning: Command '/bin/echo Running Command nop' needs to be executed, but only warning was promised warning: Command '/bin/echo Running Command warn' needs to be executed, but only warning was promisedR: MY classes: MY_commands_promise_fix_reached MY_commands_promise_fix_repaired MY_commands_promise_nop_error MY_commands_promise_nop_failed MY_commands_promise_nop_not_kept MY_commands_promise_nop_reached MY_commands_promise_warn_error MY_commands_promise_warn_failed MY_commands_promise_warn_not_kept MY_commands_promise_warn_reached MY_files_promise_fix_reached MY_files_promise_fix_repaired MY_files_promise_nop_error MY_files_promise_nop_failed MY_files_promise_nop_not_kept MY_files_promise_nop_reached MY_files_promise_warn_error MY_files_promise_warn_failed MY_files_promise_warn_not_kept MY_files_promise_warn_reached warning: Method 'example_action_policy' invoked repairs, but only warnings promisedifelapsed
Description: The number of minutes before next allowed assessment of apromise is set usingifelapsed. This overrides the global settings. Promiseswhich take a long time to verify should usually be protected with a long valuefor this parameter.
This serves as a resource 'spam' protection. A CFEngine check could easily runevery 5 minutes provided resource intensive operations are not performed onevery run. Using time classes such asHr12 is one part of this strategy;usingifelapsed is another, which is not tied to a specific time.
ifelapsed => "0" disablesfunction cachingfor the specific promise it's attached to.
Type:int
Allowed input range:0,99999999999
Default value:body agent control ifelapsed value
Example:
bodyactionexample{ifelapsed=>"120";# 2 hoursexpireafter=>"240";# 4 hours}Notes:
- This is not a reliable way to control frequency over a long period of time.
- Locks provide simple but weak frequency control.
- Locks older than 4 weeks are automatically purged.
See also:promise locking,ifelapsed in body agent control,ifelapsed and function caching
History:
ifelapsed => "0"disables function caching for specific promise introduced in 3.19.0, 3.18.1
expireafter
Description: The Number of minutes a promise is allowed to run before theagent is terminated.
Note: Not to be confusedwithbody contain exec_timeout in commands typepromises, the original agent doesnot terminate the promise. When asubsequent agent notices that a promise actuation has persisted for longer thanexpireafter the subsequent agent will kill the agent that appears to be stuckon the long running promise.
Type:int
Allowed input range:0,99999999999
Default value:control body value
Example:
bodyactionexample{ifelapsed=>"120";# 2 hoursexpireafter=>"240";# 4 hours}See also:body contain exec_timeout,body agent control expireafter,body executor control agent_expireafter
log_string
Description: The message to be written to the log when a promiseverification leads to a repair.
Thelog_string works together withlog_kept,log_repaired, andlog_failed to define a string for logging to one of the named files dependingon promise outcome, or to standard output if the log file is stipulated asstdout. Log strings on standard output are denoted by anL: prefix.
Note thatlog_string does not interact withlog_level, which is aboutregular system output messages.
Type:string
Allowed input range: (arbitrary string)
Example:
promise-type:"promiser"attr=>"value",action=>log_me("checked$(this.promiser) in promise$(this.handle)");# ..bodyactionlog_me(s){log_string=>"$(s)";}Hint: The promise handle$(this.handle) can be auseful referent in a log message, indicating the origin of the message. InCFEngine Enterprise, promise handles make it easy to interpret report data.
log_kept
log_repaired
log_failed
Description: The names of files to whichlog_string will be savedfor kept, repaired and failed promises.
When used together withlog_string, the current promise will log its statususing the log string to the respective file.
If these log names are absent, the default logging destination for the logstring is syslog, but only for non-kept promises. Only thelog_string isaffected by this setting. Other messages destined for logging are sent tosyslog.
Type:string
Allowed input range:stdout|udp_syslog|("?[a-zA-Z]:\\.*)|(/.*)
This string should be the full path to a text file which will contain the log,or one of the following special values:
stdout
Send the log message to the standard output, prefixed with an L: to indicate alog message.
udp_syslog
Log messages tosyslog_host asdefined in body common control over UDP. Please noteUDP is unreliable.
Example:
bundleagenttest{vars:"software"slist=>{"/root/xyz","/tmp/xyz"};files:"$(software)"create=>"true",action=>logme("$(software)");}bodyactionlogme(x){log_kept=>"/tmp/private_keptlog.log";log_failed=>"/tmp/private_faillog.log";log_repaired=>"/tmp/private_replog.log";log_string=>"$(sys.date)$(x) promise status";}bodyactionimmediate_syslog(x){log_repaired=>"udp_syslog";log_string=>"CFEngine repaired promise$(this.handle) -$(x)";}It is intended that named file logs should be different for the three cases:promise kept, promise not kept and promise repaired.
log_level
Description: Describes the reporting level sent to syslog.
Use this as an alternative to auditing if you wish to use the syslog mechanismto centralize or manage messaging from CFEngine. A backup of these messageswill still be kept inWORKDIR/outputs if you are usingcf-execd.
On the native Windows version of CFEngine Enterprise, using verbose willinclude a message when the promise is kept or repaired in the event log.
Type: (menu option)
Allowed input range:
informverboseerrorlogExample:
bodyactionexample{log_level=>"inform";}Note: This attribute can not make the logging for an individual promise lessverbose than specified by an agent option (-v,--verbose,-I,--inform,-d,--debug ).
log_priority
Type: (menu option)
Allowed input range:
emergencyalertcriticalerrorwarningnoticeinfodebugDescription: Thelog_priority menu option policy is the priority levelof the log message, as interpreted by a syslog server. It determines theimportance of messages from CFEngine.
Example:
bodyactionlow_priority{log_priority=>"info";}value_kept
Deprecated: This menu option policy is deprecated as of 3.6.0. It performsno action and is kept for backward compatibility.
value_repaired
Deprecated: This menu option policy is deprecated as of 3.6.0. It performsno action and is kept for backward compatibility.
value_notkept
Deprecated: This menu option policy is deprecated as of 3.6.0. It performsno action and is kept for backward compatibility.
audit
Deprecated: This menu option policy is deprecated as of 3.6.0. It performsno action and is kept for backward compatibility.
background
Description: A true/false switch for parallelizing the promise repair.
If possible, perform the verification of the current promise in the background (up tomax_children in body agent control).This is advantageous only if the verification might take a significant amountof time, e.g. in remote copying of filesystem/disk scans.
On the Windows version of CFEngine Enterprise, this can be useful if we don'twant to wait for a particular command to finish execution before checking thenext promise. This is particular for the Windows platform because there isno way that a program can start itself in the background here; in other words,fork off a child process. However, file operations can not be performed in thebackground on Windows.
Type:boolean
Default value: false
Example:
bundleagentmain{commands:"/bin/sleep 10"action=>background;"/bin/sleep"args=>"20",action=>background;}bodyactionbackground{background=>"true";}See also:max_children in body agent control
report_level
Description: Defines the reporting level for standard output for this promise.
cf-agent can be run in verbose mode (-v), inform mode (-I) and just printerrors (no arguments). This attribute allows to set these three output levelson a per promise basis, allowing the promise to be more verbose than the globalsetting (but not less).
Type: (menu option)
Allowed input range:
informverboseerrorlogDefault value: none
Example:
bodyactionexample{report_level=>"verbose";}measurement_class
Description: If set, performance will be measured and recorded under thisidentifier.
By setting this string you switch on performance measurement for the currentpromise, and also give the measurement a name.
Type:string
Allowed input range: (arbitrary string)
Example:
bodyactionmeasure{measurement_class=>"$(this.promiser) long job scan of /usr";}The identifier forms a partial identity for optional performance scanning ofpromises of the form:
ID:promise-type:promiser.classes
Type:body classes
scope
Description: Scope of the class set by this body.
Type: (menu option)
Allowed input range:
namespacebundleDefault value: namespace
Example:
bodyclassesbundle_class{scope=>"bundle";promise_kept=>{"bundle_context"};}History: This attribute was introduced in CFEngine 3.5
See also:scope inclasses promises
promise_repaired
Description: Classes to be defined globally if the promise was 'repaired'.
If the classes are set, a corrective action had to be taken to keep thepromise.
Type:slist
Allowed input range:[a-zA-Z0-9_$(){}\[\].:]+
Note that any strings passed to this list are automatically canonified, so itis unnecessary to call a canonify function on such inputs.
Example:
bodyclassesexample{promise_repaired=>{"change_happened"};}Important: Complex promises can report misleadingly; for example,filespromises that set multiple parameters on a file simultaneously.
The classes for different parts of a promise are not separable. Thus, if youpromise to create and file and change its permissions, when the file existswith incorrect permissions,cf-agent will report that thepromise_kept forthe file existence, butpromise_repaired for the permissions. If you needseparate reports, you should code two separate promises rather than'overloading' a single one.
repair_failed
Description: Classes to be defined globally if the promise could not bekept.
If the classes are set, the corrective action to keep the promise failed forsome reason.
Type:slist
Allowed input range:[a-zA-Z0-9_$(){}\[\].:]+
Note that any strings passed to this list are automatically canonified, so itis unnecessary to call a canonify function on such inputs.
Example:
bodyclassesexample{repair_failed=>{"unknown_error"};}repair_denied
Description: Classes to be defined globally if the promise could not berepaired due to denied access to required resources.
Type:slist
Allowed input range:[a-zA-Z0-9_$(){}\[\].:]+
Note that any strings passed to this list are automatically canonified, so itis unnecessary to call a canonify function on such inputs.
Example:
bodyclassesexample{repair_denied=>{"permission_failure"};}In the above example, a promise could not be kept because access to a keyresource was denied.
repair_timeout
Description: Classes to be defined globally if the promise could not berepaired due to timeout.
Type:slist
Allowed input range:[a-zA-Z0-9_$(){}\[\].:]+
Note that any strings passed to this list are automatically canonified, so itis unnecessary to call a canonify function on such inputs.
Example:
bodyclassesexample{repair_timeout=>{"too_slow","did_not_wait"};}In the above example, a promise maintenance repair timed-out waiting for somedependent resource.
promise_kept
Description: Classes to be defined globally if the promise was kept withoutany corrective action.
Type:slist
Allowed input range:[a-zA-Z0-9_$(){}\[\].:]+
Note that any strings passed to this list are automatically canonified, so itis unnecessary to call a canonify function on such inputs.
Example:
bodyclassesexample{promise_kept=>{"success","kaplah"};}The class in the above example is set if no action was necessary bycf-agent,because the promise concerned was already kept without further action required.
Note: Complex promises can report misleadingly. For example,filespromises that set multiple parameters on a file simultaneously.
The classes for different parts of a promise are not separable. Thus, if youpromise to create and file and change its permissions, when the file existswith incorrect permissions,cf-agent will report that thepromise_kept forthe file existence, butpromise_repaired for the permissions. If you needseparate reports, you should code two separate promises rather than'overloading' a single one.
cancel_kept
Description: Classes to be canceled if the promise is kept.
Type:slist
Allowed input range:[a-zA-Z0-9_$(){}\[\].:]+
Note that any strings passed to this list are automatically canonified, so itis unnecessary to call a canonify function on such inputs.
Example:
bodyclassesexample{cancel_kept=>{"success","kaplah"};}In the above example, if the promise was already kept and nothing was done,cancel (undefine) any of the listed classes so that they are no longer defined.
Notes:
- Hard classes cannot be undefined. If you try to undefine or cancel a hardclass an error will be emitted, for example
error: You cannot cancel areserved hard class 'cfengine' in post-condition classes.
History: This attribute was introduced in CFEngine version 3.0.4 (2010)
cancel_repaired
Description: Classes to be canceled if the promise is repaired.
Type:slist
Allowed input range:[a-zA-Z0-9_$(){}\[\].:]+
Note that any strings passed to this list are automatically canonified, soit is unnecessary to call a canonify function on such inputs.
Example:
bodyclassesexample{cancel_repaired=>{"change_happened"};}In the above example, if the promise was repaired and changes were made to thesystem, cancel (undefine) any of the listed classes so that they are no longerdefined.
Notes:
- Hard classes cannot be undefined. If you try to undefine or cancel a hardclass an error will be emitted, for example
error: You cannot cancel areserved hard class 'cfengine' in post-condition classes.
History: This attribute was introduced in CFEngine version 3.0.4 (2010)
cancel_notkept
Description: Classes to be canceled if the promise is not kept for anyreason.
Type:slist
Allowed input range:[a-zA-Z0-9_$(){}\[\].:]+
Note that any strings passed to this list are automatically canonified, soit is unnecessary to call a canonify function on such inputs.
Example:
bodyclassesexample{cancel_notkept=>{"failure"};}In the above example, if the promise was not kept but nothing could be done,cancel (undefine) any of the listed classes so that they are no longerdefined.
Notes:
- Hard classes cannot be undefined. If you try to undefine or cancel a hardclass an error will be emitted, for example
error: You cannot cancel areserved hard class 'cfengine' in post-condition classes.
History: This attribute was introduced in CFEngine version 3.0.4 (2010)
kept_returncodes
Description: Return codes that indicate a keptcommands promise.
Currently, the attribute has impact on the following command-related promises:
- All promises of type
commands: files-promises containing atransformer-attribute- The package manager change command in
packages-promises (e.g. the commandfor add, remove, etc.)
If none of the attributeskept_returncodes,repaired_returncodes, orfailed_returncodes are set, the default is to consider a return code zero aspromise repaired, and nonzero as promise failed.
Type:slist
Allowed input range:[-0-9_$(){}\[\].]+
Note that the return codes may overlap, so multiple classes may be set from onereturn code. In Unix systems the possible return codes are usually in the rangefrom 0 to 255.
Example:
bundleagentcmdtest{commands:"/bin/false"classes=>example;reports:waskept::"The command-promise was kept!";}bodyclassesexample{kept_returncodes=>{"0","1"};promise_kept=>{"waskept"};}In the above example, a list of integer return codes indicates that acommand-related promise has been kept. This can in turn be used to defineclasses using thepromise_kept attribute, or merely alter the totalcompliance statistics.
History: Was introduced in version 3.1.3, Nova 2.0.2 (2010)
repaired_returncodes
Description: Return codes that indicate a repairedcommands promise
Currently, the attribute has impact on the following command-related promises:
- All promises of type
commands: files-promises containing atransformer-attribute- The package manager change command in
packages-promises (e.g. the commandfor add, remove, etc.)
If none of the attributeskept_returncodes,repaired_returncodes, orfailed_returncodes are set, the default is to consider a return code zero aspromise repaired, and nonzero as promise failed.
Type:slist
Allowed input range:[-0-9_$(){}\[\].]+
Note that the return codes may overlap, so multiple classes may be set from onereturn code. In Unix systems the possible return codes are usually in the rangefrom 0 to 255.
Example:
bundleagentcmdtest{commands:"/bin/false"classes=>example;reports:wasrepaired::"The command-promise got repaired!";}bodyclassesexample{repaired_returncodes=>{"0","1"};promise_repaired=>{"wasrepaired"};}In the above example, a list of integer return codes indicating that acommand-related promise has been repaired. This can in turn be used to defineclasses using thepromise_repaired attribute, or merely alter the totalcompliance statistics.
History: Was introduced in version 3.1.3, Nova 2.0.2 (2010)
failed_returncodes
Description: Afailed_returncodes slist contains return codes indicatinga failed command-related promise.
Currently, the attribute has impact on the following command-related promises:
- All promises of type
commands: files-promises containing atransformer-attribute- The package manager change command in
packages-promises (e.g. the commandfor add, remove, etc.)
If none of the attributeskept_returncodes,repaired_returncodes, orfailed_returncodes are set, the default is to consider a return code zero aspromise repaired, and nonzero as promise failed.
Type:slist
Allowed input range:[-0-9_$(){}\[\].]+
Note that the return codes may overlap, so multiple classes may be set from onereturn code. In Unix systems the possible return codes are usually in the rangefrom 0 to 255.
Example:
bodycommoncontrol{bundlesequence=>{"cmdtest"};}bundleagentcmdtest{files:"/tmp/test"copy_from=>copy("/etc/passwd");"/tmp/test"classes=>example,transformer=>"/bin/grep -q lkajfo999999$(this.promiser)";reports:hasfailed::"The files-promise failed!";}bodyclassesexample{failed_returncodes=>{"1"};repair_failed=>{"hasfailed"};}bodycopy_fromcopy(file){source=>"$(file)";}The above example contains a list of integer return codes indicating that acommand-related promise has failed. This can in turn be used to define classesusing thepromise_repaired attribute, or merely alter the total compliancestatistics.
History: Was introduced in version 3.1.3, Nova 2.0.2 (2010)
persist_time
Description: The number of minutes the specified classes should remainactive.
By default classes are ephemeral entities that disappear whencf-agentterminates. By setting a persistence time, they can last even when the agent isnot running. When a persistent class is activated it getsscope namespace.
Type:int
Allowed input range:0,99999999999
Example:
bodyclassesexample{persist_time=>"10";}See also:persistance classes attribute,persist_time in classes body
timer_policy
Description: Determines whether a persistent class restarts its counterwhen rediscovered.
In most cases resetting a timer will give a more honest appraisal of whichclasses are currently important, but if we want to activate a response oflimited duration as a rare event then an absolute time limit is useful.
Type: (menu option)
Allowed input range:
absoluteresetDefault value: reset
Example:
bodyclassesexample{timer_policy=>"reset";}comment
Description: Describes the real intention of the promise.
Comments written in code follow the program, they are not merely discarded;they appear in verbose logs and error messages.
Type:string
Allowed input range: (arbitrary string)
Example:
comment=>"This comment follows the data for reference ...",depends_on
Description: A list of promise handles for promises that must have an outcome of KEPT or REPAIRED in order for the promise to be actuated.
This is a list of promise handles for whom this promise is a promisee. In otherwords, we acknowledge that this promise will be affected by the list ofpromises whose handles are specified. It has the effect of partially orderingpromises.
As of version 3.4.0, this feature may be considered short-hand for settingclasses. If one promise depends on a list of others, it will not be verifiedunless the dependent promises have already been verified and kept: in otherwords, as long as the dependent promises are either kept or repaired thedependee can be verified.
Handles in other namespaces may be referred to by namespace:handle.
Type:slist
Allowed input range: (arbitrary string)
Example:
bodycommoncontrol{bundlesequence=>{"one"};}bundleagentone{reports:"two"depends_on=>{"handle_one"};"one"handle=>"handle_one";}This policy can be found in/var/cfengine/share/doc/examples/depends_on.cfand downloaded directly fromgithub.
handle
Description: A unique id-tag string for referring to this as a promiseeelsewhere.
A promise handle allows you to refer to a promise as the promisee ofdepends_on client of another promise. Handles are essential for mappingdependencies and performing impact analyses.
Type:string
Allowed input range: (arbitrary string)
Handles may consist of regular identifier characters. If the handle is likely tocontain non-identifier characters, you can usecanonify() to turn them intosuch characters.
Example:
access:"/source"handle=>"update_rule",admit=>{"127.0.0.1"};Notes: If the handle name is based on a variable, and the variablefails to expand, the handle will be based on the name of the variablerather than its content.
if
Description: Class expression to further restrict the promise context.Previously calledifvarclass.
This is an additional class expression that will be evaluated after theclass:: classes have selected promises. It is provided in order to enable achannel between variables and classes.
The result is thus the logical AND of the ordinary classes and the variableclasses.
Type:string
Allowed input range: (arbitrary string)
Example:
The generic example has the form:
promise-type:"promiser"if=>"$(program)_running|($(program)_notfoundHr12)";A specific example would be:
bundleagentexample{commands:any::"/bin/echo This is linux"if=>"linux";"/bin/echo This is solaris"if=>"solaris";}This function is provided so that one can form expressions that link variablesand classes. For example:
# Check that all components are runningvars:"component"slist=>{"cf-monitord","cf-serverd"};processes:"$(component)"restart_class=>canonify("$(component)_not_runnning");commands:"/var/cfengine/bin/$(component)"if=>canonify("$(component)_not_runnning");Notes:
While strings are automatically canonified during class definition, they are notautomatically canonified when checking. You may need to usecanonify() toconvert strings containing invalid class characters into a valid class.
In most cases,if => something andif => not(something) are opposite,but because offunction skipping, both of thesewill be skipped ifsomething is never resolved:
bundleagentmain{classes:"a"if=>"$(no_such_var)";# Will be skipped"b"if=>not("$(no_such_var)");# Will be skipped}If you need a condition which defaults tonot skipping in the cases above,unless does this; for any expression whereif will skip,unless will notskip.
if andunless both make choices about whether toskip a promise. Bothif andunless canforce a promise to be skipped - if a promise has bothif andunless constraints,skipping takes precedence.
History: In 3.7.0if was introduced as a shorthand forifvarclass (andunless as an opposite).
ifvarclass
Description: Deprecated, useif instead.
History: New nameif was introduced in 3.7.0,ifvarclass deprecated in 3.17.0.
meta
Description: A list of strings to be associated with the promise for knowledge management purposes.The strings are usually called "meta tags" or simply "tags."
Any promise (of any type) can be given a "meta" attribute.Since the right hand side for this attribute is an slist, multiple strings (tags) can be associated with the same promise.
Note that the inventory reporting of CFEngine Enterprise 3.6 and later uses the meta attributesinventory andattribute_name=, so these should be considered reserved for this purpose.
A "meta" attribute can likewise be added into any body (of any type).
Type:slist
Allowed input range: (arbitrary string list)
Example:
files:"/etc/special_file"comment=>"Special file is a requirement. Talk to John.",create=>"true",meta=>{"owner=John","version=2.0","ticket=CFE-1234"};Another example:
some_promise_type:any::"my_promiser"meta=>{"Team Foo","workaround","non-critical"};The meta tags may be referred to programmatically in various ways, or may be solely for human consumption.Meta tags on vars promises and classes promises are particularly suited for programmatic interpretation;meta tags on other promise types (or in bodies) are more likely to be intended only for human consumption.
Relevant CFEngine functions are:classesmatching(),classmatch(),countclassesmatching(),getclassmetatags(),getvariablemetatags(),variablesmatching(),variablesmatching_as_data().
Also seemeta promises: While "meta" attribute can be added to a promise of any type, there can also be promises of promise type "meta" added to any bundle.If mention is made of "tags" on abundle, what is actually meant is metapromises in that bundle.(This is just a terminology point.)
Note: When a variable is re-defined the associated meta tags are also re-defined.
History: Was introduced in 3.3.0, Nova 2.2.0 (2012)
unless
Description: Class expression to further restrict the promise context. Thisis exactly likeif but logically inverted; see its descriptionfor details. For any case whereif would skip the promise, unless shouldevaluate the promise.
Type:string
Allowed input range: (arbitrary string)
Example:
The generic example has the form:
promise-type:"promiser"unless=>"forbidden";A specific example would be:
bundleagentexample{commands:any::"/bin/echo This is NOT linux"unless=>"linux";}Notes:
While strings are automatically canonified during class definition, they are notautomatically canonified when checking. You may need to usecanonify() toconvert strings containing invalid class characters into a valid class.
if andunless both make choices about whether toskip a promise. Bothif andunless canforce a promise to be skipped - if a promise has bothif andunless constraints,skipping takes precedence.
unless will skip a promise, only if the class expression is evaluated tofalse. If the class expression is true, or not evaluated (because ofunexpanded variables, or unresolved function calls) it will not cause thepromise to be skipped. Sinceif defaults to skipping in those cases,unless defaults tonot skipping.
bundleagentmain{classes:"a"if=>"any";# Will be evaluated"b"unless=>"any";# Will be skipped"c"if=>"$(no_such_var)";# Will be skipped"d"unless=>"$(no_such_var)";# Will be evaluated}History: Was introduced in 3.7.0.
with
Description: Reusable promise attribute to avoid repetition.
Very often, it's handy to refer to a single value in many places in a promise,especially in the promiser. Especially when iterating over a list, thewithattribute can save you a lot of work and code.
Another use of thewith attribute is when inreports you want to useformat() or other functions that produce lots of text, but don't want tocreate an intermediate variable.
Another common use ofwith is to avoid canonifying a value. In that case,you'd usewith => canonify("the value") so you don't have to create a"canonification" array.
Type:string
Allowed input range: (arbitrary string)
Example:
bundleagentmain{vars:"todo"slist=>{"a 1","b 2","c 3"};# Here, `with` is the canonified version of $(todo), letting us avoid an# intermediate canonification array."$(with)"string=>"$(todo)",with=>canonify($(todo));"complex"data=>'{"x":200,"y":[1,2,null,true,false]}';reports:"For iterable '$(todo)' we created variable '$(with)' and its value is '$(todo)'"with=>canonify($(todo));"We can print a data container compactly without creating a temporary variable:$(with)"with=>format("%S",complex);"We can print a data container fully without creating a temporary variable:$(with)"with=>storejson(complex);}Output:
R: For iterable 'a 1' we created variable 'a_1' and its value is 'a 1'R: For iterable 'b 2' we created variable 'b_2' and its value is 'b 2'R: For iterable 'c 3' we created variable 'c_3' and its value is 'c 3'R: We can print a data container compactly without creating a temporary variable: {"x":200,"y":[1,2,null,true,false]}R: We can print a data container fully without creating a temporary variable: { "x": 200, "y": [ 1, 2, null, true, false ]}History: Was introduced in 3.11.0
Common body attributes
The following attributes are available to all body types.
inherit_from
Description: Inherits all attributes from another body of the sametype as a function call. For a detailed description, seeBodies.
Type:fncall
Allowed input range: (arbitrary body invocation)
Examples:
bundleagent__main__{files:"$(this.promise_filename).txt"content=>"Hello World$(const.n)2$(const.n)3$(const.n)4$(const.n)half-way6$(const.n)7$(const.n)8$(const.n)9$(const.n)Byeeeeeee",create=>"true";reports:"The first 3 lines of this file are:"printfile=>head_n("$(this.promise_filename).txt","3");"The whole file contains:"printfile=>cat("$(this.promise_filename).txt");}bodyprintfilehead_n(file,lines){# Sets file_to_print the same as catinherit_from=>cat($(file));# Overrides number_of_lines from catnumber_of_lines=>"$(lines)";}bodyprintfilecat(file){file_to_print=>"$(file)";number_of_lines=>"inf";}R: The first 3 lines of this file are:R: Hello WorldR: 2R: 3R: The whole file contains:R: Hello WorldR: 2R: 3R: 4R: half-wayR: 6R: 7R: 8R: 9R: ByeeeeeeeThis policy can be found in/var/cfengine/share/doc/examples/inherit_from.cfand downloaded directly fromgithub.
bundleagent__main__{commands:"/bin/true"handle=>"some meaningful string",classes=>my_set_some_extra_fancy_classes("$(this.promiser)","$(this.handle)","some_class_to_handle_dependencies");"/bin/false"handle=>"some meaningless string",classes=>my_set_some_extra_fancy_classes("$(this.promiser)","$(this.handle)","some_class_to_handle_dependencies");reports:"Defined classes:$(const.n)$(with)"with=>join("$(const.n)",sort(classesmatching("some_.*"),"lex"));}bodyclassesmy_set_some_extra_fancy_classes(x,y,z){inherit_from=>set_some_fancy_classes($(x),$(y));promise_repaired=>{"some_fancy_class_${x}_${y}_repaired",$(z)};}bodyclassesset_some_fancy_classes(x,y){promise_kept=>{"some_fancy_class_${x}_${y}_kept"};promise_repaired=>{"some_fancy_class_${x}_${y}_repaired"};repair_failed=>{"some_fancy_class_${x}_${y}_notkept"};repair_denied=>{"some_fancy_class_${x}_${y}_notkept"};repair_timeout=>{"some_fancy_class_${x}_${y}_notkept"};} error: Finished command related to promiser '/bin/false' -- an error occurred, returned 1R: Defined classes:some_class_to_handle_dependenciessome_fancy_class__bin_false_some_meaningless_string_notkeptsome_fancy_class__bin_true_some_meaningful_string_repairedThis policy can be found in/var/cfengine/share/doc/examples/inherit_from_classes.cfand downloaded directly fromgithub.
History: Was introduced in 3.8.0.
meta
Description: A list of strings to be associated with the body for knowledge management purposes.The strings are usually called "meta tags" or simply "tags."
Any body can be given a "meta" attribute.Since the right hand side for this attribute is an slist, multiple strings (tags) can be associated with the same body.
Type:slist
Allowed input range: (arbitrary string list)
Example:
bodyANYTYPEmybody{meta=>{"deprecated","CFE-1234","CVE-2020-1234"};}Note: When a variable is re-defined the associated meta tags are also re-defined.
History: Was introduced in 3.7.0.
- Overview
- Getting started
- Reference
- Components
- Functions
- accessedbefore
- accumulated
- ago
- and
- basename
- bundlesmatching
- bundlestate
- callstack_callers
- callstack_promisers
- canonify
- canonifyuniquely
- cf_version_after
- cf_version_at
- cf_version_before
- cf_version_between
- cf_version_maximum
- cf_version_minimum
- changedbefore
- classesmatching
- classfiltercsv
- classify
- classmatch
- concat
- countclassesmatching
- countlinesmatching
- data_expand
- data_readstringarray
- data_readstringarrayidx
- data_regextract
- data_sysctlvalues
- datastate
- difference
- dirname
- diskfree
- escape
- eval
- every
- execresult
- execresult_as_data
- expandrange
- file_hash
- fileexists
- filesexist
- filesize
- filestat
- filter
- findfiles
- findfiles_up
- findprocesses
- format
- getclassmetatags
- getenv
- getfields
- getgid
- getindices
- getuid
- getuserinfo
- getusers
- getvalues
- getvariablemetatags
- grep
- groupexists
- hash
- hash_to_int
- hashmatch
- host2ip
- hostinnetgroup
- hostrange
- hostsseen
- hostswithclass
- hubknowledge
- ifelse
- int
- intersection
- ip2host
- iprange
- irange
- isdir
- isexecutable
- isgreaterthan
- isipinsubnet
- islessthan
- islink
- isnewerthan
- isplain
- isreadable
- isvariable
- join
- lastnode
- laterthan
- ldaparray
- ldaplist
- ldapvalue
- length
- lsdir
- makerule
- maparray
- mapdata
- maplist
- max
- mean
- mergedata
- min
- network_connections
- none
- not
- now
- nth
- on
- or
- packagesmatching
- packageupdatesmatching
- parseintarray
- parsejson
- parserealarray
- parsestringarray
- parsestringarrayidx
- parseyaml
- peerleader
- peerleaders
- peers
- processexists
- product
- randomint
- read_module_protocol
- readcsv
- readdata
- readenvfile
- readfile
- readintarray
- readintlist
- readjson
- readrealarray
- readreallist
- readstringarray
- readstringarrayidx
- readstringlist
- readtcp
- readyaml
- regarray
- regcmp
- regex_replace
- regextract
- registryvalue
- regldap
- regline
- reglist
- remoteclassesmatching
- remotescalar
- returnszero
- reverse
- rrange
- selectservers
- shuffle
- some
- sort
- splayclass
- splitstring
- storejson
- strcmp
- strftime
- string
- string_downcase
- string_head
- string_length
- string_mustache
- string_replace
- string_reverse
- string_split
- string_tail
- string_trim
- string_upcase
- sublist
- sum
- sysctlvalue
- translatepath
- type
- unique
- url_get
- usemodule
- userexists
- validdata
- validjson
- variablesmatching
- variablesmatching_as_data
- variance
- version_compare
- Language concepts
- Masterfiles Policy Framework
- promises.cf
- .no-distrib/
- update.cf
- standalone_self_upgrade.cf
- cfe_internal/
- cfe_internal/CFE_cfengine.cf
- cfe_internal/core/
- cfe_internal/core/watchdog
- cfe_internal/core/watchdog/watchdog.cf
- cfe_internal/enterprise/
- cfe_internal/enterprise/federation/
- cfe_internal/enterprise/federation/federation.cf
- cfe_internal/recommendations.cf
- cfe_internal/update/
- cfe_internal/update/cfe_internal_dc_workflow.cf
- cfe_internal/update/cfe_internal_update_from_repository.cf
- cfe_internal/update/lib.cf
- cfe_internal/update/systemd_units.cf
- cfe_internal/update/update_bins.cf
- cfe_internal/update/update_policy.cf
- cfe_internal/update/update_processes.cf
- controls/
- controls/cf_agent.cf
- controls/cf_execd.cf
- controls/cf_hub.cf
- controls/cf_monitord.cf
- controls/cf_runagent.cf
- controls/cf_serverd.cf
- controls/def.cf
- controls/def_inputs.cf
- controls/reports.cf
- controls/update_def.cf
- controls/update_def_inputs.cf
- inventory/
- inventory/any.cf
- inventory/debian.cf
- inventory/freebsd.cf
- inventory/generic.cf
- inventory/linux.cf
- inventory/lsb.cf
- inventory/macos.cf
- inventory/os.cf
- inventory/redhat.cf
- inventory/suse.cf
- inventory/windows.cf
- lib/
- lib/autorun.cf
- lib/bundles.cf
- lib/cfe_internal.cf
- lib/cfe_internal_hub.cf
- lib/cfengine_enterprise_hub_ha.cf
- lib/commands.cf
- lib/common.cf
- lib/databases.cf
- lib/edit_xml.cf
- lib/event.cf
- lib/examples.cf
- lib/feature.cf
- lib/files.cf
- lib/guest_environments.cf
- lib/monitor.cf
- lib/packages.cf
- lib/paths.cf
- lib/processes.cf
- lib/reports.cf
- lib/services.cf
- lib/stdlib.cf
- lib/storage.cf
- lib/testing.cf
- lib/users.cf
- lib/vcs.cf
- modules/
- modules/mustache/
- modules/packages/
- modules/packages/vendored/
- modules/promises/
- modules/promises/cfengine.py
- modules/promises/cfengine.sh
- services/
- services/autorun/
- services/main.cf
- Macros
- Promise types
- Special variables
- All promise and body types
- Release notes
- Web UI
- Settings
- Health
- Hosts
- Alerts and notifications
- Custom actions for alerts
- Enterprise reporting
- Federated reporting
- Measurements app
- Hub administration
- Decommissioning hosts
- Extending Mission Portal
- Extending query builder in Mission Portal
- Adjusting schedules
- Backup and restore
- Configure a custom LDAP port
- Custom LDAPs certificate
- Custom SSL certificate
- Enable plain http
- Lookup license info
- Policy deployment
- Public key distribution
- Re-installing Enterprise hub
- Regenerate self signed SSL certificate
- Reset administrative credentials
- Debugging Mission Portal
- License
- Examples and tutorials
- Example snippets
- General examples
- Administration examples
- Measuring examples
- Software administration examples
- Commands, scripts, and execution examples
- File and directory examples
- File template examples
- Interacting with directory services
- Database examples
- Network examples
- System security examples
- System information examples
- System administration examples
- System file examples
- Windows registry examples
- File permissions
- User management examples
- Common promise patterns
- Aborting execution
- Change detection
- Check filesystem space
- Copy single files
- Create files and directories
- Customize message of the day
- Distribute ssh keys
- Ensure a process is not running
- Ensure a service is enabled and running
- Find the MAC address
- Install packages
- Mount NFS filesystem
- Restart a process
- Set up name resolution with DNS
- Set up sudo
- Set up time management through NTP
- Updating from a central policy server
- Tutorials
- JSON and YAML support in CFEngine
- Installing CFEngine Enterprise agent
- Managing local users
- Managing network time protocol
- Managing processes and services
- Package management
- Writing CFEngine policy
- Distributing files from a central location
- File editing
- Reporting and remediation of security vulnerabilities
- Masterfiles Policy Framework upgrade
- Tags for variables, classes, and bundles
- Custom inventory
- Dashboard alerts
- Integrating alerts with PagerDuty
- Integrating alerts with ticketing systems
- Integrating with Sumo Logic
- Rendering files with Mustache templates
- Reporting
- File comparison
- High availability
- Writing and serving policy
- Example snippets
- Resources
- FAQ
- Why knowledge management?
- Requesting a CFEngine Enterprise License
- Uninstalling / reinstalling
- Agent output email
- Debugging slow queries
- Enterprise Report Filtering
- Enterprise report collection
- Enterprise reporting database
- How can I tell what classes and variables are defined?
- How do I find the public key for a given host
- How do I fix trust after an IP change?
- How do I fix undefined body errors?
- How do I integrate custom policy?
- How do I pass a data type variable?
- Manual execution
- Mustache templating
- Unable to log into Mission Portal
- Users
- What is promise locking?
- Why are remote agents not updating?
- Why are some files inside masterfiles not being updated/distributed?
- Why does CFEngine install into /var/cfengine instead of following the FHS?
- Bootstrapping
- Tuning PostgreSQL
- What did CFEngine do?
- External resources
- Additional topics
- Best practices
- FAQ
- API
- Enterprise API examples
- Enterprise API reference
- Actions API
- Build API
- CMDB API
- Changes REST API
- Federated reporting configuration API
- File changes API
- Health diagnostic API
- Host REST API
- Import & export API
- Import & export compliance report API
- Inventory API
- LDAP authentication API
- Personal groups API
- Query REST API
- SQL schema
- SSH keys API
- Shared groups API
- Status and settings REST API
- Two-factor authentication API
- Users and access-control REST API
- VCS settings API
- Web RBAC API