Donate. I desperately need donations to survive due to my health

Get paid by answering surveys Click here

Click here to donate

Remote/Work from Home jobs

Find and replace a key in yaml using python

I'm a python newbie, so I must be asking something that was already answered and I didn't understand... sorry if I'm repeating

I want to make a general python script that will:

  • Take yaml file as input
  • Take 3 params: serviceName, keyToModify and value
  • Find the serviceName, which may be at different level of the yaml (not necessarily the top level) and once found - look for the keyToModify under the serviceName and modify the value of the key to value

I'm struggling with the recursion piece and how to iterate over every possible item in yaml, find the correct serviceName and then inside it the key-value pair to modify

For example:

service1:
  image:
    tag: 1.0.0
agents:
  service2:
    image:
      tag: 2.0.0
service3:
  image:
    tag: 3.0.0

I want to get the serviceName that can potentially be service1, service2, service3 and then modify the tag value under image for the proper service to something else

so if:

serviceName = service2, keyToModify = tag, value = 5.0.0

the output should be:

service1:
  image:
    tag: 1.0.0
agents:
  service2:
    image:
      tag: 5.0.0
service3:
  image:
    tag: 3.0.0

I'm pretty sure Replacing strings in YAML using Python has most of what I need and https://yaml.readthedocs.io/en/latest/ is the way to implement it, but I couldn't figure out what I need to change to make it more general

Comments