1

I wonder whether this can be done or not:

So I have a .yaml file with the following pattern

- xxx: xxxxxxx
  xxxxxxxxx:
  - xxxxxxxxx: xxxx
    http_config: %httpProxy%

I want to replace %httpProxy% with some string displayed in a well-indented new line:

- xxx: xxxxxxx
  xxxxxxxxx:
  - xxxxxxxxx: xxxx
    http_config:
      proxy_url: http://proxy:8080

I can use .replace("%httpProxy%", "\n\r proxy_url: http://proxy:8080"), but I don't want to hard-code the number of spaces (6 in this case) before proxy_url, as the number of space before http_config may not necessarily be 4.

Are there any better ideas?

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
Ken Tsoi
  • 1,195
  • 1
  • 17
  • 37
  • 1
    You need a YAML parser. It'll take care of the indentation for you. – MattDMo Jun 01 '21 at 21:11
  • @MattDMo I use yaml parser to load it after the replacement, `yaml.load(output_str, Loader=yaml.FullLoader)`, but if the indentation is wrong, the parser will fail – Ken Tsoi Jun 01 '21 at 21:15
  • You need to parse it *before* you make the change outlined in your question. Once parsed, you should be able to search for `http_config` keys and if their value equals your match string, create a new daughter key with the proxy info. – MattDMo Jun 01 '21 at 21:18
  • with this tag `%httpProxy%`, the yaml file cannot be parsed – Ken Tsoi Jun 01 '21 at 21:20
  • So how did it get in there if it's invalid YAML? – MattDMo Jun 01 '21 at 21:22
  • It is a template used in a pipeline, with the tags to be replaced with different settings by a script. After the replacement, it will become a valid YAML – Ken Tsoi Jun 01 '21 at 21:23
  • Hi @MattDMo, seems this question is closed, can you re-open it again? – Ken Tsoi Jun 01 '21 at 22:28
  • If it's a template, use a templating engine. Jinja for example has [an indent filter](https://jinja.palletsprojects.com/en/3.0.x/templates/#jinja-filters.indent) to help you with proper indentation. – flyx Jun 02 '21 at 01:06
  • @KenTsoi I reopened it. Please add all the relevant information from the comments to your question so it is clearer. – MattDMo Jun 02 '21 at 12:27

0 Answers0