GitLab-CI Kubernetes Variables aren't set?

2020-07-07 01:41发布

问题:

I'm trying to setup auto deploy with Kubernetes on GitLab. I've successfully enabled Kubernetes integration in my project settings.

Well, the integration icon is green and when I click "Test Settings" I see "We sent a request to the provided URL":

My deployment environment is the Google Container Engine.

Here's the auto deploy section in my gitlab-ci.yml config:

deploy:
  image: registry.gitlab.com/gitlab-examples/kubernetes-deploy
  stage: deploy
  script:
    - export
    - echo CI_PROJECT_ID=$CI_PROJECT_ID
    - echo KUBE_URL=$KUBE_URL
    - echo KUBE_CA_PEM_FILE=$KUBE_CA_PEM_FILE
    - echo KUBE_TOKEN=$KUBE_TOKEN
    - echo KUBE_NAMESPACE=$KUBE_NAMESPACE

    - kubectl config set-cluster "$CI_PROJECT_ID" --server="$KUBE_URL" --certificate-authority="$KUBE_CA_PEM_FILE"
    - kubectl config set-credentials "$CI_PROJECT_ID" --token="$KUBE_TOKEN"
    - kubectl config set-context "$CI_PROJECT_ID" --cluster="$CI_PROJECT_ID" --user="$CI_PROJECT_ID" --namespace="$KUBE_NAMESPACE"
    - kubectl config use-context "$CI_PROJECT_ID"

When I look at the results, the deploy phase fails. This is because all the KUBE variables are empty.

I'm not having much luck with the Kubernetes services beyond this point. Am I missing something?

回答1:

As it turns out, the Deployment Variables will not materialise unless you have configured and referenced an Environment.

Here's what the .gitlab-ci.yaml file looks like with the environment keyword:

deploy:
  image: registry.gitlab.com/gitlab-examples/kubernetes-deploy
  stage: deploy
  environment: production
  script:
    - export
    - echo CI_PROJECT_ID=$CI_PROJECT_ID
    - echo KUBE_URL=$KUBE_URL
    - echo KUBE_CA_PEM_FILE=$KUBE_CA_PEM_FILE
    - echo KUBE_TOKEN=$KUBE_TOKEN
    - echo KUBE_NAMESPACE=$KUBE_NAMESPACE

    - kubectl config set-cluster "$CI_PROJECT_ID" --server="$KUBE_URL" --certificate-authority="$KUBE_CA_PEM_FILE"
    - kubectl config set-credentials "$CI_PROJECT_ID" --token="$KUBE_TOKEN"
    - kubectl config set-context "$CI_PROJECT_ID" --cluster="$CI_PROJECT_ID" --user="$CI_PROJECT_ID" --namespace="$KUBE_NAMESPACE"
    - kubectl config use-context "$CI_PROJECT_ID"