0

I am using saltstack state pattern and replace to match a pattern and replace with a new pattern. My init.sls file executes below:

`modify_script.sh:
   file.replace:
      - name: /path/to/script.sh
      - pattern: /aaa/bbb
      - repl: /aaa/ccc
      - pattern: /xxx/yyy
      - repl: /xxx/zzz`

The above works good if I use a single pattern and replace. This fails for multiple patterns and replaces as shown above. How to achieve multiple pattern replace for two or more patterns in a single file?

Secondly, I have multiple files in a directory which requires a pattern match and replace.

modify_script.sh: file.replace: - name: /path/to/dir [having multiple files which require update] - pattern: /aaa/bbb - repl: /aaa/ccc

Can I match the patterns for all the files under directory? I wouldn't want to match and replace a single file individually. Please advise.

0

You should use Jinja to loop over a list of files and pattern/replacement pairs.

{% set files = ['/a/foo.sh', '/b/bar.sh', '/b/baz.sh'] %}

{% for file in files %}
{% for p, r in [('/aaa/bbb', '/aaa/ccc'), ('/xxx/yyy', '/xxx/zzz')] %}
replace {{ p }} in {{ file }}:
   file.replace:
      - name: {{ file }}
      - pattern: {{ p }}
      - repl: {{ r }}
{% endfor %}
{% endfor %}

Keep in mind the identifiers need to be unique, that's why variables in replace {{ p }} in {{ file }}: are used.

  • A. Z. Thank you, your answer works. However for a variable input under {% for p, r in [('/aaa/bbb', '/aaa/{{ var }}'), ('/xxx/yyy', '/xxx/{{ var }}')] %} where {{ var }} is a variable defined in jinja, the replacement fails. Can I pass variable input instead of a hardcoded value? – Narasimha Dec 6 '18 at 10:13

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.