HELP for Replace module regex

Hi All,

I am try to figure out the regex exp that will catch a key in a yaml file but i am not getting the way to pass through. I hope that you expertise on this can help me.

Problem Statement: I have a yaml file (which will be dynamic), where i need to replace a specific key value.

Example: in the below yaml file i only need to update “id” value which is under payroll_emp in the all the file.

If i am using regex: id:.* this will catch all the id in the file.

Help Needed: if there a way that i can have a regex to match the id under payroll_emp and change the value id: 1000 to id: 2000 .

NOTE: we can’t use the after and before parameter as this file will be dynamic its not sure what will be before and after id

What does your ansible task look like?

Hi Dick,

Thank you for the response.

as you see the commented code where i was trying use the after: ‘payroll_emp.*’ it does not do anything and i use the replace without any guard then all the id: xxxxx gets change with id: 2000

Ah Ok, i see.
Using a string manipulating module like replace is inherently fragile,
so whatever works now may break tomorrow (as you pointed out).
Since your input is yaml, I would look into another approach, like
lookup the file content, parse it as yaml, change the required
keys/values, and then write the file back.
This way is more robust in terms of input (the ordering/comments/etc
won't matter), and also output, as that will be valid yaml.

Agreed to what you have pointed out.

But my apologies as i have lack of knowledge to do such level of parsing as i have just started with ansible.

it will be great help if you can help me on this. Also, a pointer the value that need to be change will be passed using the with_items: xxxx, as value is fetch in previous task and store as a set fact.

Hi All,

can anyone me out on this. i had been trying to check around the regex but no luck

Hi Manisha,
I just looked into your issue and found that you’re using only id for replacement which gives you wrong output so instead of using it use the below syntax

tasks:

  • name: Replaces all the IDs from 1000 to 2000.
    replace:
    path:
    regexp: ‘id: 1000’
    replace: ‘id: 2000’

And yes similarly for replacing 1001 with 2001 you’ve to add one more replace module.
If this is helpful for you then its really grateful for me.

Thanks & Regards,
Shrasti Sahni