salt icon indicating copy to clipboard operation
salt copied to clipboard

salt.modules.file.line documentation improvements

Open JensRantil opened this issue 11 years ago • 32 comments

See https://docs.saltstack.com/en/latest/ref/modules/all/salt.modules.file.html#salt.modules.file.line.

  • Fix the :param. Nothing else in the documentation is using that format.
  • I have no idea what "Match the target line for an action by a fragment of a string or regular expression." even means. There is no general description of file.line. I assume match will be required for every call to file.line? How do I decide whether I want to only match a fixed string fragment or regular expression?
  • what before and after actually are used for. Are they lines that need to be before or after? How do I choose if they should be regexps or not?
  • A lot of the parameters default to None. Which are required? Do they have any default values?
  • Use a better example that covers more cases.

JensRantil avatar Sep 22 '15 11:09 JensRantil

@JensRantil, thanks for the the report.

jfindlay avatar Sep 22 '15 20:09 jfindlay

Additionally, the CLI Examples: of the documentation is wrong and causes an error if someone attempts to follow it as it contains commas that aren't supposed to be there as seen below:

salt '' file.line /etc/nsswitch.conf "networks: files dns", after="hosts:.?", mode='ensure'

commas should be removed in all occurrences of this cli example.

zenion avatar Dec 23 '15 22:12 zenion

I don't understand why this doesn't work:

my-state:
  file.line:
   - name: /my/file
   - mode: ensure
   - content: "line-I-want-to-exist"
   - location: end

This is the error I'm getting (incomprehensible):

          ID: my-state
    Function: file.line
        Name: /my/file
      Result: False
     Comment: An exception occurred in this state: Traceback (most recent call last):
                File "/usr/lib/python2.7/dist-packages/salt/state.py", line 1624, in call
                  **cdata['kwargs'])
                File "/usr/lib/python2.7/dist-packages/salt/loader.py", line 1491, in wrapper
                  return f(*args, **kwargs)
                File "/usr/lib/python2.7/dist-packages/salt/states/file.py", line 2560, in line
                  backup=backup, quiet=quiet, indent=indent)
                File "/usr/lib/python2.7/dist-packages/salt/modules/file.py", line 1611, in line
                  raise CommandExecutionError("Wrong conditions? "
              CommandExecutionError: Wrong conditions? Unable to ensure line without knowing where to put it before and/or after.
     Started: 21:30:00.738783
    Duration: 4.958 ms
     Changes:

I'd like Salt to add this line to the end of the file if it doesn't exist. Feels like a common use-case. Is my use case not possible? Please make sure that the documentation explains why this doesn't work.

JensRantil avatar Feb 17 '16 20:02 JensRantil

Okay, looks like I should use file.append instead...

JensRantil avatar Feb 17 '16 20:02 JensRantil

Another example of where I don't understand how file.line should be used:

/etc/fstab:
  file.line:
    - match: "/dev/xvda.*"
    - mode: Delete

What I want to do: Remove any line starting with /dev/xvda.

Error message I am getting:

          ID: /etc/fstab
    Function: file.line
      Result: False
     Comment: Missing parameter content for state file.line
     Started:
    Duration:
     Changes:

Why would I need to specify content when I'm deleting a line matching a regexp? Can file.line only delete fixed lines? The documentation doesn't state.

JensRantil avatar Apr 03 '16 21:04 JensRantil

Also, why are modes specified with capital first letter? Feels weird since nothing else is in capitals Salt.

JensRantil avatar Apr 03 '16 21:04 JensRantil

Stuck in the same way (if that helps)...

brevilo avatar Apr 13 '16 14:04 brevilo

On the subject of file.line mode: Delete, aside from having to use contentrather than match...

It seems there is double escape processing for regex strings. That is, with a single escape: Rendering SLS 'base:blah' failed: found unknown escape character '.'; line xxx

This means double escaping to obtain a literal period:

\. for a literal period must be \\.

As it's not standard regex escaping, although not uncommon when there is more than one string processor, it should be documented to save people a whole bunch of time.

campbellmc avatar Apr 15 '16 10:04 campbellmc

Gah! I wished I'd know that last week! Thanks! That explains why the state didn't match... I eventually resorted to a really ugly workaround involving file.replace...

JensRantil avatar Apr 15 '16 11:04 JensRantil

I agree with the previous posts. The behavior of file.line is everything else than intiutive.

I think the most common situation that people want to describe with such a resource would be: "find occurence in file and replace it with my given line, if not present append it to the end of the file (with the OPTION to override end of file with something like after and/or before)"

EDIT: Ignore this post, actually file.replace seems to be doing what I want, I'll give it a try, however the names are somehow confusing.

Heiko-san avatar Jul 02 '16 20:07 Heiko-san

I am having trouble forcing file.line to replace occurrences of the match string at the beginning of a line. I am using '^' but it seems to be interpreted literally and the match is not found.

file.line:
  - name: filename
  - mode: replace
  - match: '^match string'
  - content: 'to be replaced with this'

file contents:

match string
some other test. match string again.

outcome: nothing is replaced when using ^ without ^ all occurrences of 'match string' are replaced

aabognah avatar Aug 03 '16 16:08 aabognah

@aabognah Have you tried using file.replace instead?

JensRantil avatar Aug 03 '16 18:08 JensRantil

I'm having same issues here, the state should not generate an exception but just return what's wrong in a user friendly way. Making sure a simple line exists using Saltstack takes a lot of effort in current situation.

file.append is not a great alternative, it keeps adding lines as the name suggests, not what you want.

The docs are still not updated and suffer from a markup bug I think.

githubcdr avatar Oct 04 '16 12:10 githubcdr

@githubcdr file.append should not append a line more than once. If it does, there is something wrong in your state or a bug in the function. I use it

As for file.line, I consider it as not working as expected, and very badly documented. I use other functions such as file.replace or file.append instead.

dr4Ke avatar Oct 06 '16 08:10 dr4Ke

I agree, I was looking for an easy way to change a keyword using file.line, I failed.

On another note file.append will not help you you want to change the value of FOO;

FOO=BAR

This is something that file.line should make easy, at least try :) file.replace seem to be better at everything compared to file.line.

githubcdr avatar Oct 06 '16 09:10 githubcdr

I usually use file.replace, but it only seems to work with regular expressions. If I want to look for a URL which is pulled from a pillar source and is not in regex format, it's probably not going to work so well due to slashes and other characters that have special meanings in regex land.

file.line looks like a solution here, but it clearly has a lot of problems. I'd be happy with file.replace if it only supported fixed strings.

boltronics avatar Nov 02 '16 06:11 boltronics

@boltronics if file.replace is not working with basic strings, that should be reported as a bug.

lorengordon avatar Nov 02 '16 12:11 lorengordon

@lorengordon You mean a feature request? There's nothing to indicate it was meant to support fixed strings.

boltronics avatar Nov 02 '16 23:11 boltronics

@boltronics no, a bug. strings definitely work. if you are finding they are not, it is either a bug, or a usage error.

C:\salt\srv\states\base> cat foo.sls
foo:
  file.replace:
    - name: C:\salt\srv\states\base\foo.txt
    - pattern: foo
    - repl: '#foo'
C:\salt\srv\states\base> cat foo.txt
foo
bar
baz
C:\salt\srv\states\base> C:\salt\salt-call.bat state.sls foo
local:
----------
          ID: foo
    Function: file.replace
        Name: C:\salt\srv\states\base\foo.txt
      Result: True
     Comment: Changes were made
     Started: 21:53:51.975000
    Duration: 36.0 ms
     Changes:
              ----------
              diff:
                  ---
                  +++
                  @@ -1,3 +1,3 @@
                  -foo
                  +#foo
                   bar
                   baz

Summary for local
------------
Succeeded: 1 (changed=1)
Failed:    0
------------
Total states run:     1
Total run time:  36.000 ms
C:\salt\srv\states\base> cat .\foo.txt
#foo
bar
baz

lorengordon avatar Nov 03 '16 01:11 lorengordon

@lorengordon But that's just because your string example happens to be regex-compatible. ie. it's no different to running:

$ echo 'foobar' | sed 's/foo/#foo/'
#foobar
$

Try this instead:

$ cat urls.sls 
foo:
  file.replace:
    - name: /tmp/urls.txt
    - pattern: https://encrypted.google.com/search?hl=en&q=Test%20search%20argument
    - repl: 'https://duckduckgo.com/?q=Test+search+argument&t=ffsb&ia=web'
$ cat /tmp/urls.txt
https://saltstack.com/
https://encrypted.google.com/search?hl=en&q=Test%20search%20argument
https://www.gnu.org/
$ diff <(tail -n 2 /tmp/urls.txt | head -n 1) <(tail -n 2 urls.sls | head -n 1 | sed 's/.*:\ //')
$ echo $?
0
$ sudo salt-call state.sls urls
[INFO    ] Loading fresh modules for state activity
[INFO    ] Fetching file from saltenv 'base', ** done ** 'urls.sls'
[INFO    ] Running state [/tmp/urls.txt] at time 14:19:14.277698
[INFO    ] Executing state file.replace for [/tmp/urls.txt]
[INFO    ] No changes needed to be made
[INFO    ] Completed state [/tmp/urls.txt] at time 14:19:14.282500 duration_in_ms=4.802
local:
----------
          ID: foo
    Function: file.replace
        Name: /tmp/urls.txt
      Result: True
     Comment: No changes needed to be made
     Started: 14:19:14.277698
    Duration: 4.802 ms
     Changes:   

Summary for local
------------
Succeeded: 1
Failed:    0
------------
Total states run:     1
Total run time:   4.802 ms
$ cat /tmp/urls.txt
https://saltstack.com/
https://encrypted.google.com/search?hl=en&q=Test%20search%20argument
https://www.gnu.org/
$ 

This makes perfect sense, since the URL is not a regex but is being treated as one as per the docs. But we can do this instead:

$ cat urls.sls 
foo:
  file.replace:
    - name: /tmp/urls.txt
    - pattern: https:\/\/encrypted\.google\.com\/search\?hl=en&q=Test%20search%20argument
    - repl: 'https://duckduckgo.com/?q=Test+search+argument&t=ffsb&ia=web'
$ sudo salt-call state.sls urls
[INFO    ] Loading fresh modules for state activity
[INFO    ] Fetching file from saltenv 'base', ** done ** 'urls.sls'
[INFO    ] Running state [/tmp/urls.txt] at time 14:20:32.908637
[INFO    ] Executing state file.replace for [/tmp/urls.txt]
[INFO    ] File changed:
--- 
+++ 
@@ -1,3 +1,3 @@
 https://saltstack.com/
-https://encrypted.google.com/search?hl=en&q=Test%20search%20argument
+https://duckduckgo.com/?q=Test+search+argument&t=ffsb&ia=web
 https://www.gnu.org/

[INFO    ] Completed state [/tmp/urls.txt] at time 14:20:32.915406 duration_in_ms=6.769
local:
----------
          ID: foo
    Function: file.replace
        Name: /tmp/urls.txt
      Result: True
     Comment: Changes were made
     Started: 14:20:32.908637
    Duration: 6.769 ms
     Changes:   
              ----------
              diff:
                  --- 
                  +++ 
                  @@ -1,3 +1,3 @@
                   https://saltstack.com/
                  -https://encrypted.google.com/search?hl=en&q=Test%20search%20argument
                  +https://duckduckgo.com/?q=Test+search+argument&t=ffsb&ia=web
                   https://www.gnu.org/

Summary for local
------------
Succeeded: 1 (changed=1)
Failed:    0
------------
Total states run:     1
Total run time:   6.769 ms
$

From the file.replace docs, pattern is passed to re.search, which clearly says it operates on a "regular expression pattern". This does not appear to be something that can be changed via one of the optional flags either.

Hence the only option right now is to use file.line for such operations, and that is not a bug.

boltronics avatar Nov 03 '16 03:11 boltronics