在目录中找到包含特定内容的文件,然后仅对该文件运行命令

时间:2019-04-30 10:24:44

标签: kubernetes ansible

- 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 }}"

我只想在文件包含“种类:命名空间”时运行命令,但是它将与找到的所有文件一起运行。

2 个答案:

答案 0 :(得分:0)

尝试search

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

(未经测试)

答案 1 :(得分:0)

  - 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')

它应该为您工作