LoginSignup
2
1

More than 1 year has passed since last update.

Github Actionsでmasterにpushされたらterraform applyするCIを作る

Posted at

やりたいこと

  • mainブランチにpushされたら、fmtされているかチェックしてterraform applyを実行する

用意するファイル

  • .github/workflows/にyamlファイルをセットするのみでいい
  • jobsの上から実行されて、一つでも失敗するとGithubActionsがエラーになる
  • ディレクトリを指定する場合は、working-directory: ./deployment/terraformのようにする(run cdとかではない)
  • 次の例はdevelopmentproductionのWorkspaceを利用している環境
  • aws userを作成しクレデンシャルを控えておく
github/workflows/ci-master.yml
name: ci-master

on:
  push:
    branches: [ main ]
  pull_request:
    branches: [ main ]

jobs:
  terraform:
    name: Terraform
    runs-on: ubuntu-latest

    defaults:
      run:
        shell: bash
    steps:
    - name: Checkout
      uses: actions/checkout@v2

    - name: configure AWS credentials
      uses: aws-actions/configure-aws-credentials@v1
      with:
        aws-access-key-id: <key>
        aws-secret-access-key: <secretkey>
        aws-region: ap-northeast-1

    - name: Setup Terraform
      uses: hashicorp/setup-terraform@v1
      with:
        terraform_version: 0.13.5

    - name: Terraform Format
      working-directory: ./deployment/terraform
      run: terraform fmt -recursive -check

    - name: Terraform development
      working-directory: ./deployment/terraform
      run: |
        terraform init
        terraform workspace select development
        terraform validate
        terraform plan -var-file=development.tfvars
        terraform apply -var-file=development.tfvars -auto-approve

    - name: Terraform production
      working-directory: ./deployment/terraform
      run: |
        terraform init
        terraform workspace select production
        terraform validate
        terraform plan -var-file=production.tfvars
        terraform apply -var-file=production.tfvars -auto-approve

実行している様子

  • mainにpushすれば動作 image.png

参考

2
1
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
2
1