---
title: TektonでTestcontainersを使うメモ (要privileged)
tags: ["Tekton", "Testcontainers", "Kubernetes"]
categories: ["Dev", "CI", "Tekton"]
date: 2022-07-05T07:16:50Z
updated: 2022-09-15T09:06:33Z
---

Tektonで実行したいテストコードがTestcontainersを使っているため、TektonでTestcontainersを試しました。

[Docker-in-Docker (DinD)](https://www.testcontainers.org/supported_docker_environment/continuous_integration/dind_patterns/#docker-in-docker)以外に実現する方法がわかりませんでした。
KubernetesでDinDを使うには`privileged: true`の設定が必要なので、セキュリティ観点でイマイチですが、実行した方法をメモします。

[こちらのサンプル](https://github.com/eddumelendez/testcontainers-samples/blob/main/tekton.yaml)を参考にしました。


Pipelineの定義

```yaml
cat <<'EOF' > unit-test.yaml
---
apiVersion: tekton.dev/v1beta1
kind: Pipeline
metadata:
  name: unit-test
spec:
  workspaces:
  - name: cache
  tasks:
  - name: mvn-test
    workspaces:
    - name: cache
      workspace: cache
    taskSpec:
      volumes:
      - name: dind-storage
        emptyDir: { }
      - name: dind-socket
        emptyDir: { }
      workspaces:
      - name: cache
      sidecars:
      - name: docker
        image: docker:20.10-dind
        securityContext:
          privileged: true
        volumeMounts:
        - mountPath: /var/lib/docker
          name: dind-storage
        - mountPath: /var/run/
          name: dind-socket
      steps:
      - name: git-clone
        image: alpine/git
        workingDir: /workspace
        script: |
          #!/usr/bin/env sh
          git clone https://github.com/categolj/blog-api 
      - name: mvn-test
        image: eclipse-temurin:17
        workingDir: /workspace
        volumeMounts:
        - mountPath: /var/run/
          name: dind-socket
        script: |
          #!/bin/bash
          set -ex
          cd blog-api
          rm -rf ~/.m2
          mkdir -p $(workspaces.cache.path)/.m2
          ln -fs $(workspaces.cache.path)/.m2 ~/.m2          
          ./mvnw test -V
EOF
```

キャッシュ用のPVC

```yaml
cat <<'EOF' > unit-test-pipeline-cache.yaml
---
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: unit-test-pipeline-cache
spec:
  accessModes:
  - ReadWriteOnce
  resources:
    requests:
      storage: 1Gi
EOF
```

PipelineRunの定義

```yaml
cat <<'EOF' > unit-test-run.yaml
---
apiVersion: tekton.dev/v1beta1
kind: PipelineRun
metadata:
  generateName: unit-test-run-
spec:
  pipelineRef:
    name: unit-test
  workspaces:
  - name: cache
    persistentVolumeClaim:
      claimName: unit-test-pipeline-cache
EOF
```

実行方法

```yaml
kubectl apply -f unit-test.yaml
kubectl apply -f unit-test-pipeline-cache.yaml
kubectl create -f unit-test-run.yaml
```
