> ## Documentation Index
> Fetch the complete documentation index at: https://www.latitude.sh/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Using Terraform with Latitude.sh

> Use infrastructure as code with Terraform on Latitude.sh for consistent, repeatable deployments

[Terraform](https://www.terraform.io/) is an infrastructure as code (IaC) driven software that allows you to programmatically configure your project infrastructure using configuration files and version control.

Terraform ensures logical management and monitoring of resources such as servers, networks, and cloud storage instead of a manual operation for each required resource.

These infrastructure configurations are handled via a declarative language called HCL (HashiCorp Configuration Language). For example, when you create a project or deploy a server, Terraform parses your code and translates it to an API call to the resource provider.

Terraform integrations are called Providers. Providers are published to the [Terraform Registry](https://registry.terraform.io/) and can be consumed to quickly integrate infrastructure providers with the resources that compose your infrastructure.

This guide will teach you how to use the [Latitude.sh Terraform provider](https://registry.terraform.io/providers/latitudesh/latitudesh/latest/docs).

Latitude.sh is a [verified HashiCorp partner](https://www.hashicorp.com/partners/tech/latitude-sh).

## About the integration

With the [Latitude.sh Terraform provider](https://registry.terraform.io/providers/latitudesh/latitudesh/latest/docs) you can:

* Create and update projects
* Create and update servers
* Create and update SSH keys
* Use [data sources](https://developer.hashicorp.com/terraform/language/data-sources) and [outputs](https://developer.hashicorp.com/terraform/language/values/outputs) to retrieve data.

If you already use Terraform to manage your infrastructure, getting started with the Latitude.sh provider is straightforward. If you don't use Terraform yet, it shouldn't take more than 10 minutes to get familiar with the basic concepts and start versioning your infrastructure.

## Getting started

<Steps>
  <Step title="Install Terraform CLI">
    Install the Terraform CLI. [This guide](https://developer.hashicorp.com/terraform/downloads) explains how to do this for your operating system.
  </Step>

  <Step title="Create API token">
    Create a Latitude.sh API token.
    [Here](https://www.latitude.sh/docs/api-reference/authentication) is how to
    create an API token.
  </Step>

  <Step title="Export API token">
    Export the API token as a variable

    ```sh theme={null}
    export LATITUDESH_AUTH_TOKEN=your_api_token
    ```
  </Step>
</Steps>

## Example integration

We will start by creating a project, getting the `id` of the project we just created, then adding our ssh key to that project, and finally creating a server that deploys to our new project and uses the SSH key we just added.

<Steps>
  <Step title="Create project directory">
    Create a directory for your Terraform project.

    ```bash theme={null}
    mkdir latitudesh-terraform-example
    cd latitudesh-terraform-example
    ```
  </Step>

  <Step title="Create main.tf">
    Create a file named `main.tf` with the following content:

    ```hcl theme={null}
    terraform {
      required_providers {
        latitudesh = {
          source  = "latitudesh/latitudesh"
          version = "~> 0.1.5" # Make sure you are using the latest version published to the Terraform registry
        }
      }
    }
    ```
  </Step>

  <Step title="Initialize project">
    Run the following command in your terminal to Initialize the project.

    ```bash theme={null}
    terraform init
    ```

    You should see a success message after initializing the project that will contain something like this:

    > Terraform has been successfully initialized!
    >
    > You may now begin working with Terraform. Try running "terraform plan" to see\
    > any changes that are required for your infrastructure. All Terraform commands\
    > should now work.
    >
    > If you ever set or change modules or backend configuration for Terraform,\
    > rerun this command to reinitialize your working directory. If you forget, other\
    > commands will detect it and remind you to do so if necessary.
  </Step>

  <Step title="Create configuration files">
    Now we are finally ready to start creating infrastructure with Terraform. While you can add your codified resources to `main.tf`, as your infrastructure grows, it gets hard and dangerous to manage things from a single file, so it is usually best to split your files from the beginning.

    Create a file named `variables.tf` with the following content. This is optional but useful for this guide.

    ```hcl variables.tf theme={null}
    # Determines the server configuration we are going to deploy
    variable "plan" {
      description = "Latitude.sh server plan"
      default     = "c2-small-x86"
    }

    # Determines the location we are going to deploy to
    variable "region" {
      description = "Latitude.sh server region slug"
      default     = "MH1"
    }

    variable "ssh_public_key" {
      description = "Latitude.sh SSH public key"
    }
    ```

    Create the following files

    ```hcl outputs.tf theme={null}
    # Prints the IPv4 of the server we just created when the deploy is finished on the terminal
    output "server-ip" {
      value = latitudesh_server.server.primary_ip_v4
    }
    ```

    ```hcl project.tf theme={null}
    # Creates our project
    resource "latitudesh_project" "project" {
      name        = "Terraform example project"
      description = "Latitude.sh Terraform Integration"
      environment = "Development" # Development, Production or Staging
    }
    ```

    ```hcl server.tf theme={null}
    resource "latitudesh_server" "server" {
      hostname         = "terraform-guide.latitude.sh"
      operating_system = "ubuntu_22_04_x64_lts"
      plan             = var.plan                        # Uses the plan slug we defined on variables.tf
      project          = latitudesh_project.project.id   # Uses the project id we will create
      site             = var.region                      # Uses the region slug we defined on variables.tf
      ssh_keys         = [latitudesh_ssh_key.ssh_key.id] # Uses the ssh id we will create. If you don't have an SSH key ready to use, you can remove this line and servers will be created with password auth instead
    }
    ```

    Optional if you have an SSH key in hand. If not, remove the `ssh_keys` from `server.tf` and the ssh section from `variables.tf` and ignore the next file.

    ```hcl ssh_key.tf theme={null}
    resource "latitudesh_ssh_key" "ssh_key" {
      project    = latitudesh_project.project.id # Uses the project id we will create
      name       = "John's Key" # Name your key so it's easy to identify later
      public_key = var.ssh_public_key
    }
    ```
  </Step>
</Steps>

## Run the plan

Now that we have all our files organized and referenced, we can create the infrastructure defined in them. Let's start by reviewing the changes that will be made.

<Steps>
  <Step title="Review the plan">
    Run this on your terminal:

    ```bash theme={null}
    terraform plan
    ```

    If you decide to use an SSH key, Terraform will ask for your public SSH key. Terraform will list every action it will take after we apply our plan. Review to make sure everything is how you want it to be.
  </Step>

  <Step title="Apply the plan">
    Apply the plan:

    ```bash theme={null}
    terraform apply
    ```

    Paste your public SSH key again when requested and type *yes* on the prompt.
  </Step>
</Steps>

## That's it

You've just created three different resources with relationships between them. Commit this code to your repository to start versioning your infrastructure like a pro!

Cleaning up is easy, just run the destroy command to rollback:

```shell theme={null}
terraform apply -destroy
```

We touched the surface of what you can do with the Latitude.sh Terraform provider. To learn more, review the following links:

* [Latitude.sh Terraform provider docs](https://registry.terraform.io/providers/latitudesh/latitudesh/latest/docs)
* [Contribute to the provider with code, feature requests, or bug reports](https://github.com/latitudesh/terraform-provider-latitudesh)
