【问题标题】:Ansible: variable in variable / loop or iterating through itemAnsible:变量/循环中的变量或迭代项目
【发布时间】:2018-07-19 23:32:40
【问题描述】:

这是一个我们必须调试的简单 vars 文件 ./roles/test/vars/{{ ansible_distribution|lower }}/apt-packages.yml

  packages:
    required:
      - htop
#      - aptitude

  package:
    htop:
      allow_unauthenticated: no
      autoclean: no
      autoremove: no
      cache_valid_time: 0
#    default_release:
      force: no
      force_apt_get: no
      install_recommends: yes
      only_upgrade: no
      purge: no 
      state: latest
      update_cache: yes
      upgrade: no

这是一个简单的调试任务 ./roles/test/tasks/main.yml

- name: "Register variable"
  include_vars:
    #dir: vars/ubuntu
    file: "vars/{{ ansible_distribution|lower }}/apt-packages.yml"
    name: apt_install

- name: "This a test"
  apt:
    name: "{{item}}"
    cache_valid_time: "{{ apt_install.package[item].cache_valid_time }}"
    state: "{{ apt_install.package[item].state }}"
    update_cache: "{{ apt_install.package[item].update_cache }}"
  with_items: "{{ apt_install.packages.required }}"

./roles/test-playbook.yml

- name: "playbook test"
  hosts: localhost
  roles:
    - role: test
  become: true
  become_user: root
  become_method: sudo

使用以下答案stackoverflow.com/questions/29276198,我们正在尝试遍历项目并获取项目相关值。

Tasks 可以很好地循环遍历项目,但无法使用 [item] 语法或我们测试过的任何其他语法检索相关变量。

我们总是犯同样的错误

致命:[本地主机]:失败! => { "msg": "任务包含一个带有未定义变量的选项。错误是:dict object has no element [u'htop']

但是直接调用变量是有效的

- name: "echo variable test"
  debug: 
    msg: "{{ apt_install.package.htop.allow_unauthenticated }}"

获取变量的当前循环值并在另一个变量中使用它来检索相关值的正确语法是什么......(在同一任务中)?

到目前为止,是我们一直在兜圈子!

亲切的问候

【问题讨论】:

    标签: ansible


    【解决方案1】:

    这完全可以使用loop / loop_control 而不是with_items

    - name: "This a test"
      apt:
        name: "{{item}}"
        cache_valid_time: "{{ apt_install.package[item].cache_valid_time }}"
        state: "{{ apt_install.package[item].state }}"
        update_cache: "{{ apt_install.package[item].update_cache }}"
      loop: "{{ apt_install.packages.required|flatten(levels=1) }}"
      loop_control:
        index_var: index
    

    因此,我们可以为每个包和每个发行版定义不同的设置。 现在我可以将每个包的设置导出到不同的 var 文件中。

    学习很难:)

    【讨论】:

    • 未验证这一点,但使用“flatten(level=1)”看起来很有希望,但不确定“loop_control.index_var: index”是否正确,当在任务正文。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-21
    • 2022-01-23
    • 2015-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多