Roopendra
Roopendra

Reputation: 7762

Explode variable from space and append basedir in ansible playbook

In my use case I am reading directories from conf and source path is space separated. Number of space separated source may increase or decrease. My product.conf look like below

product.conf

{
    "directories": [{
        "source": "src/main/php/en/path1 src/main/php/en/path2 src/main/php/en/path3",
        "lang": "en"
    }, {
        "source": "src/main/php/jp/path1 src/main/php/jp/path2",
        "lang": "jp"
    }]
}

Playbook to read conf and assign source into separate variable.

playbook.yml

---

 - hosts: 127.0.0.1
   connection: local

   vars:
     BASE_DIR: /home/roop

   tasks:
     - include_vars: product.conf

     - set_fact:
         en_source="{{ item.source }}"
       with_items: directories 
       when: item.lang == "en"

     - set_fact:
         jp_source="{{ item.source }}"
       with_items: directories 
       when: item.lang == "jp"

     - debug: var=en_source
     - debug: var=jp_source

I am getting BASE_DIR dynamically. I need to add this BASE_DIR with every source. like

"en_source" = "/home/roop/src/main/php/en/path1 /home/roop/src/main/php/en/path2"

Any suggestion?

Upvotes: 0

Views: 624

Answers (1)

udondan
udondan

Reputation: 59989

A little hacky:

- set_fact:
    en_source="{{ BASE_DIR + '/' + item.source | regex_replace('(\s)', '\\1' + BASE_DIR + '/') }}"

regex_replace is a filter from Ansible.

For a cleaner solution you can create a custom filter plugin.

Upvotes: 1

Related Questions