Skip to content

Deploy application to Kubernetes with OpenTofu

This tutorial contains a pipeline that deploys an feedback application to a Kubernetes cluster.

This example uses local state

This example does not configure state backend and thus stores the state locally. When managing real infrastructure, configure a persistent state storage, for example, with S3 bucket or Postgres database as the backend.

Prerequisites and preparing the Jenkins instance

See Deploy application to Kubernetes with Ansible tutorial for prerequisites and instruction for configuring access from the Jenkins instance to the Kubernetes cluster.

Configure the pipeline

First, create a new pipeline via New Item button in the right side menu of the Jenkins dashboard. The name of the pipeline could be for example Feedback-Deploy and it should be an pipeline.

In the configure pipeline view, scroll to the bottom and under Pipeline sub-header select Pipeline script. Copy the script from below to the Script textarea.

The pipeline deploys an example application to a Kubernetes cluster using OpenTofu configuration. The pipeline will first plan the deployment and then ask approval from an user before applying the plan to the target cluster.

Jenkinsfile
String d = "docs/tutorials/jenkins/opentofu-kubernetes"
def status = 0

pipeline {
  agent any
  environment {
    KUBE_CONFIG_PATH = credentials('kubeconfig')
    TF_VAR_namespace = "terraform-example"
  }
  stages {
    stage('Checkout') {
      steps {
        git branch: 'main', url: 'https://github.com/cicd-tutorials/feedback.git'
      }
    }
    stage('Plan') {
      agent { docker {
        image 'ghcr.io/opentofu/opentofu:latest'
        args '--entrypoint=""'
        reuseNode true
      } }
      steps {
        dir("iac/tf") {
          sh "tofu init -no-color"
          script {
            status = sh returnStatus: true, script: "tofu plan -no-color -detailed-exitcode -out ${env.BUILD_TAG}.plan"
          }
          stash includes: "${env.BUILD_TAG}.plan", name: 'plan'
        }
      }
    }
    stage('Apply') {
      agent { docker {
        image 'ghcr.io/opentofu/opentofu:latest'
        args '--entrypoint=""'
        reuseNode true
      } }
      when {
        beforeInput true
        equals expected: 2, actual: status
      }
      input {
        message 'Apply the plan?'
        ok 'Apply'
      }
      steps {
        dir("iac/tf") {
          unstash 'plan'
          sh """
            tofu init -no-color
            tofu apply -no-color ${env.BUILD_TAG}.plan
          """
        }
      }
    }
  }
}

After you have created the pipeline, try to execute it by clicking Build Now. The pipeline should have deployed the example application.

You can find the URL of the created application from the console output of the build. Open the application with your browser or use curl to see the application response.