Priya
Priya

Reputation: 303

Ansible how to split string in newline

I am running in ansible playbook with:

--extra-vars "log_path=/var/logs/a*.log,/repo/log-events-a*.json,repo/user1/log-events-b*.json"

as comma separated lines, I want the output in filebeat.yml file as

      paths:    
        - /var/logs/a*.log    
        - /repo/log-events-a*.json    
        - /repo/user1/log-events-b*.json    

I am using jinja2 for filebeat.yml

     paths:    
        -  {{ log_path }}

And my ansible file testconfigure.yml is

      - hosts: localhost    
         gather_facts: no    
      
         vars:    
             log_path: "{{ logpath.replace(',', '\n-')}}"    
         tasks:    
    
          - name: a jija test    
            template:    
              src: /repo/filebeat/filebeat.j2    
              dest : /repo/filebeat/filebeat.yml    
    

I am getting the output in filebeat.yml file as:

    paths:
     - /var/logs/*.log,/repo/log-events-a*.json,/repo/user1/log-events-b*.json

I also tried logpath: "{{ logpath | regex_replace(',', '\n-') }" in my playbook, but still getting same output. How should I try it?

Upvotes: 0

Views: 6304

Answers (1)

Frenchy
Frenchy

Reputation: 17037

create a j2 file :

paths:
{% for log in log_path %}
  - {{ log }}
{% endfor %}

playbook:

- hosts: localhost
  vars:    
    log_path: "{{ logpath.split(',') }}"
  tasks:

    - name: templating
      template:
        src: filebeat.j2
        dest: filebeat.yml

and the command to call:

ansible-playbook yourplaybook.yml --extra-vars "logpath=/var/logs/a*.log,/repo/log-events-a*.json,repo/user1/log-events-b*.json

result:

paths:
  - /var/logs/a*.log
  - /repo/log-events-a*.json
  - repo/user1/log-events-b*.json

if you just want to create a var file, no need to template:

- name: create var file
  copy:
    content: "{{ log_path | to_nice_yaml }}"
    dest: filebeat.yml

result:

paths:
- /var/logs/a*.log
- /repo/log-events-a*.json
- repo/user1/log-events-b*.json

Upvotes: 2

Related Questions