# add helm repos for autoscalers
- name: Add cluster autoscaler chart repo
  kubernetes.core.helm_repository:
    name: autoscaler
    repo_url: "https://icr.io/helm/iks-charts"

# deploy cluster autoscaler for IBM Cloud IKS "cas" cluster
- name: Deploy Cluster Autoscaler (IKS)
  kubernetes.core.helm:
    name: cas
    chart_ref: autoscaler/cluster-autoscaler
    release_namespace: cas
    set_values:
      - value: "'autoDiscovery.clusterName'={{ clusters_iks['iks_cas'] }}"
        value_type: string
    environment:
      KUBECONFIG: "{{ lookup('vars', 'KUBECONFIG_CAS_IKS') }}"

# deploy karpenter for IBM Cloud IKS "karpenter" cluster
- name: Deploy Karpenter Autoscaler (IKS)
  kubernetes.core.helm:
    name: karpenter
    chart_ref: pfeifferj/ibm-cloud-karpenter
    release_namespace: karpenter
  environment:
    KUBECONFIG: "{{ lookup('vars', 'KUBECONFIG_KARPENTER_IKS') }}"
  when: run_iks
  tags:
    - iks

- name: Create service account token for Prometheus
  kubernetes.core.k8s:
    api_version: v1
    kind: ServiceAccount
    namespace: monitoring
    name: prometheus-sa
  environment:
    KUBECONFIG: "{{ lookup('vars', 'KUBECONFIG_' + item | upper + '_IKS') }}"
  loop:
    - karpenter
    - cas

- name: Retrieve the token for Prometheus SA
  kubernetes.core.k8s_info:
    api_version: v1
    kind: Secret
    namespace: monitoring
    label_selectors:
      - "kubernetes.io/service-account.name=prometheus-sa"
  register: prometheus_sa_token
  environment:
    KUBECONFIG: "{{ lookup('vars', 'KUBECONFIG_' + item | upper + '_IKS') }}"
  loop:
    - karpenter
    - cas

- name: Set Prometheus token fact
  set_fact:
    "IKS_PROM_TOKEN_{{ item | upper }}": "{{ item.data.token | b64decode }}"
  with_items: "{{ prometheus_sa_token.resources }}"

- name: Deploy Prometheus for monitoring
  kubernetes.core.helm:
    name: prometheus
    chart_ref: stable/prometheus
    release_namespace: monitoring
    create_namespace: true
  environment:
    KUBECONFIG: "{{ lookup('vars', 'KUBECONFIG_' + item | upper + '_IKS') }}"
  loop:
    - karpenter
    - cas

- name: Get Prometheus endpoint
  kubernetes.core.k8s_info:
    api_version: v1
    kind: Service
    namespace: monitoring
    name: prometheus-server
  register: prometheus_svc
  environment:
    KUBECONFIG: "{{ lookup('vars', 'KUBECONFIG_' + item | upper + '_IKS') }}"
  loop:
    - karpenter
    - cas

- name: Set Prometheus endpoint fact
  set_fact:
    "IKS_PROM_ENDPOINT_{{ item | upper }}": "http://{{ item.spec.clusterIP }}:{{ item.spec.ports[0].port }}"
  loop: "{{ prometheus_svc.resources }}"
