Terraform Rancher Integration: Infrastructure as Code for Kubernetes Clusters

Terraform enables infrastructure-as-code management of Rancher resources, making cluster creation, project management, and configuration reproducible and version-controlled. When Terraform is combined with Rancher, the result is a declarative pipeline that can provision Kubernetes clusters, enforce hardware standards, and keep configuration drift under control. The official Rancher2 Terraform provider supports Rancher v2 resources, allowing automation from cluster provisioning to RBAC configuration. This article covers the core concepts, provider configuration, RKE templates, node templates, and practical patterns for using Terraform with Rancher in production.

Terraform and Rancher Fundamentals

Terraform is written in files with the extension .tf. It is written in HashiCorp Configuration Language, which is a declarative language that lets you define the infrastructure you want in your cluster, the cloud provider you are using, and your credentials for the provider. Then Terraform makes API calls to the provider in order to efficiently create that infrastructure.

Terraform allows you to:

  • Define almost any kind of infrastructure-as-code, including servers, databases, load balancers, monitoring, firewall settings, and SSL certificates
  • Codify infrastructure across many platforms, including Rancher and major cloud providers
  • Commit infrastructure-as-code to version control
  • Easily repeat configuration and setup of infrastructure
  • Incorporate infrastructure changes into standard development practices
  • Prevent configuration drift, in which some servers become configured differently than others

It can automate the process of server provisioning in a way that is self-documenting and easy to track in version control. Terraform can be used to codify infrastructure across many platforms including Rancher. Using a tool like Terraform allows for easily repeating configuration and setup of infrastructure. It also allows for incorporating infrastructure changes into standard development practices and processes such as versioning, reviews, and promotions.

The Rancher 2 Terraform provider is a recommended option to standardize the hardware for your Kubernetes clusters. If you use the Rancher Terraform provider to provision hardware, and then use an RKE template to provision a Kubernetes cluster on that hardware, you can quickly create a comprehensive, production-ready cluster.

Prerequisites and Provider Setup

Before provisioning Rancher resources with Terraform, ensure the environment meets the baseline requirements.

  • Terraform 1.5+ installed
  • Rancher instance with API access
  • Rancher API token, create in User Settings > API & Keys
  • Compatible Rancher and Rancher2 provider versions
  • Basic Terraform knowledge

The first step to managing a Rancher server with Terraform is to configure the rancher provider for Terraform. Create a working directory for this example and place the following code in the rancher.tf within the directory.

hcl provider "rancher" { api_url = "http://localhost:8080" // access_key = "" // secret_key = "" }

The only required configuration for the rancher provider is apikey. This should be configured to point to the Rancher server location. Optionally, the API access and secret keys can be configured with the accesskey and secret_key properties as shown. If Rancher server does not have access control configured, then these settings can be omitted. If access control is enabled, then API credentials are required. Credentials can be created by following the instructions.

Rancher is also able to access these properties using the environment variables RANCHERURL, RANCHERACCESSKEY, and RANCHERSECRET_KEY respectively.

For Rancher2 provider configuration, a more complete example is:

```hcl
terraform {
required_providers {
rancher2 = {
source = "rancher/rancher2"
}
}

backend "s3" {
bucket = "terraform-state-rancher"
key = "rancher/terraform.tfstate"
region = "us-east-1"
}
}

provider "rancher2" {
apiurl = var.rancherurl
tokenkey = var.ranchertoken
insecure = false
}
```

The provider configuration pins the provider major version that matches your Rancher minor release and stores state in S3 for team collaboration. Set insecure = true only if Rancher uses a self-signed certificate.

Variables are used to keep sensitive values out of code.

```hcl
variable "rancher_url" {
description = "Rancher server URL"
type = string
}

variable "rancher_token" {
description = "Rancher API token"
type = string
sensitive = true
}

variable "environment" {
description = "Deployment environment"
type = string
default = "production"
}

variable "devops_password" {
description = "Password for the example DevOps user"
type = string
sensitive = true
}
```

To create a Rancher-provisioned cluster with Terraform, go to your Terraform configuration file and define the provider as Rancher 2. You can set up your Rancher 2 provider with a Rancher API key. Note: The API key has the same permissions and access level as the user it is associated with.

Then Terraform calls the Rancher API to provision your infrastructure, and Rancher calls the infrastructure provider. As an example, if you wanted to use Rancher to provision infrastructure on AWS, you would provide both your Rancher API key and your AWS credentials in the Terraform configuration file or in environment variables so that they could be used to provision the infrastructure.

State Management and Collaboration

This state is required to modify and destroy your infrastructure, so keep it safe. To inspect the complete state use the terraform show command.

State path: terraform.tfstate

Outputs example:

rancher_agent_command = sudo docker run -d --privileged -v /var/run/docker.sock:/var/run/docker.sock -v /var/lib/rancher:/var/lib/rancher rancher/agent:v1.1.3 http://localhost:8080/v1/scripts/A17BDBB62228B4B18B4A:1485622800000:E0L4yrjYajfxbg7mKSNxLZGup0

When you need to make changes to your infrastructure, instead of manually updating the servers, you can make changes in the Terraform configuration files. Then those files can be committed to version control, validated, and reviewed as necessary.

A common pattern is to store state in S3 for team collaboration, as shown in the backend block above, which prevents concurrent modification and enables audit trails.

RKE Templates, Node Templates, and Hardware Standardization

In Rancher, RKE templates are used to provision Kubernetes and define Rancher settings, while node templates are used to provision nodes. Therefore, even if RKE template enforcement is turned on, the end user still has flexibility when picking the underlying hardware when creating a Rancher cluster. The end users of an RKE template can still choose an infrastructure provider and the nodes they want to use.

If you want to standardize the hardware in your clusters, use RKE templates conjunction with node templates or with a server provisioning tool such as Terraform.

Node Templates

Node templates are responsible for node configuration and node provisioning in Rancher. From your user profile, you can set up node templates to define which templates are used in each of your node pools. With node pools enabled, you can make sure you have the required number of nodes in each node pool, and ensure that all nodes in the pool are the same.

Terraform is a server provisioning tool. It uses infrastructure-as-code that lets you create almost every aspect of your infrastructure with Terraform configuration files. It can automate the process of server provisioning in a way that is self-documenting and easy to track in version control.

This section focuses on how to use Terraform with the Rancher 2 Terraform provider, which is a recommended option to standardize the hardware for your Kubernetes clusters.

The full list of supported resources for Rancher can be found here. Any issues should be reported at Github.

Authentication, Permissions, and Global Configuration

The Rancher2 provider interacts with the Rancher API using a token created for a user. The API key has the same permissions and access level as the user it is associated with. This makes it important to create dedicated service accounts for Terraform with the minimal required permissions for cluster provisioning, project creation, and RBAC configuration.

Terraform allows you to:

  • Define almost any kind of infrastructure-as-code, including servers, databases, load balancers, monitoring, firewall settings, and SSL certificates
  • Codify infrastructure across many platforms, including Rancher and major cloud providers
  • Commit infrastructure-as-code to version control
  • Easily repeat configuration and setup of infrastructure
  • Incorporate infrastructure changes into standard development practices
  • Prevent configuration drift, in which some servers become configured differently than others

When using the Rancher2 provider, authentication is handled via apiurl and tokenkey. Insecure mode can be enabled for self-signed certificates, but should be restricted to internal environments.

Configuration Comparison

The following table summarizes key configuration elements for the Rancher provider patterns described.

Component Rancher Classic Provider Rancher2 Provider
Provider block name rancher rancher2
Required config api_url apiurl, tokenkey
Optional credentials accesskey, secretkey insecure flag
Environment variables RANCHERURL, RANCHERACCESSKEY, RANCHERSECRET_KEY TFVARrancherurl, TFVARranchertoken
Typical use Legacy Rancher server Rancher v2 resources

The following table lists prerequisites for a production setup.

Prerequisite Description
Terraform 1.5+ installed Required provider version support
Rancher instance with API access Target control plane
Rancher API token Create in User Settings > API & Keys
Compatible Rancher and Rancher2 provider versions Version pinning
Basic Terraform knowledge HCL and state management

Practical Workflow for Cluster Provisioning

This post assumes that a Rancher server is available for testing, and the latest version of Terraform is installed. If a Rancher server is not available, one can be started locally using the following Docker command:

$ docker run -d -p 8080:8080 rancher/server:v1.3.3

A typical workflow is:

  • Define provider and variables in main.tf and variables.tf
  • Configure backend for remote state
  • Define Rancher resources such as clusters, node pools, projects, and RBAC using the Rancher2 provider
  • Run terraform init, terraform plan, terraform apply
  • Commit configuration to version control
  • Use terraform show to inspect state

Open your Rancher dashboard, switch the demo environment, and note that the ghost stack is created and active.

Conclusion

Terraform and Rancher together deliver a complete infrastructure-as-code path for Kubernetes from bare metal and cloud VMs to running workloads. The Rancher2 provider brings Rancher v2 resources into Terraform, enabling automated cluster provisioning, project management, and RBAC configuration with version-controlled, repeatable definitions. RKE templates provide Kubernetes defaults and Rancher settings, while node templates and Terraform enforce hardware standards across node pools. Authentication via API tokens with environment variable injection keeps credentials out of code, and remote state backends support team collaboration. By defining infrastructure declaratively in HCL, committing changes to version control, and reviewing them through standard development practices, organizations prevent configuration drift and accelerate production-ready cluster delivery. The combination remains practical for both self-hosted Rancher instances and multi-cloud provisioning where Rancher orchestrates the Kubernetes control plane and Terraform provisions the underlying infrastructure.

Sources

  1. oneuptime.com
  2. ranchermanager.docs.rancher.com
  3. suse.com

Related Posts