Functions
Functions take zero or more values as arguments and return a value.Argument values need to be of the type and range as documented for eachfunction. Some functions are documented with a..., in which case theytake an arbitrary amount of arguments.
They can return scalar (string|int|real|bool), list (slist, ilist, rlist) and data values:
printf "one\ntwo\nthree\n" > /tmp/list.txtprintf "1\n2\n3\n" >> /tmp/list.txtprintf "1.0\n2.0\n3.0" >> /tmp/list.txtbundleagentexample_function_return_types{classes:"this_file_exists"expression=>fileexists($(this.promise_filename));vars:"my_string"string=>concat("Promises you cannot keep"," are no better than lies");"my_list_of_strings"slist=>readstringlist("/tmp/list.txt",# File to read"",# Don't ignore any lines"\n",# Split on newlinesinf,# Extract as many entries as possibleinf);# Read in as much data as possible"my_list_of_integers"ilist=>readintlist("/tmp/list.txt",# File to read"^(\D+)|(\d+[^\n]+)",# Ignore any lines that are not integers"\n",# Split on newlinesinf,# Maximum number of entriesinf);# Maximum number of bytes to read"my_list_of_reals"rlist=>readreallist("/tmp/list.txt",# File to read"^(\D+)",# Ignore any lines that are not digits"\n",# Split on newlinesinf,# Maximum number of entriesinf);# Maximum number of bytes to read"my_integer"int=>string_length($(my_string));"my_real"real=>sum(my_list_of_integers);"my_data"data=>mergedata('{"Hello":"world!"}');reports:"my_string: '$(my_string)'";"my_list_of_strings includes '$(my_list_of_strings)'";"my_list_of_integers includes '$(my_list_of_integers)'";"my_list_of_reals includes '$(my_list_of_reals)'";"my_integer: '$(my_integer)'";"my_real: '$(my_real)'";"my_data: '$(with)'"with=>string_mustache("",my_data);this_file_exists::"This file exists.";}bundleagent__main__{methods:"example_function_return_types";}R: my_string: 'Promises you cannot keep are no better than lies'R: my_list_of_strings includes 'one'R: my_list_of_strings includes 'two'R: my_list_of_strings includes 'three'R: my_list_of_strings includes '1'R: my_list_of_strings includes '2'R: my_list_of_strings includes '3'R: my_list_of_strings includes '1.0'R: my_list_of_strings includes '2.0'R: my_list_of_strings includes '3.0'R: my_list_of_integers includes '1'R: my_list_of_integers includes '2'R: my_list_of_integers includes '3'R: my_list_of_reals includes '1'R: my_list_of_reals includes '2'R: my_list_of_reals includes '3'R: my_list_of_reals includes '1.0'R: my_list_of_reals includes '2.0'R: my_list_of_reals includes '3.0'R: my_integer: '48'R: my_real: '6.000000'R: my_data: '{ "Hello": "world!"}'R: This file exists.This policy can be found in/var/cfengine/share/doc/examples/function-return-types.cfand downloaded directly fromgithub.
Boolean return type
Functions which returnboolean, technically return a stringany or!any.This is for compatibility with other functions and promise attributes whichexpect class expressions.
Normally, you don't need to worry about this, you use the function call todefine classes, and use classes instead of boolean values:
bundleagentmain{vars:"five"int=>"5";classes:"is_var"if=>isvariable("five");reports:is_var::"Success!";}There is no boolean data type forvars promises.If you want to store or print the class expression, you can useconcat():
bundleagentmain{vars:"five"int=>"5";"expression"string=>concat(isvariable("five"));classes:"is_var"if=>"$(expression)";# Will be expanded and evaluatedreports:is_var::"Success: expression expanded to '$(expression)' and evaluated to true!";}Note: the truth of a class expression or the result of a function call maychange during evaluation, but typically, a class, once defined, will stay defined.
See also:persistence in classes and decisions
Promise attributes and function calls
Promise attributes which use a class expression (string) as input, likeifandunless, can take a function call which returns string or boolean as well.
- A boolean function will be resolved to
any, which is always true, or!anywhich is always false. - A string function will be resolved, and the returned string will beevaluated as a class expression.
bundleagentmain{vars:"five"int=>"5";"is_var_class_expression"string=>concat(isvariable("$(five)"));classes:"five_less_than_seven"expression=>islessthan("$(five)",7);"five_is_variable"if=>"$(is_var_class_expression)";reports:any::"five:$(five)";"is_var_class_expression:$(is_var_class_expression)";five_less_than_seven::"$(five) is smaller than 7";}Function caching
During convergence, CFEngine's evaluation model will evaluatefunctions multiple times, which can be a performance concern.
Somesystem functions are particularly expensive:
execresult()andreturnszero()for shell executionregldap(),ldapvalue(), andldaplist()for LDAP queriesfindprocesses(), andprocessexists()for querying processes.host2ip()andip2host()for DNS queriesreadtcp()for TCP interactionshubknowledge(), andremotescalar()for hub queries
When enabledcached functionsarenot executed on every pass of convergence. Instead, the function willonly be executed once during theagent evaluation stepand its result will be cached until the end of that agent execution.
Note: Cached functions are executed multiple times duringpolicy validation and pre-evaluation.Function caching isper-process, so results will not be cached betweenseparate components e.g.cf-agent,cf-serverd andcf-promises.Additionally functions are cached by hashing the function arguments. If you havethe exact same function call in two different promises (it does not matter ifthey are in the same bundle or not) only the first executed function will becached. That cached result will be re-used for other identical functionoccurrences.
Function caching can be globally disabled by settingcache_system_functions inbody common control tofalse or locally for a specific promise by usingifelapsed => "0" in theaction bodyof the promise.
Function skipping
If a variable passed to a function is unable to be resolved the function willbe skipped. The function will be evaluated during a later pass when allvariables passed as arguments are able to be resolved. The function will neverbe evaluated if any argument contains a variable that never resolves.
Collecting Functions
Some function arguments are marked ascollecting which means theycan "collect" an argument from various sources. The data is normalizedinto the JSON format internally, so all of the following data typeshave consistent behavior.
If a key inside a data container is specified (
mycontainer[key]),the value under that key is collected. The key can be a string forJSON objects or a number for JSON arrays.If a single data container, CFEngine array, or slist is specified(
mycontainerormyarrayormyslist), the contents of it arecollected.If a single data container, CFEngine array, or slist is specifiedwith
@()around it (@(mycontainer)or@(myarray)or@(myslist)), the contents of it are collected.If a function call that returns a data container or slist isspecified, that function call is evaluated and the results areinserted, so you can say for instance
sort(data_expand(...), "lex")to expand a data container then sort it.If a list (slist, ilist, or rlist) is named, its entries are collected.
If any CFEngine "classic" array (
array[key]) is named, it's firstconverted to a JSON key-value map, then collected.If a literal JSON string like
[ 1,2,3 ]or{ "x": 500 }isprovided, it will be parsed and used.If any of the above-mentioned ways to reference variables are usedinside a literal JSON string they will be expanded (or thefunction call will fail). This is similar to the behavior ofJavascript, for instance. For example,
mergedata('[ thing, { "mykey": otherthing[123] } ]')will wrap thethingin a JSON array; then the contents ofotherthing[123]will be wrapped in a JSON map which will also go inthe array.
Delayed Evaluation Functions
Since CFEngine 3.10, some functions are marked asdelayed evaluation whichmeans they can evaluate a function call across every element of a collection.This makes intuitive sense for the collection traversing functionsmaparray(),maplist(), andmapdata().
The practical use is for instancemaplist(format("%03d", $(this)), mylist)which will evaluate thatformat() call once for every element ofmylist.
Before 3.10, the same call would have resulted in running theformat()functionbefore the list is traversed, which is almost never what the userwants.
List of all functions
There are a large number of functions built into CFEngine. The followingtables might make it easier for you to find the function you need.
Functions by Category
Functions by Return Type
- 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