Variables
Just likeclasses are defined aspromises, variables (or "variable definitions") are also promises. Variablescan be defined in any promisebundle. This bundle name can be usedas a context when using variables outside of the bundle they are defined in.
CFEngine variables have three high-level types: scalars, lists, anddata containers.
- A scalar is a single value,
- a list is a collection of scalars.
- a data container is a lot like a JSON document, it can be a key-value map or an array or anything else allowed by the JSON standard with unlimited nesting.
Scalar variables
Each scalar may have one of three types: string, int or real. String scalarsare sequences of characters, integers are whole numbers, and reals are floatpointing numbers.
vars:"my_scalar"string=>"String contents...";"my_int"int=>"1234";"my_real"real=>"567.89";Integer constants may use suffixes to represent large numbers. The followingsuffixes can be used to create integer values for common powers of 1000.
- 'k' = value times 1000
- 'm' = value times 10002
- 'g' = value times 10003
Since computing systems such as storage and memory are based on binary values,CFEngine also provide the following uppercase suffixes to create integervalues for common powers of 1024.
- 'K' = value times 1024.
- 'M' = value times 10242
- 'G' = value times 10243
However, the values must have an integer numeric part (e.g. 1.5M is notallowed).
In some contexts,% can be used a special suffix to denote percentages.
Lastly, there is a reserved value which can be used to specify a parameter ashaving no limit at all.
'inf' = a constant representing an unlimited value.
infis a special value that in the code corresponds to the magic number of999999999(nine nines). Thus any function that accepts a number, can accept inf without a problem. Keep in mind though that you can get a higher number if you set the upper limit manually, but that's almost never a problem.For a few functions
infis being treated specially and truly means "there is no limit" instead of "nine nines limit". This is the case for themaxbytesparameter and applies to most read* functions.
CFEngine typing is mostly dynamic, and CFEngine will try to coerce stringvalues into int and real types, and if it cannot it will report an error.However, arguments to built-infunctions check thedefined argument type for consistency.
Scalar referencing and expansion
Scalar variables are referenced by$(my_scalar) (or${my_scalar}) andexpand to the single value they hold at that time. If you refer to a variableby$(unqualified), then it is assumed to belong to the current bundle. Toaccess any other (scalar) variable, you must qualify the name, using the nameof the bundle in which it is defined:
$(bundle_name.qualified)Quoting
When quoting strings CFEngine allows the use of',", and or`. Thisallows flexibilty when defining strings that contain quotes. Single or doublequotes can be escaped with\ however, please note that backticks (`) cannotbe escaped.
bundleagentmain{vars:'single'string=>'singlequotes';`backtick`string=>`backtickquotes`;"double"string=>"double";'single_escape'string=>'Youcan\'escape\'singlequotes';"double_escape"string=>"You can\"escape\" double quotes";`backtick_escape`string=>`Note:Youcan'tescapebacktickquotes`;reports:"$(single)";`$(backtick)`;`$(double)`;'$(single_escape)';"$(double_escape)";`$(backtick_escape)`;}R: single quotesR: backtick quotesR: doubleR: You can 'escape' single quotesR: You can "escape" double quotesR: Note: You can't escape backtick quotesThis policy can be found in/var/cfengine/share/doc/examples/quoting.cfand downloaded directly fromgithub.
Scalar size limitations
At the moment, up to 4095 bytes can fit into a scalar variable. Thislimitation may be removed in the future.
If you try to expand strings in a variable or string context that addup to more that 4095 bytes, you will notice this limitation as well.The functionseval() to do math,string_head() andstring_tail()to extract a certain number of characters from either end of a string,andstring_length() to find a string's length may be helpful.
Seereadfile() for more detail on reading values from a file.
Seedata_readstringarray() anddata_readstringarrayidx() for a wayto read large files' contents into a data container without goingthrough scalar variables or arrays.
Lists
List variables can be of typeslist,ilist orrlist to hold lists ofstrings, integers or reals, respectively.
Every element of a list is subject to the same size limitations as aregular scalar.
They are declared as follows:
vars:"my_slist"slist=>{"list","of","strings"};"my_ilist"ilist=>{"1234","5678"};"my_rlist"rlist=>{"567.89"};List substitution and expansion
An entire list is referenced with the symbol '@' and can be passed in theirentirety in any context where a list is expected as@(list). For example,the following variable definition references a list named "shortlist":
vars:"shortlist"slist=>{"you","me"};"longlist"slist=>{@(shortlist),"plus","plus"};The declaration order does not matter - CFEngine will understand thedependency, and execute the promise to assign the variable@(shortlist)before the promise to assign the variable@(longlist).
Using the @ symbol in a string scalar will not result in list substitution.For example, the string value "My list is @(mylist)" will not expand thisreference.
Using the scalar reference to a local list variable, will cause CFEngine toiterate over the values in the list. E.g. suppose we have local list variable@(list), then the scalar$(list) implies an iteration over every value ofthe list.
In some function calls,listname instead of@(listname) isexpected. See the specific function's documentation to be sure.
Data container variables
Thedata containers can contain several levels of data structures,e.g. list of lists of key-value arrays. They are used to storestructured data, such as data read from JSON or YAML files. Thevariable type isdata.
Data containers are obtained from functions that returndata types,such asreadjson() orparsejson(),readyaml() orparseyaml(),or from merging existing containers.
They canNOT bemodified, once created, but they can be re-defined.
Data containers do not have the size limitations of regular scalarvariables.
bundleagentexample_reference_values_inside_data{vars:"data"data=>'{"Key1":"Value1","Key2":"Value2","Key3":["Value3","Value4"]}';reports:"Key1 contains '$(data[Key1])'";"Key2 contains '$(data[Key2])'";"Key3 iterates and contains '$(data[Key3])'";}bundleagent__main__{methods:"example_reference_values_inside_data";}R: Key1 contains 'Value1'R: Key2 contains 'Value2'R: Key3 iterates and contains 'Value3'R: Key3 iterates and contains 'Value4'This policy can be found in/var/cfengine/share/doc/examples/reference_values_inside_data.cfand downloaded directly fromgithub.
Associative arrays
Associative arrays in CFEngine are fundamentally a collection of individualvariables that together represent a data structure with key value pairs. Theycan be built up, dynamically one key at a time and individual keys can bere-defined.
While in many cases associative arrays can be used interchangeably withdatavariables (e.g. as input to a function) if there is not explicit need to use anassociative array for it's ability to be built up dynamically or for managingthe size of individual variables use of adata variable is recommended.
Every value in an associative array is subject to the same sizelimitations as a regular scalar.
Associative array variables are written with[ and] brackets that enclosean arbitrary key.
Arrays are associative and may be of type scalar or list. Enumerated arraysare simply treated as a special case of associative arrays, since there are nonumerical loops in CFEngine. Special functions exist to extract lists of keysfrom array variables for iteration purposes.
Example:
bundlecommong{vars:"array[key1]"string=>"one";"array[key2]"string=>"two";}bundleagent__main__{vars:"thing[1][color]"string=>"red";"thing[1][name]"string=>"one";"thing[2][color]"string=>"blue";"thing[2][name]"string=>"two";"_thing_idx"slist=>sort(getindices(thing),lex);reports:"Keys in default:g.array =$(with)"with=>join(", ",sort(getindices("default:g.array"),lex));"Keys of default:main.thing[1] =$(with)"with=>join(", ",sort(getindices("default:main.thing[1]"),lex));"Thing$(thing[$(_thing_idx)][name]) is$(thing[$(_thing_idx)][color])";}R: Keys in default:g.array = key1, key2R: Keys of default:main.thing[1] = color, nameR: Thing one is redR: Thing two is blueThis policy can be found in/var/cfengine/share/doc/examples/arrays.cfand downloaded directly fromgithub.
See also:getindices(),getvalues()
- 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