現在、gitlab-ciスクリプトをテンプレート化して使用しています。

テンプレートは、script、baseテンプレート、jobテンプレートの3つの階層で構成されています。


これによって得られる効果は大きく3つあります。

- 新しいパイプラインが必要なときに、既存のテンプレートに変数だけを置き換えて使用できます。

- gitlabが提供するCI/CD変数ベースで動作し、パイプラインランタイムに動的に必要なスクリプトを読み込みます。 これにより、アプリケーションのソースコードバージョンに影響を与えずに独立してパイプラインを修正するなどの管理が可能になります。

- テンプレートだけを修正すると、そのテンプレートが適用されたすべてのパイプラインに共通して適用されるため、面倒な作業なしで効率的な管理が可能です。

以下のterraform作業例を簡単に作成しておきました。


* このポストには含まれていませんが、workflowを活用して環境分岐をすると、gitlabCI/CD環境変数も分岐できます。
その他のパイプライン構成テクニックに関する内容は省略し、この例コードではテンプレートをどのように作って使用するかについてのみ扱います。



[script例]
  
.before_scripts:
  set-terraform-registry-credentials:
    - |
      cat > $HOME/.terraformrc << EOF
      credentials "${TF_REGISTRY}" {
        token = "${TF_REGISTRY_ACCESS_TOKEN}"
      }
      EOF

.scripts:
  terraform-init:
    - terraform init
  terraform-plan:
    - terraform plan -var-file configurations/${VAR_FILE} 
  terraform-apply:
    - terraform apply -auto-approve -var-file configurations/${VAR_FILE}
  

[baseテンプレート例]
  
.terraform-base-template:
  image: ${RUNNER_IMAGE}
  before_script:
    - !reference [.before_scripts, set-terraform-registry-credentials]
  

[jobテンプレート例]
  
.terraform-plan-template:
  extends: .terraform-base-template
  script:
    - !reference [.scripts, terraform-init]
    - !reference [.scripts, terraform-plan]

.terraform-apply-template:
  extends: .terraform-base-template
  script:
    - !reference [.scripts, terraform-init]
    - !reference [.scripts, terraform-apply]
  

[.gitlab-ciへの応用例]
  
include:
  - project: "templates"
    file: "/.template.yml"
    
stages:
  - terraform-plan
  - terraform-apply

terraform-plan:
  stage: terraform-plan
  extends: .terraform-plan-template

terraform-apply:
  stage: terraform-apply
  extends: .terraform-apply-template