Network examples
Table of contents
- Find MAC address
- Client-server example
- Read from a TCP socket
- Set up a PXE boot server
- Resolver management
- Mount NFS filesystem
- Unmount NFS filesystem
- Find the MAC address
- Mount NFS filesystem
Find MAC address
Finding the ethernet address can be hard, but on Linux it is straightforward.
code
bundleagenttest{vars:linux::"interface"string=>execresult("/sbin/ifconfig eth0","noshell");solaris::"interface"string=>execresult("/usr/sbin/ifconfig bge0","noshell");freebsd::"interface"string=>execresult("/sbin/ifconfig le0","noshell");darwin::"interface"string=>execresult("/sbin/ifconfig en0","noshell");classes:linux::"ok"expression=>regextract(".*HWaddr ([^\s]+).*(\n.*)*","$(interface)","mac");solaris::"ok"expression=>regextract(".*ether ([^\s]+).*(\n.*)*","$(interface)","mac");freebsd::"ok"expression=>regextract(".*ether ([^\s]+).*(\n.*)*","$(interface)","mac");darwin::"ok"expression=>regextract("(?s).*ether ([^\s]+).*(\n.*)*","$(interface)","mac");reports:ok::"MAC address is$(mac[1])";}Client-server example
code
bodycommoncontrol{bundlesequence=>{"testbundle"};version=>"1.2.3";#fips_mode => "true";}bundleagenttestbundle{files:"/home/mark/tmp/testcopy"comment=>"test copy promise",copy_from=>mycopy("/home/mark/LapTop/words","127.0.0.1"),perms=>system,depth_search=>recurse("inf"),classes=>satisfied("copy_ok");"/home/mark/tmp/testcopy/single_file"comment=>"test copy promise",copy_from=>mycopy("/home/mark/LapTop/Cfengine3/trunk/README","127.0.0.1"),perms=>system;reports:copy_ok::"Files were copied..";}bodypermssystem{mode=>"0644";}bodydepth_searchrecurse(d){depth=>"$(d)";}bodycopy_frommycopy(from,server){source=>"$(from)";servers=>{"$(server)"};compare=>"digest";encrypt=>"true";verify=>"true";copy_backup=>"true";#/false/timestamppurge=>"false";type_check=>"true";force_ipv4=>"true";trustkey=>"true";}bodyclassessatisfied(x){promise_repaired=>{"$(x)"};persist_time=>"0";}bodyservercontrol{allowconnects=>{"127.0.0.1","::1"};allowallconnects=>{"127.0.0.1","::1"};trustkeysfrom=>{"127.0.0.1","::1"};# allowusers}bundleservermy_access_rules(){access:"/home/mark/LapTop"admit=>{"127.0.0.1"};}Read from a TCP socket
code
bodycommoncontrol{bundlesequence=>{"example"};}bundleagentexample{vars:"my80"string=>readtcp("research.iu.hio.no","80","GET /index.php HTTP/1.1$(const.r)$(const.n)Host: research.iu.hio.no$(const.r)$(const.n)$(const.r)$(const.n)",20);classes:"server_ok"expression=>regcmp(".*200 OK.*\n.*","$(my80)");reports:server_ok::"Server is alive";!server_ok::"Server is not responding - got$(my80)";}Set up a PXE boot server
Use CFEngine to set up a PXE boot server.
code
bodycommoncontrol{bundlesequence=>{"pxe"};inputs=>{"$(sys.libdir)/stdlib.cf"};}bundleagentpxe{vars:"software"slist=>{"atftp","dhcp-server","syslinux","apache2"};"dirs"slist=>{"/tftpboot","/tftpboot/CFEngine/rpm","/tftpboot/CFEngine/inputs","/tftpboot/pxelinux.cfg","/tftpboot/kickstart","/srv/www/repos"};"tmp_location"string=>"/tftpboot/CFEngine/inputs";# Distros that we can install"rh_distros"slist=>{"4.7","5.2"};"centos_distros"slist=>{"5.2"};# File contents of atftp configuration"atftpd_conf"string=>"ATFTPD_OPTIONS=\"--daemon\"ATFTPD_USE_INETD=\"no\"ATFTPD_DIRECTORY=\"/tftpboot\"ATFTPD_BIND_ADDRESSES=\"\" ";# File contents of DHCP configuration"dhcpd"string=>"DHCPD_INTERFACE=\"eth0\"DHCPD_RUN_CHROOTED=\"yes\"DHCPD_CONF_INCLUDE_FILES=\"\"DHCPD_RUN_AS=\"dhcpd\"DHCPD_OTHER_ARGS=\"\"DHCPD_BINARY=\"\" ";"dhcpd_conf"string=>"allow booting;allow bootp;ddns-update-style none; ddns-updates off; subnet 192.168.0.0 netmask 255.255.255.0 { range 192.168.0.20 192.168.0.254; default-lease-time 3600; max-lease-time 4800; option routers 192.168.0.1; option domain-name\"test.CFEngine.com\"; option domain-name-servers 192.168.0.1; next-server 192.168.0.1; filename\"pxelinux.0\"; } group { host node1 { # Dummy machine hardware ethernet 00:0F:1F:94:FE:07; fixed-address 192.168.0.11; option host-name\"node1\"; } host node2 { # Dell Inspiron 1150 hardware ethernet 00:0F:1F:0E:70:E7; fixed-address 192.168.0.12; option host-name\"node2\"; } } ";# File contains of Apache2 HTTP configuration"httpd_conf"string=>"<Directory /srv/www/repos>Options IndexesAllowOverride None</Directory>Alias /repos /srv/www/repos<Directory /tftpboot/distro/RHEL/5.2>Options IndexesAllowOverride None</Directory>Alias /distro/rhel/5.2 /tftpboot/distro/RHEL/5.2<Directory /tftpboot/distro/RHEL/4.7>Options IndexesAllowOverride None</Directory>Alias /distro/rhel/4.7 /tftpboot/distro/RHEL/4.7<Directory /tftpboot/distro/CentOS/5.2>Options IndexesAllowOverride None</Directory>Alias /distro/centos/5.2 /tftpboot/distro/CentOS/5.2<Directory /tftpboot/kickstart>Options IndexesAllowOverride None</Directory>Alias /kickstart /tftpboot/kickstart<Directory /tftpboot/CFEngine>Options IndexesAllowOverride None</Directory>Alias /CFEngine /tftpboot/CFEngine ";# File contains of Kickstart for RHEL5 configuration"kickstart_rhel5_conf"string=>"auth --useshadow --enablemd5bootloader --location=mbrclearpart --all --initlabelgraphicalfirewall --disabledfirstboot --disablekey 77244a6377a8044akeyboard nolang en_USlogging --level=infourl --url=http://192.168.0.1/distro/rhel/5.2network --bootproto=dhcp --device=eth0 --onboot=onrebootrootpw --iscrypted $1$eOnXdDPF$279sQ//zry6rnQktkATeM0selinux --disabledtimezone --isUtc Europe/Osloinstallpart swap --bytes-per-inode=4096 --fstype=\"swap\" --recommendedpart / --bytes-per-inode=4096 --fstype=\"ext3\" --grow --size=1%packages@core@basedb4-developenssl-develgccflexbisonlibacl-devellibselinux-develpcre-develdevice-mapper-multipath-sysreport%postcd /rootrpm -i http://192.168.0.1/CFEngine/rpm/CFEngine-3.0.1b1-1.el5.i386.rpmcd /etc/yum.repos.dwget http://192.168.0.1/repos/RHEL5.Base.reporpm --import /etc/pki/rpm-gpg/*yum clean allyum updatemkdir -p /root/CFEngine_initcd /root/CFEngine_initwget -nd -r http://192.168.0.1/CFEngine/inputs//usr/local/sbin/cf-agent -B/usr/local/sbin/cf-agent ";# File contains of PXElinux boot menu"pxelinux_boot_menu"string=>"boot options: rhel5 - install 32 bit i386 RHEL 5.2 (MANUAL) rhel5w - install 32 bit i386 RHEL 5.2 (AUTO) rhel4 - install 32 bit i386 RHEL 4.7 AS (MANUAL) centos5 - install 32 bit i386 CentOS 5.2 (Desktop) (MANUAL) ";# File contains of PXElinux default configuration"pxelinux_default"string=>"default rhel5timeout 300prompt 1display pxelinux.cfg/boot.msgF1 pxelinux.cfg/boot.msglabel rhel5 kernel vmlinuz-RHEL5U2 append initrd=initrd-RHEL5U2 load_ramdisk=1 ramdisk_size=16384 install=http://192.168.0.1/distro/rhel/5.2label rhel5w kernel vmlinuz-RHEL5U2 append initrd=initrd-RHEL5U2 load_ramdisk=1 ramdisk_size=16384 ks=http://192.168.0.1/kickstart/kickstart-RHEL5U2.cfglabel rhel4 kernel vmlinuz-RHEL4U7 append initrd=initrd-RHEL4U7 load_ramdisk=1 ramdisk_size=16384 install=http://192.168.0.1/distro/rhel/4.7label centos5 kernel vmlinuz-CentOS5.2 append initrd=initrd-CentOS5.2 load_ramdisk=1 ramdisk_size=16384 install=http://192.168.0.1/distro/centos/5.2 ";# File contains of specified PXElinux default to be a RHEL5 webserver"pxelinux_rhel5_webserver"string=>"default rhel5wlabel rhel5w kernel vmlinuz-RHEL5U2 append initrd=initrd-RHEL5U2 load_ramdisk=1 ramdisk_size=16384 ks=http://192.168.0.1/kickstart/kickstart-RHEL5U2.cfg ";# File contains of a local repository for RHEL5"rhel5_base_repo"string=>"[Server]name=Serverbaseurl=http://192.168.0.1/repos/rhel5/Server/enable=1[VT]name=VTbaseurl=http://192.168.0.1/repos/rhel5/VT/enable=1[Cluster]name=Clusterbaseurl=http://192.168.0.1/repos/rhel5/Cluster/enable=1[ClusterStorage]name=Cluster Storagebaseurl=http://192.168.0.1/repos/rhel5/ClusterStorage/enable=1 ";#####################################################files:packages_ok::# Create files/dirs and edit the new files"/tftpboot/distro/RHEL/$(rh_distros)/."create=>"true";"/tftpboot/distro/CentOS/$(centos_distros)/."create=>"true";"$(dirs)/."create=>"true";"/tftpboot/pxelinux.cfg/boot.msg"create=>"true",perms=>mo("644","root"),edit_line=>append_if_no_line("$(pxelinux_boot_menu)"),edit_defaults=>empty;"/tftpboot/pxelinux.cfg/default"create=>"true",perms=>mo("644","root"),edit_line=>append_if_no_line("$(pxelinux_default)"),edit_defaults=>empty;"/tftpboot/pxelinux.cfg/default.RHEL5.webserver"create=>"true",perms=>mo("644","root"),edit_line=>append_if_no_line("$(pxelinux_rhel5_webserver)"),edit_defaults=>empty;"/tftpboot/kickstart/kickstart-RHEL5U2.cfg"create=>"true",perms=>mo("644","root"),edit_line=>append_if_no_line("$(kickstart_rhel5_conf)"),edit_defaults=>empty;"/srv/www/repos/RHEL5.Base.repo"create=>"true",perms=>mo("644","root"),edit_line=>append_if_no_line("$(rhel5_base_repo)"),edit_defaults=>empty;# Copy files"/tftpboot"copy_from=>local_cp("/usr/share/syslinux"),depth_search=>recurse("inf"),file_select=>pxelinux_files,action=>immediate;"$(tmp_location)"perms=>m("644"),copy_from=>local_cp("/var/cfengine/inputs"),depth_search=>recurse("inf"),file_select=>input_files,action=>immediate;# Edit atftp, dhcp and apache2 configurations"/etc/sysconfig/atftpd"edit_line=>append_if_no_line("$(atftpd_conf)"),edit_defaults=>empty,classes=>satisfied("atftpd_ready");"/etc/sysconfig/dhcpd"edit_line=>append_if_no_line("$(dhcpd)"),edit_defaults=>empty;"/etc/dhcpd.conf"edit_line=>append_if_no_line("$(dhcpd_conf)"),edit_defaults=>empty,classes=>satisfied("dhcpd_ready");"/etc/apache2/httpd.conf"edit_line=>append_if_no_line("$(httpd_conf)"),edit_defaults=>std_defs,classes=>satisfied("apache2_ok");# Make a static link"/tftpboot/pxelinux.cfg/C0A8000C"link_from=>mylink("/tftpboot/pxelinux.cfg/default.RHEL5.webserver");# Hash comment some lines for apachesapache2_ok::"/etc/apache2/httpd.conf"edit_line=>comment_lines_matching_apache2("#"),classes=>satisfied("apache2_ready");commands:# Restart servicesatftpd_ready::"/etc/init.d/atftpd restart";dhcpd_ready::"/etc/init.d/dhcpd restart";apache2_ready::"/etc/init.d/apache2 restart";#####################################################packages:ipv4_192_168_0_1::# Only the PXE boot server"$(software)"package_policy=>"add",package_method=>zypper,classes=>satisfied("packages_ok");}bodyfile_selectpxelinux_files{leaf_name=>{"pxelinux.0"};file_result=>"leaf_name";}bodycopy_frommycopy_local(from,server){source=>"$(from)";compare=>"digest";}bodylink_frommylink(x){source=>"$(x)";link_type=>"symlink";}bodyclassessatisfied(new_class){promise_kept=>{"$(new_class)"};promise_repaired=>{"$(new_class)"};}bundleedit_linecomment_lines_matching_apache2(comment){vars:"regex"slist=>{"\s.*Options\sNone","\s.*AllowOverride\sNone","\s.*Deny\sfrom\sall"};replace_patterns:"^($(regex))$"replace_with=>comment("$(comment)");}bodyfile_selectinput_files{leaf_name=>{".*.cf",".*.dat",".*.txt"};file_result=>"leaf_name";}Resolver management
code
bundlecommong# globals{vars:"searchlist"slist=>{"search iu.hio.no","search cfengine.com"};"nameservers"slist=>{"128.39.89.10","128.39.74.16","192.168.1.103"};classes:"am_name_server"expression=>reglist("@(nameservers)","$(sys.ipv4[eth1])");}bodycommoncontrol{any::bundlesequence=>{"g",resolver(@(g.searchlist),@(g.nameservers))};domain=>"iu.hio.no";}bundleagentresolver(s,n){files:# When passing parameters down, we have to refer to# a source context"$(sys.resolv)"# test on "/tmp/resolv.conf" #create=>"true",edit_line=>doresolv("@(this.s)","@(this.n)"),edit_defaults=>reconstruct;# or edit_defaults => modify}bundleedit_linedoresolv(s,n){vars:"line"slist=>{@(s),@(n)};insert_lines:"$(line)";}bodyedit_defaultsreconstruct{empty_file_before_editing=>"true";edit_backup=>"false";max_file_size=>"100000";}bodyedit_defaultsmodify{empty_file_before_editing=>"false";edit_backup=>"false";max_file_size=>"100000";}Mount NFS filesystem
code
bodycommoncontrol{bundlesequence=>{"mounts"};}bundleagentmounts{storage:"/mnt"mount=>nfs("slogans.iu.hio.no","/home");}bodymountnfs(server,source){mount_type=>"nfs";mount_source=>"$(source)";mount_server=>"$(server)";#mount_options => { "rw" };edit_fstab=>"true";unmount=>"true";}Unmount NFS filesystem
code
bodycommoncontrol{bundlesequence=>{"mounts"};}bundleagentmounts{storage:# Assumes the filesystem has been exported"/mnt"mount=>nfs("server.example.org","/home");}bodymountnfs(server,source){mount_type=>"nfs";mount_source=>"$(source)";mount_server=>"$(server)";edit_fstab=>"true";unmount=>"true";}- 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