ラベル Terraform の投稿を表示しています。 すべての投稿を表示
ラベル Terraform の投稿を表示しています。 すべての投稿を表示
2023年8月19日土曜日

TerraformでオンプレESXiに仮想マシンを作成・削除してみる

先日、TerraformをAlmaLinuxにインストールして使ってみた。

Terraformは主にAWSやAzureといったクラウドの設定をする際に利用されるツールという印象が強いが、オンプレミスのvSphere環境などでも各種設定を行うことができる

本記事では、TerraformでオンプレESXiに仮想マシンを作成・削除する手順を作る方法を記載する。

環境

環境は以下の通り。

  • ESXi : 7.0 Update 3
  • OS : AlmaLinux 9.2
  • Terraform : v1.5.2

以下URLの手順にてTerraformがインストール済みであることを前提とする。

Terraformによる仮想マシン作成手順

通常のTerraformと同じく、tfファイルを作ってterraform initterraform applyで仮想マシンを作成し、terraform destoryで仮想マシンが削除されることを確認する。

1. tfファイルを作成

TerraformでESXiを操作する場合は、「Terraform Provider for VMware vSphere」を用いる。

マニュアルに使用例は書いてあるが、vCenter Serverが存在する環境の実行例がとなるので、ESXiに対して実行する際の注意点を以下に記載する。

  • vsphere_datacenterha-datacenterを指定
  • vsphere_compute_clusterは不要。ただし、vsphere_virtual_machineのリソース指定において、resource_pool_idは必須項目なので、vsphere_resource_poolを空で作って作成しておく
  • guest_idは以下URLから[Enumerated Types]→[VirtualMachineGuestOsIdentifier]にアクセスし作成するOSの種類に合わせて正しく指定する。
  • 仮想マシン作成後にTerraformが応答待ちになってしまうことから、wait_for_guest_net_timeout = -1を設定する

上記をもとに作成したtfファイルは以下の通り。

main.tf

terraform {
  required_version = ">= 1.2.0"
}

locals {
  esxi_user              = "[ESXiのユーザ名]"
  esxi_password          = "[ESXiのユーザのパスワード]"
  esxi_server            = "[ESXiのIPアドレス]"
}

provider "vsphere" {
  user                 = local.esxi_user
  password             = local.esxi_password
  vsphere_server       = local.esxi_server
  allow_unverified_ssl = true
}

data "vsphere_datacenter" "datacenter" {
  name = "ha-datacenter"
}

data "vsphere_datastore" "datastore" {
  name          = "ssd_01"
  datacenter_id = data.vsphere_datacenter.datacenter.id
}

data "vsphere_datastore" "media" {
  name          = "nfs_01"
  datacenter_id = data.vsphere_datacenter.datacenter.id
}

data "vsphere_resource_pool" "pool" {
}

data "vsphere_network" "network" {
  name          = "Network_01"
  datacenter_id = data.vsphere_datacenter.datacenter.id
}

resource "vsphere_virtual_machine" "vm" {
  name             = "terraform-testvm"
  resource_pool_id = data.vsphere_resource_pool.pool.id
  datastore_id     = data.vsphere_datastore.datastore.id
  num_cpus         = 1
  memory           = 1024
  guest_id         = "other5xLinux64Guest"

  network_interface {
    network_id = data.vsphere_network.network.id
  }

  disk {
    label = "disk0"
    size  = 16
    thin_provisioned = true
  }

  cdrom {
    datastore_id = data.vsphere_datastore.media.id
    path = "/04_ISO/Linux/AlmaLinux/AlmaLinux-9.2-x86_64-dvd.iso"
  }

  wait_for_guest_net_timeout = -1
}

2. Terraform実行

上記tfファイルをesxi_vm_linuxディレクトリに作成し、Terraformを実行する。

# cd esxi_vm_linux
# terraform init
~(省略)~

# terraform apply 
data.vsphere_datacenter.datacenter: Reading...
data.vsphere_resource_pool.pool: Reading...
data.vsphere_datacenter.datacenter: Read complete after 0s [id=ha-datacenter]
data.vsphere_datastore.media: Reading...
data.vsphere_datastore.datastore: Reading...
data.vsphere_network.network: Reading...
data.vsphere_datastore.media: Read complete after 0s [id=192.168.1.1:/nfs]
data.vsphere_resource_pool.pool: Read complete after 0s [id=ha-root-pool]
data.vsphere_datastore.datastore: Read complete after 0s [id=63942c98-19e3f477-d004-90e2ba3d67d0]
data.vsphere_network.network: Read complete after 0s [id=HaNetwork-Network_01]

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:

  # vsphere_virtual_machine.vm will be created
  + resource "vsphere_virtual_machine" "vm" {
      + annotation                              = (known after apply)
      + boot_retry_delay                        = 10000
      + change_version                          = (known after apply)
      + cpu_limit                               = -1
      + cpu_share_count                         = (known after apply)
      + cpu_share_level                         = "normal"
      + datastore_id                            = "63942c98-19e3f477-d004-90e2ba3d67d0"
      + default_ip_address                      = (known after apply)
      + ept_rvi_mode                            = "automatic"
      + extra_config_reboot_required            = true
      + firmware                                = "bios"
      + force_power_off                         = true
      + guest_id                                = "other5xLinux64Guest"
      + guest_ip_addresses                      = (known after apply)
      + hardware_version                        = (known after apply)
      + host_system_id                          = (known after apply)
      + hv_mode                                 = "hvAuto"
      + id                                      = (known after apply)
      + ide_controller_count                    = 2
      + imported                                = (known after apply)
      + latency_sensitivity                     = "normal"
      + memory                                  = 1024
      + memory_limit                            = -1
      + memory_share_count                      = (known after apply)
      + memory_share_level                      = "normal"
      + migrate_wait_timeout                    = 30
      + moid                                    = (known after apply)
      + name                                    = "terraform-testvm"
      + num_cores_per_socket                    = 1
      + num_cpus                                = 1
      + power_state                             = (known after apply)
      + poweron_timeout                         = 300
      + reboot_required                         = (known after apply)
      + resource_pool_id                        = "ha-root-pool"
      + run_tools_scripts_after_power_on        = true
      + run_tools_scripts_after_resume          = true
      + run_tools_scripts_before_guest_shutdown = true
      + run_tools_scripts_before_guest_standby  = true
      + sata_controller_count                   = 0
      + scsi_bus_sharing                        = "noSharing"
      + scsi_controller_count                   = 1
      + scsi_type                               = "pvscsi"
      + shutdown_wait_timeout                   = 3
      + storage_policy_id                       = (known after apply)
      + swap_placement_policy                   = "inherit"
      + tools_upgrade_policy                    = "manual"
      + uuid                                    = (known after apply)
      + vapp_transport                          = (known after apply)
      + vmware_tools_status                     = (known after apply)
      + vmx_path                                = (known after apply)
      + wait_for_guest_ip_timeout               = 0
      + wait_for_guest_net_routable             = true
      + wait_for_guest_net_timeout              = -1

      + cdrom {
          + datastore_id   = "192.168.1.1:/nfs"
          + device_address = (known after apply)
          + key            = (known after apply)
          + path           = "/04_ISO/Linux/AlmaLinux/AlmaLinux-9.2-x86_64-dvd.iso"
        }

      + disk {
          + attach            = false
          + controller_type   = "scsi"
          + datastore_id      = "<computed>"
          + device_address    = (known after apply)
          + disk_mode         = "persistent"
          + disk_sharing      = "sharingNone"
          + eagerly_scrub     = false
          + io_limit          = -1
          + io_reservation    = 0
          + io_share_count    = 0
          + io_share_level    = "normal"
          + keep_on_remove    = false
          + key               = 0
          + label             = "disk0"
          + path              = (known after apply)
          + size              = 16
          + storage_policy_id = (known after apply)
          + thin_provisioned  = true
          + unit_number       = 0
          + uuid              = (known after apply)
          + write_through     = false
        }

      + network_interface {
          + adapter_type          = "vmxnet3"
          + bandwidth_limit       = -1
          + bandwidth_reservation = 0
          + bandwidth_share_count = (known after apply)
          + bandwidth_share_level = "normal"
          + device_address        = (known after apply)
          + key                   = (known after apply)
          + mac_address           = (known after apply)
          + network_id            = "HaNetwork-Network_01"
        }
    }

Plan: 1 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

vsphere_virtual_machine.vm: Creating...
vsphere_virtual_machine.vm: Creation complete after 1s [id=564de646-7f10-7d49-33d3-7c55f22ef581]

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

作成した結果をVMware Host Clientにて確認してみると、問題なくterraform-testvmの仮想マシンが作成され、起動まで実行されていることがわかる。

「設定の編集」を確認すると、USBコントローラなどがない、必要最低限の構成で仮想マシンが作成されていた。

Terraformによる仮想マシン削除手順

最後に作成した仮想マシンを削除してみよう。仮想マシンの削除はterraform destroyをすればよい。

# terraform destroy 
data.vsphere_resource_pool.pool: Reading...
data.vsphere_datacenter.datacenter: Reading...
data.vsphere_datacenter.datacenter: Read complete after 0s [id=ha-datacenter]
data.vsphere_network.network: Reading...
data.vsphere_datastore.media: Reading...
data.vsphere_datastore.datastore: Reading...
data.vsphere_datastore.datastore: Read complete after 0s [id=63942c98-19e3f477-d004-90e2ba3d67d0]
data.vsphere_datastore.media: Read complete after 0s [id=192.168.1.1:/nfs]
data.vsphere_resource_pool.pool: Read complete after 0s [id=ha-root-pool]
data.vsphere_network.network: Read complete after 0s [id=HaNetwork-Network_01]
vsphere_virtual_machine.vm: Refreshing state... [id=564de646-7f10-7d49-33d3-7c55f22ef581]

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:

  # vsphere_virtual_machine.vm will be destroyed
  - resource "vsphere_virtual_machine" "vm" {
      - boot_delay                              = 0 -> null
      - boot_retry_delay                        = 10000 -> null
      - boot_retry_enabled                      = false -> null
      - change_version                          = "2023-08-11T09:27:30.121451Z" -> null
      - cpu_hot_add_enabled                     = false -> null
      - cpu_hot_remove_enabled                  = false -> null
      - cpu_limit                               = -1 -> null
      - cpu_performance_counters_enabled        = false -> null
      - cpu_reservation                         = 0 -> null
      - cpu_share_count                         = 1000 -> null
      - cpu_share_level                         = "normal" -> null
      - datastore_id                            = "63942c98-19e3f477-d004-90e2ba3d67d0" -> null
      - efi_secure_boot_enabled                 = false -> null
      - enable_disk_uuid                        = false -> null
      - enable_logging                          = false -> null
      - ept_rvi_mode                            = "automatic" -> null
      - extra_config                            = {} -> null
      - extra_config_reboot_required            = true -> null
      - firmware                                = "bios" -> null
      - force_power_off                         = true -> null
      - guest_id                                = "other5xLinux64Guest" -> null
      - guest_ip_addresses                      = [] -> null
      - hardware_version                        = 19 -> null
      - host_system_id                          = "ha-host" -> null
      - hv_mode                                 = "hvAuto" -> null
      - id                                      = "564de646-7f10-7d49-33d3-7c55f22ef581" -> null
      - ide_controller_count                    = 2 -> null
      - latency_sensitivity                     = "normal" -> null
      - memory                                  = 1024 -> null
      - memory_hot_add_enabled                  = false -> null
      - memory_limit                            = -1 -> null
      - memory_reservation                      = 0 -> null
      - memory_share_count                      = 10240 -> null
      - memory_share_level                      = "normal" -> null
      - migrate_wait_timeout                    = 30 -> null
      - moid                                    = "59" -> null
      - name                                    = "terraform-testvm" -> null
      - nested_hv_enabled                       = false -> null
      - num_cores_per_socket                    = 1 -> null
      - num_cpus                                = 1 -> null
      - pci_device_id                           = [] -> null
      - power_state                             = "on" -> null
      - poweron_timeout                         = 300 -> null
      - reboot_required                         = false -> null
      - resource_pool_id                        = "ha-root-pool" -> null
      - run_tools_scripts_after_power_on        = true -> null
      - run_tools_scripts_after_resume          = true -> null
      - run_tools_scripts_before_guest_reboot   = false -> null
      - run_tools_scripts_before_guest_shutdown = true -> null
      - run_tools_scripts_before_guest_standby  = true -> null
      - sata_controller_count                   = 0 -> null
      - scsi_bus_sharing                        = "noSharing" -> null
      - scsi_controller_count                   = 1 -> null
      - scsi_type                               = "pvscsi" -> null
      - shutdown_wait_timeout                   = 3 -> null
      - swap_placement_policy                   = "inherit" -> null
      - sync_time_with_host                     = false -> null
      - sync_time_with_host_periodically        = false -> null
      - tools_upgrade_policy                    = "manual" -> null
      - uuid                                    = "564de646-7f10-7d49-33d3-7c55f22ef581" -> null
      - vapp_transport                          = [] -> null
      - vbs_enabled                             = false -> null
      - vmware_tools_status                     = "guestToolsNotRunning" -> null
      - vmx_path                                = "terraform-testvm/terraform-testvm.vmx" -> null
      - vvtd_enabled                            = false -> null
      - wait_for_guest_ip_timeout               = 0 -> null
      - wait_for_guest_net_routable             = true -> null
      - wait_for_guest_net_timeout              = -1 -> null

      - cdrom {
          - client_device  = false -> null
          - datastore_id   = "192.168.1.1:/nfs" -> null
          - device_address = "ide:0:0" -> null
          - key            = 3000 -> null
          - path           = "04_ISO/Linux/AlmaLinux/AlmaLinux-9.2-x86_64-dvd.iso" -> null
        }

      - disk {
          - attach           = false -> null
          - controller_type  = "scsi" -> null
          - datastore_id     = "63942c98-19e3f477-d004-90e2ba3d67d0" -> null
          - device_address   = "scsi:0:0" -> null
          - disk_mode        = "persistent" -> null
          - disk_sharing     = "sharingNone" -> null
          - eagerly_scrub    = false -> null
          - io_limit         = -1 -> null
          - io_reservation   = 0 -> null
          - io_share_count   = 1000 -> null
          - io_share_level   = "normal" -> null
          - keep_on_remove   = false -> null
          - key              = 2000 -> null
          - label            = "disk0" -> null
          - path             = "terraform-testvm/terraform-testvm.vmdk" -> null
          - size             = 16 -> null
          - thin_provisioned = true -> null
          - unit_number      = 0 -> null
          - uuid             = "6000C29e-8a40-b94b-d566-a61c53225832" -> null
          - write_through    = false -> null
        }

      - network_interface {
          - adapter_type          = "vmxnet3" -> null
          - bandwidth_limit       = -1 -> null
          - bandwidth_reservation = 0 -> null
          - bandwidth_share_count = 50 -> null
          - bandwidth_share_level = "normal" -> null
          - device_address        = "pci:0:7" -> null
          - key                   = 4000 -> null
          - mac_address           = "00:0c:29:2e:f5:81" -> null
          - network_id            = "HaNetwork-Network_01" -> null
          - use_static_mac        = false -> null
        }
    }

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

Do you really want to destroy all resources?
  Terraform will destroy all your managed infrastructure, as shown above.
  There is no undo. Only 'yes' will be accepted to confirm.

  Enter a value: yes

vsphere_virtual_machine.vm: Destroying... [id=564de646-7f10-7d49-33d3-7c55f22ef581]
vsphere_virtual_machine.vm: Destruction complete after 1s

Destroy complete! Resources: 1 destroyed.

ESXiの「最近のタスク」においても、仮想マシンの電源をOFFしてから削除処理が実行されていることがわかる。

以上で、TerraformでオンプレESXiに仮想マシンを作成・削除する手順は完了となる。

2023年8月12日土曜日

TerraformをAlmaLinuxにインストールして簡単な動作確認をしてみた

Terraformは、HashiCorp社にて開発された各種プラットフォームのITインフラの設定をIaC (Infrastructure as code)にて設定可能とするOSSツールとなる。

今回は、TerraformをAlmaLinuxにインストールし、簡単な動作確認を行う手順を記載する。

環境

環境は以下の通り。

  • OS : AlmaLinux 9.2
  • Terraform : v1.5.2

Terraformインストール手順

1. HashiCorpのレポジトリ追加

TerraformはHashicorpのリポジトリで公開されている。yum-config-managerコマンドを使って、以下の通りリポジトリの追加を行う。

# dnf install yum-utils -y
# yum-config-manager --add-repo https://rpm.releases.hashicorp.com/RHEL/hashicorp.repo

2. Terraformインストール

dnfを用いてTerraformをインストールする。gitperlの各種ライブラリが依存関係パッケージとして、大量にインストールされる。

# dnf install terraform
メタデータの期限切れの最終確認: 0:00:16 前の 2023年07月07日 21時12分38秒 に実施しました。
依存関係が解決しました。
====================================================================================================================================================
 パッケージ                                 アーキテクチャー           バージョン                               リポジトリー                  サイズ
====================================================================================================================================================
インストール:
 terraform                                  x86_64                     1.5.2-1                                  hashicorp                      21 M
依存関係のインストール:
 emacs-filesystem                           noarch                     1:27.2-8.el9_2.1                         appstream                     7.9 k
 git                                        x86_64                     2.39.3-1.el9_2                           appstream                      61 k
 git-core                                   x86_64                     2.39.3-1.el9_2                           appstream                     4.2 M
 git-core-doc                               noarch                     2.39.3-1.el9_2                           appstream                     2.6 M
 perl-AutoLoader                            noarch                     5.74-480.el9                             appstream                      21 k
 perl-B                                     x86_64                     1.80-480.el9                             appstream                     179 k
 perl-Carp                                  noarch                     1.50-460.el9                             appstream                      29 k
 perl-Class-Struct                          noarch                     0.66-480.el9                             appstream                      22 k

~(中略)~

 perl-subs                                  noarch                     1.03-480.el9                             appstream                      12 k
 perl-vars                                  noarch                     1.05-480.el9                             appstream                      13 k
弱い依存関係のインストール:
 perl-IO-Socket-SSL                         noarch                     2.073-1.el9                              appstream                     216 k
 perl-Mozilla-CA                            noarch                     20200520-6.el9                           appstream                      12 k
 perl-NDBM_File                             x86_64                     1.15-480.el9                             appstream                      22 k

トランザクションの概要
====================================================================================================================================================
インストール  68 パッケージ

ダウンロードサイズの合計: 34 M
インストール後のサイズ: 123 M
これでよろしいですか? [y/N]: y

~(以下略)~

インストール後、Terraformのバージョンを確認しておこう。

# terraform -v
Terraform v1.5.2
on linux_amd64
+ provider registry.terraform.io/kreuzwerker/docker v3.0.2

3. terraformコマンドのTab補完を使えるようにする

Terraformを使用する際は、その名の通りterraformコマンドを使用する。その際にTab補完を使えるよう、以下の通りコマンドを実行する。

# touch ~/.bashrc
# terraform -install-autocomplete
# source ~/.bashrc

実行後の~/.bashrcは以下の通り。最終行にTab補完用のコマンドが実行されるようになっている。

~/.bashrc

# .bashrc

# Source global definitions
if [ -f /etc/bashrc ]; then
        . /etc/bashrc
fi

# User specific environment
if ! [[ "$PATH" =~ "$HOME/.local/bin:$HOME/bin:" ]]
then
    PATH="$HOME/.local/bin:$HOME/bin:$PATH"
fi
export PATH

# Uncomment the following line if you don't like systemctl's auto-paging feature:
# export SYSTEMD_PAGER=

# User specific aliases and functions

alias rm='rm -i'
alias cp='cp -i'
alias mv='mv -i'

complete -C /usr/bin/terraform terraform   # <- ★追加される

これによって、例えばterraform a[TAB]とキーを入力すれば、terraform applyのコマンドが補完されるようになる。

# terraform apply   <- ★Tabで補完されるようになる

Terraform動作確認 (Docekrコンテナ作成)

ここからは、公式サイトで公開されている以下のチュートリアル通りに確認作業を進める。

前提として、事前にTerraformを導入したOSにDockerをインストールすること。Dockerのインストール手順は以下を参照いただきたい。

1. 作業用ディレクトリ作成

Terraformでは、作業用ディレクトリを作成し、そこに*.tfという拡張子を持つファイルにてTerraformのコードを記載する。Terraformコマンドはtfファイルのコードを解釈し、必要な一時ファイル等をディレクトリ内に作成し、各プラットフォームに対して操作を行う。

今回は以下の通りディレクトリを作成する。

# mkdir learn-terraform-docker-container
# cd learn-terraform-docker-container

2. tfファイルを作成

作成したディレクトリ内にmain.tfというファイルを作成し、以下の通り記述する。

main.tf

terraform {
  required_providers {
    docker = {
      source  = "kreuzwerker/docker"
      version = "~> 3.0.1"
    }
  }
}

provider "docker" {}

resource "docker_image" "nginx" {
  name         = "nginx"
  keep_locally = false
}

resource "docker_container" "nginx" {
  image = docker_image.nginx.image_id
  name  = "tutorial"

  ports {
    internal = 80
    external = 8000
  }
}

3. Terraform初期化 (terraform init)

Terraformを初期化するため、terraform initコマンドを実行する。このコマンドを実行すると、プロバイダと呼ばれるプラットフォームとのインタフェースとなるファイルが.terraformディレクトリにダウンロードされる。使用するプロバイダによってはかなり容量が大きいため注意しよう(例えばAWSのプロバイダであれば400MB程度)。

# terraform init

Initializing the backend...

Initializing provider plugins...
- Finding kreuzwerker/docker versions matching "~> 3.0.1"...
- Installing kreuzwerker/docker v3.0.2...
- Installed kreuzwerker/docker v3.0.2 (self-signed, key ID BD080C4571C6104C)

Partner and community providers are signed by their developers.
If you'd like to know more about provider signing, you can read about it here:
https://www.terraform.io/docs/cli/plugins/signing.html

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.

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.

なお、Terraformで使用可能なプロバイダは、以下URLから確認できる。

4. Terraform実行前確認 (terraform plan)

実行前に実行内容を確認するため、terraform planコマンドを実行する。

# terraform plan

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:

  # docker_container.nginx will be created
  + resource "docker_container" "nginx" {
      + attach                                      = false
      + bridge                                      = (known after apply)
      + command                                     = (known after apply)
      + container_logs                              = (known after apply)
      + container_read_refresh_timeout_milliseconds = 15000
      + entrypoint                                  = (known after apply)
      + env                                         = (known after apply)
      + exit_code                                   = (known after apply)
      + hostname                                    = (known after apply)
      + id                                          = (known after apply)
      + image                                       = (known after apply)
      + init                                        = (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
      + wait                                        = false
      + wait_timeout                                = 60

      + ports {
          + external = 8000
          + internal = 80
          + ip       = "0.0.0.0"
          + protocol = "tcp"
        }
    }

  # docker_image.nginx will be created
  + resource "docker_image" "nginx" {
      + id           = (known after apply)
      + image_id     = (known after apply)
      + keep_locally = false
      + name         = "nginx"
      + repo_digest  = (known after apply)
    }

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

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

Note: You didn't use the -out option to save this plan, so Terraform can't guarantee to take exactly these actions if you run "terraform apply" now.

5. Terraform実行 (terraform apply)

Terraformの処理をするため、terraform applyコマンドを実行する。

# terraform apply

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:

  # docker_container.nginx will be created
  + resource "docker_container" "nginx" {
      + attach                                      = false
      + bridge                                      = (known after apply)
      + command                                     = (known after apply)
      + container_logs                              = (known after apply)
      + container_read_refresh_timeout_milliseconds = 15000
      + entrypoint                                  = (known after apply)
      + env                                         = (known after apply)
      + exit_code                                   = (known after apply)
      + hostname                                    = (known after apply)
      + id                                          = (known after apply)
      + image                                       = (known after apply)
      + init                                        = (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
      + wait                                        = false
      + wait_timeout                                = 60

      + ports {
          + external = 8000
          + internal = 80
          + ip       = "0.0.0.0"
          + protocol = "tcp"
        }
    }

  # docker_image.nginx will be created
  + resource "docker_image" "nginx" {
      + id           = (known after apply)
      + image_id     = (known after apply)
      + keep_locally = false
      + name         = "nginx"
      + repo_digest  = (known after apply)
    }

Plan: 2 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   <- ★yesを入力

docker_image.nginx: Creating...
docker_image.nginx: Creation complete after 9s [id=sha256:021283c8eb95be02b23db0de7f609d603553c6714785e7a673c6594a624ffbdanginx]
docker_container.nginx: Creating...
docker_container.nginx: Creation complete after 1s [id=c70291e91ade2fef0b1051a92a7a7e657d9b32c8bf63cafb7e5a3a4b7449bca2]

Apply complete! Resources: 2 added, 0 changed, 0 destroyed.

6. 実行後確認

実行後にDockerコンテナとコンテナイメージの状況を確認すると、NGINXのコンテナイメージがダウンロードされ、コンテナとして起動していることがわかる。

# docker ps
CONTAINER ID   IMAGE          COMMAND                   CREATED          STATUS          PORTS                  NAMES
c70291e91ade   021283c8eb95   "/docker-entrypoint.…"   27 seconds ago   Up 26 seconds   0.0.0.0:8000->80/tcp   tutorial

# docker images
REPOSITORY   TAG       IMAGE ID       CREATED      SIZE
nginx        latest    021283c8eb95   4 days ago   187MB

NGINXコンテナは8000番ポートで接続できる。実際に接続すると、NGINXのウェルカムページが表示された。

7. Dockerコンテナ削除 (terraform destroy)

Terraformで作成したDockerコンテナを削除するため、terraform destroyコマンドを実行する。

# terraform destroy
docker_image.nginx: Refreshing state... [id=sha256:021283c8eb95be02b23db0de7f609d603553c6714785e7a673c6594a624ffbdanginx]
docker_container.nginx: Refreshing state... [id=c70291e91ade2fef0b1051a92a7a7e657d9b32c8bf63cafb7e5a3a4b7449bca2]

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.nginx will be destroyed
  - resource "docker_container" "nginx" {
      - attach                                      = false -> null
      - command                                     = [
          - "nginx",
          - "-g",
          - "daemon off;",
        ] -> null
      - container_read_refresh_timeout_milliseconds = 15000 -> null
      - cpu_shares                                  = 0 -> null
      - dns                                         = [] -> null
      - dns_opts                                    = [] -> null
      - dns_search                                  = [] -> null
      - entrypoint                                  = [
          - "/docker-entrypoint.sh",
        ] -> null
      - env                                         = [] -> null
      - group_add                                   = [] -> null
      - hostname                                    = "c70291e91ade" -> null
      - id                                          = "c70291e91ade2fef0b1051a92a7a7e657d9b32c8bf63cafb7e5a3a4b7449bca2" -> null
      - image                                       = "sha256:021283c8eb95be02b23db0de7f609d603553c6714785e7a673c6594a624ffbda" -> null
      - init                                        = false -> null
      - ipc_mode                                    = "private" -> 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              = ""
              - mac_address               = "02:42:ac:11:00:02"
              - 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
      - wait                                        = false -> null
      - wait_timeout                                = 60 -> null

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

  # docker_image.nginx will be destroyed
  - resource "docker_image" "nginx" {
      - id           = "sha256:021283c8eb95be02b23db0de7f609d603553c6714785e7a673c6594a624ffbdanginx" -> null
      - image_id     = "sha256:021283c8eb95be02b23db0de7f609d603553c6714785e7a673c6594a624ffbda" -> null
      - keep_locally = false -> null
      - name         = "nginx" -> null
      - repo_digest  = "nginx@sha256:08bc36ad52474e528cc1ea3426b5e3f4bad8a130318e3140d6cfe29c8892c7ef" -> null
    }

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

Do you really want to destroy all resources?
  Terraform will destroy all your managed infrastructure, as shown above.
  There is no undo. Only 'yes' will be accepted to confirm.

  Enter a value: yes   <- ★yesを入力

docker_container.nginx: Destroying... [id=c70291e91ade2fef0b1051a92a7a7e657d9b32c8bf63cafb7e5a3a4b7449bca2]
docker_container.nginx: Destruction complete after 0s
docker_image.nginx: Destroying... [id=sha256:021283c8eb95be02b23db0de7f609d603553c6714785e7a673c6594a624ffbdanginx]
docker_image.nginx: Destruction complete after 0s

Destroy complete! Resources: 2 destroyed.

削除後にDockerコンテナとコンテナイメージを確認すると、いずれも削除されていることが確認できる。

# docker ps -a
CONTAINER ID   IMAGE     COMMAND   CREATED   STATUS    PORTS     NAMES

# docker images
REPOSITORY   TAG       IMAGE ID   CREATED   SIZE

以上で、TerraformをAlmaLinuxにインストールし、簡単な動作確認を行う手順は完了となる。

参考

人気の投稿