classes
Classes promises may be made in any bundle. Classes defined byclasses type promises incommon bundles arenamespace (aka global) scoped bydefault.
bundlecommong{classes:"one"expression=>"any";# always defined"two";# always defined"client_network"expression=>iprange("128.39.89.0/24");}Notes:
- The promiser is automatically canonified when classes are defined.
- Classes are not automatically canonified when checked.
bundleagentmain{classes:"my-illegal-class";reports:# We search to see what class was defined:"$(with)"with=>join(" ",classesmatching("my.illegal.class"));# We see that the illegal class is explicitly not defined."my-illegal-class is NOT defined (as expected, its invalid)"unless=>"my-illegal-class";# We see the canonified form of the illegal class is defined."my_illegal_class is defined"if=>canonify("my-illegal-class");# Note, if takes expressisons, you couldn't do that if it were# automatically canonified. Here I canonify the string using with, and use# it as part of the expression which contains an invalid classcharacter, but# its desireable for constructing expressions."Slice and dice using `with`"with=>canonify("my-illegal-class"),if=>"linux|$(with)";}First we promise to definemy-illegal-class. When the promise is actuatedit is automatically canonified and defined. This automatic canonification islogged in verbose logs (verbose: Class identifier 'my-illegal-class' contains illegal characters - canonifying).Next several reports prove which form of the class was defined. The lastreport shows howif takes a class expression, and if you are checking a classthat contains invalid characters you must canonify it.
R: my_illegal_classR: my-illegal-class is NOT defined (as expected, its invalid)R: my_illegal_class is definedR: Slice and dice using `with`This policy can be found in/var/cfengine/share/doc/examples/class-automatic-canonificiation.cfand downloaded directly fromgithub.
- The term
classandcontextare sometimes used interchangeably. The following attributes to make a complete promise.
- and
- expression
- dist
- or
- not
- xor
If you omit all of them, the class is always defined (as if you saidexpression=> "any").
For example, the following promise defines the classweb when a file exists:
bundleagentexample{classes:"web"if=>fileexists("/etc/httpd/httpd.conf");}History: The context attributesexpression,and,or,not,xor,dist were made optional in CFEngine 3.9.0. Before that, one of them wasrequired. So the following examples were the valid equivalents of the exampleabove before 3.9.0:
bundle agent example{ classes: "web" expression => fileexists("/etc/httpd/httpd.conf"); "webserver" expression => "any", if => fileexists("/etc/httpd/httpd.conf");}Attributes
and
Description: Combine class sources with AND
The class on the left-hand side is set if all of the class expressions listedon the right-hand side are true.
Type:clist
Allowed input range:[a-zA-Z0-9_!@@$|.()\[\]{}:]+
Example:
classes:"compound_class"and=>{classmatch("host[0-9].*"),"Monday","Hr02"};Notes:
If an expression contains a mixture of different object types that need to beANDed together, this list form is more convenient than providing anexpression.
dist
Description: Generate a probabilistic class distribution
Always set one generic class and one additional class, randomly weighted on aprobability distribution.
Type:rlist
Allowed input range:-9.99999E100,9.99999E100
Example:
classes:"my_dist"dist=>{"10","20","40","50"};Notes:
In the example above the values sum up to10+20+40+50 = 120. When generatingthe distribution, CFEngine picks a number between1-120, and set the classmy_dist as well as one of the following classes:
my_dist_10(10/120ofthetime)my_dist_20(20/120ofthetime)my_dist_40(40/120ofthetime)my_dist_50(50/120ofthetime)expression
Description: Evaluate string expression of classes in normal form
Set the class on the left-hand side if the expression on the right-hand sideevaluates to true. With classes, the notion of "true" is not a boolean state,because classes can never be false. They are not booleans. They can be definedor undefined, but it's important to understand that a class may be definedduring the execution of the agent, so the result of an expression maychange during execution.
Expressions can be:
class names, with or without a namespace
the literals
true(always defined) andfalse(never defined) that allow JSON booleans to be used inside expressionsthe logicaland operation, expressed as
a&bora.b, which is true if bothaandbare truethe logicalor operation, expressed as
a|b, which is true if eitheraorbare truethe logicalnot operation, expressed as
!a, which is true ifais nottrue. Note again here thatacouldbecome true during the execution. Soif you have"myclass" expression => "!x"andxstarts undefined but isdefined later, you could have bothxandmyclassdefined!parenthesis
(whatever)which operate as expected to prioritize expression evaluationthe return value of a function that returns a class, such as
fileexists()and()userexists()etc.
Type:class
Allowed input range:[a-zA-Z0-9_!@@$|.()\[\]{}:]+
Example:
classes:"class_name"expression=>"solaris|(linux.specialclass)";"has_toor"expression=>userexists("toor");# it's unlikely a machine will become Linux during execution# so this is fairly safe"not_linux"expression=>"!linux";"a_or_b"expression=>"a|b";# yes, it's OK to define a class twice, and this is the same outcome# with different syntax"a_and_b"expression=>"a&b";"a_and_b"expression=>"a.b";# yes, it's OK to define a class twice, and this is the same outcome# with different syntax"linux_and_has_toor"expression=>and(userexists("toor"),"linux");"linux_and_has_toor"and=>{userexists("toor"),"linux"};or
Description: Combine class sources with inclusive OR
The class on the left-hand side will be set if any one (or more) ofthe class expressions on the right-hand side are true.
Type:clist
Allowed input range:[a-zA-Z0-9_!@@$|.()\[\]{}:]+
Example:
classes:"compound_test"or=>{classmatch("linux_x86_64_2_6_22.*"),"suse_10_3"};Notes:
This is useful construction for writing expressions that contain functions.
persistence
Description: Make the class persistent to avoid re-evaluation
The value specifies time in minutes.
Type:int
Allowed input range:0,99999999999
Example:
bundlecommonsetclasses{classes:"cached_classes"or=>{"any"},persistence=>"1";"cached_class"expression=>"any",persistence=>"1";}Notes:
This feature can be used to avoid recomputing expensive classes calculationson each invocation. This is useful if a class discovered is essentiallyconstant or only slowly varying, such as a hostname or alias from anon-standard naming facility.Persistent classes are always global and can not be set to localbyscope directive.
For example, to create a conditional inclusion of costly class evaluations,put them into a separate bundle in a fileclasses.cf.
# promises.cfbodycommoncontrol{persistent_classes::bundlesequence=>{"test"};!persistent_classes::bundlesequence=>{"setclasses","test"};!persistent_classes::inputs=>{"classes.cf"};}bundleagenttest{reports:!my_persistent_class::"no persistent class";my_persistent_class::"persistent class defined";}Then createclasses.cf
# classes.cfbundlecommonsetclasses{classes:"persistent_classes"# timer flagexpression=>"any",persistence=>"480";"my_persistent_class"or=>{...longlistorheavyfunction...},persistence=>"480";}History: Was introduced in CFEngine 3.3.0
See also:persistance classes attribute,persist_time in classes body
not
Description: Evaluate the negation of string expression in normal form
The class on the left-hand side will be set if the class expression on theright-hand side evaluates to false.
Type:class
Allowed input range:[a-zA-Z0-9_!@@$|.()\[\]{}:]+
Example:
classes:"others"not=>"linux|solaris";"no_toor"not=>userexists("toor");Notes:
Knowing that something is not the case is not the same as not knowing whethersomething is the case. That a class is not set could mean either. See the noteonNegative knowledge.
scope
Description: Scope of the class set by this promise.
Type: (menu option)
Allowed input range:
namespacebundleDefault value:bundle in agent bundles,namespace in common bundles
Example:
classes:"namespace_context"scope=>"namespace";"bundle_or_namespace_context";# without an explicit scope, depends on bundle type"bundle_context"scope=>"bundle";See also:scope inbody classes
select_class
Description: Select one of the named list of classes to define based onhost's fully qualified domain name, the primary IP address and the UID thatcf-agent is running under.
This feature is useful for decentralized dynamic grouping. The class is chosendeterministically (not randomly) but it is not possible to say which host willend up in which class in advance. Only that given stable input a host willalways end up in the same class every time while running a given version ofCFEngine.
Type:clist
Allowed input range:[a-zA-Z0-9_!@@$|.()\[\]{}:]+
Example:
bundlecommong{classes:"selection"select_class=>{"one","two"};reports:one::"One was selected";two::"Two was selected";selection::"A selection was made";}Notes:
This feature is similar to thesplayclass function. However,instead of selecting a class for a moment in time, it always chooses one classin the list; the same class each time for a given host. This allows hosts tobe distributed across a controlled list of classes (e.g for load balancingpurposes).
If a list is used as the input to select_class the promise will only actuate ifthe list is expandable. If the list has not yet been evaluated, theselect_class will be skipped and wait for a subsequent evaluation pass.
Given stable input, the output of this function will not change between executions of the same version of CFEngine. Its output should not change between versions of CFEngine within the same minor release (3.12.0 -> 3.12.1). Its output may change between minor versions (3.12.0 -> 3.13.0).
xor
Description: Combine class sources with XOR
The class on the left-hand side is set if an odd number of class expressionson the right-hand side matches. This is most commonly used with two classexpressions.
Type:clist
Allowed input range:[a-zA-Z0-9_!@@$|.()\[\]{}:]+
Example:
classes:"order_lunch"xor=>{"Friday","Hr11"};# we get pizza every Friday- 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