name: Terraform Plan and Apply on: pull_request: branches: - main push: branches: - main permissions: pull-requests: write env: TF_PLUGIN_CACHE_DIR: ${{ gitea.workspace }}/.terraform.d/plugin-cache TF_IN_AUTOMATION: true TF_CLI_ARGS: "-no-color" NOMAD_ADDR: "${{ vars.NOMAD_ADDR }}" NOMAD_TOKEN: "${{ secrets.NOMAD_TOKEN }}" PG_CONN_STR: "${{ secrets.PG_CONN_STR }}" jobs: cicd: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: hashicorp/setup-terraform@v3 - name: Create Terraform Plugin Cache Dir run: mkdir -v -p $TF_PLUGIN_CACHE_DIR - uses: actions/cache@v4 with: path: ${{ env.TF_PLUGIN_CACHE_DIR }} key: ${{ runner.os }}-terraform-${{ hashFiles('**/.terraform.lock.hcl') }} - name: Terraform fmt id: fmt run: terraform fmt -recursive -check continue-on-error: true - name: Terraform Init id: init run: terraform init -input=false - name: Terraform Validate id: validate run: terraform validate - name: Terraform Plan id: plan run: terraform plan -out=tfplan continue-on-error: true - uses: hashicorp/setup-nomad@main - name: Nomad Validate run: terraform show -json tfplan | jq -r '.planned_values.root_module.child_modules[].resources[].values.jobspec' | nomad job validate -json - - uses: actions/github-script@v7 if: github.event_name == 'pull_request' env: PLAN: "terraform\n${{ steps.plan.outputs.stdout }}" with: github-token: ${{ secrets.GITHUB_TOKEN }} script: | const { data: comments } = await github.rest.issues.listComments({ owner: context.repo.owner, repo: context.repo.repo, issue_number: context.issue.number, }) const botComment = comments.find(comment => { return comment.user.type === 'Bot' && comment.body.includes('Terraform Format and Style') }) const output = `#### Terraform Format and Style 🖌\`${{ steps.fmt.outcome }}\` #### Terraform Initialization ⚙️\`${{ steps.init.outcome }}\` #### Terraform Validation 🤖\`${{ steps.validate.outcome }}\`
Validation Output \`\`\`\n ${{ steps.validate.outputs.stdout }} \`\`\`
#### Terraform Plan 📖\`${{ steps.plan.outcome }}\`
Show Plan \`\`\`\n ${process.env.PLAN} \`\`\`
*Pusher: @${{ github.actor }}, Action: \`${{ github.event_name }}\`, Working Directory: \`${{ env.tf_actions_working_dir }}\`, Workflow: \`${{ github.workflow }}\`*`; if (botComment) { github.rest.issues.updateComment({ owner: context.repo.owner, repo: context.repo.repo, comment_id: botComment.id, body: output }) } else { github.rest.issues.createComment({ issue_number: context.issue.number, owner: context.repo.owner, repo: context.repo.repo, body: output }) } - name: Terraform apply if: github.ref == 'refs/heads/main' && steps.plan.outcome == 'success' run: terraform apply -auto-approve tfplan