以下Terraform開発者向け。
import機能?
Terraformで作成していないインフラリソースをインポートし、terraformの管理下に置く機能です。
まだドキュメントがないのにAWSやDigitalOceanプラグインはimport機能実装中なのです。
悔しいので手探りでimport機能を試してみました。
terraform import
ヘルプ
$ terraform import --help
Usage: terraform import [options] ADDR ID
Import existing infrastructure into your Terraform state.
This will find and import the specified resource into your Terraform
state, allowing existing infrastructure to come under Terraform
management without having to be initially created by Terraform.
The ADDR specified is the address to import the resource to. Please
see the documentation online for resource addresses. The ID is a
resource-specific ID to identify that resource being imported. Please
reference the documentation for the resource type you're importing to
determine the ID syntax to use. It typically matches directly to the ID
that the provider uses.
In the current state of Terraform import, the resource is only imported
into your state file. Once it is imported, you must manually write
configuration for the new resource or Terraform will mark it for destruction.
Future versions of Terraform will expand the functionality of Terraform
import.
This command will not modify your infrastructure, but it will make
network requests to inspect parts of your infrastructure relevant to
the resource being imported.
Options:
-backup=path Path to backup the existing state file before
modifying. Defaults to the "-state-out" path with
".backup" extension. Set to "-" to disable backup.
-input=true Ask for input for variables if not directly set.
-no-color If specified, output won't contain any color.
-state=path Path to read and save state (unless state-out
is specified). Defaults to "terraform.tfstate".
-state-out=path Path to write updated state file. By default, the
"-state" path will be used.
使い方
terraform import
の後にリソースのアドレスとIDを指定します。
リソースのアドレスとはこちらのページに記載があるもので、要はリソースのタイプ名.リソースのID
の形です。
例として、さくらのクラウドのサーバーリソース(sakuracloud_server)をserver01
という名前でインポートする場合は、
$ terraform import sakuracloud_server.server01 [さくらのクラウドサーバーのID]
となります。
インポートするとどうなるの?
リソースごとに若干異なりますが、tfstate
ファイルに実際のサーバーの値が登録されます。
ただし、この状態だとtfファイルがないため、次回terraform apply
をするとサーバーがdestroyされてしまいます。
現状ではtfファイルを自動で作成してくれる機能はありません。
(将来的には実装される見込みです)
このため、importした後はtfファイルを手動で作成してあげることで
terraformの管理下に置くことができるようになります。
実装は?
各リソースの実装でImporterを実装してあげればOKです。
以下のように単純にReadを呼ぶだけで良いリソースなら3行足せばOKデース。
func resourceSakuraCloudServer() *schema.Resource {
return &schema.Resource{
// 以下は通常のリソースとしてCRUDを定義
Create: resourceSakuraCloudServerCreate,
Update: resourceSakuraCloudServerUpdate,
Read: resourceSakuraCloudServerRead,
Delete: resourceSakuraCloudServerDelete,
// インポートをサポートするリソースでは以下のようにImporterを実装
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
//以降省略
すでに存在するインフラでもTerraformで管理できるようになるのは嬉しいですね
以上です。