---

- name: Check if /tmp is noexec
  shell: "cat /etc/fstab | grep -E \" +/tmp\" | grep noexec"
  register: fstab_tmp_noexec
  failed_when: False
  changed_when: False
  check_mode: no

- name: Tmpdir is moved to custom path
  block:
    - name: "Create {{ elasticsearch_custom_tmpdir or elasticsearch_default_tmpdir | mandatory }}"
      file:
        path: "{{ elasticsearch_custom_tmpdir or elasticsearch_default_tmpdir | mandatory }}"
        owner: elasticsearch
        group: elasticsearch
        mode: "0755"
        state: directory
      tags:
        - elasticsearch

    - name: change JVM tmpdir (< 6.x)
      lineinfile:
        dest: /etc/elasticsearch/jvm.options
        line: "-Djava.io.tmpdir={{ elasticsearch_custom_tmpdir or elasticsearch_default_tmpdir | mandatory }}"
        regexp: "^-Djava.io.tmpdir="
        insertafter: "## JVM configuration"
      notify:
        - restart elasticsearch
      tags:
        - elasticsearch
      when: elastic_stack_version is version('6', '<')

    - name: check if ES_TMPDIR is available (>= 6.x)
      lineinfile:
        dest: /etc/default/elasticsearch
        line: "ES_TMPDIR={{ elasticsearch_custom_tmpdir or elasticsearch_default_tmpdir | mandatory }}"
        regexp: "^ES_TMPDIR="
        insertafter: "JAVA_HOME"
      notify:
        - restart elasticsearch
      tags:
        - elasticsearch
      when: elastic_stack_version is version('6', '>=')

    - name: change JVM tmpdir (>= 6.x)
      lineinfile:
        dest: /etc/elasticsearch/jvm.options
        line: "-Djava.io.tmpdir=${ES_TMPDIR}"
        regexp: "^-Djava.io.tmpdir="
        insertafter: "## JVM configuration"
      notify:
        - restart elasticsearch
      tags:
        - elasticsearch
      when: elastic_stack_version is version('6', '>=')
  when: (elasticsearch_custom_tmpdir != '' and elasticsearch_custom_tmpdir != None) or fstab_tmp_noexec.rc == 0
