find the file which contains the specific content in a directory, then run a command only with that file

4/30/2019
- name: find config files
  find:
    paths: "/directory/files/"
    patterns: "*.yaml,*.yml"
  register: yaml_files

- set_fact:
    yaml_list: "{{ yaml_files.files | map(attribute='path') | list}}"


- name: Create namespace first
  command: "{{ bin_dir }}/kubectl apply -f {{ item }}"
  when: contents.find('kind\:\ Namespace')
  vars:
    contents: "{{ lookup('file', '{{ item }}') }}"
  with_items:
    "{{ yaml_list }}"

I just want to run command when the file contains "kind: Namespace", but this will run with all the file found.

-- pugna
ansible
kubernetes

2 Answers

4/30/2019

Try search

- name: Create namespace first
  command: "{{ bin_dir }}/kubectl apply -f {{ item }}"
  loop: "{{ yaml_list }}"
  when: lookup('file', item) is search('kind\:\ Namespace')

(not tested)

-- Vladimir Botka
Source: StackOverflow

4/30/2019
  - name: find config files
    command: 'find /directory/files/ -type f \( -iname \*.yml -o -iname \*.yaml \)'
    register: yaml_files

  - name: Create namespace first
    command: 'kubectl apply -f {{ item }}'
    with_items:
      - "{{ yaml_files.stdout_lines }}"
    when: lookup('file', item) is search('kind\:\ Namespace')

It should work for you

-- coolinuxoid
Source: StackOverflow