- hosts: localhost
  connection: local
  gather_facts: false

  vars:
    # these are the defaults from the consul-vagrant cluster setup
    - mgmt_token: '4791402A-D875-4C18-8316-E652DBA53B18'
    - acl_host: '11.0.0.2'
    - metadata_json: '{"clearance": "top_secret"}'

  pre_tasks:
    # this works except for the KV_lookusp
    - name: check that the consul agent is running locally
      local_action: wait_for port=8500 timeout=5
      ignore_errors: true
      register: consul_running

  roles:

    - {role: test_consul_service,
       when: not consul_running.failed is defined}

    - {role: test_consul_kv,
       when: not consul_running.failed is defined}

    - {role: test_consul_acl,
       when: not consul_running.failed is defined}

    - {role: test_consul_session,
       when: not consul_running.failed is defined}

  tasks:

    - name: setup services with passing check for consul inventory test
      consul:
        service_name: nginx
        service_port: 80
        script: "sh -c true"
        interval: 5
        token: '4791402A-D875-4C18-8316-E652DBA53B18'
        tags:
          - dev
          - master


    - name: setup failing service for inventory test
      consul:
        service_name: nginx
        service_port: 443
        script: "sh -c false"
        interval: 5
        tags:
          - qa
          - slave

    - name: setup ssh service for inventory test
      consul:
        service_name: ssh
        service_port: 2222
        script: "sh -c true"
        interval: 5
        token: '4791402A-D875-4C18-8316-E652DBA53B18'

    - name: update the Anonymous token to allow anon access to kv store
      consul_acl:
        mgmt_token: '{{mgmt_token}}'
        host: '{{acl_host}}'
        token: 'anonymous'
        rules:
          - key: ''
            policy: write
      register: inventory_token

    - name: add metadata for the node through kv_store
      consul_kv: "key=ansible/metadata/dc1/consul-1 value='{{metadata_json}}'"

    - name: add metadata for the node through kv_store
      consul_kv: key=ansible/groups/dc1/consul-1 value='a_group, another_group'

    - name: warn that tests are ignored if consul agent is not running
      debug: msg="A consul agent needs to be running inorder to run the tests. To setup a vagrant cluster for use in testing see http://github.com/sgargan/consul-vagrant"
      when: consul_running.failed is defined