今日はなにの日。

気になったこと勉強になったことのメモ。

今日は、CDK for Terraform がGAしたので再挑戦してみるの日。

目次

とある日

この間CDK for Terraform(以下cdktfと呼ぶ)がGAされたらしいです。

CDK for Terraform Is Now Generally Available

以前挑戦して惨敗したので、GAした今ならできるやろう理論で再度やってみた内容です。

updraft.hatenadiary.com

概要

検証環境

やっていく上で、Windows特有の問題にあたったので、環境について記述しておきます。

  • Windows環境
  • WSL2インストール済み
  • go 1.19
  • VSCodeでプログラム作成

やっていく

↓参考にするチュートリアルです。

Install CDK for Terraform and Run a Quick Start Demo | Terraform - HashiCorp Learn

インストール

前回入れてたのでスルーしましたが、必要なので最新版をインストールします。

npm install --global cdktf-cli@latest

あと、Go言語で必要なモジュールをインストールします。

go get github.com/hashicorp/cdktf-provider-docker-go/docker

チュートリアルだとない工程ですがあとあとで必要なります。

プロジェクトを作成して初期化

VSCodeディレクトリ作ってPowerShellで移動します。

cdktf init --template=go --local

色々聞かれますがEnterとYesを押して進めます。

PS C:\Users\user\Documents\GitHub\Terraform\Docker\CDK\Go3> cdktf init --template=go --local
Note: By supplying '--local' option you have chosen local storage mode for storing the state of your stack.
This means that your Terraform state file will be stored locally on disk in a file 'terraform.<STACK NAME>.tfstate' in the root of your project.
? Project Name Go3
? Project Description A simple getting started project for cdktf.
? Do you want to send crash reports to the CDKTF team? See
https://www.terraform.io/cdktf/create-and-deploy/configuration-file#enable-crash-reporting-for-the-cli for more
information Yes
go: upgraded github.com/aws/constructs-go/constructs/v10 v10.0.25 => v10.1.83
========================================================================================================

  Your cdktf go project is ready!

  cat help                Prints this message

  Compile:
    go build              Builds your go project

  Synthesize:
    cdktf synth [stack]   Synthesize Terraform resources to cdktf.out/

  Diff:
    cdktf diff [stack]    Perform a diff (terraform plan) for the given stack

  Deploy:
    cdktf deploy [stack]  Deploy the given stack

  Destroy:
    cdktf destroy [stack] Destroy the given stack

  Learn more about using modules and providers https://cdk.tf/modules-and-providers

Use Providers:

  Use the add command to add providers:

  cdktf provider add "aws@~>3.0" null kreuzwerker/docker

  Learn more: https://cdk.tf/modules-and-providers

========================================================================================================

プロバイダーインストールします。

PS C:\Users\user\Documents\GitHub\Terraform\Docker\CDK\Go3> cdktf provider add kreuzwerker/docker
Checking whether pre-built provider exists for the following constraints:
  provider: kreuzwerker/docker
  version : latest
  language: go
  cdktf   : 0.12.2

Found pre-built provider.
Adding package github.com/hashicorp/cdktf-provider-docker-go/docker @ 2.0.38
[2022-08-28T17:45:15.804] [ERROR] default - go: downloading github.com/hashicorp/cdktf-provider-docker-go/docker/v2 v2.0.38

go: downloading github.com/hashicorp/cdktf-provider-docker-go/docker/v2 v2.0.38
[2022-08-28T17:45:20.272] [ERROR] default - go: downloading github.com/aws/constructs-go/constructs/v10 v10.1.88

go: downloading github.com/aws/constructs-go/constructs/v10 v10.1.88
[2022-08-28T17:45:20.693] [ERROR] default - go: upgraded github.com/aws/constructs-go/constructs/v10 v10.1.83 => v10.1.88
go: added github.com/hashicorp/cdktf-provider-docker-go/docker/v2 v2.0.38

go: upgraded github.com/aws/constructs-go/constructs/v10 v10.1.83 => v10.1.88
go: added github.com/hashicorp/cdktf-provider-docker-go/docker/v2 v2.0.38
Package installed.

コードの修正 PART1

チュートリアルのコードをそのまま使用します。

package main

import (
    "github.com/aws/constructs-go/constructs/v10"
    "github.com/aws/jsii-runtime-go"
    "github.com/hashicorp/terraform-cdk-go/cdktf"

    "cdk.tf/go/stack/generated/kreuzwerker/docker"
)

func NewMyStack(scope constructs.Construct, id string) cdktf.TerraformStack {
    stack := cdktf.NewTerraformStack(scope, &id)

    docker.NewDockerProvider(stack, jsii.String("docker"), &docker.DockerProviderConfig{})

    dockerImage := docker.NewImage(stack, jsii.String("nginxImage"), &docker.ImageConfig{
        Name:        jsii.String("nginx:latest"),
        KeepLocally: jsii.Bool(false),
    })

    docker.NewContainer(stack, jsii.String("nginxContainer"), &docker.ContainerConfig{
        Image: dockerImage.Latest(),
        Name:  jsii.String("tutorial"),
        Ports: &[]*docker.ContainerPorts{{
            Internal: jsii.Number(80), External: jsii.Number(8000),
        }},
    })

    return stack
}

func main() {
    app := cdktf.NewApp(nil)

    NewMyStack(app, "learn-cdktf-docker")

    app.Synth()
}

コンテナデプロイ

失敗します。

PS C:\Users\user\Documents\GitHub\Terraform\Docker\CDK\Go3> cdktf deploy
[2022-08-28T17:48:00.450] [INFO] default - Error reporting disabled: SENTRY_DSN not set

⠧  Synthesizing
[2022-08-28T17:48:01.818] [ERROR] default - main.go:8:5: no required module provides package cdk.tf/go/stack/generated/kreuzwerker/docker; to add it:
ERROR: cdktf encountered an error while synthesizing

Synth command: go run main.go
Error:         spawn go run main.go ENOENT

Command output on stderr:

    main.go:8:5: no required module provides package cdk.tf/go/stack/generated/kreuzwerker/docker; to add it:
        go get cdk.tf/go/stack/generated/kreuzwerker/docker




⠼  Synthesizing

コード修正 PART2

外部モジュールがなくてエラーが出ます。

GitHubや以下の記事参考にして修正しました。

hashicorp/cdktf-provider-docker: Prebuilt Terraform CDK (cdktf) provider for docker.

Goでterraform

"cdk.tf/go/stack/generated/kreuzwerker/docker"

↓に変更します。

"github.com/hashicorp/cdktf-provider-docker-go/docker"

package main

import (
    "github.com/aws/constructs-go/constructs/v10"
    "github.com/aws/jsii-runtime-go"
    "github.com/hashicorp/terraform-cdk-go/cdktf"

    "github.com/hashicorp/cdktf-provider-docker-go/docker"
)

func NewMyStack(scope constructs.Construct, id string) cdktf.TerraformStack {
    stack := cdktf.NewTerraformStack(scope, &id)

    docker.NewDockerProvider(stack, jsii.String("docker"), &docker.DockerProviderConfig{})

    dockerImage := docker.NewImage(stack, jsii.String("nginxImage"), &docker.ImageConfig{
        Name:        jsii.String("nginx:latest"),
        KeepLocally: jsii.Bool(false),
    })

    docker.NewContainer(stack, jsii.String("nginxContainer"), &docker.ContainerConfig{
        Image: dockerImage.Latest(),
        Name:  jsii.String("tutorial"),
        Ports: &[]*docker.ContainerPorts{{
            Internal: jsii.Number(80), External: jsii.Number(8000),
        }},
    })

    return stack
}

func main() {
    app := cdktf.NewApp(nil)

    NewMyStack(app, "learn-cdktf-docker")

    app.Synth()
}

ちなみに、エラーのアドバイス通りにやってもだめです。

PS C:\Users\user\Documents\GitHub\Terraform\Docker\CDK\Go3>  go get cdk.tf/go/stack/generated/kreuzwerker/docker
go: unrecognized import path "cdk.tf/go/stack/generated/kreuzwerker/docker": reading https://cdk.tf/go/stack/generated/kreuzwerker/docker?go-get=1: 404 Not Found
        server response: The page could not be found

他にもVSCodeでやっているとGOPATHの参照場所がおかしい問題があったので別途解決するために色々と調べてました。

go.useLanguageServer": trueを設定に追加しました。

Go + VSCode でサブディレクトリに go.mod を置くと `could not import ... (no package for import ...)` になる - Note

コンテナデプロイ

エラーになりました。

PS C:\Users\user\Documents\GitHub\Terraform\Docker\CDK\Go3> cdktf deploy
[2022-08-28T17:52:35.026] [INFO] default - Error reporting disabled: SENTRY_DSN not set
learn-cdktf-docker  Initializing the backend...
learn-cdktf-docker
                    Successfully configured the backend "local"! Terraform will automatically
                    use this backend unless the backend configuration changes.
learn-cdktf-docker  Initializing provider plugins...
                    - Finding kreuzwerker/docker versions matching "2.19.0"...
learn-cdktf-docker  - Using kreuzwerker/docker v2.19.0 from the shared cache directory
learn-cdktf-docker  Terraform has created a lock file .terraform.lock.hcl to record the provider
                    selections it made above. Include this file in your version control repository
                    so that Terraform can guarantee to make the same selections by default when
                    you run "terraform init" in the future.
learn-cdktf-docker  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.


1 Stack deploying     0 Stacks done     0 Stacks waiting
[2022-08-28T17:52:46.707] [ERROR] default - ╷
│ Error: Error initializing Docker client: protocol not available
│
│   with provider["registry.terraform.io/kreuzwerker/docker"],
│   on cdk.tf.json line 14, in provider.docker[0]:
│   14:       }
learn-cdktf-docker  ╷
                    │ Error: Error initializing Docker client: protocol not available
                    │
                    │   with provider["registry.terraform.io/kreuzwerker/docker"],
                    │   on cdk.tf.json line 14, in provider.docker[0]:
                    │   14:       }
                    │
                    ╵


1 Stack deploying     0 Stacks done     0 Stacks waiting
non-zero exit code 1

コードの修正 PART3

エラーをそのまま調べるとWindows特有の問題らしいです。

Error initializing Docker client: protocol not available · Issue #180 · hashicorp/terraform-provider-docker

Fix "Error initializing Docker client: protocol not available" on Terraform for Windows with WSL2 - Kajabity.com

言われている通り、プロバイダーのHostでnpipe:////.//pipe//docker_engineを追加します。

が、cdktfのドキュメントがないのでどうしていすればいいのか全くわかりません。

コードを見る

プロバイダーのところで指定するっぽいのでそれらしいコードを見つけます。

docker.NewDockerProvider(stack, jsii.String("docker"), &docker.DockerProviderConfig{})

↑これが一番関係ありそう。

cdktf-provider-docker-go/docker at main · hashicorp/cdktf-provider-docker-go

GitHubでNewDockerProviderが書かれている場所を探します。

色々とファイルがありますが、Providerと書かれているファイル名があったので見ます。

cdktf-provider-docker-go/docker_DockerProvider.go at main · hashicorp/cdktf-provider-docker-go

するとSetHost関数があるのでこれを呼び出せば良さそう。

cdktf-provider-docker-go/docker_DockerProvider.go at main · hashicorp/cdktf-provider-docker-go

func (j *jsiiProxy_DockerProvider) SetHost(val *string) {
    _jsii_.Set(
        j,
        "host",
        val,
    )
}

Goについてはそこまで詳しくないので色々と試行錯誤して↓になりました。

package main

import (
    "github.com/hashicorp/cdktf-provider-docker-go/docker"
    "github.com/aws/constructs-go/constructs/v10"
    "github.com/aws/jsii-runtime-go"
    "github.com/hashicorp/terraform-cdk-go/cdktf"
)

func NewMyStack(scope constructs.Construct, id string) cdktf.TerraformStack {
    stack := cdktf.NewTerraformStack(scope, &id)

    provider := docker.NewDockerProvider(stack, jsii.String("docker"), &docker.DockerProviderConfig{})
    host := "npipe:////.//pipe//docker_engine"
    provider.SetHost(&host)
    dockerImage := docker.NewImage(stack, jsii.String("nginxImage"), &docker.ImageConfig{
        Name:        jsii.String("nginx:latest"),
        KeepLocally: jsii.Bool(false),
    })
    docker.NewContainer(stack, jsii.String("nginxContainer"), &docker.ContainerConfig{
        Image: dockerImage.Latest(),
        Name:  jsii.String("tutorial"),
        Ports: &[]*docker.ContainerPorts{{
            Internal: jsii.Number(80), External: jsii.Number(8000),
        }},
        Provider:provider,
    })

    return stack
}

func main() {
    app := cdktf.NewApp(nil)
    NewMyStack(app, "learn-cdktf-docker")
    app.Synth()
}

NewDockerProviderの返り値を変数にして、SetHost関数を呼び出して値を渡します。

コンテナデプロイ

3度目の正直です。

PS C:\Users\user\Documents\GitHub\Terraform\Docker\CDK\Go3>cdktf deploy
[2022-08-28T18:07:29.020] [INFO] default - Error reporting disabled: SENTRY_DSN not set
learn-cdktf-docker  Initializing the backend...
learn-cdktf-docker  Initializing provider plugins...
                    - Reusing previous version of kreuzwerker/docker from the dependency lock file
learn-cdktf-docker  - Using previously-installed kreuzwerker/docker v2.19.0
learn-cdktf-docker  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.
learn-cdktf-docker  Terraform used the selected providers to generate the following execution
                    plan. Resource actions are indicated with the following symbols:
                    + create

                    Terraform will perform the following actions:
learn-cdktf-docker    # docker_container.nginxContainer (nginxContainer) will be created
                      + resource "docker_container" "nginxContainer" {
                    + attach           = false
                    + bridge           = (known after apply)
                    + command          = (known after apply)
                    + container_logs   = (known after apply)
                    + entrypoint       = (known after apply)
                    + env              = (known after apply)
                    + exit_code        = (known after apply)
                    + gateway          = (known after apply)
                    + hostname         = (known after apply)
                    + id               = (known after apply)
                    + image            = (known after apply)
                    + init             = (known after apply)
                    + ip_address       = (known after apply)
                    + ip_prefix_length = (known after apply)
                    + ipc_mode         = (known after apply)
                    + log_driver       = (known after apply)
                    + logs             = false
                    + must_run         = true
                    + name             = "tutorial"
                    + network_data     = (known after apply)
                    + read_only        = false
                    + remove_volumes   = true
                    + restart          = "no"
                    + rm               = false
                    + runtime          = (known after apply)
                    + security_opts    = (known after apply)
                    + shm_size         = (known after apply)
                    + start            = true
                    + stdin_open       = false
                    + stop_signal      = (known after apply)
                    + stop_timeout     = (known after apply)
                    + tty              = false

                    + healthcheck {
                    + interval     = (known after apply)
                    + retries      = (known after apply)
                    + start_period = (known after apply)
                    + test         = (known after apply)
                    + timeout      = (known after apply)
                    }

                    + labels {
                    + label = (known after apply)
                    + value = (known after apply)
                    }

                    + ports {
                    + external = 8000
                    + internal = 80
                    + ip       = "0.0.0.0"
                    + protocol = "tcp"
                    }
                    }
learn-cdktf-docker    # docker_image.nginxImage (nginxImage) will be created
                      + resource "docker_image" "nginxImage" {
                    + id           = (known after apply)
                    + keep_locally = false
                    + latest       = (known after apply)
                    + name         = "nginx:latest"
                    + output       = (known after apply)
                    + repo_digest  = (known after apply)
                    }

                    Plan: 2 to add, 0 to change, 0 to destroy.

                    ─────────────────────────────────────────────────────────────────────────────

                    Saved the plan to: plan

                    To perform exactly these actions, run the following command to apply:
                    terraform apply "plan"
learn-cdktf-docker  docker_image.nginxImage (nginxImage): Creating...
learn-cdktf-docker  docker_image.nginxImage (nginxImage): Creation complete after 10s [id=sha256:2b7d6430f78d432f89109b29d88d4c36c868cdbf15dc31d2132ceaa02b993763nginx:latest]
learn-cdktf-docker  docker_container.nginxContainer (nginxContainer): Creating...
learn-cdktf-docker  docker_container.nginxContainer (nginxContainer): Creation complete after 1s [id=ce42b217cdd27a7832e23e4188f488227193d1b186dd656bd07c4824c0a0f94e]
learn-cdktf-docker
                    Apply complete! Resources: 2 added, 0 changed, 0 destroyed.

コンテナ起動確認

コンテナが起動したのかを確認します。

PS C:\Users\user\Documents\GitHub\Terraform\Docker\CDK\Go3> docker ps
CONTAINER ID   IMAGE                  COMMAND                  CREATED          STATUS          PORTS                       NAMES
ce42b217cdd2   2b7d6430f78d           "/docker-entrypoint.…"   52 seconds ago   Up 52 seconds   0.0.0.0:8000->80/tcp        tutorial

問題なさそうです。

お片付け

cdktf destroyでリソースを削除します。

PS C:\Users\user\Documents\GitHub\Terraform\Docker\CDK\Go3> cdktf destroy
[2022-08-28T18:09:23.559] [INFO] default - Error reporting disabled: SENTRY_DSN not set
learn-cdktf-docker  Initializing the backend...
learn-cdktf-docker  Initializing provider plugins...
                    - Reusing previous version of kreuzwerker/docker from the dependency lock file
learn-cdktf-docker  - Using previously-installed kreuzwerker/docker v2.19.0
learn-cdktf-docker  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.
learn-cdktf-docker  docker_image.nginxImage (nginxImage): Refreshing state... [id=sha256:2b7d6430f78d432f89109b29d88d4c36c868cdbf15dc31d2132ceaa02b993763nginx:latest]
learn-cdktf-docker  docker_container.nginxContainer (nginxContainer): Refreshing state... [id=ce42b217cdd27a7832e23e4188f488227193d1b186dd656bd07c4824c0a0f94e]
learn-cdktf-docker
                    Note: Objects have changed outside of Terraform

                    Terraform detected the following changes made outside of Terraform since the
                    last "terraform apply":

                      # docker_container.nginxContainer (nginxContainer) has been changed
                      ~ resource "docker_container" "nginxContainer" {
                    + dns               = []
                    + dns_opts          = []
                    + dns_search        = []
                    + group_add         = []
                    id                = "ce42b217cdd27a7832e23e4188f488227193d1b186dd656bd07c4824c0a0f94e"
                    + links             = []
                    + log_opts          = {}
                    name              = "tutorial"
                    + storage_opts      = {}
                    + sysctls           = {}
                    + tmpfs             = {}
                    # (34 unchanged attributes hidden)

                    # (1 unchanged block hidden)
                    }

                    Unless you have made equivalent changes to your configuration, or ignored the
                    relevant attributes using ignore_changes, the following plan may include
                    actions to undo or respond to these changes.
learn-cdktf-docker
                    ─────────────────────────────────────────────────────────────────────────────

                    Terraform used the selected providers to generate the following execution
                    plan. Resource actions are indicated with the following symbols:
                    - destroy

                    Terraform will perform the following actions:

                      # docker_container.nginxContainer (nginxContainer) will be destroyed
                      - resource "docker_container" "nginxContainer" {
                    - attach            = false -> null
                    - command           = [
                    - "nginx",
                    - "-g",
                    - "daemon off;",
                    ] -> null
                    - cpu_shares        = 0 -> null
                    - dns               = [] -> null
                    - dns_opts          = [] -> null
                    - dns_search        = [] -> null
                    - entrypoint        = [
                    - "/docker-entrypoint.sh",
                    ] -> null
                    - env               = [] -> null
                    - gateway           = "172.17.0.1" -> null
                    - group_add         = [] -> null
                    - hostname          = "ce42b217cdd2" -> null
                    - id                = "ce42b217cdd27a7832e23e4188f488227193d1b186dd656bd07c4824c0a0f94e" -> null
                    - image             = "sha256:2b7d6430f78d432f89109b29d88d4c36c868cdbf15dc31d2132ceaa02b993763" -> null
                    - init              = false -> null
                    - ip_address        = "172.17.0.2" -> null
                    - ip_prefix_length  = 16 -> null
                    - ipc_mode          = "private" -> null
                    - links             = [] -> null
                    - log_driver        = "json-file" -> null
                    - log_opts          = {} -> null
                    - logs              = false -> null
                    - max_retry_count   = 0 -> null
                    - memory            = 0 -> null
                    - memory_swap       = 0 -> null
                    - must_run          = true -> null
                    - name              = "tutorial" -> null
                    - network_data      = [
                    - {
                    - gateway                   = "172.17.0.1"
                    - global_ipv6_address       = ""
                    - global_ipv6_prefix_length = 0
                    - ip_address                = "172.17.0.2"
                    - ip_prefix_length          = 16
                    - ipv6_gateway              = ""
                    - network_name              = "bridge"
                    },
                    ] -> null
                    - network_mode      = "default" -> null
                    - privileged        = false -> null
                    - publish_all_ports = false -> null
                    - read_only         = false -> null
                    - remove_volumes    = true -> null
                    - restart           = "no" -> null
                    - rm                = false -> null
                    - runtime           = "runc" -> null
                    - security_opts     = [] -> null
                    - shm_size          = 64 -> null
                    - start             = true -> null
                    - stdin_open        = false -> null
                    - stop_signal       = "SIGQUIT" -> null
                    - stop_timeout      = 0 -> null
                    - storage_opts      = {} -> null
                    - sysctls           = {} -> null
                    - tmpfs             = {} -> null
                    - tty               = false -> null

                    - ports {
                    - external = 8000 -> null
                    - internal = 80 -> null
                    - ip       = "0.0.0.0" -> null
                    - protocol = "tcp" -> null
                    }
                    }

                      # docker_image.nginxImage (nginxImage) will be destroyed
                      - resource "docker_image" "nginxImage" {
                    - id           = "sha256:2b7d6430f78d432f89109b29d88d4c36c868cdbf15dc31d2132ceaa02b993763nginx:latest" -> null
                    - keep_locally = false -> null
                    - latest       = "sha256:2b7d6430f78d432f89109b29d88d4c36c868cdbf15dc31d2132ceaa02b993763" -> null
                    - name         = "nginx:latest" -> null
                    - repo_digest  = "nginx@sha256:b95a99feebf7797479e0c5eb5ec0bdfa5d9f504bc94da550c2f58e839ea6914f" -> null
                    }

                    Plan: 0 to add, 0 to change, 2 to destroy.

                    ─────────────────────────────────────────────────────────────────────────────

                    Saved the plan to: plan

                    To perform exactly these actions, run the following command to apply:
                    terraform apply "plan"
learn-cdktf-docker  docker_image.nginxImage (nginxImage): Refreshing state... [id=sha256:2b7d6430f78d432f89109b29d88d4c36c868cdbf15dc31d2132ceaa02b993763nginx:latest]
learn-cdktf-docker  docker_container.nginxContainer (nginxContainer): Refreshing state... [id=ce42b217cdd27a7832e23e4188f488227193d1b186dd656bd07c4824c0a0f94e]
learn-cdktf-docker
                    Note: Objects have changed outside of Terraform

                    Terraform detected the following changes made outside of Terraform since the
                    last "terraform apply":

                      # docker_container.nginxContainer (nginxContainer) has been changed
                      ~ resource "docker_container" "nginxContainer" {
                    + dns               = []
                    + dns_opts          = []
                    + dns_search        = []
                    + group_add         = []
                    id                = "ce42b217cdd27a7832e23e4188f488227193d1b186dd656bd07c4824c0a0f94e"
                    + links             = []
                    + log_opts          = {}
                    name              = "tutorial"
                    + storage_opts      = {}
                    + sysctls           = {}
                    + tmpfs             = {}
                    # (34 unchanged attributes hidden)

                    # (1 unchanged block hidden)
                    }

                    Unless you have made equivalent changes to your configuration, or ignored the
                    relevant attributes using ignore_changes, the following plan may include
                    actions to undo or respond to these changes.
learn-cdktf-docker
                    ─────────────────────────────────────────────────────────────────────────────

                    Terraform used the selected providers to generate the following execution
                    plan. Resource actions are indicated with the following symbols:
                    - destroy

                    Terraform will perform the following actions:
learn-cdktf-docker    # docker_container.nginxContainer (nginxContainer) will be destroyed
                      - resource "docker_container" "nginxContainer" {
                    - attach            = false -> null
                    - command           = [
                    - "nginx",
                    - "-g",
                    - "daemon off;",
                    ] -> null
                    - cpu_shares        = 0 -> null
                    - dns               = [] -> null
                    - dns_opts          = [] -> null
                    - dns_search        = [] -> null
                    - entrypoint        = [
                    - "/docker-entrypoint.sh",
                    ] -> null
                    - env               = [] -> null
                    - gateway           = "172.17.0.1" -> null
                    - group_add         = [] -> null
                    - hostname          = "ce42b217cdd2" -> null
                    - id                = "ce42b217cdd27a7832e23e4188f488227193d1b186dd656bd07c4824c0a0f94e" -> null
                    - image             = "sha256:2b7d6430f78d432f89109b29d88d4c36c868cdbf15dc31d2132ceaa02b993763" -> null
                    - init              = false -> null
                    - ip_address        = "172.17.0.2" -> null
                    - ip_prefix_length  = 16 -> null
                    - ipc_mode          = "private" -> null
                    - links             = [] -> null
                    - log_driver        = "json-file" -> null
                    - log_opts          = {} -> null
                    - logs              = false -> null
                    - max_retry_count   = 0 -> null
                    - memory            = 0 -> null
                    - memory_swap       = 0 -> null
                    - must_run          = true -> null
                    - name              = "tutorial" -> null
                    - network_data      = [
                    - {
                    - gateway                   = "172.17.0.1"
                    - global_ipv6_address       = ""
                    - global_ipv6_prefix_length = 0
                    - ip_address                = "172.17.0.2"
                    - ip_prefix_length          = 16
                    - ipv6_gateway              = ""
                    - network_name              = "bridge"
                    },
                    ] -> null
                    - network_mode      = "default" -> null
                    - privileged        = false -> null
                    - publish_all_ports = false -> null
                    - read_only         = false -> null
                    - remove_volumes    = true -> null
                    - restart           = "no" -> null
                    - rm                = false -> null
                    - runtime           = "runc" -> null
                    - security_opts     = [] -> null
                    - shm_size          = 64 -> null
                    - start             = true -> null
                    - stdin_open        = false -> null
                    - stop_signal       = "SIGQUIT" -> null
                    - stop_timeout      = 0 -> null
                    - storage_opts      = {} -> null
                    - sysctls           = {} -> null
                    - tmpfs             = {} -> null
                    - tty               = false -> null

                    - ports {
                    - external = 8000 -> null
                    - internal = 80 -> null
                    - ip       = "0.0.0.0" -> null
                    - protocol = "tcp" -> null
                    }
                    }

                      # docker_image.nginxImage (nginxImage) will be destroyed
                      - resource "docker_image" "nginxImage" {
                    - id           = "sha256:2b7d6430f78d432f89109b29d88d4c36c868cdbf15dc31d2132ceaa02b993763nginx:latest" -> null
                    - keep_locally = false -> null
                    - latest       = "sha256:2b7d6430f78d432f89109b29d88d4c36c868cdbf15dc31d2132ceaa02b993763" -> null
                    - name         = "nginx:latest" -> null
                    - repo_digest  = "nginx@sha256:b95a99feebf7797479e0c5eb5ec0bdfa5d9f504bc94da550c2f58e839ea6914f" -> null
                    }

                    Plan: 0 to add, 0 to change, 2 to destroy.

learn-cdktf-docker  docker_container.nginxContainer (nginxContainer): Destroying... [id=ce42b217cdd27a7832e23e4188f488227193d1b186dd656bd07c4824c0a0f94e]
learn-cdktf-docker  docker_container.nginxContainer (nginxContainer): Destruction complete after 1s
learn-cdktf-docker  docker_image.nginxImage (nginxImage): Destroying... [id=sha256:2b7d6430f78d432f89109b29d88d4c36c868cdbf15dc31d2132ceaa02b993763nginx:latest]
learn-cdktf-docker  docker_image.nginxImage (nginxImage): Destruction complete after 0s
learn-cdktf-docker
                    Destroy complete! Resources: 2 destroyed.

ドキュメントがないのでかなり苦戦しました。

得意なPythonとかならまた結果が違ったかなと思いつつ。

デプロイはできたものの、Go言語の書き方として正しいのか疑問が残ります。

今後使っていくかと問われると.....なんとも言えないって感じです。

普段はDocker-composeをメインでよく使うので現状ではそっちのほうが構築スピードは早い気がします。

参考記事

Fix "Error initializing Docker client: protocol not available" on Terraform for Windows with WSL2 - Kajabity.com

API Reference for Go | Terraform by HashiCorp

cdktf-provider-docker/API.md at main · hashicorp/cdktf-provider-docker

@cdktf/provider-docker 2.0.37 - Construct Hub