- name: Get influxdb organization ID
  delegate_to: localhost
  uri:
    url: '{{ influxdb_info.influxdb_url }}/api/v2/orgs'
    headers:
      Authorization: Token {{ influxdb_info.influxdb_operator_token }}
  register: response

- name: Parse influxdb orgID
  set_fact:
    influxdb_orgID: '{{ response.json.orgs | selectattr("name", "==", influxdb_info.influxdb_org) | map(attribute="id") | first }}'

- name: Get influxdb bucket ID
  delegate_to: localhost
  uri:
    url: '{{ influxdb_info.influxdb_url }}/api/v2/buckets?orgID={{ influxdb_orgID }}'
    headers:
      Authorization: Token {{ influxdb_info.influxdb_operator_token }}
  register: response

- name: Parse influxdb bucketID
  set_fact:
    influxdb_bucketID: '{{ response.json.buckets | selectattr("name", "==", "servers") | map(attribute="id") | first }}'

- name: Create influxdb token
  delegate_to: localhost
  uri:
    url: '{{ influxdb_info.influxdb_url }}/api/v2/authorizations'
    method: POST
    body_format: json
    status_code: 201
    headers:
      Authorization: Token {{ influxdb_info.influxdb_operator_token }}
      Content-Type: application/json
    body: |
      {
        "description": "{{ inventory_hostname }}",
        "orgID": "{{ influxdb_orgID }}",
        "permissions": [{ "action": "write", "resource": { "type": "buckets", "id": "{{ influxdb_bucketID }}" } }]
      }
  register: response

- name: Parse influxdb token
  set_fact:
    influxdb_token: '{{ response.json.token }}'

# Ansible’s passwordstore lookup plugin should be able to do that but is pretty broken,
# so we do it manually.
- name: Store influxdb token in password store
  delegate_to: localhost
  command:
    cmd: 'pass insert --force --multiline {{ ("vm/" if is_virtual else "host/")~inventory_hostname }}'
    stdin: '{{ password | to_nice_yaml(sort_keys=false) }}influxdb_token: {{ influxdb_token }}'