filemapper
Version information
This version is compatible with:
- Puppet Enterprise 2023.8.x, 2023.7.x, 2023.6.x, 2023.5.x, 2023.4.x, 2023.3.x, 2023.2.x, 2023.1.x, 2023.0.x, 2021.7.x, 2021.6.x, 2021.5.x, 2021.4.x, 2021.3.x, 2021.2.x, 2021.1.x, 2021.0.x
- Puppet >= 7.0.0 < 9.0.0
Start using this module
Add this module to your Puppetfile:
mod 'puppet-filemapper', '4.0.0'
Learn more about managing modules with a PuppetfileDocumentation
FileMapper module for Puppet
Synopsis
Map files to resources and back with this handy dandy mixin!
Description
Things that are harder than they should be:
- Acquiring a pet monkey
- Getting anywhere in Los Angeles
- Understanding the ParsedFile provider
- Writing Puppet providers that directly manipulate files
The solution for this is to completely bypass parsing in any sort of base provider, and delegate the role of parsing and generating to including classes.
You figure out how to parse and write the file, and this will do the rest.
Synopsis of implementation requirements
Providers using the Filemapper extension need to implement the following methods.
self.target_files
This should return an array of filenames specifying which files should be prefetched.
self.parse_file(filename, file_contents)
This should take two values, a string containing the file name, and a string containing the contents of the file. It should return an array of hashes, where each hash represents {property => value} pairs.
select_file
This is a provider instance method. It should return a string containing the filename that the provider should be flushed to.
self.format_file(filename, providers)
This should take two values, a string containing the file name to be flushed, and an array of providers that should be flushed to this file. It should return a string containing the contents of the file to be written.
Synopsis of optional implementation hooks
self.pre_flush_hook(filename)
and self.post_flush_hook(filename)
These methods can be implemented to add behavior right before and right after filesystem operations. Both methods take a single argument, a string containing the name of the file to be flushed.
If self.pre_flush_hook
raises an exception, the flush will not occur and the
provider will be marked as failed and will refuse to perform any more flushes.
If some sort of critical error occurred, this can force the provider to error
out before it starts stomping on files.
self.post_flush_hook
is guaranteed to run after any filesystem operations
occur. This can be used for recovery if something goes wrong during the flush.
If this method raises an exception, the provider will be marked as failed and
will refuse to perform any more flushes.
Removing empty files
If a file is empty, it's often reasonable to just delete it. The Filemapper
mixin implements attr_accessor :unlink_empty_files
. If that value is set to
true, then if self.format_file
returns the empty string then the file will be
deleted from the file system.
How it works
The Filemapper extension takes advantage of hooks within the Transaction to reduce the number of reads and writes needed to perform operations.
prefetching
When a catalog is being applied, providers can define the prefetch
method to
load all resources before runtime. The Filemapper extension uses this method to
preemptively read all files that the provider requires, and generates and stores
the state of the requested resources. This means that if you have a few thousand
resources in 20 files, you only need to do 20 reads for the entire Puppet run.
post-evaluation flushing
When resources are normally evaluated, each time a property is synchronized it's expected that an action will be run right then. The Filemapper extension instead records all the requested changes and defers operating on them. When the resource is finished, it will be flushed, at which time all of the requested changes will be applied in one pass. Given a resource with 10 properties, all of which are out of sync, the file will be written only once. If no properties are out of sync, the file will be untouched.
To ensure that the system state matches what Puppet thinks is going on, any file that has changed resources will be re-written after each resource is flushed. That means that if you have 20 resources out of sync, that file will have to be written 20 times. While it's technically possible to write the file in a single pass, this means that some resources will be applied either early or late, which utterly smashes POLA.
Use on the command line
The Filemapper extension implements the instances
method, which means that you
can use the puppet resource
command to interact with the associated provider
without having to perform a full blown Puppet run.
Selecting files to load
In order to provide prefetching and puppet resource
in a clean manner, the
Filemapper extension has to have a full list of what files to read. Implementing
classes need to implement the target_files
method which returns a list of
files to read. The implementation is entirely up to the implementing class; it
can return a single file every time, such as "/etc/inittab", or it can generate
that information on the fly, by returning Dir["/etc/sysconfig/network/ifcfg-*"]
.
Basically, files that will be used as a source of data can be as complex or
simple as you need.
Writing back files
In a similar vein, resources can be written back to files in whatever method you
need. Implementing classes need to implement the instance method #select_file
so that when that resource is changed, the correct file is modified.
Parsing
When parsing a file, the implementing class needs to implement the parse_file
method. It will get the name of the file being parsed as well as the contents.
It can parse this file in whatever manner needed, and should return an array of
any provider instances generated. If the file only contains a single provider
instance, then just wrap that instance in an array.
Writing
Whenever a file is marked as dirty, that is a resource associated with that file
has changed, the format_file
method will be called. The implementing class
needs to implement a method that takes the filename and an array of provider
instances associated with that file, and return a string. The method needs to
determine how that file should be written to disk and then return the contents.
This can be as complex as needed.
Under no conditions should implementing classes modify any files directly. No, seriously, don't do it. The Filemapper extension uses the built in methods for modifying files, which will back up changed files to the filebucket. This is for your own safety, so if you bypass this then you are on your own.
Storing state outside of resources
It's more or less expected that there will be no state outside of the provider
instances, but there are plenty of cases where this could be the case. For
instance, if one wanted to preserve the comments in a file but didn't directly
associate them with resource attributes, the parse_file
method can store data
in an instance variable, such as @comments = my_list_of_comments
. When
formatting the file, the implementing class can read the @comments
variable
and re-add that data to the content that will be written back.
Basically, you can store whatever data you need in these methods and pass things around to maintain more complex state.
Using this sort of operation of reading outside state, you can theoretically have multiple Filemapper extensions that work on shared files. By communicating the state between them, you can manage multiple different resources in one file. HOWEVER, this will require careful communication, so don't take this sort of thing lightly. However, I don't thing that anything else in Puppet can provide this sort of behavior. YMMV.
Why a mixin?
While the ParsedFile provider is supposed to be inherited, this class is a mixin and needs to be included. This is done because the Filemapper extension only adds behavior, and isn't really an object or entity in its own right. This way you can use the Filemapper extension while inheriting from something like the Puppet::Provider::Package provider.
The Backstory
Managing Unix-ish systems generally means dealing with one of two things:
- Processes - starting them, stopping them, monitoring them, etc.
- Files - Creating them, editing, deleting them, specifying permissions, etc.
Puppet has pretty good support in the provider layer for running commands, but the file manipulation layer has been lacking. The long-standing approach for manipulating files has been to select one of the following, and hope for the best.
Shipping flat files to the client
Using the File
resource to ship flat files is a really common solution, and
it's very easy. It also has the finesse of a brick thrown through a window.
There is very little customizability here, aside from the array notation for
specifying the source
field.
Using ERB templates to customize files
The File resource can also take a content field, to which you can pass the output of a template. This allows more sophistication, but not much. It also adds more of a burden to your master; template rendering happens on the master and if you're doing really crazy number crunching then this pain will be centralized.
Using Augeas
Augeas is a very powerful tool that allows you to manipulate files, and the
Augeas
type allows you to harness this inside of Puppet. However, it has a
rather byzantine syntax, and is dependent on lenses being available.
Sed
I personally love sed, but sed a file configuration management tool is not.
Using the ParsedFile provider
Puppet has a provider extension called the ParsedFile provider that's used to manipulate text like crontabs and so forth. It also uses a number of advanced features in puppet, which makes it quite powerful. However, it's incredibly complex, tightly coupled with the FileParsing utility language, has tons of obscure and undocumented hooks that are the only way to do complex operations, and is entirely record based which makes it unsuitable for managing files that have complex structure. While it has basic support for managing multiple files, basic is the indicative word.
The Filemapper extension has been designed as a lower level alternative to the ParsedFile.
Examples
The Filemapper extension was largely extracted out of the puppet-network module. That code base should display the weird edge cases that this extension handles.
Changelog
All notable changes to this project will be documented in this file. Each new release typically also includes the latest modulesync defaults. These should not affect the functionality of the module.
v4.0.0 (2023-11-30)
Breaking changes:
- Drop Puppet 6 support #74 (bastelfreak)
Implemented enhancements:
- Add Puppet 8 support #75 (bastelfreak)
Merged pull requests:
- Correct spelling mistake #73 (EdwardBetts)
v3.1.0 (2020-11-07)
Breaking changes:
- Drop Puppet 4 #64 (bastelfreak)
Closed issues:
- Add examples to filemapper to demonstrate use. #7
Merged pull requests:
v3.0.2 (2018-10-14)
Merged pull requests:
- modulesync 2.1.0 and allow puppet 6.x #59 (bastelfreak)
- Remove docker nodesets #53 (bastelfreak)
v3.0.1 (2018-03-29)
Merged pull requests:
- Bump puppet dependency to minimum supported version 4.10.0 #50 (bastelfreak)
v3.0.0 (2017-10-19)
Merged pull requests:
- Release 3.0.0 #46 (bastelfreak)
- Fix github license detection #44 (alexjfisher)
v2.1.0 (2017-02-11)
This is the last release with Puppet3 support!
- Set minimum version_requirement for Puppet
- Remove unnecessary disabling of RSpec/NestedGroups
2016-12-08 Release 2.0.1
- Modulesync with latest Vox Pupuli changes
- Fix several rubocop issues
- define #path on filetype mocks/fix broken symbols
2016-08-19 Release 2.0.0
This is a backwards incompatible release.
- Drop Ruby 1.8.7 support
- Move to Vox Pupuli namespace
- Significant code quality improvements
- Modulesync with latest Vox Pupuli defaults
- Sync mk_resource_methods with Puppet Core
Thanks to Joseph Yaworski and the Vox Pupuli teams for their work on this release.
2014-09-02 Release 1.1.3
This is a backwards compatible bugfix release.
- Invoke super in self.initvars to initialize
@defaults
Thanks to Igor Galić for his work on this release.
2014-07-04 Release 1.1.2
This is a backwards compatible bugfix release.
- Update permissions of built modules to be a+rX.
2012-12-30 Release 1.1.1
This is a backwards compatible bugfix release.
- (filemapper-#4) Add resource failure when in error state
Thanks to Reid Vandewiele for his contribution for this release.
2012-12-07 Release 1.1.0
This is a backwards compatible feature release.
- Add Apache 2.0 LICENSE
- Add Gemfile
- (filemapper-#3) Add
unlink_empty_files
attribute - (maint) spec cleanup for readability
- (filemapper-#2) Add pre and post flush hook support
2012-10-28 Release 1.0.2
This is a backwards compatible maintenance release.
- Update metadata to reference forge username
- Ensure implementing classes return a string from format_file
2012-10-16 Release 1.0.1
This is a backwards compatible maintenance release.
- Remove call
#symbolize
method; said method was removed in Puppet 3.0.0 - Fail fast if an including class returns bad data from Provider.parse_file
- Don't try to fall back to
@resource.should
value for properties
* This Changelog was automatically generated by github_changelog_generator
Copyright 2012 Adrien Thebo Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS