I
I
itbidlo2019-10-18 14:50:44
Jinja
itbidlo, 2019-10-18 14:50:44

How to select a value from a list by key using jinja?

Welcome all.
There is a list of values:

services: 
  - name: es
    dirs:
      - { type: "es_script", path: "/opt/distrib/efk/script", user: "elasticsearch", group: "elasticsearch", mode: '0765' }
      - { type: "es_config", path: "/etc/elasticsearch", user: "elasticsearch", group: "elasticsearch", mode: '0765' } 
      - { type: es_data, path: /opt/data/elasticsearch, user: elasticsearch, group: elasticsearch, mode: '0765' }
      - { type: es_log, path: /opt/log/elasticsearch, user: elasticsearch, group: elasticsearch, mode: '0765' }

I would like to pull out other values ​​of the path, usr line using the type key using j2.
I'm trying like this:
- name: Set the l_env
  set_fact:  
    l_env: "{% for tmp in service.dirs %}{% if tmp.type == 'es_script' %}{% set t_env = tmp.path %}{{- t_env }}{% endif %}{%- endfor %}"
  
- name: Ensure Systemd unit file is present.
  template:
    src: jinja2.j2
    dest:  "{{ l_env  }}"

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
MaxKozlov, 2019-10-31
@MaxKozlov

If you want to get only dirs., which have type == "es_script" attribute,
then you can do this (if, of course, I understood the task correctly)

set_fact:
  scriptdirs: {{ dirs. | selectattr(type, 'equalto', 'es_script') | list }}

template:
  src: template.j2
  dest: " {{ item.path }}"
  mode: "{{ item.mode }}"
loop: "{{ scriptdirs }}"

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question