> For the complete documentation index, see [llms.txt](https://docs.ionos.com/terraform-provider/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.ionos.com/terraform-provider/readme.md).

# README

[![Gitter](https://img.shields.io/gitter/room/ionos-cloud/sdk-general)](https://gitter.im/ionos-cloud/sdk-general) [![Release](https://img.shields.io/github/v/release/ionos-cloud/terraform-provider-ionoscloud.svg)](https://github.com/ionos-cloud/terraform-provider-ionoscloud/releases/latest) [![Release Date](https://img.shields.io/github/release-date/ionos-cloud/terraform-provider-ionoscloud.svg)](https://github.com/ionos-cloud/terraform-provider-ionoscloud/releases/latest) [![Compute-engine test run](https://github.com/ionos-cloud/terraform-provider-ionoscloud/actions/workflows/compute-test-run.yml/badge.svg)](https://github.com/ionos-cloud/terraform-provider-ionoscloud/actions/workflows/compute-test-run.yml) [![Go](https://img.shields.io/github/go-mod/go-version/ionos-cloud/terraform-provider-ionoscloud.svg)](https://github.com/ionos-cloud/terraform-provider-ionoscloud)

## IONOS CLOUD Terraform Provider

The IONOS CLOUD provider gives the ability to deploy and configure resources using the IONOS CLOUD APIs.

***

### Requirements

* [Terraform](https://www.terraform.io/downloads.html) 0.12.x+

**NOTE:** In order to use a specific version of this provider, please include the following block at the beginning of your terraform config files [details](https://www.terraform.io/docs/configuration/terraform.html#specifying-a-required-terraform-version):

```terraform
terraform {
  required_providers {
    ionoscloud = {
      source  = "ionos-cloud/ionoscloud"
      version = ">= 6.4.10"
    }
  }
}
```

### Using the provider

The provider needs to be configured with proper credentials before it can be used.

You can use token authentication. We strongly suggest to use token authentication for security reasons. Details on how to generate your token [here](https://github.com/ionos-cloud/sdk-go#token-authentication):

```bash
export IONOS_TOKEN="token"
```

Or you can set the environment variables for HTTP basic authentication:

```bash
export IONOS_USERNAME="username"
export IONOS_PASSWORD="password"
```

For managing IONOS Object Storage resources you need to set the following environment variables with your credentials

```bash
export IONOS_S3_ACCESS_KEY="accesskey"
export IONOS_S3_SECRET_KEY="secretkey"
```

Another way of configuring it is by providing your credentials/api\_url in a `.tf` configuration file in the `provider` block as shown in the below example.

```hcl
provider "ionoscloud" {
token             = var.ionos_token
# we suggest to use token authentication
# username          = var.ionos_username
# password          = var.ionos_password
#  optional, to be used only for reseller accounts
#  contract_number = "contract_number_here"
#  optional, does not need to be configured in most cases
#  endpoint = "custom_cloud_api_url"
#  s3_access_key     =  <your_access_key>
#  s3_secret_key     =  <your_secret_key>
#  s3_region     =  <your_bucket_region>
}
```

⚠️ **Note:** It's NOT usually necessary to set `endpoint` field. The SDKs the terraform uses know how to route requests to the correct endpoints in the API.

You can either explicitly write them in the .tf file or use var.name as in the example above. For setting the var.name, environment variables can be used. The environment variables must be in the format TF\_VAR\_name and this will be checked last for a value. For example:

```bash
export TF_VAR_ionos_token="token"
export TF_VAR_ionos_username="username"
export TF_VAR_ionos_password="password"
export TF_VAR_ionos_s3_access_key="accesskey"
export TF_VAR_ionos_s3_secret_key="secretkey"
export TF_VAR_ionos_s3_region="eu-central-3" # optional
```

<details>

<summary>How to use a configuration file</summary>

For more complex configurations, with multiple user profiles and environments with custom API URLs, you can use a YAML configuration file.

The path to the file can be set using the `IONOS_CONFIG_FILE` environment variable, or it defaults to `~/.ionos/config`. The file can either be written manually by the user, or generated through the `ionosctl login` command (see [ionosctl docs](https://github.com/ionos-cloud/ionosctl/blob/master/docs/subcommands/CLI%20Setup/login.md)).

A product's `endpoints` can be defined as **regional** (one entry per `location`) or **global** (no `location`). An optional top-level `failover` block controls transport-level failover across the configured endpoints. The supported keys are:

* `strategy`: `roundRobin` to fail over across the endpoints, or `none` (the default) to disable failover.
* `retryableMethods`: the HTTP methods eligible for failover. If omitted, only safe/idempotent methods are retried (`POST` is not).
* `failoverOnStatusCodes`: HTTP status codes that also trigger a failover to the next endpoint.
* `retryOnTimeout`: whether to fail over on request timeouts.
* `maxRetries`: the number of retries before giving up.
* `exponentialBackoff`: `initialInterval`, `maxInterval` (Go durations, e.g. `500ms`, `60s`), `multiplier` and `randomizationFactor`.

> **Note:** For the `cloud` product, regional (location-based) endpoints and global endpoints **cannot be mixed** in the same configuration. Define the `cloud` product with **either** regional endpoints **or** global endpoints, never both.

**Example — regional endpoints for the Cloud API** (the endpoint URLs below are illustrative; replace them with your own):

```yaml
version: 1.0
currentProfile: user # The current profile can also be overridden by the environment variable IONOS_CURRENT_PROFILE
profiles:
  - name: user
    environment: prod
    credentials:
      # You can use either username and password, or token.
      # If both username and password, as well as token are provided, the token will take precedence.
      token: <token>
environments:
  - name: prod
    products:
      - name: cloud
        endpoints:
          # One or more endpoints per location. When a location defines multiple endpoints,
          # requests for that location fail over across them (here, the two de/fra endpoints).
          - location: de/fra
            name: https://api.de-fra.ionos.com/cloudapi/v6
            skipTlsVerify: false
          - location: de/fra
            name: https://api.de-fra-2.ionos.com/cloudapi/v6
            skipTlsVerify: false
          - location: de/txl
            name: https://api.de-txl.ionos.com/cloudapi/v6
            skipTlsVerify: false
failover:
  strategy: roundRobin
  maxRetries: 3
  exponentialBackoff:
    initialInterval: 500ms
    maxInterval: 60s
```

**Example — global endpoints for the Cloud API** (the endpoint URLs below are illustrative; replace them with your own):

```yaml
version: 1.0
currentProfile: user
profiles:
  - name: user
    environment: prod
    credentials:
      token: <token>
environments:
  - name: prod
    products:
      - name: cloud
        endpoints:
          # Global endpoints have no location. List more than one to fail over between them.
          - name: https://api.ionos.com/cloudapi/v6
            skipTlsVerify: false
          - name: https://api.fra.ionos.com/cloudapi/v6
            skipTlsVerify: false
failover:
  strategy: roundRobin
  retryableMethods: [GET, HEAD, PUT, DELETE, OPTIONS, POST] # methods eligible for failover
  failoverOnStatusCodes: [503, 504]                         # also fail over on these HTTP statuses
  retryOnTimeout: true
  maxRetries: 3
  exponentialBackoff:
    initialInterval: 500ms
    maxInterval: 60s
    multiplier: 1.5
    randomizationFactor: 0.5
```

A configuration file can be used in conjunction with the `token`, `username`, `password`, `endpoint`, `s3_access_key`, `s3_secret_key` and `s3_region` fields in the provider block or the corresponding environment variables, replacing the credentials set for the `currentProfile`. All endpoints defined in the `currentProfile` environment will still be used.

</details>

See the [IONOS CLOUD Provider documentation](https://registry.terraform.io/providers/ionos-cloud/ionoscloud/latest/docs) for more details.

### Environment Variables

| Environment Variable    | Description                                                                                                                                                                                             |
| ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `IONOS_USERNAME`        | Specify the username used to login, to authenticate against the IONOS CLOUD API                                                                                                                         |
| `IONOS_PASSWORD`        | Specify the password used to login, to authenticate against the IONOS CLOUD API                                                                                                                         |
| `IONOS_TOKEN`           | Specify the token used to login, if a token is being used instead of username and password                                                                                                              |
| `IONOS_CONFIG_FILE`     | Path to the YAML configuration file with profiles, environments and endpoint overrides. Defaults to `~/.ionos/config`                                                                                   |
| `IONOS_CURRENT_PROFILE` | Overrides the `currentProfile` selected in the configuration file                                                                                                                                       |
| `IONOS_LOG_LEVEL`       | Specify the Log Level used to log messages. Possible values: Off, Debug, Trace                                                                                                                          |
| `IONOS_PINNED_CERT`     | Specify the SHA-256 public fingerprint here, enables certificate pinning                                                                                                                                |
| `IONOS_CONTRACT_NUMBER` | Specify the contract number on which you wish to provision. Only valid for reseller accounts, for other types of accounts the header will be ignored                                                    |
| `IONOS_S3_ACCESS_KEY`   | Specify the access key used to authenticate against the IONOS Object Storage API                                                                                                                        |
| `IONOS_S3_SECRET_KEY`   | Specify the secret key used to authenticate against the IONOS Object Storage API                                                                                                                        |
| `IONOS_S3_REGION`       | Region for IONOS Contract Owned Object Storage operations. Default value: eu-central-3. **If you use IONOS\_API\_URL\_OBJECT\_STORAGE, `IONOS_S3_REGION` is mandatory**                                 |
| `IONOS_API_URL`         | DO NOT USE unless for testing. Specify the API URL. It will overwrite the API endpoint default value `api.ionos.com`. It is not necessary to override this value unless you have special routing config |

### Certificate pinning:

You can enable certificate pinning if you want to bypass the normal certificate checking procedure, by doing the following:

Set env variable IONOS\_PINNED\_CERT=`<insert_sha256_public_fingerprint_here>`

You can get the sha256 fingerprint most easily from the browser by inspecting the certificate.

### Debugging

In the default mode, the Terraform provider returns only HTTP client errors. These usually consist only of the HTTP status code. There is no clear description of the problem. But if you want to see the API call error messages as well, you need to set the SDK and Terraform provider environment variables.

You can enable logging now using the `IONOS_LOG_LEVEL` env variable. Allowed values: `off`, `debug` and `trace`. Defaults to `off`.

⚠️ **Note:** We recommend you only use `trace` level for debugging purposes. Disable it in your production environments because it can log sensitive data. It logs the full request and response without encryption, even for an HTTPS call. Verbose request and response logging can also significantly impact your application’s performance.

```bash
$ export IONOS_LOG_LEVEL=debug
```

⚠️ **Note:** `IONOS_DEBUG` is now deprecated and will be removed in a future release.

⚠️ **Note:** We recommend you only use `IONOS_DEBUG` for debugging purposes. Disable it in your production environments because it can log sensitive data. It logs the full request and response without encryption, even for an HTTPS call. Verbose request and response logging can also significantly impact your application’s performance.

```bash
$ export TF_LOG=debug
$ export IONOS_DEBUG=true
$ terraform apply
```

now you can see the response body incl. api error message:

```json
{
  "httpStatus" : 422,
  "messages" : [ {
    "errorCode" : "200",
    "message" : "[VDC-yy-xxxx] Operation cannot be executed since this Kubernetes Nodepool is already marked for deletion. Current state of the resource is FAILED_DESTROYING."
  }]
}
```

### Building The Provider

**NOTE:**: Building the provider is only necessary if you want to contribute to the provider. It is not a prerequisite for using it.

#### Requirements:

```
- [Go](https://golang.org/doc/install) 1.20 (to build the provider plugin)
```

Clone repository to: `$GOPATH/src/github.com/ionos-cloud/terraform-provider-ionoscloud`

```sh
$ mkdir -p $GOPATH/src/github.com/ionos-cloud; cd $GOPATH/src/github.com/ionos-cloud
$ git clone https://github.com/ionos-cloud/terraform-provider-ionoscloud.git
```

Enter the provider directory and build the provider

```sh
$ cd $GOPATH/src/github.com/ionos-cloud/terraform-provider-ionoscloud
$ make build
```

### Developing the Provider

If you wish to work on the provider, you'll first need [Go](http://www.golang.org) installed on your machine (version 1.18+ is *required*). You'll also need to correctly set up a [GOPATH](http://golang.org/doc/code.html#GOPATH), as well as adding `$GOPATH/bin` to your `$PATH`.

To compile the provider, run `make build`. This will build the provider and put the provider binary in the `$GOPATH/bin` directory.

```sh
$ make build
...
$ $GOPATH/bin/terraform-provider-ionoscloud
...
```

### Testing the Provider

#### What Are We Testing?

The purpose of our acceptance tests is to **provision** resources containing all the available arguments, followed by **updates** on all arguments that allow this action. Beside the provisioning part, **data-sources** with all possible arguments and **imports** are also tested.

All tests are integrated into [github actions](https://github.com/ionos-cloud/terraform-provider-ionoscloud/actions) that run daily and are also run manually before any release.

#### How to Run Tests Locally

⚠️ **Warning:** Acceptance tests provision resources in the IONOS CLOUD, and often may involve extra billing charges on your account.

In order to test the provider, you can simply run:

```sh
$ make test
```

In order to run the full suite of Acceptance tests, run:

```sh
$ make testacc TAGS=all
```

**Test Tags**

Tests can also be run for a batch of resources or for a single resource, using tags.

*Example of running server and lan tests:*

```sh
$ make testacc TAGS=server,lan
```

<details>

<summary>See more details about test tags</summary>

````
**Build tags** are named as follows:

- `compute` - all **compute engine** tests (datacenter, firewall rule, image, IP block, IP failover, lan, location, nic, cross connect, server, snapshot, template, volume)
- `nlb` - **network load balancer** and **network load balancer forwarding rule** tests
- `natgateway` - **NAT gateway** and **NAT gateway rule** tests
- `k8s` - **k8s cluster** and **k8s node pool** tests
- `dbaas` - **DBaaS postgres cluster** tests
- `alb` - **Application Load Balancer** tests

``` sh
$ make testacc TAGS=dbaas
```

You can also test one single resource, using one of the tags: `backup`, `datacenter`, `dbaas`, `firewall`, `group`, `image`, `ipblock`, `ipfailover`, `k8s`, `lan`, `location`, `natgateway`,
`nlb`, `nic`, `pcc`, `resource`, `s3key`, `server`, `share`, `snapshot`, `template`, `user`, `volume`
````

</details>

### Migrating from the ProfitBricks provider

Please see the [Documentation](/terraform-provider/docs/index.md#migrating-from-the-profitbricks-provider) on how to migrate from the ProfitBricks provider.

### Frequently Asked Questions

#### How can I find out the IP for the added NIC on a K8s nodepool?

Please check out this [module](https://github.com/ionos-cloud/terraform-ionoscloud-kube-lan-ip).

#### For more complex examples on how to use the provider

Please check out the [examples](https://github.com/ionos-cloud/terraform-provider-ionoscloud/tree/master/examples/README.md) directory.
