# Example: Import Existing

### Overview

Terraform can import existing infrastructure that was created outside of Terraform (e.g., through the console or API). This allows you to:

* Bring legacy infrastructure under version control
* Migrate from manual management to Infrastructure as Code
* Consolidate infrastructure into a single Terraform configuration

### Supported Resources

| Resource                   | Import Support |
| -------------------------- | -------------- |
| `teraswitch_metal`         | Supported      |
| `teraswitch_cloud_compute` | Supported      |
| `teraswitch_network`       | Supported      |
| `teraswitch_volume`        | Supported      |

### Import Process

#### Step 1: Find the Resource ID

Locate the resource ID in the TeraSwitch console:

1. Navigate to the resource in the console
2. The ID is visible in the URL or resource details page

For example:

```
https://console.tsw.io/projects/123/metal/45678
                                         ^^^^^
                                     Resource ID
```

#### Step 2: Write the Resource Block

Create a Terraform configuration file with an empty resource block:

```hcl
# main.tf

terraform {
  required_providers {
    teraswitch = {
      source  = "TeraSwitch/teraswitch"
      version = "~> 0.0.7"
    }
  }
}

provider "teraswitch" {
  # Credentials from environment variables
}

# Resource to import
resource "teraswitch_metal" "existing_server" {
  # Configuration will be added after import
}
```

#### Step 3: Run Terraform Import

```bash
terraform init
terraform import teraswitch_metal.existing_server 45678
```

Expected output:

```
teraswitch_metal.existing_server: Importing from ID "45678"...
teraswitch_metal.existing_server: Import prepared!
  Prepared teraswitch_metal for import
teraswitch_metal.existing_server: Refreshing state... [id=45678]

Import successful!

The resources that were imported are shown above. These resources are now in
your Terraform state and will henceforth be managed by Terraform.
```

#### Step 4: Generate Configuration

Run `terraform plan` to see the current state:

```bash
terraform plan
```

Terraform will show the detected configuration. Update your resource block to match:

```hcl
resource "teraswitch_metal" "existing_server" {
  hostname         = "legacy-db-01"
  region           = "PIT1"
  operating_system = "ubuntu-22.04"

  ssh_key_ids = [1234]

  tags = {
    imported    = "true"
    previous_id = "45678"
  }
}
```

#### Step 5: Verify Configuration

Run `terraform plan` again to confirm no changes:

```bash
terraform plan
```

Expected output:

```
No changes. Your infrastructure matches the configuration.
```

### Complete Example: Import Metal Server

#### Initial Setup

```hcl
# main.tf

terraform {
  required_version = ">= 1.0"

  required_providers {
    teraswitch = {
      source  = "TeraSwitch/teraswitch"
      version = "~> 0.0.7"
    }
  }
}

provider "teraswitch" {
  api_key    = var.teraswitch_api_key
  project_id = var.teraswitch_project_id
}

# Server to import
resource "teraswitch_metal" "database" {
  # Initially empty - populated after import
}
```

```hcl
# variables.tf

variable "teraswitch_api_key" {
  type      = string
  sensitive = true
}

variable "teraswitch_project_id" {
  type = number
}
```

#### Import Command

```bash
export TERASWITCH_API_KEY="your-api-key"
export TERASWITCH_PROJECT_ID="12345"

terraform init
terraform import teraswitch_metal.database 45678
```

#### Post-Import Configuration

After reviewing `terraform plan`, update the configuration:

```hcl
resource "teraswitch_metal" "database" {
  hostname         = "prod-db-01"
  region           = "PIT1"
  operating_system = "ubuntu-22.04"

  ssh_key_ids = [1234, 5678]

  tags = {
    environment = "production"
    role        = "database"
    managed_by  = "terraform"
  }
}
```

### Importing Multiple Resources

You can import multiple resources in sequence:

```bash
# Import all resources
terraform import teraswitch_metal.db1 45678
terraform import teraswitch_metal.db2 45679
terraform import teraswitch_cloud_compute.web1 12345
terraform import teraswitch_network.internal 78901
```

Or use a shell script for bulk imports:

```bash
#!/bin/bash
# import-resources.sh

set -e

# Metal servers
terraform import teraswitch_metal.db_primary 45678
terraform import teraswitch_metal.db_replica 45679

# Cloud instances
for i in 1 2 3; do
  terraform import "teraswitch_cloud_compute.web[$((i-1))]" "1234$i"
done

# Networks
terraform import teraswitch_network.internal 78901

echo "Import complete!"
```

### Using Data Sources During Migration

During migration, you can use data sources to reference resources not yet imported:

```hcl
# Reference an existing server without importing
data "teraswitch_metal" "legacy" {
  id = 45678
}

# New server that references the legacy one
resource "teraswitch_cloud_compute" "app" {
  hostname     = "app-server"
  region       = "PIT1"
  machine_type = "c1.medium"
  image        = "ubuntu-22.04"

  user_data = <<-EOF
    #!/bin/bash
    echo "DB_HOST=${data.teraswitch_metal.legacy.ip_addresses[0].address}" >> /etc/environment
  EOF
}
```

### Best Practices

#### 1. Back Up State Before Import

```bash
cp terraform.tfstate terraform.tfstate.backup
```

#### 2. Import One Resource at a Time

Avoid importing too many resources at once to make troubleshooting easier.

#### 3. Review Plan Carefully

Always run `terraform plan` after import to ensure the configuration matches the actual state.

#### 4. Add Tags for Tracking

Mark imported resources with tags:

```hcl
tags = {
  imported_at = "2024-01-15"
  imported_by = "terraform"
}
```

#### 5. Use Version Control

Commit your configuration after each successful import:

```bash
terraform import teraswitch_metal.database 45678
terraform plan  # Verify
git add .
git commit -m "Import database server into Terraform"
```

### Troubleshooting

#### Resource Not Found

```
Error: Cannot import non-existent remote object
```

Verify the resource ID exists and you have access to it.

#### Configuration Mismatch

If `terraform plan` shows unexpected changes after import:

1. Review the plan carefully
2. Update your configuration to match the actual state
3. Run `terraform plan` again until no changes are shown

#### State Conflicts

If a resource was partially imported or there's a state conflict:

```bash
# Remove from state (does not delete the actual resource)
terraform state rm teraswitch_metal.database

# Re-import
terraform import teraswitch_metal.database 45678
```

{% hint style="warning" %}
`terraform state rm` only removes the resource from Terraform's state file. The actual infrastructure remains unchanged.
{% endhint %}

\## See Also

* [teraswitch\_metal resource](/integrations/terraform/metal.md)
* [teraswitch\_metal data source](/integrations/terraform/metal-1.md)
* [Managing Bare Metal Services](/compute/metal/managing-services.md)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.teraswitch.com/integrations/terraform/import-existing.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
