Examples and tutorials
Links to examples
- Example snippets: This section is divided into topical areas and includes many examples of policy and promises. Each of the snippets can be easily copied or downloaded to a policy server and used as is.
Note: CFEngine also includes a small set of examples by default, which can be found in/var/cfengine/share/doc/examples.
See also:
Tutorial for running examples
In this tutorial, you will perform the following:
- Create a simple "Hello World!" example policy file
- Make the example a standalone policy
- Make the example an executable script
- Add the example to the main policy file (
promises.cf)
Note if your CFEngine administrator has enabled continuous deployment of the policy from a Version control System, your changes may be overwritten!
"Hello world" policy example
Policies containbundles, which are collections of promises. Apromise is a declaration ofintent. Bundles allow related promises to be grouped together, as illustrated in the steps that follow.
Following these steps, you will login to your policy server via the SSH protocol, use the vi command line editor to create a policy file named hello_world.cf, and create a bundle that calls a promise to display some text.
- Log into a running server machine using ssh (PuTTY may be used if using Windows).
- Type
sudo sufor super user (enter your password if prompted). - To get to themasterfiles directory, type
cd /var/cfengine/masterfiles. - Create the file with the command:
vi hello_world.cf - In the vi editor, enter
ifor "Insert" and enter the following content (ie. copy and paste from a text editor):cf3[file=hello_world.cf]bundle agent hello_world{ reports: any:: "Hello World!";} - Exit the "Insert" mode by pressing the "esc" button. This will return to the command prompt.
- Save the changes to the file by typing
:wthen "Enter". - Exit vi by typing
:qthen "Enter".
In the policy file above, we have defined anagent bundle namedhello_world. Agentbundles are only evaluated bycf-agent, theagent component of CFEngine.
This bundlepromises toreport on anyclass of hosts.
Activate a bundle manually
Activate the bundle manually by executing the following command at prompt:
/var/cfengine/bin/cf-agent --no-lock --file ./hello_world.cf --bundlesequence hello_worldThis command instructs CFEngine to ignorelocks, loadthehello_world.cf policy, and activate thehello_world bundle. See the output below:
/var/cfengine/bin/cf-agent --no-lock --file ./hello_world.cf --bundlesequence hello_world2013-08-20T14:03:43-0500 notice: R: Hello World!As you get familiar with CFEngine, you'll probably start shortening this command to this equivalent:
/var/cfengine/bin/cf-agent -Kf ./hello_world.cf -b hello_worldNote the full path to the binary in the above command. CFEngine stores its binaries in/var/cfengine/binon Linux and Unix systems. Your path might vary depending on your platform and the packages your are using.CFEngine uses /var because it is one of the Unix file systems that resides locally.Thus, CFEngine can function even if everything else fails(your other file systems, your network, and even system binaries) and possibly repair problems.
Make the example stand alone
Instead of specifying the bundle sequence on the command line (as it was above), abody commoncontrol section can be added tothe policy file. Thebody common control refers to those promises that are hard-coded intoall CFEngine components and therefore affect the behavior of all components. Note that only onebody common control is allowed per agent activation.
Go back into vi by typing "vi" at the prompt. Then typei to insertbody common control tohello_world.cf. Place it abovebundle agent hello_world, asshown in the following example:
bodycommoncontrol{bundlesequence=>{"hello_world"};}bundleagenthello_world{reports:any::"Hello World!";}Now press "esc" to exit the "Insert" mode, then type:w to save the file changes and "Enter".Exit vi by typing:q then "Enter." This will return to the prompt.
Execute the following command:
/var/cfengine/bin/cf-agent --no-lock --file ./hello_world.cfnotice: R: Hello World!Note: It may be necessary to add a reference to the standard library within the body common control section, and remove thebundlesequence line.Example:
bodycommoncontrol{inputs=>{"libraries/cfengine_stdlib.cf",};}Make the example an executable script
Add the#! marker ("shebang") tohello_world.cf in order to invoke CFEngine policy as an executable script:Again type "vi" then "Enter" theni to insert the following:
#!/var/cfengine/bin/cf-agent --no-lockAdd it beforebody common control, as shown below:
#!/var/cfengine/bin/cf-agent --no-lockbodycommoncontrol{bundlesequence=>{"hello_world"};}bundleagenthello_world{reports:any::"Hello World!";}Now exit "Insert" mode by pressing "esc". Save file changes by typing:w then "Enter"then exit vi by typing:q then "Enter". This will return to the prompt.
Make the policy file executable:
chmod +x ./hello_world.cfAnd it can now be run directly:
./hello_world.cf2013-08-20T14:39:34-0500 notice: R: Hello World!Integrating the example into your main policy
Make the example policy part of your main policy bydoing the following on your policy server:
Ensure the example is located in
/var/cfengine/masterfiles.If the example contains a
body common controlsection, delete it. Thatsection will look something like this:codebodycommoncontrol{bundlesequence=>{"hello_world"};}
You cannot have duplicate control bodies (i.e. twoagent control bodies, one in the main file and onein the example) as CFEngine won't know which itshould use and they may conflict.
To resolve this, copy the contents of the control body section from theexample into the identically named control body section in the main policyfile/var/cfengine/masterfiles/promises.cfand then remove the control bodyfrom the example.
Insert the example's bundle name in the
bundlesequencesectionof the main policy file/var/cfengine/masterfiles/promises.cf:codebundlesequence=>{..."hello_world",...};Insert the policy file name in the
inputssection of the main policy file/var/cfengine/masterfiles/promises.cf:codeinputs=>{..."hello_world.cf",...};You must also remove any inputs section from the example thatincludes the external library:
codeinputs=>{"libraries/cfengine_stdlib.cf"};This is necessary, since
cfengine_stdlib.cfis already includedin the inputs section of the master policy.The example policy will now be executed every five minutes along with the restof your main policy.
Notes: You may have to fill the example with data before it will work.For example, the LDAP query inactive_directory.cf needs a domain name.In the variable declaration, replace "cftesting" with your domain name:
vars:# NOTE: Edit this to your domain, e.g. "corp""domain_name"string=>"cftesting";- 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