---
apiVersion: tekton.dev/v1beta1
kind: Task
metadata:
  name: ibmcloud-secrets-manager-get
  labels:
    app.kubernetes.io/version: "0.1"
  annotations:
    tekton.dev/categories: IBM Cloud
    tekton.dev/pipelines.minVersion: "0.17.0"
    tekton.dev/tags: cli
    tekton.dev/displayName: "IBM Cloud Secrets Manager Get Secret"
    tekton.dev/platforms: "linux/amd64"
spec:
  description: >-
    This task retrieves a secret from IBM Cloud Secrets Manager using a key ID
  params:
    - name: KEY_ID
      description: An IBM Cloud Secrets Manager key ID
      type: string
      default: 968d7819-f2c5-7b67-c420-3c6bfd51521e
    - name: SECRETS_MANAGER_ENDPOINT_URL
      description: An IBM Cloud Secrets Manager instance endpoint URL (https://cloud.ibm.com/apidocs/secrets-manager/secrets-manager-v2#endpoints)
      type: string
      default: https://{instance_ID}.us-south.secrets-manager.appdomain.cloud
  results:
    - name: secret-value
      description: A secret value retrieved using the provided KEY_ID
  steps:
    - name: retrieve-key
      image: quay.io/openshift/origin-cli:4.7
      script: |
        #!/usr/bin/env bash
        set -x

        # Retrives the IBM Cloud API Key configured in a `deployer` cluster
        export IBMCLOUD_API_KEY=$(oc get secret ibm-secret -n kube-system -o jsonpath='{.data.apiKey}' | base64 -d)
        export AUTH_RESPONSE_JSON=$(curl -s -X POST \
          "https://iam.cloud.ibm.com/identity/token" \
          --header 'Content-Type: application/x-www-form-urlencoded' \
          --header 'Accept: application/json' \
          --data-urlencode 'grant_type=urn:ibm:params:oauth:grant-type:apikey' \
          --data-urlencode "apikey=${IBMCLOUD_API_KEY}")
        export ACCESS_TOKEN=$(echo $AUTH_RESPONSE_JSON | grep -o '"access_token":"[^"]*' | grep -o '[^"]*$')
        export SECRET_JSON=$(curl -s -X GET --location --header "Authorization: Bearer ${ACCESS_TOKEN}" --header "Accept: application/json" "$(params.SECRETS_MANAGER_ENDPOINT_URL)/api/v2/secrets/$(params.KEY_ID)")
        export SECRET=$(echo $SECRET_JSON |  grep -o '"payload":"[^"]*' | grep -o '[^"]*$')
        printf "${SECRET}" | tee $(results.secret-value.path)
