LINUX.ORG.RU

terraform и docker

 ,


0

1

здравствуй читатель

пытаюсь освоить связку terraform и docker пишу следующую конструкцию, которая по моей задаче должна бы запустить три хеловорлда в докере

provider "docker" {
  host = "ssh://user@docker:22"
}

# Create a container
resource "docker_container" "foo" {
  count      = 3
  depends_on = [docker_image.hello-world]
  image      = docker_image.hello-world.latest

  name = "foo${count.index}"
}

resource "docker_image" "hello-world" {
  name = "hello-world"
}

terraform plan проходит без предупреждений

$ terraform apply

An execution plan has been generated and is shown below.
Resource actions are indicated with the following symbols:
  + create

Terraform will perform the following actions:

  # docker_container.foo[0] will be created
  + resource "docker_container" "foo" {
      + 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)
      + ip_address       = (known after apply)
      + ip_prefix_length = (known after apply)
      + ipc_mode         = (known after apply)
      + log_driver       = (known after apply)
      + log_opts         = (known after apply)
      + logs             = false
      + must_run         = true
      + name             = "foo0"
      + network_data     = (known after apply)
      + read_only        = false
      + restart          = "no"
      + rm               = false
      + shm_size         = (known after apply)
      + start            = true
      + user             = (known after apply)

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

  # docker_container.foo[1] will be created
  + resource "docker_container" "foo" {
      + 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)
      + ip_address       = (known after apply)
      + ip_prefix_length = (known after apply)
      + ipc_mode         = (known after apply)
      + log_driver       = (known after apply)
      + log_opts         = (known after apply)
      + logs             = false
      + must_run         = true
      + name             = "foo1"
      + network_data     = (known after apply)
      + read_only        = false
      + restart          = "no"
      + rm               = false
      + shm_size         = (known after apply)
      + start            = true
      + user             = (known after apply)

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

  # docker_container.foo[2] will be created
  + resource "docker_container" "foo" {
      + 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)
      + ip_address       = (known after apply)
      + ip_prefix_length = (known after apply)
      + ipc_mode         = (known after apply)
      + log_driver       = (known after apply)
      + log_opts         = (known after apply)
      + logs             = false
      + must_run         = true
      + name             = "foo2"
      + network_data     = (known after apply)
      + read_only        = false
      + restart          = "no"
      + rm               = false
      + shm_size         = (known after apply)
      + start            = true
      + user             = (known after apply)

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

  # docker_image.hello-world will be created
  + resource "docker_image" "hello-world" {
      + id     = (known after apply)
      + latest = (known after apply)
      + name   = "hello-world"
    }

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

Do you want to perform these actions?
  Terraform will perform the actions described above.
  Only 'yes' will be accepted to approve.

  Enter a value: yes

docker_image.hello-world: Creating...
docker_image.hello-world: Creation complete after 0s [id=sha256:bf756fb1ae65adf866bd8c456593cd24beb6a0a061dedf42b26a993176745f6bhello-world]
docker_container.foo[0]: Creating...
docker_container.foo[1]: Creating...
docker_container.foo[2]: Creating...
docker_container.foo[1]: Still creating... [10s elapsed]
docker_container.foo[2]: Still creating... [10s elapsed]

Error: Container afd354e763dfb796c74fa7d4e253ecb961b7301d15d5343e7cbf9f0b094f309d exited after creation, error was: 

  on main.tf line 6, in resource "docker_container" "foo":
   6: resource "docker_container" "foo" {



Error: Container 8d7638874ea4c8705cbc760f8e1f36118018fa90a50bda0df0c883cc6c0c6f55 exited after creation, error was: 

  on main.tf line 6, in resource "docker_container" "foo":
   6: resource "docker_container" "foo" {



Error: Container 260404f0618ebbd4e481f0a5fe41414e2a0e8ec03aa1e2aeba7e8de4ab91e0bc exited after creation, error was: 

  on main.tf line 6, in resource "docker_container" "foo":
   6: resource "docker_container" "foo" {


$ docker -v Docker version 19.03.11, build 42e35e61f3

$ terraform -v Terraform v0.12.26

  • provider.docker v2.7.1

запускаю пальчиками или через ansible все без проблем

$ docker ps -a
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS                      PORTS               NAMES
fa5fb066ee85        hello-world         "/hello"            26 minutes ago      Exited (0) 26 minutes ago                       quizzical_merkle
12b62aefd47b        hello-world         "/hello"            26 minutes ago      Exited (0) 26 minutes ago                       quizzical_robinson
f92c9a5ed928        hello-world         "/hello"            26 minutes ago      Exited (0) 26 minutes ago                       relaxed_euler

убираю count и запускаю один экземпляр hello-world прекрасно работает из terraform. Где и что я упустил из виду?

спасибо



Последнее исправление: WaterSlon (всего исправлений: 3)

Поправь разметку, пожалуйста. На форуме по умолчанию используется markdown, а ты lorcode используешь. cut работает только в новостях.

ox55ff ★★★★★
()
Ответ на: комментарий от ox55ff

и рад бы, но

В комментариях и сообщениях форума эта разметка игнорируется.

WaterSlon
() автор топика

Я с этим провайдером не работал. Но навскидку

resource "docker_image" "hello-world" {
  name = "hello-world"
}

выглядит подозрительно. resource, это то, что вы создаёте, а судя по отсутствию каких-либо параметров, вы обращаетесь к уже существующему образу, что надо делать через data.

ugoday ★★★★★
()
Ответ на: комментарий от ugoday

выглядит подозрительно

это потому что я чудак на букву сами знаете какую - в субботу заниматься изучением terraform. пока с разметкой Markdown лора воевал не тот файл копипастил. должно было быть это

provider "docker" {
  host = "ssh://user@docker:22"
}

# Create a container
resource "docker_container" "foo" {
  count      = 3
  depends_on = [docker_image.hello-world]
  image      = docker_image.hello-world.latest
  name       = "foo${count.index}"
}

resource "docker_image" "hello-world" {
  name         = "${data.docker_registry_image.hello-world.name}"
  pull_trigger = "${data.docker_registry_image.hello-world.sha256_digest}"
}

data "docker_registry_image" "hello-world" {
  name = "hello-world:latest"
}

это уже исправленный файл - у меня была ошибка в count.index поэтому при комментировании count все нормально работало в единичном экземпляре. Сейчас не понятно лишь почему terraform plan не орал.

WaterSlon
() автор топика
Ответ на: комментарий от WaterSlon

Чистый докер тоже уже не особо популярен. Раз для собеседований, то сейчас модно делать так:
Teraform разворачивает Kubernetes и всякие тяжёлые сервисы вроде БД.
В Kubernetes деплой контейнеризированых сервисов делается через Helm.
Cамо приложение пакуется в Docker и снабжается хелм чартом.
И конечно весь CI/CD процесс автоматизируется через GitLab/GitHub/Jenkins пайплайны.

manntes-live ★★★
()
Вы не можете добавлять комментарии в эту тему. Тема перемещена в архив.