使用具有多个权限的rabbitmq_user模块

时间:2017-01-14 14:05:51

标签: ansible

我正在处理RabbitMQ Ansible角色,我必须编写专门用于用户创建和配置的任务。

我在我的剧本中定义了以下变量:

vars:  
  - rabbitmq_resources:
      - type_resource: "vhost"
        name: "/test"
        node: "rabbit@host1ansible"
      - type_resource: "vhost"
        name: "/other"
        node: "rabbit@host1ansible"
      - type_resource: "user"
        name: "rabbitmqadmin"
        password: "rabbitmqadmin"
        permissions:
          - vhost: "/test"
            configure_priv: ".*"
            read_priv: ".*"
            write_priv: ".*"
          - vhost: "/other"
            configure_priv: ".*"
            read_priv: ".*"
            write_priv: ".*"
        tags: "administrator"
        state: present

然后我想编写专用于用户处理的任务代码:

- name: Creating RabbitMQ users
  rabbitmq_user:
    name: "{{ item.name|mandatory }}"
    permissions:
      vhost: "{{ item.value.vhost }}"
      configure_priv: "{{ item.value.configure_priv }}"
      read_priv: "{{ item.value.read_priv }}"
      write_priv: "{{ item.value.write_priv }}"
    tags: "{{ item.tags }}"
    state: present
  with_subelements:
    - "{{ rabbitmq_resources }}"
    - type_resource
    - permissions
  when: item.type_resource == "user"

上面的语法生成一条消息"子元素查找需要两个或三个项目的列表,可选的第三个项目必须是带有标记skip_missing"的字典。

我测试了各种循环语法(with_items,with_subelements,with_dict),但我仍然无法找到正确的语法。

帮助将不胜感激。

2 个答案:

答案 0 :(得分:1)

你的方法不正确。您只需要从dict中选择用户并循环它:

- name: Creating RabbitMQ users
  rabbitmq_user:
    name: "{{ item.name | mandatory }}"
    permissions: "{{ item.permissions | default(omit) }}"
    tags: "{{ item.tags | default(omit) }}"
    state: present
  with_items:
    - "{{ rabbitmq_resources | selectattr('type_resource','equalto','user') | list }}"

答案 1 :(得分:1)

最后,我决定用JSON数组替换权限列表:
permissions: [{"vhost": "/test","configure_priv": ".*","read_priv": ".*","write_priv": ".*"}, {"vhost": "/other","configure_priv": ".*","read_priv": ".*","write_priv": ".*"}]

现在任务代码:
- name: Creating RabbitMQ users rabbitmq_user: name: "{{ item.name|mandatory }}" permissions: "{{ item.permissions }}" tags: "{{ item.tags }}" state: present with_items: "{{ rabbitmq_resources }}" when: item.type_resource == "user"

并且工作正常(不包括默认值代码)。