---

- name: create an ACL
  consul_acl:
    host: "{{ acl_host }}"
    mgmt_token: "{{ mgmt_token }}"
    name: "{{ test_consul_acl_token_name }}"
    rules:
      - key: "foo"
        policy: read
  register: created_acl

- name: update ACL's rules
  consul_acl:
    host: "{{ acl_host }}"
    mgmt_token: "{{ mgmt_token }}"
    token: "{{ created_acl.token }}"
    rules:
      - key: "foo"
        policy: write
      - key: "moo"
        policy: deny
  register: updated_acl

- name: verify updated ACL's rules
  assert:
    that:
      - updated_acl.changed
      - updated_acl.operation == "update"
      - updated_acl.token | length == 36
      - (updated_acl.rules | json_query("key.foo.policy")) == "write"
      - (updated_acl.rules | json_query("key.moo.policy")) == "deny"

- name: update already updated rule
  consul_acl:
    host: "{{ acl_host }}"
    mgmt_token: "{{ mgmt_token }}"
    token: "{{ created_acl.token }}"
    rules:
      - key: "foo"
        policy: write
      - key: "moo"
        policy: deny
  register: doubly_updated_acl

- name: verify idempotence when setting rules
  assert:
    that:
      - not doubly_updated_acl.changed

- name: update to remove all ACL's rules
  consul_acl:
    host: "{{ acl_host }}"
    mgmt_token: "{{ mgmt_token }}"
    token: "{{ created_acl.token }}"
    rules: []
  register: updated_acl

- name: verify ACL has no rules
  assert:
    that:
      - updated_acl.changed
      - updated_acl.token | length == 36
      - updated_acl.rules == {}

- name: clean up
  consul_acl:
    host: "{{ acl_host }}"
    mgmt_token: "{{ mgmt_token }}"
    token: "{{ created_acl.token }}"
    state: absent
