TerraformでOpenShiftクラスターのnamespaceを作成してみる


# はじめに
## 事前準備

 - Openshitfクラスターを作成済みで、端末から`oc login`可能な状態であること
 - 端末上でTerraformコマンドが実行可能であること
   -  [Windows10用のインストーラ] (https://www.terraform.io/downloads.html)をダウンロード、展開する
      - 今回利用したものは「terraform_1.0.1_windows_amd64.zip」
   - pathを通して利用できるようにしておく

# 検証メモ
## Terraform Providerの調査

### RegistryでのProvider検索
- TeffaformのOpenShiftのProviderを探します（下記のRegistryでProviderを検索）
  - https://registry.terraform.io/browse/providers
  - 以下のProviderが見つかりました（OfficialでもVerifiedでもない、Community Tierのものでした）
 　　  - https://registry.terraform.io/providers/llomgui/openshift/latest
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/270508/0422d059-71c7-deaf-9148-5c847e807777.png)


### Providerの利用方法の確認
- 見つけたProviderの使い方を確認します
  - [USE PROVIDER]ボタンをクリックします
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/270508/bb40e14b-baf5-fb0a-1c30-f711f7a69fae.png)
  - tfファイルのProviderセクションへの記述が表示されます
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/270508/92542bb8-4a7c-da95-a57f-98d9a3209bf9.png)


### GitHubの情報確認
- [GitHub Repository](https://github.com/llomgui/terraform-provider-openshift)のReadmeやIsseをチェックします
  - 認証の情報としてURLとTOKENが使えそうです
    - https://github.com/llomgui/terraform-provider-openshift/issues/13 

## 動かしてみる
### main.tfファイルに必要な情報の確認
1. Openshift ClusterへのアクセスTokenとURLの確認
    - 今回はRed Hat OpenShift on IBM Cloud上に作成したClusterを利用します
    - OpenShift Webコンソールを開き、以下の[Copy Login Command]メニューをクリックします
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/270508/1538ea1a-fa8d-863e-791a-1418ebf7c795.png)
    - [Display Token]リンクをクリックします
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/270508/7e983479-4671-6f15-9007-16ca8eebb6e2.png)
    - 表示された項目の[Your API token is]の値と、[Login with this token]のコマンドに記載されている「--server」の値（URL）を確認します
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/270508/479bd3f9-7191-b864-280e-19283ed279a9.png)
 
### main.tfファイルの作成
1. 空のディレクトリを用意し、作成したディレクトリ内にtfファイルを新規作成します
  - [Providerの利用方法の確認](### Providerの利用方法の確認)で確認した情報を基に記載します

```
terraform {
 required_providers {
    openshift = {
      source = "llomgui/openshift"
      version = "1.1.0"
    }
  }
}

provider "openshift" {
  load_config_file = "false"
  host      = "https://XXXX.us-south.containers.cloud.ibm.com:31989"
  token = "sha256~EXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXc"
}

resource "openshift_project" "create" {
  metadata {
    annotations = {
      "openshift.io/description" = "hanako-description"
      "openshift.io/display-name" = "hanako--display-name"
    }
    labels = {
      name      = "hanako-terraform-ns"
    }
    name = "hanako-terraform-ns"
  }
}

```

### `terraform init`の実行

1. tfファイルを作成したディレクトリ上で`terraform init`コマンドを実行します

```
PS C:\mywork\roks\myoc> terraform init

Initializing the backend...

Initializing provider plugins...
- Finding llomgui/openshift versions matching "1.1.0"...
- Installing llomgui/openshift v1.1.0...
- Installed llomgui/openshift v1.1.0 (self-signed, key ID 660E3614297F7EEC)

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.
PS C:\mywork\roks\myoc>
```

### `terraform plan`の実行

1. tfファイルを作成したディレクトリ上で`terraform plan`コマンドを実行します

```
PS C:\mywork\roks\myoc> 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:

  # openshift_project.create will be created
  + resource "openshift_project" "create" {
      + id = (known after apply)

      + metadata {
          + annotations      = {
              + "openshift.io/description"  = "hanako-description"
              + "openshift.io/display-name" = "hanako--display-name"
            }
          + generation       = (known after apply)
          + labels           = {
              + "name" = "hanako-terraform-ns"
            }
          + name             = "hanako-terraform-ns"
          + resource_version = (known after apply)
          + self_link        = (known after apply)
          + uid              = (known after apply)
        }
    }

Plan: 1 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.
PS C:\mywork\roks\myoc>
```

### `terraform apply`の実行


1. tfファイルを作成したディレクトリ上で`terraform apply`コマンドを実行します

```
PS C:\mywork\roks\myoc> 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:

  # openshift_project.create will be created
  + resource "openshift_project" "create" {
      + id = (known after apply)

      + metadata {
          + annotations      = {
              + "openshift.io/description"  = "hanako-description"
              + "openshift.io/display-name" = "hanako--display-name"
            }
          + generation       = (known after apply)
          + labels           = {
              + "name" = "hanako-terraform-ns"
            }
          + name             = "hanako-terraform-ns"
          + resource_version = (known after apply)
          + self_link        = (known after apply)
          + uid              = (known after apply)
        }
    }

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:
```

- [Enter a value]に対して「yes」を入力しEnterを実行します

```
  Enter a value: yes

openshift_project.create: Creating...
openshift_project.create: Creation complete after 1s [id=hanako-terraform-ns]

Apply complete! Resources: 1 added, 0 changed, 0 destroyed.
PS C:\mywork\roks\myoc>
```


### Web Console上での確認

1. Projectとして作成されていることを確認します
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/270508/3b9f9e17-f7af-22c4-b1e9-558738029b99.png)

2. `labels`、`description`にも、指定した内容が記載されていることを確認します
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/270508/3df1d4f8-7f43-25a9-de7d-763756e0073e.png)

# 感想など

- まずはTerraform初心者なので動かしてみよう！とCommunity提供のProviderを試しましたが、できれば、OfficialもしくはVerifiedなProviderでnamespaceの作成等ができるものを使いたいところなので、以下あたりももう少し調査しなければと思いました
  - https://registry.terraform.io/modules/terraform-ibm-modules/cluster/ibm/latest
  - https://registry.terraform.io/providers/hashicorp/kubernetes/latest
- Infrastructure as Codeとして運用プロセスを整備してツールで自動化を考えたいところなので、Gitのリポジトリでどう管理するか？等も考える必要がありそうです


以上。