Q: "Is there a way to maintain the position just change the value?"
A: No. There isn't such a filter available in Ansible which would preserve this format. If you need any special format you'll have to use template.
Except for the changed formatting, your code should be working fine, actually. For example
- hosts: localhost
tasks:
- slurp:
src: config.yml
register: fileContent
- set_fact:
fileContent: "{{ fileContent.content|
b64decode|from_yaml|
combine(myvariable) }}"
vars:
myvariable:
next_key:
key1: "value"
key2:
key1: "value"
key2: "value"
- copy:
content: "{{ fileContent }}"
dest: config2.yml
gives valid JSON
shell> cat config2.yml
{"key": {"key": {"key1": "value", "key2": {"key1": "value", "key2": "value"}}}, "next_key": {"key1": "value", "key2": {"key1": "value", "key2": "value"}}}
The content of the file depends on formating. For example the default JSON above. You can change it to YAML, e.g.
- copy:
content: "{{ fileContent|to_nice_yaml }}"
dest: config2.yml
gives
shell> cat config2.yml
key:
key:
key1: value
key2:
key1: value
key2: value
next_key:
key1: value
key2:
key1: value
key2: value
or you can get nice JSON by using the filter to_nice_json, e.g.
- copy:
content: "{{ fileContent|to_nice_json }}"
dest: config2.yml
gives
shell> cat config2.yml
{
"key": {
"key": {
"key1": "value",
"key2": {
"key1": "value",
"key2": "value"
}
}
},
"next_key": {
"key1": "value",
"key2": {
"key1": "value",
"key2": "value"
}
}
}