While initially setting up our Rancher clusters manually, we started to use Terraform, which simplifies the management of the clusters tremendously.
Introduction
As the Rancher clusters already exists, the first thing is to import existing resources into Terraform using the verified provider rancher2.
You basically start importing the cluster and then go on from here, importing everything else like projects, etc. A bit more challenging is the import of apps, which ultimately are helm charts. For apps you can use the rancher2_app_v2. I started with the logging app, which is pretty simple:
Create logging.tf with minimal config
Then you import the resource as follows
Now you run tf plan which gives you the differences - remember we only have the minimal config. tf plan will show you mainly the values passed to the helm chart, hence take this info and add it to a file called vaules.logging.yaml
Add the file to the resource
ClusterFlows and ClusterOutput
While we have the app installed, we still need ClusterFlows and ClusterOutputs. They can be configured in the Rancher UI or you can install it as kubernetes manifests. Looking at the Terraform Registry, the official provider is kubernetes_manifest. You can use your local kubeconfig, so I configured the provider as follows
Once you configured the provider, you have to create a manifest using [hcl]. Can use tfk8s to convert YAML to HCL. The ClusterOutput in my case would look like this
[hcl]:
You can import using apiVersion=<APIVERSION>,kind=<KIND>,namespace=<NAMESPACE>,name=<NAME> as follows:
Weired, as the object is there cluster_output_default:
Well, if you have multiple contexts in your KUBECONFIG, it uses the selected one, which may be different than the cluster you want to manage. So you have to specify config_context. Alternatively you can also use host and token, which may be even better, than relying on a KUBECONFIG-file:
This however still does not work:
It turnes out, that the host was not pointing to the cluster API. Hence the host has to be corrected by pointing to <RANCHER_API_URL>//k8s/clusters/<CLUSTERID>:
After that, the import works fine.
HCL vs YAML
If you don’t like to convert YAML to HCL, you may have a look at kubectl_manifest, which allows you to use YAML as follows
You have to take care, as the import is slightly different and uses the API format i.e. <APIVERSION>//<KIND>//<NAME>//<NAMESPACE>
Importing resource are not always that easy, you have to be familiar with the specific of the provider you are using, as well as with the syntax on how to identify the actual object. Once you get that right, you realize that Terraform is very powerful with all the providers available.