使用with_items时如何访问项目外部的var?

时间:2019-06-10 15:26:12

标签: ansible

我有一个使用with_items的角色:

- name: Create backup config files
  template:
    src: "config.yml.j2"
    dest: "/tmp/{{ project }}_{{ env }}_{{ item.type }}.yml"
  with_items:
    - "{{ backups }}"

我可以像往常一样访问item.type,但不能访问在集合外部定义的projectenv

deploy / main.yml

- hosts: ...
  vars:
    project: ...
    rails_env: qa

  roles:
    - role: ../../../roles/deploy/dolly
      project: "{{ project }}"
      env: "{{ rails_env }}"
      backups:
        - type: mysql
          username: ... 
          password: ...

我得到的错误是:

Error was a <class 'ansible.errors.AnsibleError'>, original message: An unhandled exception occurred while templating '{{ project }}'

模板config.j2.yml为:

type: {{  item.type }}
project: {{ project }}
env: {{ env }}
database:
  username: {{ item.username }}
  password: {{ item.password }}

1 个答案:

答案 0 :(得分:0)

事实证明,无法重新定义与现有var相同名称的var,因此project: {{ project }}总是会因错误而失败。

相反,可以省略project,而可以使用vars中的现有定义。

- hosts: ...
  vars:
    project: ... # <- already defined here

  roles:
    - role: ../../../roles/deploy/dolly
      backups:
        - type: mysql
          username: ... 
          password: ...

如果未在vars中定义var,则可以在角色中定义:

- hosts: ...
  vars:
    name: ...

  roles:   
    - role: ../../../roles/deploy/dolly
      project: "{{ name }}" # <- define here
      backups:
        - type: mysql
          username: ... 
          password: ...