はじめに
前章までは Terraformのインストール方法、Terraformの文法、実行方法を説明しました。しかしこれらはTerraform v0.11.13
前提での話なので、Terraformのバージョンが違うことで挙動が異なってしまうこともあります。Terraformでよく使うメソッドが急に廃止、、というのもよくあります。それを防ぐためにdockerを使ったインストール、利用する方法があります。dockerはパッケージングを行うための技術です。
*注:Terraformのバージョン食い違いは基本的にtfenvでカバーできます。詳しくはインストールを参照してください
https://pangsen.github.io/help/Terraform/Terraform01.install
1. dockerについて
dockerはOS・ミドルウェア・ファイルシステム全体をイメージという単位で取り扱い、まるごとやりとり出来るツールです。また、イメージの配布やバージョン管理も可能です。メリットとして、手軽に同じ環境を何人のユーザ・ユーザ・他のマシンでも手に入れることができ、即座に同環境を再現( CI (Continuous Integration) 継続的インテグレーションと CD (Continuous Delivery) 継続的デリバリー )することができます。 また、dockerはTerraformで大きく3つの役割があり、Terraformのインストールや実行環境の再現、各種リソースの接続設定、docker Imageを使った既存のプロダクトリソースをそのまま導入することが可能です。(docker Imageとは、dockerコンテナを作成する際に必要となるファイルシステムです。)
2. dockerのTerraform位置について
Terraformによるdockerの利用は大きく3パターンあります。他の便利な役割もありますが、ここは以下3つに絞って紹介します。
- 1.Terraformのバージョン違いなど環境差分を抑えつつ実行する場合
- 2.Terraformで新規作成した各種リソースの接続設定をする場合
- 3.docker-imageを使った、CI/CD:継続的インテグレーションと継続的デリバリーをする場合
1はバージョン固定や実行環境を汚さずに使用するメリットがあります。様々な環境でterraformを使用したい場合は直接terraformコマンドをインストールせず、バージョン管理が可能なツール(tfenv
)を使用してインストールすルことを勧めます。
2はTerraformで新規作成したリソースに対し、docker-compose.yml ファイルを使ってアプリケーションの環境を設定します。こちらは公式サイトにて説明がありますので参考にしてください。 http://docs.docker.jp/compose/overview.html
3は、dockerのImageファイルをdocker hub(リポジトリ)へ保存することで、新規ECSや各種アプリケーション、Webサイトを立ち上げる時、docker hub(リポジトリ)から対象のDocker ImageファイルをPullしそのまま実行することで、どの環境でも継続CI/CDを実現することができます。
本章はTerraformをメインとしてるため、ここにCI/CDや方法は載せませんが、やり方は以下サイトを参照してみてください。(近日中にCI/CD手法を載せる予定です)
Dockerize App and Push to Container Registry: CI/CD Automation on Container Service (1)
Continuous Deployment Automation on Alibaba Cloud: CI/CD Automation on Container Service (2)
Deploy Docker Image to Alibaba Cloud Container Service: CI/CD Automation on Container Service (3)
3. docker上でのTerraform実行について
それではdocker上でterraformを実行してみます。実行するためには先にdocker Imageを入手する必要がありますので、まずは以下サイトを参照してください。 https://hub.docker.com/r/hashicorp/terraform/
参考:Terraformのdocker Imageについて https://github.com/hashicorp/docker-hub-images/tree/master/packer
Desktopにてterraform-docker
というディレクトリを作成し、そこでdockerを実行します。
$ mkdir ~/Desktop/terraform-docker$ cd ~/Desktop/terraform-docker$ touch main.tf
以下サンプルソース main.tfを作ってみます。
provider "alicloud" {region = "ap-northeast-1"}resource "alicloud_vpc" "vpc" {name = "docker-test-vpc"cidr_block = "192.168.1.0/24"}
これで準備完了です。構成はこの通りになります。
$ pwd/Users/hironobu.ohara/Desktop/terraform-docker$ lstotal 8drwxr-xr-x 3 hironobu.ohara staff 96B 7 19 11:43 .drwx------@ 54 hironobu.ohara staff 1.7K 7 19 11:43 ..-rw-r--r-- 1 hironobu.ohara staff 147B 7 19 11:31 main.tf$ cat main.tfprovider "alicloud" {region = "ap-northeast-1"}resource "alicloud_vpc" "vpc" {name = "docker-test-vpc"cidr_block = "192.168.1.0/24"}
次にTerraformをdocker上で起動します。
そのとき、access_key・secret_keyを渡すことでAlibabaCloudのTerraformが実行できます。また、ホストのカレントディレクトリをコンテナ上へマウント( -v $(pwd):/terraform )してファイルの共有を行います。
今後の記述するTerraformのコードはこのディレクトリに配置してコンテナと共有します。
またterraformのバージョンは過去の0.10.1
を指定してみます。
docker run \-e access_key=<ACCESS KEY> \-e secret_key=<SECRET KEY> \-v $(pwd):/terraform \-w /terraform \-it \--entrypoint=ash \hashicorp/terraform:0.10.1
これが実行できたらdocker環境上に入ります。 最後に、docker内でTerraformを操作するためのコマンドを確認してみます。実行内容、結果はこのようになります。
/terraform # terraform versionTerraform v0.10.1Your version of Terraform is out of date! The latest versionis 0.12.5. You can update by downloading from www.terraform.io/terraform #
あとはいつもの通りに terraform init
や terraform plan
、 terraform apply
を実行するだけです。(docker環境、terraform version 0.10.1での実行になります。)
/terraform #/terraform # terraform initInitializing provider plugins...- Checking for available provider plugins on https://releases.hashicorp.com...- Downloading plugin for provider "alicloud" (1.52.1)...The following providers do not have any version constraints in configuration,so the latest version was installed.To prevent automatic upgrades to new major versions that may contain breakingchanges, it is recommended to add version = "..." constraints to thecorresponding provider blocks in configuration, with the constraint stringssuggested below.* provider.alicloud: version = "~> 1.52"Terraform has been successfully initialized!You may now begin working with Terraform. Try running "terraform plan" to seeany changes that are required for your infrastructure. All Terraform commandsshould 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, othercommands will detect it and remind you to do so if necessary./terraform #/terraform # terraform playUsage: terraform [--version] [--help] <command> [args]The available commands for execution are listed below.The most common, useful commands are shown first, followed byless common or more advanced commands. If you're just gettingstarted with Terraform, stick with the common commands. For theother commands, please read the help and docs before usage.Common commands:apply Builds or changes infrastructureconsole Interactive console for Terraform interpolationsdestroy Destroy Terraform-managed infrastructureenv Workspace managementfmt Rewrites config files to canonical formatget Download and install modules for the configurationgraph Create a visual graph of Terraform resourcesimport Import existing infrastructure into Terraforminit Initialize a Terraform working directoryoutput Read an output from a state fileplan Generate and show an execution planproviders Prints a tree of the providers used in the configurationpush Upload this Terraform module to Atlas to runrefresh Update local state file against real resourcesshow Inspect Terraform state or plantaint Manually mark a resource for recreationuntaint Manually unmark a resource as taintedvalidate Validates the Terraform filesversion Prints the Terraform versionworkspace Workspace managementAll other commands:debug Debug output management (experimental)force-unlock Manually unlock the terraform statestate Advanced state management/terraform #/terraform #/terraform # terraform applyalicloud_vpc.vpc: Creating...cidr_block: "" => "192.168.1.0/24"name: "" => "docker-test-vpc"resource_group_id: "" => "<computed>"
docker環境を終了する場合はexit
を入力するだけです。
/terraform #/terraform #/terraform # exit$$