簡體   English   中英

Ansible include_vars進入字典

[英]Ansible include_vars into dictionary

在我的ansible劇本中,我將目錄列表讀入列表。 然后,我想從每個目錄中讀取一個“ config.yml”文件並將其內容放入字典中,以便可以通過該字典中的目錄名稱引用config-data。 第一部分沒有問題,但是我無法使第二部分工作:

步驟1,加載目錄:

- name: Include directories
  include_vars:
  file: /main-config.yml
  name: config

步驟2,從目錄加載配置:

- name: load deploymentset configurations
  include_vars:
    file: /path/{{ item }}/config.yml
    name: "allconfs.{{ item }}"   ## << This is the problematic part 
  with_items:
    - "{{ config.dirs }}"

我嘗試了諸如"allconfs['{{ item }}'] ,但似乎都無法正常工作。劇本已成功完成,但數據不在詞典中。我也嘗試過預先定義外部詞典,但沒有要么工作。

配置文件本身非常簡單:

/main-config.yml:

dirs:
- dir1
- dir2
- dir3

/path/dir1/config.yml:

some_var: "some_val"
another_var: "another val"

我希望能夠然后像這樣訪問config.yml文件的值:

{{ allconfs.dir1.some_var }}

嘗試Konstantins方法的更新

  - name: load deploymentset configurations
    include_vars:
      file: /repo/deploymentsets/{{ item }}/config.yml
      name: "default_config"
    with_items:
    - "{{ config.deploymentsets }}"
    register: default_configs


  - name: combine configs
    set_fact:
      default_configs: "{{ dict(default_configs.results | json_query('[].[item, ansible_facts.default_config]')) }}"

錯誤信息:

fatal: [127.0.0.1]: FAILED! => {"failed": true, "msg": "Unexpected templating type error occurred on ({{ dict(default_configs.results | json_query('[].[item, ansible_facts.default_config]')) }}): <lambda>() takes exactly 0 arguments (1 given)"}

這是我的一個項目中具有類似功能的一段代碼:

- name: Load config defaults
  include_vars:
    file: "{{ item }}.yml"
    name: "default_config"
  with_items: "{{ config_files }}"
  register: default_configs
  tags:
    - configuration

- name: Combine configs into one dict
  # Здесь мы делаем словарь вида
  # default_configs:
  #   config_name_1: { default_config_object }
  #   config_name_2: { default_config_object }
  #   config_name_3: { default_config_object }
  #   ...
  set_fact:
    default_configs: "{{ dict(default_configs.results | json_query('[].[item, ansible_facts.default_config]')) }}"
  tags:
    - configuration

default_config是用於臨時加載var數據的虛擬var。
訣竅是使用register: default_configsinclude_vars並通過以下任務將其解析以除去不必要的字段。

AFAIK無法創建包含多個include_vars的單個字典。 根據我的測試,它將為每個包含的目錄創建單獨的字典。 您可以改用以下方法。

刪除所有allconfs. 從您的變量名。

- name: load deploymentset configurations
  include_vars:
    file: /path/{{ item }}/config.yml
    name: "{{ item }}"
  with_items:
    - "{{ config.dirs }}"

然后,您可以直接使用

debug:
  msg: "{{ dir1.some_var }}"
with_items: "{{ config.dirs }}"

或者,如果您需要遍歷包含目錄中的所有變量,請使用此方法(從Ansible提出:如何從另一個變量構造一個變量,然后獲取其值 )。

debug:
  msg: "{{ hostvars[inventory_hostname][item].some_var }}"
with_items: "{{ config.dirs }}"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM