file.comment / file.uncomment
Comments or uncomments lines matching a regular expression by prefixing or removing a comment character. Modeled after Salt's file.comment and file.uncomment modules. Both states share one implementation.
Source: pkg/state/modules/file_comment.go
Parameters
Both file.comment and file.uncomment accept the same parameters:
| Parameter | Type | Required | Default | Description |
|---|---|---|---|---|
name | string | No | State ID | Absolute path to the target file. path is accepted as an alias. |
regex | string | Yes | — | Go regular expression matched against the uncommented line content. |
char | string | No | # | The comment prefix added or stripped. |
All states also accept the full set of requisite parameters and Salt-parity state attributes — see Dependencies & Requisites.
Check Behavior
- If the file does not exist, the state reports no changes needed (missing files are a no-op).
- Otherwise the transformation is computed in memory and the state reports changes only if any line would be modified.
file.comment — a line needs commenting when it is not already commented (optional leading whitespace followed by char) and it matches regex.
file.uncomment — a line needs uncommenting when it is commented and its text with the comment character stripped matches regex.
Apply Behavior
- Reads the file (stored as a backup for revert). A missing file is a no-op (
Changed: false). file.commentprefixes every matching uncommented line withchar.file.uncommentremoves a single leadingchar(after optional whitespace, preserving indentation) from every commented line whose uncommented text matchesregex.- Writes the result back with mode
0644, preserving the trailing newline.
Revert Behavior
- Restores the original content from the backup taken during Apply.
- If no backup exists (the file was absent), the file is removed.
Examples
Direct Execution
# Comment out swap entries in fstab
zester 'web-01' file.comment /etc/fstab regex='\sswap\s'
# Re-enable a repo line
zester 'web-01' file.uncomment /etc/apt/sources.list regex='deb-src'State File
Disable a setting by commenting it out:
/etc/fstab:
file.comment:
- regex: '\sswap\s'Uncomment a directive with a custom comment character:
/etc/samba/smb.conf:
file.uncomment:
- regex: 'load printers'
- char: ';'Divergences from Salt
regexmust be a valid Go (RE2) regular expression; the builder fails otherwise.- Salt strips a leading
^and trailing$from the pattern before wrapping it; Zester uses the regex as-is (unanchored substring match unless you anchor it). - Salt's
backupparameter is not supported (Revert uses an in-memory backup instead).
file.blockreplace
Manages content between two marker lines in a file. Content between the start and end markers is replaced with the desired content value. Lines outside the block are preserved.
file.copy
Copies a source file that already exists on the peel to a destination path. Modeled after Salt's file.copy module.