<p>I have created a workload on Rancher. This workload created from an image which is hosted on a gitlab-ci project registry.</p>

<p>I want to force rancher to download a new version of this image and upgrade workload.</p>

<p>I want to do this from a .gitlab-ci.yml script. How to do this with Rancher <strong>version 2</strong>? With Rancher 1.6 I used this script:</p>

<pre><code>deploy:
  stage: deploy
  image: cdrx/rancher-gitlab-deploy
  script:
    - upgrade --stack mystack --service myservice --no-start-before-stopping
</code></pre>

<p>In rancher 2, much of the management of workloads is delegated to Kubernetes via its api or CLI (kubectl).</p>

<p>You could patch the deployment to specify a new image/version, but if you are using a tag like <code>:latest</code> which moves, you will need to force Kubernetes to redeploy the pods by changing something about the deployment spec. </p>

<p>One common way to do this is to change/add an environment variable, which forces a redeploy. </p>

<p>In Gitlab, set two variables in your gitlab project or group to pass authentication information into the build.</p>

<p>The <code>kubectl patch</code> will update or add an environment variable called <code>FORCE_RESTART_AT</code> on your deployment's container that will force a redeploy each time it is set because Gitlab's pipeline ID changes. </p>

<p>You will need to specify the namespace, the name of your deployment, the name of the container and the image. If the image tag is changing, there is no need to supply the environment variable. If you are using <code>:latest</code>, be sure that the your container's <code>imagePullPolicy: Always</code> is set, which is the default if Kubernetes detects an image using <code>:latest</code>.</p>

<p>The image <code>diemscott/rancher-cli-k8s</code> is a simple image derived from <code>rancher/cli</code> that also includes <code>kubectl</code>.</p>

<pre><code>RANCHER_SERVER_URL=https://rancher.example.com
RANCHER_API_TOKEN="token-sd5kk:d27nrsstx6z5blxgkmspqv94tzkptnrpj7rkcrt7vtxt28tvw4djxp"

deploy:
  stage: deploy
  image: diemscott/rancher-cli-k8s:v2.0.2
  script:
    - rancher login "$RANCHER_SERVER_URL" -t "$RANCHER_API_TOKEN"
    - rancher kubectl --namespace=default patch deployment nginx --type=strategic -p '{"spec":{"template":{"spec":{"containers":[{"name":"nginx","image": "nginx","env":[{"name":"FORCE_RESTART_AT","value":"$CI_PIPELINE_ID"}]}]}}}}'
</code></pre>
