How to create an "AppendToLineIfNotContains" rule

Jay2k1 <[email protected]>
Newsgroups gmane.comp.sysutils.cfengine.general
Message-ID <[email protected]>
Hello,

I am in the process of migrating from cfe2 to cfe3 and am stuck with this 
problem:

I need to append a string to a line only...
...if this line exists AND
...if the string is not already in the line

Example: A firewall config file that contains IP aliases like so:

WEB_SERVERS=10.0.0.5,10.0.06,10.0.0.8,10.0.0.42

Now when a new web server is being added, its IP should be appended to the 
line:

,10.0.0.66

Cfengine2 had a command 
<https://docs.cfengine.com/docs/archive/manuals/cf2-Reference.html#AppendToLineIfNotContains> 
for that, it would look like this:

editfiles:
  any::
  { /etc/firewall/aliases.cfg
    LocateLineMatching "^WEB_SERVERS=.*"
    AppendToLineIfNotContains ",10.0.0.66"
  }

I am trying to replicate this behaviour. The only thing I could come up 
with was this:

bundle agent firewall
{
  files:
    any::
      "/etc/firewall/aliases.cfg"
      edit_line => add_webserver;
}

bundle edit_line add_webserver
{
  replace_patterns:
    "^WEB_SERVERS=(.*)"
      replace_with => appendToLine(",10.0.0.66"),
      if => not(regline("^WEB_SERVERS=.*,10\.0\.0\.66", 
"/etc/firewall/aliases.cfg"));
}

body replace_with appendToLine(text)
{
  replace_value => "$(match.0)$(text)"; # backreference
  occurrences => "first";          # first, last all
}

This does not work, it complains that the "regular expression matches the 
replacement string":

*error: Promised replacement 
'WEB_SERVERS=10.0.0.5,10.0.06,10.0.0.8,10.0.0.42,10.0.0.66' on line 
'WEB_SERVERS=10.0.0.5,10.0.06,10.0.0.8,10.0.0.42' for pattern 
'^WEB_SERVERS=(.*')' is not convergent while editing 
'/etc/firewall/aliases.cfg' (regular expression matches the replacement 
string)*

How would I fix this?

I know that there is field editing 
<https://docs.cfengine.com/docs/3.19/reference-promise-types-files-edit_line-field_edits.html> 
in cfe3, but we might need this in other places which don't necessarily all 
have a field structure.

Thanks,
Jay

-- 
You received this message because you are subscribed to the Google Groups "help-cfengine" group.
To unsubscribe from this group and stop receiving emails from it, send an email to [email protected].
To view this discussion on the web visit https://groups.google.com/d/msgid/help-cfengine/0fbc63a9-b873-407a-bfda-ace72172528bn%40googlegroups.com.
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.