Home > Enterprise >  Ansible replace a string in a variable with a variable
Ansible replace a string in a variable with a variable

Time:08-24

debug:
  msg: "{{backup_facts | replace(',world',',{{custom}}')}}"
 register: replace_csv

in the above code, I am trying to replace a string/word in a variable with a variable.

so in this case these are the vars:

backup_facts = "hello,world"
custom = "prab"

so the end results I would like is: "hello, prab" after the replace. But everytime I run the playbook, I get the following:

"replace_csv": {
        "changed": false,
        "failed": false,
        "msg": "hello,{{custom}}"
   }

I have attempted different variation such as putting a quotation around the curly brackets or not putting the curly brackets at all but no results.

CodePudding user response:

Q: "The result is: hello,prab after the replace."

Keep it simple. Put the parameters into variables. This will simplify the code. For example,

- hosts: localhost
  vars:
    backup_facts: "hello,world"
    custom: "prab"
  tasks:
    - debug:
        msg: "{{ backup_facts|replace(old, new) }}"
      vars:
        old: ",world"
        new: ",{{ custom }}"

gives (abridged)

ok: [localhost] => 
  msg: hello,prab
  • Related