# =====================================================================================================================
# === GCP Auth template variant (provide ADC authentification)
# === https://cloud.google.com/docs/authentication/application-default-credentials
# =====================================================================================================================
spec:
  inputs:
    gcp-oidc-aud:
      description: The `aud` claim for the JWT token _(only required for [OIDC authentication](https://docs.gitlab.com/ee/ci/cloud_services/google_cloud/)))_
      default: $CI_SERVER_URL
    gcp-oidc-account:
      description: Default Service Account to which impersonate with OpenID Connect authentication
      default: ''
    gcp-oidc-provider:
      description: Default Workload Identity Provider associated with GitLab to [authenticate with OpenID Connect](https://docs.gitlab.com/ee/ci/cloud_services/google_cloud/)
      default: ''
---
variables:
  GCP_OIDC_AUD: $[[ inputs.gcp-oidc-aud ]]
  GCP_OIDC_ACCOUNT: $[[ inputs.gcp-oidc-account ]]
  GCP_OIDC_PROVIDER: $[[ inputs.gcp-oidc-provider ]]

.gcp-provider-auth:
  before_script:
    - set -e
    - echo -e "[\\e[1;94mINFO\\e[0m] Installing GCP authentication with env GOOGLE_APPLICATION_CREDENTIALS file"
    - echo $GCP_JWT > "$CI_BUILDS_DIR/.auth_token.jwt"
    - |-
      cat << EOF > "$CI_BUILDS_DIR/google_application_credentials.json"
      {
        "type": "external_account",
        "audience": "//iam.googleapis.com/${GCP_OIDC_PROVIDER}",
        "subject_token_type": "urn:ietf:params:oauth:token-type:jwt",
        "token_url": "https://sts.googleapis.com/v1/token",
        "credential_source": {
          "file": "$CI_BUILDS_DIR/.auth_token.jwt"
        },
        "service_account_impersonation_url": "https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/${GCP_OIDC_ACCOUNT}:generateAccessToken"
      }
      EOF
    - export GOOGLE_APPLICATION_CREDENTIALS="$CI_BUILDS_DIR/google_application_credentials.json"


.python-base:
  image: $PYTHON_IMAGE
  services:
    - name: "$TBC_TRACKING_IMAGE"
      command: ["--service", "python", "6.11.1"]
  variables:
    GCP_JWT: $GCP_JWT
  before_script:
    - !reference [.gcp-provider-auth, before_script]
    - !reference [.python-scripts]
    - install_ca_certs "${CUSTOM_CA_CERTS:-$DEFAULT_CA_CERTS}"
    - cd ${PYTHON_PROJECT_DIR}
    - guess_build_system

  id_tokens:
    GCP_JWT:
      aud: "$GCP_OIDC_AUD"
