> For the complete documentation index, see [llms.txt](https://developer.harness.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://developer.harness.io/artifact-registry/3.0/platform-integrations/terraform.md).

# Terraform

Create, configure, and manage Harness Artifacts registries as infrastructure as code using the Harness Terraform provider registry resource.

You can create, configure, and manage Harness Artifacts registries using [Terraform](https://www.terraform.io/), an infrastructure-as-code tool that lets you define cloud resources in configuration files instead of clicking through a UI. The [Harness Terraform provider](https://registry.terraform.io/providers/harness/harness/latest) includes the `harness_platform_har_registry` resource, which supports virtual registries, upstream proxies, and the links between them.

Instead of creating registries by hand in the Harness console, you write a few short configuration files and run `terraform apply`. The result is the same, but the setup is version-controlled, repeatable, and auditable.

{% hint style="info" %}
This page covers using the Harness Terraform provider to **create and manage registries** as infrastructure as code.

* To host Terraform modules and providers **as packages** in a Terraform-type registry, go to [Terraform client setup](https://developer.harness.io/artifact-registry/3.0/setup/terraform.md).
* For the full `harness_platform_har_registry` resource reference, go to [Terraform provider reference](https://developer.harness.io/artifact-registry/3.0/reference/terraform-provider.md).
  {% endhint %}

***

## How it works

The integration follows a three-part pattern:

1. **Define registry resources**. Write HCL configuration files that declare your registries using the `harness_platform_har_registry` resource. Each registry is a separate Terraform resource with its own type (`VIRTUAL` or `UPSTREAM`), package type, and configuration.
2. **Authenticate with Harness**. Configure the Harness Terraform provider with your API key. The provider handles all API communication with the Harness platform.
3. **Apply the configuration**. Run `terraform apply` to create, update, or destroy registries in your Harness project. Terraform tracks state, so subsequent runs only modify what has changed.

***

## Before you begin

* **Harness account with Artifacts enabled**. [Sign up](https://app.harness.io/auth/#/signup) if you do not have one.
* **Terraform v1.5.0 or later** installed on your machine. To install Terraform, go to [Install Terraform](https://developer.hashicorp.com/terraform/install).
* **Docker** installed on your machine (used to verify the registry at the end of the tutorial). To install Docker, go to [Get Docker](https://docs.docker.com/get-docker/).
* **Harness API key**. Generate a Personal Access Token (PAT) or Service Account Token in the Harness UI under **My Profile** > **+ API Key** > **+ Token**.
* **Your project identifiers**:
  * **Account ID**: Visible in your Harness URL or under **Account Settings** > **Overview**.
  * **Organization ID**: The identifier of your Harness organization (for example, `default`).
  * **Project ID**: The identifier of the project where you want to create the registries.

***

## Tutorial: creating a Docker registry

This tutorial walks you through creating a fully functional Docker registry in Harness Artifacts using Terraform. You will build three resources:

* A **virtual registry**, which is the URL your team uses to pull and push Docker images.
* An **upstream proxy**, a caching layer that connects to Docker Hub. The first time someone pulls a public image, it is fetched from Docker Hub and cached. Every subsequent pull is served from the cache.
* A **link** between them, so pulls from the virtual registry automatically resolve through Docker Hub when needed.

```
  docker pull <your-registry>/library/nginx:latest

        │
        ▼
  ┌─────────────────────────┐
  │  my-docker (VIRTUAL)    │  ← Your team points Docker here
  │                         │
  │  Checks local cache     │
  │  Cache miss? Ask proxy: │
  │         │               │
  │         ▼               │
  │  dockerhub-proxy        │  ← Fetches from Docker Hub
  │  (UPSTREAM)             │     and caches the result
  └─────────────────────────┘
```

Each step creates its own Terraform configuration in a separate directory:

| Step   | What it creates                                 | Directory              |
| ------ | ----------------------------------------------- | ---------------------- |
| Step 1 | Virtual registry (client-facing endpoint)       | `01-virtual-registry/` |
| Step 2 | Upstream proxy connected to Docker Hub          | `02-upstream-proxy/`   |
| Step 3 | Link between the proxy and the virtual registry | `03-link-virtual/`     |

Each directory contains five standard Terraform files: `versions.tf`, `providers.tf`, `variables.tf`, `main.tf`, and `outputs.tf`.

**Shared provider configuration**

The `versions.tf` and `providers.tf` files are the same across all three steps. Create them once and copy them into each directory.

{% code title="versions.tf" overflow="wrap" %}

```hcl
terraform {
  required_version = ">= 1.5.0"

  required_providers {
    harness = {
      source  = "harness/harness"
      version = ">= 0.30.0"
    }
  }
}
```

{% endcode %}

{% code title="providers.tf" overflow="wrap" %}

```hcl
provider "harness" {
  endpoint         = var.harness_endpoint
  account_id       = var.harness_account_id
  platform_api_key = var.harness_platform_api_key
}
```

{% endcode %}

{% hint style="info" %}
Harness Artifacts is a Next Gen feature. Always use `platform_api_key` (not the legacy `api_key`) when configuring the provider.
{% endhint %}

**Setting credentials**

Before running any step, set your credentials as environment variables:

{% tabs %}
{% tab title="macOS / Linux" %}

```bash
export TF_VAR_harness_account_id="YOUR_ACCOUNT_ID"
export TF_VAR_harness_platform_api_key="YOUR_HARNESS_API_KEY"
export TF_VAR_space_ref="YOUR_ACCOUNT_ID/YOUR_ORG_ID/YOUR_PROJECT_ID"
```

{% endtab %}

{% tab title="Windows (PowerShell)" %}

```powershell
$env:TF_VAR_harness_account_id="YOUR_ACCOUNT_ID"
$env:TF_VAR_harness_platform_api_key="YOUR_HARNESS_API_KEY"
$env:TF_VAR_space_ref="YOUR_ACCOUNT_ID/YOUR_ORG_ID/YOUR_PROJECT_ID"
```

{% endtab %}
{% endtabs %}

Replace the placeholder values with your actual account ID, API key, and project scope.

{% hint style="warning" %}
**Protect your API key**

Never commit API keys to version control. Add a `.gitignore` file to your project root that includes:

```
terraform.tfvars
*.tfstate
*.tfstate.*
.terraform/
```

{% endhint %}

***

### Step 1: creating the virtual registry

The virtual registry is the entry point for your team's Docker operations. In this step, you create it without an upstream proxy attached. The proxy connection is made in Step 3.

Create a directory called `01-virtual-registry` and add the shared `versions.tf` and `providers.tf` files, then add the following files.

<details>

<summary>variables.tf</summary>

```hcl
variable "harness_endpoint" {
  type    = string
  default = "https://app.harness.io/gateway"
}

variable "harness_account_id" {
  type        = string
  description = "Your Harness account ID."
}

variable "harness_platform_api_key" {
  type        = string
  sensitive   = true
  description = "Harness API key (PAT or Service Account Token)."
}

variable "space_ref" {
  type        = string
  description = "Project scope: account_id/org_id/project_id."
}

variable "virtual_registry_identifier" {
  type    = string
  default = "my-docker"
}

variable "virtual_registry_description" {
  type    = string
  default = "Docker virtual registry managed by Terraform"
}

variable "virtual_upstream_proxies" {
  type        = list(string)
  description = "Upstream proxy identifiers to attach. Leave empty for Step 1."
  default     = []
}
```

</details>

{% code title="main.tf" overflow="wrap" %}

```hcl
resource "harness_platform_har_registry" "virtual" {
  identifier   = var.virtual_registry_identifier
  description  = var.virtual_registry_description
  space_ref    = var.space_ref
  package_type = "DOCKER"

  config {
    type             = "VIRTUAL"
    upstream_proxies = var.virtual_upstream_proxies
  }

  parent_ref = var.space_ref
}
```

{% endcode %}

| Attribute                 | Description                                                                                                             |
| ------------------------- | ----------------------------------------------------------------------------------------------------------------------- |
| `identifier`              | A unique name for this registry within your project. Becomes part of the URL you use with `docker pull`.                |
| `space_ref`               | The project to create the registry in. Format: `account_id/org_id/project_id`.                                          |
| `package_type`            | The type of artifacts this registry holds. Options: `DOCKER`, `HELM`, `MAVEN`, `NPM`, `PYTHON`, `GO`, `NUGET`, `CARGO`. |
| `config.type`             | `VIRTUAL` for a client-facing registry, `UPSTREAM` for a proxy.                                                         |
| `config.upstream_proxies` | A list of upstream proxy identifiers. Empty in Step 1; populated in Step 3.                                             |

{% code title="outputs.tf" overflow="wrap" %}

```hcl
output "virtual_registry_identifier" {
  value = harness_platform_har_registry.virtual.identifier
}

output "virtual_registry_url" {
  value = harness_platform_har_registry.virtual.url
}

output "import_command_for_step3" {
  value = "terraform import harness_platform_har_registry.virtual \"${var.space_ref}/${var.virtual_registry_identifier}\""
}
```

{% endcode %}

Initialize and apply:

```bash
cd 01-virtual-registry
terraform init -upgrade
terraform validate
terraform apply
```

Type `yes` when prompted. The output looks similar to the following:

```
Apply complete! Resources: 1 added, 0 changed, 0 destroyed.

Outputs:

virtual_registry_identifier = "my-docker"
virtual_registry_url        = "https://pkg.harness.io/abc123xyz/my-docker"
import_command_for_step3    = "terraform import harness_platform_har_registry.virtual \"abc123xyz/default/my-project/my-docker\""
```

Save the `import_command_for_step3` value. You need it in Step 3.

***

### Step 2: creating the upstream proxy

The upstream proxy connects to Docker Hub and caches images locally in Harness. This resource is independent of the virtual registry you created in Step 1.

Create a directory called `02-upstream-proxy` and add the shared `versions.tf` and `providers.tf` files, then add the following files.

<details>

<summary>variables.tf</summary>

```hcl
variable "harness_endpoint" {
  type    = string
  default = "https://app.harness.io/gateway"
}

variable "harness_account_id" {
  type        = string
  description = "Your Harness account ID."
}

variable "harness_platform_api_key" {
  type        = string
  sensitive   = true
  description = "Harness API key (PAT or Service Account Token)."
}

variable "space_ref" {
  type        = string
  description = "Project scope: account_id/org_id/project_id."
}

variable "upstream_registry_identifier" {
  type    = string
  default = "dockerhub-proxy"
}

variable "upstream_registry_description" {
  type    = string
  default = "Docker Hub upstream proxy managed by Terraform"
}

variable "upstream_use_anonymous" {
  type        = bool
  description = "Use anonymous Docker Hub pulls. Set to false for authenticated access."
  default     = true
}

variable "dockerhub_username" {
  type    = string
  default = ""

  validation {
    condition     = var.upstream_use_anonymous || length(trimspace(var.dockerhub_username)) > 0
    error_message = "Required when upstream_use_anonymous is false."
  }
}

variable "dockerhub_secret_identifier" {
  type    = string
  default = ""

  validation {
    condition     = var.upstream_use_anonymous || length(trimspace(var.dockerhub_secret_identifier)) > 0
    error_message = "Required when upstream_use_anonymous is false. Set to your Harness secret ID."
  }
}

variable "dockerhub_secret_space_path" {
  type        = string
  description = "Harness secret scope. Defaults to space_ref when empty."
  default     = ""
}
```

</details>

{% code title="main.tf" overflow="wrap" %}

```hcl
resource "harness_platform_har_registry" "upstream_proxy" {
  identifier   = var.upstream_registry_identifier
  description  = var.upstream_registry_description
  space_ref    = var.space_ref
  parent_ref   = var.space_ref
  package_type = "DOCKER"

  config {
    type      = "UPSTREAM"
    source    = "Dockerhub"
    auth_type = var.upstream_use_anonymous ? "Anonymous" : "UserPassword"

    dynamic "auth" {
      for_each = var.upstream_use_anonymous ? [] : [1]
      content {
        auth_type         = "UserPassword"
        user_name         = var.dockerhub_username
        secret_identifier = var.dockerhub_secret_identifier
        secret_space_path = var.dockerhub_secret_space_path != "" ? var.dockerhub_secret_space_path : var.space_ref
      }
    }
  }
}
```

{% endcode %}

The `dynamic "auth"` block is a Terraform pattern for conditional configuration. If anonymous mode is on, the `auth` block is skipped entirely. If it is off, the block includes the Docker Hub credentials. The same configuration file works for both setups.

{% code title="outputs.tf" overflow="wrap" %}

```hcl
output "upstream_registry_identifier" {
  value = harness_platform_har_registry.upstream_proxy.identifier
}

output "upstream_registry_url" {
  value = harness_platform_har_registry.upstream_proxy.url
}
```

{% endcode %}

Initialize and apply:

```bash
cd 02-upstream-proxy
terraform init -upgrade
terraform validate
terraform apply
```

For **anonymous Docker Hub access** (the default), no additional variables are needed. This is sufficient for pulling public images such as `nginx`, `alpine`, or `redis`.

For **authenticated Docker Hub access** (higher rate limits, private image support), set these additional variables before running `terraform apply`:

{% tabs %}
{% tab title="macOS / Linux" %}

```bash
export TF_VAR_upstream_use_anonymous=false
export TF_VAR_dockerhub_username="your-dockerhub-username"
export TF_VAR_dockerhub_secret_identifier="your-harness-secret-id"
```

{% endtab %}

{% tab title="Windows (PowerShell)" %}

```powershell
$env:TF_VAR_upstream_use_anonymous="false"
$env:TF_VAR_dockerhub_username="your-dockerhub-username"
$env:TF_VAR_dockerhub_secret_identifier="your-harness-secret-id"
```

{% endtab %}
{% endtabs %}

{% hint style="info" %}
**Setting up Docker Hub credentials in Harness**

1. In **Docker Hub**, go to **Account Settings** > **Security** > **New Access Token**. A read-only token is sufficient.
2. In **Harness**, go to your project, then **Project Settings** > **Secrets** > **+ New Secret** > **Text**. Paste the Docker Hub token as the value. Note the secret identifier, which is the value for `dockerhub_secret_identifier`.
   {% endhint %}

Type `yes` when prompted. The output looks similar to the following:

```
Apply complete! Resources: 1 added, 0 changed, 0 destroyed.

Outputs:

upstream_registry_identifier = "dockerhub-proxy"
upstream_registry_url        = "https://pkg.harness.io/abc123xyz/dockerhub-proxy"
```

***

### Step 3: linking the upstream proxy to the virtual registry

This step updates the virtual registry from Step 1 to route requests through the upstream proxy from Step 2. Because the virtual registry already exists, you need to import it into this step's Terraform state before applying.

Create a directory called `03-link-virtual` and add the shared `versions.tf` and `providers.tf` files, then add the following files.

{% code title="data.tf" overflow="wrap" %}

```hcl
data "terraform_remote_state" "upstream" {
  backend = "local"

  config = {
    path = "${path.module}/../02-upstream-proxy/terraform.tfstate"
  }
}
```

{% endcode %}

{% hint style="warning" %}
**Use a remote backend in production**

Reading a peer step's local `terraform.tfstate` only works on a single workstation. For shared use or CI, configure a remote backend (S3, Terraform Cloud, GCS) on Step 2, then point this `terraform_remote_state` data source at the same backend instead of a local path. Never commit `*.tfstate` files to source control.
{% endhint %}

<details>

<summary>variables.tf</summary>

```hcl
variable "harness_endpoint" {
  type    = string
  default = "https://app.harness.io/gateway"
}

variable "harness_account_id" {
  type        = string
  description = "Your Harness account ID."
}

variable "harness_platform_api_key" {
  type        = string
  sensitive   = true
  description = "Harness API key (PAT or Service Account Token)."
}

variable "space_ref" {
  type        = string
  description = "Project scope: account_id/org_id/project_id."
}

variable "virtual_registry_identifier" {
  type    = string
  default = "my-docker"
}

variable "virtual_registry_description" {
  type    = string
  default = "Docker virtual registry with Docker Hub upstream"
}
```

</details>

{% code title="main.tf" overflow="wrap" %}

```hcl
resource "harness_platform_har_registry" "virtual" {
  identifier   = var.virtual_registry_identifier
  description  = var.virtual_registry_description
  space_ref    = var.space_ref
  parent_ref   = var.space_ref
  package_type = "DOCKER"

  config {
    type             = "VIRTUAL"
    upstream_proxies = [data.terraform_remote_state.upstream.outputs.upstream_registry_identifier]
  }
}
```

{% endcode %}

The only change from Step 1 is the `upstream_proxies` line. Instead of an empty list, it references the proxy identifier from Step 2.

{% code title="outputs.tf" overflow="wrap" %}

```hcl
output "virtual_registry_identifier" {
  value = harness_platform_har_registry.virtual.identifier
}

output "virtual_registry_url" {
  value = harness_platform_har_registry.virtual.url
}

output "upstream_proxies_configured" {
  value = data.terraform_remote_state.upstream.outputs.upstream_registry_identifier
}
```

{% endcode %}

Initialize, import, and apply:

1. **Verify Step 2 is complete**. Confirm the state file from Step 2 exists:

   ```bash
   ls ../02-upstream-proxy/terraform.tfstate
   ```
2. **Initialize Terraform**.

   ```bash
   cd 03-link-virtual
   terraform init -upgrade
   ```
3. **Import the existing virtual registry**. Use the command that Step 1 printed in its output:

   ```bash
   terraform import harness_platform_har_registry.virtual \
     "YOUR_ACCOUNT_ID/YOUR_ORG_ID/YOUR_PROJECT_ID/my-docker"
   ```

   Replace the values with your actual account ID, organization, project, and registry identifier. You should see:

   ```
   harness_platform_har_registry.virtual: Importing...
   harness_platform_har_registry.virtual: Import successful!
   ```
4. **Apply the update**.

   ```bash
   terraform validate
   terraform apply
   ```

   Type `yes` when prompted. You should see:

   ```
   Apply complete! Resources: 0 added, 1 changed, 0 destroyed.

   Outputs:

   virtual_registry_identifier  = "my-docker"
   virtual_registry_url         = "https://pkg.harness.io/abc123xyz/my-docker"
   upstream_proxies_configured  = "dockerhub-proxy"
   ```

   `0 added, 1 changed` confirms Terraform recognized the existing registry and updated it to include the upstream proxy.

***

## Verifying the setup

All three steps are complete. Verify the end-to-end flow by pulling a Docker image through the new registry.

1. **Log in to the Harness registry**.

   ```bash
   docker login pkg.harness.io \
     --username your-harness-email@example.com \
     --password YOUR_API_KEY
   ```

   You should see `Login Succeeded`.
2. **Pull an image through the virtual registry**.

   ```bash
   docker pull pkg.harness.io/YOUR_ACCOUNT_ID/my-docker/library/alpine:latest
   ```

   <div data-gb-custom-block data-tag="hint" data-style="info" class="hint hint-info"><p>The pull path format is <code>pkg.harness.io/&#x3C;account_id>/&#x3C;registry_identifier>/&#x3C;image>:&#x3C;tag></code>. It does <strong>not</strong> include the org or project segments, even though they appear in <code>space_ref</code>.</p></div>

   On the first pull, the request flows through the chain: virtual registry, then upstream proxy, then Docker Hub. The image is cached in Harness. Subsequent pulls are served directly from the cache.
3. **Verify in the Harness UI**. Navigate to **Artifact Registry** in your project. You should see:
   * **my-docker** listed as a **Virtual** registry with **dockerhub-proxy** shown as its upstream.
   * **dockerhub-proxy** listed as an **Upstream** registry connected to Docker Hub.
   * The `alpine` image visible under the virtual registry after the pull.

***

## Cleaning up

To remove the resources created in this tutorial, destroy them in reverse order:

```bash
cd 03-link-virtual && terraform destroy
cd ../02-upstream-proxy && terraform destroy
cd ../01-virtual-registry && terraform destroy
```

Type `yes` at each prompt.

{% hint style="warning" %}
Destroying a registry permanently deletes all cached artifacts in it. Verify you have alternative sources for any images before proceeding.
{% endhint %}

***

## Troubleshooting

<details>

<summary>Terraform reports an undefined response type error during apply</summary>

The registry may have been created despite the error. Check the Harness UI. If the registry exists, run `terraform import harness_platform_har_registry.NAME "account_id/org_id/project_id/registry_identifier"` to adopt it, then run `terraform init -upgrade` to pull the latest provider and retry.

</details>

<details>

<summary>Terraform import fails with a not-found error</summary>

The import path must be exactly `account_id/org_id/project_id/registry_identifier` with no leading or trailing slashes and no `https://` prefix. Verify each segment matches the values in your Harness project and re-run with the corrected path.

</details>

<details>

<summary>Authentication errors from the Harness Terraform provider</summary>

Use a Next Gen API key with `platform_api_key` (not the legacy `api_key`). Confirm the token has permission to manage registries in the target project. Verify that `space_ref` matches `account_id/org_id/project_id` exactly.

</details>

***

## Next steps

* To replicate this pattern for other package types (Helm, Maven, npm, Python, and others), change the `package_type` attribute in the resource definition. To review supported package types, go to [Supported formats](https://developer.harness.io/artifact-registry/3.0/get-started/supported-formats.md).
* For the full resource reference including all attributes and data sources, go to [Terraform provider reference](https://developer.harness.io/artifact-registry/3.0/reference/terraform-provider.md).
* To create registries through the Harness console instead of Terraform, go to [Create a registry](https://developer.harness.io/artifact-registry/3.0/registries/create-a-registry.md).
* To host Terraform modules and providers as packages in Harness Artifacts, go to [Terraform client setup](https://developer.harness.io/artifact-registry/3.0/setup/terraform.md).

{% @harness-feedback/feedback %}
