- name: add rules to an acl token
  consul_acl:
    mgmt_token: '{{mgmt_token}}'
    host: '{{acl_host}}'
    name: 'ACL rule for testing'
    rules:
      - key: 'somekey'
        policy: write
  register: test_acl

- name: cleanup from previous failed runs
  consul_kv: key={{item}} state=absent token='{{test_acl.token}}'
  with_items:
    - somekey

- name: add a kv pair to the kv store
  consul_kv: key=somekey value=somevalue token='{{test_acl.token}}'
  register: new_key

- name: verify new key
  assert:
    that:
      - new_key.key == 'somekey'
      - new_key.data.Value == 'somevalue'
      - new_key.changed == true

- name: add an existing kv to the kv store
  consul_kv: key=somekey value=somevalue token='{{test_acl.token}}'
  register: existing_key

- name: verify existing key cause no change
  assert:
    that:
      - existing_key.key == 'somekey'
      - existing_key.data.Value == 'somevalue'
      - existing_key.changed == False

- name: remove an existing kv from the kv store
  consul_kv: key=somekey state=absent token='{{test_acl.token}}'
  register: remove_key

- name: verify removal causes change and existing value is returned
  assert:
    that:
      - remove_key.key == 'somekey'
      - remove_key.data.Value == 'somevalue'
      - remove_key.changed == True

- name: attempting to remove an non-existant kv from the kv store causes no change
  consul_kv: key=not_present state=absent token='{{test_acl.token}}'
  register: non_existant_key

- name: verify removal causes change and existing value is returned
  assert:
    that:
      - non_existant_key.key == 'not_present'
      - non_existant_key.data == None
      - non_existant_key.changed == False

- name: Add a key to lookup with the lookup capability
  consul_kv: key='key/to/lookup_{{item}}' value='somevalue_{{item}}' token='{{test_acl.token}}'
  with_items:
    - one
    - two
  register: lookup_keys

  # necessary to make the new token available to the
- set_fact: acl_token={{test_acl.token}}

- name: kv test
  assert:
    that:
      - "{{ item is match('somevalue_one')}}"
  with_consul_kv:
    - 'key/to/lookup_one token={{acl_token}}'


- name: recursive kv lookup test
  assert:
    that:
      - "{{ item is match('somevalue_(one|two)')}}"
  with_consul_kv:
    - 'key/to recurse=true token={{acl_token}}'

- name: remove test acl rule
  consul_acl:
    mgmt_token: '{{mgmt_token}}'
    host: '{{acl_host}}'
    token: '{{test_acl.token}}'
    state: absent
