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

# Terraform

> Deploy and manage infrastructure with Terraform on Ryvn

Terraform services enable you to provision and manage cloud infrastructure as code. Ryvn provides automated state
management, secure credential handling, and integrated deployment controls. Infrastructure changes are coordinated with
your application deployments through [release channels](https://ryvn.ai/docs/configure/release-channels.md) and
[maintenance windows](https://ryvn.ai/docs/configure/maintenance-windows.md).

## How Terraform services work

Terraform services in Ryvn allow you to define and manage infrastructure resources across multiple cloud providers (AWS,
Google Cloud, Azure) using HashiCorp Terraform. When you create a Terraform service, Ryvn handles:

* Terraform state management
* Secure storage of provider credentials
* Execution of Terraform plans and applies
* Version control and rollback capabilities

> [!NOTE]
>
> Terraform services work out of the box on Ryvn-provisioned clusters. On an existing cluster, you first create a cloud
> role for the Ryvn agent and turn on **Allow infrastructure changes** — see
> [Infrastructure permissions](https://ryvn.ai/docs/provision/existing-cluster.md#infrastructure-permissions).

## Prerequisites

Before deploying a Terraform module, ensure you have:

* A GitHub repository containing your Terraform configuration
* Appropriate cloud provider permissions configured in your environment

### Backend configuration

Do not specify a Terraform backend in your configuration. Ryvn manages state storage automatically based on your environment.

### AWS Terraform executor policies

In Ryvn's architecture, the **Ryvn Agent** is the component responsible for executing Terraform operations and managing
Terraform state in your AWS environment. This agent runs with specific IAM permissions that determine which AWS
resources your Terraform services can create and manage.

By default, the Ryvn Agent runs with restricted IAM permissions that limit the types of resources Terraform can create
or manage. To enable broader permissions for your Terraform services, you need to configure the Ryvn Agent's IAM policy
through the `terraform_executor_policies` configuration.

To grant full access for Terraform services in your AWS environment, add the following to your AWS provisioning
configuration:

```yaml theme={null}
terraform_executor_policies:
  - effect: Allow
    actions:
      - "*"
    resource: "*"
```

This configuration replaces the Ryvn Agent role's default policy with a statement granting full AWS access. With
these expanded permissions, your Terraform services can deploy any AWS resources without restriction.

#### Policy conditions

Add IAM policy conditions for fine-grained access control. The optional `condition` field supports standard IAM condition operators like `StringEquals`, `StringNotEquals`, and `ArnLike`.

```yaml theme={null}
terraform_executor_policies:
  - effect: Allow
    actions:
      - kms:Decrypt
      - kms:Encrypt
      - kms:GenerateDataKey
    resources:
      - arn:aws:kms:us-east-1:123456789012:key/*
    condition:
      StringEquals:
        kms:ViaService: secretsmanager.us-east-1.amazonaws.com
```

This example restricts KMS operations to requests coming through Secrets Manager, letting you scope secret access per environment.

> [!NOTE]
>
> **Security Best Practice**: While the example above shows full wildcard permissions for simplicity, you should scope
> these permissions down to only what your Terraform services actually need when deploying to customer environments.
> Follow the principle of least privilege by limiting actions to specific services and resources required by your
> infrastructure.

The `terraform_executor_policies` configuration must be added during environment provisioning. For existing
environments, you'll need to update the provisioning configuration to modify the Ryvn Agent's permissions. See the
[AWS provisioning documentation](https://ryvn.ai/docs/provision/aws.md) for more details.

### Azure Terraform executor policies

On Azure, `terraform_executor_policies` replaces the Ryvn Agent's default grant with
Azure RBAC custom permissions and/or scoped existing roles. It supports management-plane
and data-plane permission lists, built-in or pre-created custom roles, and Azure ABAC
conditions. Configure it on the environment, not on an individual Terraform installation.
See the [Azure executor policy reference](https://ryvn.ai/docs/iac/environments/azure.md#configterraform_executor_policies)
for the fields, examples, and default-restoration behavior.

## Quick start

**1. Create a Terraform service**

Navigate to **Services** → **Create Service** → Select **Terraform**

**2. Configure GitHub source**

* Select your GitHub repository
* (Optional) Specify the Terraform path if in a subdirectory

**3. Deploy to environment**

Go to **Environments** → Select environment → **Add Installation** → Deploy

## Creating a Terraform service

To create a Terraform service:

1. Navigate to the **Services** tab in the Ryvn dashboard
2. Click **Create Service**
3. Select **Terraform** as the service type
4. Configure your Terraform source (see below)
5. Click **Create**

### Configuring Terraform source

Terraform services in Ryvn use GitHub repositories as their source. You can configure:

* **GitHub Repository**: Select the repository containing your Terraform code
* **Terraform Path** (Optional): Specify a subdirectory within the repository where your Terraform configuration is
  located

If your Terraform configuration is in the root of the repository, you can leave the path field empty. If it's in a
subdirectory (e.g., `terraform/production`), specify that path.

### Source credentials

Ryvn automatically manages the credentials needed to access your GitHub repository. When you deploy a Terraform service
to an environment, Ryvn:

1. Generates temporary access tokens for your GitHub repository
2. Securely passes these credentials to the Terraform execution environment
3. Ensures the credentials have the minimum necessary permissions

## Example Terraform module

Here's a minimal example that works with Ryvn:

```hcl theme={null}
terraform {
  required_version = ">= 1.0"

  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 5.0"
    }
  }
}

variable "bucket_name" {
  description = "Name of the S3 bucket"
  type        = string
}

resource "aws_s3_bucket" "main" {
  bucket = var.bucket_name

  tags = {
    ManagedBy = "Terraform"
  }
}

output "bucket_arn" {
  value = aws_s3_bucket.main.arn
}
```

## Plan approval configuration

By default, Terraform plans require manual approval before applying. You can enable automatic approval by setting `autoApprove: true` on the service:

```yaml theme={null}
kind: Service
metadata:
  name: infrastructure
spec:
  type: terraform
  repo: my-org/terraform-modules
  autoApprove: true
  build:
    path: ./aws-vpc
```

> [!WARNING]
>
> Use auto-approve with caution. Always ensure your Terraform configurations are well-tested before enabling automatic approval.

If the environment has `requireApproval: true`, plans will **always** require approval—regardless of the service's `autoApprove` setting. Environment-level approval requirements take precedence, ensuring customers or operators can review changes before they're applied.

See [Deployment Approvals](https://ryvn.ai/docs/guides/deployment-approvals.md) for the complete workflow.

## Managing variables

### Accessing the variables editor

**1. Navigate to installation**

Go to **Environments** → Select your environment → Click on your Terraform installation

**2. Open Settings**

Click the **Settings** button or navigate to the **Settings** tab

**3. Select Terraform Variables**

In the settings sidebar, click **Terraform Variables**

**4. Edit variables**

Use the built-in YAML editor to configure your variables with autocomplete support

### Basic variable configuration

Variables are defined in YAML format and can include static values or dynamic template expressions:

```yaml theme={null}
# Static values
region: us-east-1
instance_type: t3.medium
enable_monitoring: true

# Template expressions for dynamic values
vpc_id: {{ .ryvn.env.state.vpc.id }}
cluster_region: {{ .ryvn.env.state.cluster_region }}
```

Sensitive variables (like API keys or access tokens) can be marked as secret, ensuring they're encrypted and never
displayed in the dashboard.

## Template system

Ryvn provides access to environment state data through template variables. All template expressions use the `{{ }}` syntax.

### Environment state variables

Access infrastructure information provisioned by Ryvn:

> [accordion] Cluster information
>
> ```yaml theme={null}
> # Cluster details
> cluster_name: {{ .ryvn.env.state.cluster_name }}
> cluster_endpoint: {{ .ryvn.env.state.cluster_endpoint }}
> cluster_region: {{ .ryvn.env.state.cluster_region }}
> cluster_oidc_issuer_url: {{ .ryvn.env.state.cluster_oidc_issuer_url }}
> ```

> [accordion] VPC and networking
>
> ```yaml theme={null}
> # VPC configuration
> vpc_id: {{ .ryvn.env.state.vpc.id }}
> vpc_cidr: {{ .ryvn.env.state.vpc.cidr }}
>
> # Subnet IDs as arrays
> private_subnet_ids:
> {{ .ryvn.env.state.vpc.private_subnet_ids | toYaml | nindent 2 }}
>
> public_subnet_ids:
> {{ .ryvn.env.state.vpc.public_subnet_ids | toYaml | nindent 2 }}
>
> # Individual subnet references
> first_private_subnet: {{ index .ryvn.env.state.vpc.private_subnet_ids 0 }}
> ```

> [accordion] DNS configuration
>
> ```yaml theme={null}
> # Domain information
> public_domain: {{ .ryvn.env.state.public_domain.name }}
> internal_domain: {{ .ryvn.env.state.internal_domain.name }}
>
> # Route53 zone details
> public_zone_id: {{ .ryvn.env.state.public_domain.id }}
> nameservers:
> {{ .ryvn.env.state.public_domain.nameservers | toYaml | nindent 2 }}
> ```

> [accordion] IAM and security
>
> ```yaml theme={null}
> # Service roles
> ryvn_agent_role_arn: {{ .ryvn.env.state.ryvn_agent_role_arn }}
>
> # Security groups
> default_security_group: {{ .ryvn.env.state.vpc.default_security_group_id }}
> ```

### Cross-installation references

Reference outputs from other Terraform installations in the same environment using the `installation` function:

```yaml theme={null}
# Reference outputs from another installation
database_endpoint: {{ (serviceInstallation "postgres-service").outputs.endpoint }}
storage_bucket: {{ (serviceInstallation "storage-service").outputs.bucket.name }}
api_url: {{ (serviceInstallation "api-service").outputs.load_balancer.dns_name }}
```

### Secret references

Read values out of a variable group's Kubernetes secret. Terraform variables take
literal values, so `k8sSecretValue` inlines them into the generated variables
file:

```yaml theme={null}
# Basic secret reference
database_password: {{ k8sSecretValue "db-credentials" }}

# Secret with specific key
api_key: {{ k8sSecretValue "api-secrets" "key" }}
```

### Template functions

Ryvn provides helper functions to format and manipulate template values:

```yaml theme={null}
# Convert array to YAML
availability_zones: {{ .ryvn.env.state.vpc.azs | toYaml }}
# Output: ["us-east-1a", "us-east-1b", "us-east-1c"]

# Properly indent YAML arrays with nindent
private_subnets: {{ .ryvn.env.state.vpc.private_subnet_ids | toYaml | nindent 2 }}
# Output:
#   - subnet-abc123
#   - subnet-def456
```

## Configuration examples

### Database module

```yaml theme={null}
# Database configuration using environment variables
engine: postgres
engine_version: "16.8"
instance_class: db.t3.micro

# Use VPC from environment
vpc_id: {{ .ryvn.env.state.vpc.id }}
subnet_ids:
{{ .ryvn.env.state.vpc.private_subnet_ids | toYaml | nindent 2 }}

# Security configuration
allowed_cidr_blocks:
  - {{ .ryvn.env.state.vpc.cidr }}

# Credentials from secrets
username: admin
password: {{ k8sSecretValue "db-password" }}

# Naming based on environment
identifier: myapp-{{ .ryvn.env.state.cluster_name }}

# Tags
tags:
  Environment: {{ .ryvn.env.state.cluster_name }}
  ManagedBy: Ryvn
  Domain: {{ .ryvn.env.state.public_domain.name }}
```

> [!WARNING]
>
> Template expressions are processed when the Terraform task is created. If a referenced installation or secret doesn't
> exist, the task will fail with a template error. Ensure dependencies exist before referencing them.

## Deploying services

After creating a Terraform service, you can deploy it to an environment:

1. Navigate to the **Environments** tab
2. Select the target environment
3. Click **Add Installation**
4. Select your Terraform service
5. Configure any Terraform variables needed for your deployment
6. Click **Deploy**

During deployment, Ryvn will:

1. Clone your GitHub repository
2. Navigate to the specified Terraform path (if provided)
3. Initialize Terraform
4. Create an execution plan
5. Apply the changes if the plan is successful

## Monitoring deployments

After a Terraform operation completes, Ryvn updates the installation status to reflect the current state:

| Operation | Success | Status |
| - | - | - |
| Terraform Apply | Yes | Up to date |
| Terraform Apply | No | Failed |
| Terraform Plan | Yes | Pending |

When a Terraform apply task completes successfully, the installation status is automatically updated to `Up to date`. This indicates that your infrastructure is provisioned according to your Terraform configuration.

If a Terraform operation fails, the installation status will be marked as `Failed`. You can view detailed errors on the installation's Activity page or in the logs.

## Release management

Managing infrastructure changes requires coordination to avoid disrupting applications. Ryvn provides controls for Terraform deployments:

**Release Channels**: Control how infrastructure changes flow through environments. Deploy to development first, then promote through staging to production with approval gates.

**Maintenance Windows**: Schedule infrastructure changes during acceptable downtime periods (database migrations, network updates, security changes).

## Troubleshooting

> [accordion] Permission denied
>
> Check that your environment has the necessary cloud provider permissions configured. For AWS, ensure `terraform_executor_policies` are properly configured in your environment provisioning.

> [accordion] Variable not set
>
> All required variables must be set in the Terraform Variables section before deployment. Navigate to **Installation** → **Settings** → **Terraform Variables** to configure them.

> [accordion] Template rendering failed
>
> Template expressions are processed when the Terraform task is created. If a referenced installation or secret doesn't exist, the task will fail with a template error. Ensure dependencies exist before referencing them.
