【问题标题】:Execute all yaml files from different directory执行来自不同目录的所有 yaml 文件
【发布时间】:2021-06-21 20:55:31
【问题描述】:

我创建了一个包含多个子任务的目录,但我无法让 Ansible 从指定目录中运行所有任务。 脚本如下所示:

---
- hosts: localhost
  connection: local
  tasks:

# tasks file for desktop
  - name: "LOADING ALL TASKS FROM THE 'SUB_TASKS' DIRECTORY"
    include_vars:
      dir: sub_tasks
      extensions:
        - 'yml'

这是输出:

plbchk main.yml --check
[WARNING]: provided hosts list is empty, only localhost is available. Note that the implicit localhost does not
match 'all'

PLAY [localhost] ****************************************************************************************************

TASK [Gathering Facts] **********************************************************************************************
ok: [localhost]

TASK [LOADING ALL TASKS FROM THE 'SUB_TASKS' DIRECTORY] *************************************************************
fatal: [localhost]: FAILED! => {"ansible_facts": {}, "ansible_included_var_files": [], "changed": false, "message": "/home/user/Documents/ansible-roles/desktop/tasks/sub_tasks/gnome_tweaks.yml must be stored as a dictionary/hash"}

PLAY RECAP **********************************************************************************************************
localhost                  : ok=1    changed=0    unreachable=0    failed=1    skipped=0    rescued=0    ignored=0

我尝试了各种方法让它运行子任务,但无济于事。

我想这样做,而不是创建一个包含所有任务的大文件。这可能吗?

【问题讨论】:

    标签: ansible yaml


    【解决方案1】:

    include_vars 不包含 tasks ,这是包含 vars (顾名思义)。另外,如果您检查错误消息,它会显示“must be stored as a dictionary/hash.

    fatal: [localhost]: FAILED! => {"ansible_facts": {}, "ansible_included_var_files": [], "changed": false, "message": "/home/user/Documents/ansible-roles/desktop/tasks/sub_tasks/gnome_tweaks.yml must be stored as a dictionary/hash"}
    

    解决方案:

    您需要使用include_task来进行您的尝试。查看here

    这是一个完整/最小的工作示例,这里我们列出了提供的目录中存在的yamlyml 文件,然后对所有文件循环运行include_tasks

    ---
    
    - name: Sample playbook
      connection: local
      gather_facts: false
      hosts: localhost
    
      tasks:
      - name: Find all the yaml files in the directory
        find:
          paths: /home/user/Documents/ansible-roles/desktop/tasks
          patterns: '*.yaml,*.yml'
          recurse: yes
        register: file_list
    
      - name: show the yaml files present
        debug: msg="{{ item }}"
        loop: "{{ file_list.files | map(attribute='path') | list }}"
    
      - name: Include task list in play
        include_tasks: "{{ item }}"
        loop: "{{ file_list.files | map(attribute='path') | list }}"
    

    【讨论】:

    • 感谢您的回复。我已经尝试过include_tasks 但它不起作用,因为我需要执行指定文件夹中的所有任务...
    • 查看更新的答案,我已经更新了。
    • 抱歉回复晚了,但这是一个很好的答案!非常感谢!
    猜你喜欢
    • 2022-01-04
    • 2012-02-18
    • 1970-01-01
    • 1970-01-01
    • 2011-01-04
    • 2012-01-27
    • 1970-01-01
    • 2015-02-01
    相关资源
    最近更新 更多