zester
GuidesModules

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:

ParameterTypeRequiredDefaultDescription
namestringNoState IDAbsolute path to the target file. path is accepted as an alias.
regexstringYesGo regular expression matched against the uncommented line content.
charstringNo#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

  1. Reads the file (stored as a backup for revert). A missing file is a no-op (Changed: false).
  2. file.comment prefixes every matching uncommented line with char. file.uncomment removes a single leading char (after optional whitespace, preserving indentation) from every commented line whose uncommented text matches regex.
  3. 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

  • regex must 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 backup parameter is not supported (Revert uses an in-memory backup instead).

On this page