LoginSignup
8
0

【初学者向け】terraform importの手順を分かりやすく解説!Google Cloudの画面上で設定した設定値をterraformに取り込み

Last updated at Posted at 2023-12-18

はじめに

こんにちは、京セラコミュニケーションシステム鮫島(@kccs_shiho-sameshima)です!

今回は、初心者向けにterraform importコマンドを使用してGoogle Cloudの画面上で設定した入力値をtf.stateファイルにimportする方法を分かりやすく書いていきたいと思います。

本記事は2023年12月ごろに作成しております。記載している情報はこの時点での最新となります。

対象読者

  • Google Cloudの画面上からインスタンスの作成ができる方
  • Terraformを使用してリソース作成のコードが書ける方
  • Terraformの基礎的な実行コマンドを理解している方(terraform initterraform plan等)

前提

今回使用しているツールとバージョン情報は下記となります。
Google Cloud
Ubuntu(コマンド操作)
Visual Studio Code(ソースコードエディタ)※Terraformのバージョン情報は下記です。

% terraform --version
Terraform v1.3.7
on linux_amd64
+ provider registry.terraform.io/hashicorp/google v5.9.0

Your version of Terraform is out of date! The latest version
is 1.6.6. You can update by downloading from https://www.terraform.io/downloads.html

terraform importとは

Google Cloudの画面上で設定した入力値をTerraformの管理下に取り込むのコマンドです。
主に以下の用途で活用可能です。

  • 作成しているコードとコンソール上で設定されている値の差分を確認したい時
  • 画面上で設定できているがコードでの指定方法が分からない時
  • コード化できるのかを検証したい時

ドキュメントを見ても検索をかけても正しいコードの書き方が分からないこと、初心者エンジニアのうちは多いのではないでしょうか。

そんなときはterraform importコマンドを活用して開発を効率化してみましょう!

terraform importを行うための手順

今回は例でCloud Storageを作成してimportしたいと思います。
(どのコンポーネントでも実行可能です)

1. Google Cloudの画面上で対象のインスタンスを作成

importしたいコンポーネントのインスタンスを作成します。※インスタンスの作成方法は割愛します。
今回Cloud Storageにて設定した値は下記です。

設定項目                内容                     
バケット名 (Bucket Name) test-import1214
ロケーション タイプ (Location type) Region asia-northeast1 (東京)
ロケーション (Default storage class) Standard
アクセス制御 (access control) 均一 (uniform)
暗号化のタイプ (Type of encryption) Google が管理 (Managed by Google)

2. import.tfファイルを作成

今回はimport.tfと仮で設定していますが実際は好きなファイル名に設定していただいて問題ありません。
importしたいリソースを中身は空の状態で配置します。

import.tf
resource "google_storage_bucket" "import" {
}

3. terraform importコマンドを確認・作成

terraformのドキュメントからimportのコマンドを確認しましょう。

image08.png

掲載してあるコマンドのいずれかを選択して、必要事項を挿入します。
今回は下記のコマンドを使用します。

実行例
挿入前のコマンド
$ terraform import google_storage_bucket.default {{bucket}}

挿入後のコマンド
$ terraform import google_storage_bucket.import test-import1214

google_storage_bucket.defaultdefault部分は2.import.tfファイルを作成で命名したリソース名を入力。
{{bucket}}部分は今回の場合、Google Cloud上で作成したbucket名を入力。

4. terraform importコマンドを実行

下準備ができたのでコマンドを実行していきましょう〜!

実行例
    $ terraform import google_storage_bucket.import test-import1214
    
image08.png

Import successful!でimport完了です。

ここでエラーが出てしまう場合は、下記を参考に修正しましょう。
ドキュメントの選択肢にある他のコマンドに変更して実行してみるのも有効です。

importコマンドの定義の仕方が間違っているというエラーです。
対処法: 指定したinstance名やproject id等に間違えがないか確認して修正しましょう。
また、このエラーが出てくる場合はコマンドを変更すると解消することが多いです。

│The import command expects two arguments.
│Usage: terraform [global options] 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.
│
│ //以下省略

既存のリソースが見つからないというエラーです。
対処法: 指定したinstance名やproject id等がGoogle cloud上で作成したものと一致しているか確認し修正しましょう。

│ Error: Cannot import non-existent remote object
│
│ While attempting to import an existing object to "google_storage_bucket.import", the provider detected that no object
│ exists with the given id. Only pre-existing objects can be imported; check that the id is correct and that it is
│ associated with the provider's configured region or endpoint, or use "terraform apply" to create a new remote object
│ for this resource.

5. terraform.tfstateを確認

Visual Studio Codeに戻ってimportされたコードを見てみましょう。
importを実行すると自動的にterraform.tfstateが作成されます。
image08.png
importされているのが確認できました!
現在Google Cloudの画面上で設定されている値が確認できます。

terraform.tfstate
{
  "version": 4,
  "terraform_version": "1.3.7",
  "serial": 1,
  "lineage": "a4a3c8eb-609e-1ebd-a3f9-1624bbe90cdd",
  "outputs": {},
  "resources": [
    {
      "mode": "managed",
      "type": "google_storage_bucket",
      "name": "import",
      "provider": "provider[\"registry.terraform.io/hashicorp/google\"]",
      "instances": [
        {
          "schema_version": 1,
          "attributes": {
            "autoclass": [],
            "cors": [],
            "custom_placement_config": [],
            "default_event_based_hold": false,
            "effective_labels": {},
            "enable_object_retention": false,
            "encryption": [],
            "force_destroy": false,
            "id": "test-import1214",
            "labels": {},
            "lifecycle_rule": [],
            "location": "ASIA-NORTHEAST1",
            "logging": [],
            //以下省略

importの一連の流れはここまでです。
必要な設定値を確認してコードを作成しましょう。

6. コードを反映して差分をなくす  terraform planコマンドを実行

tfstateファイルを参考にtfファイルを修正してterraform planコマンドを実行します。
何回もtfファイルを修正してterraform planコマンドで試しながら、差分を埋めていきます。

最終的にNo changes.になれば、画面上から設定した内容と同様のコードが完成です。

No changes. Your infrastructure matches the configuration.

まとめ

いかがだったでしょうか。設定値の入れ方にあたりがつきにくい初学者にとってはとても便利な機能だと思います。
是非普段の業務で活用してみてください!

おしらせ

弊社X(旧:Twitter)では、Qiita投稿に関する情報や各種セミナー情報をお届けしております。情報収集や学びの場を求める皆さん!ぜひフォローしていただき、最新情報を手に入れてください:grinning:

8
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
0