Ansible - multiple roles

与世无争的帅哥 提交于 2019-12-11 05:25:23

问题


I am trying to run multiple roles using with_items command, however I am getting error:

"ERROR! 'item' is undefined"

role.yml:

---
- hosts: '{{ host }}'
  become: yes

  roles:
    - role: "{{item}}"
      with_items: "{{ roles }}"

Here is my command:

ansible-playbook -i ./inventory/Dev ./playbooks/role.yml --extra-vars='{"host": "db", "roles": ["mysql", "apache"]}'

回答1:


You cannot do it this way. with_ loops are not valid for roles.

If anything, you need to provide a list of roles to the roles: directive, so the syntax would be just like for the list of host groups hosts: '{{ host }}'. The problem is: Ansible does not resolve the variable for roles, so roles: '{{ roles }}' does not work.


What you can do, however, is to use include_role module in which you can access the variables.

No, include_role module doesn't take {{ item }} from the with_items as a value for name either.

So the only workaround I can think of (assuming you don't want to process the JSON beforehand) is to the include the roles statically:

tasks:
  - include_role:
      name: "mysql"
    when: "'mysql' in roles"
  - include_role:
      name: "apache"
    when: "'apache' in roles"

The roles need to exist on the control machine anyway, so all their names are predefined.




回答2:


{{item}} is a variable which you have not defined. You need to define it which you can do by using the extra-vars parameter that you are already using for 'host' and 'roles'

e.g.

ansible-playbook -i ./inventory/Dev ./playbooks/role.yml --extra-vars='{"item": "something", "host": "db", "roles": ["mysql", "apache"]}'


来源:https://stackoverflow.com/questions/42947301/ansible-multiple-roles

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!