We’ll review the push part of the pipeline. Here’s the relevant part of
.gitlab-ci.yml that handles it.
image: ruby:latest stages: - up dev # ... before_script: | # install terraform git clone https://github.com/tfutils/tfenv.git ~/.tfenv echo 'export PATH="$HOME/.tfenv/bin:$PATH"' >> ~/.bash_profile export PATH="$HOME/.tfenv/bin:$PATH" tfenv install latest tfenv use latest terraform --version # install terraspace bundle bundle exec terraspace new shim echo 'export PATH="/usr/local/bin:$PATH' >> ~/.bash_profile export PATH="/usr/local/bin:$PATH" # install infracost curl -fsSL https://raw.githubusercontent.com/infracost/infracost/master/scripts/install.sh | sh # ... up_dev: stage: up dev rules: - if: '$CI_PIPELINE_SOURCE == "push" && $CI_COMMIT_BRANCH == "main"' script: - terraspace up demo -y # ...
The pipeline uses the
ruby:latest Docker image.
The first part with the
before_script installs terraform and terraspace. This pipeline hook will run for every stage. This is because each GitLab pipeline stage run on a “fresh” environment. This was a GitLab design decision.
We should set these environment variables. Note that the AWS variables are required only if you’re using terraspace_plugin_aws.
AWS Variables: The workflow is environment configured with
AWS_*variables, so the CI machine has permissions to create resources on AWS. The AWS token need these minimal permissions.
GITLAB_TOKEN: Terraspace uses this to grab additional information like commit messages and Merge Request comments with the terraspace cloud link. The token should have “api” permission so it can post the Merge Request comment.
- TS_TOKEN: This allows Terraspace work with Terraspace Cloud. IE: Save plans, applies, cost etimates, live streams, etc.
- INFRACOST_API_KEY: You will need an infracost API key if you are using Cost Estimation.
With GitLab, you set the environment variables in the Settings -> CI/CD -> Variables section.
- Go to the Repo Settings. It’s the tab on the left-hand side. You must own the repo or have admin permissions to see it.
- On the left-hand menu, go to CI/CD.
- Under the Variables section on the page, click Expand
- Create the variable, IE:
TS_TOKEN. You should uncheck Protect variable if your branch is not protected.
At the very end, the
terraspace up demo -y command will run to deploy the demo stack. You can customize this command or add additional commands. IE: You probably want to use
terraspace all up if you prefer.
Commit and Push
Let’s commit and push the files.
git add . git commit -m 'add ci' git push -u origin main
This starts the build process immediately.
After the job starts, you’ll see something like the following. You may have to refresh to see the job running.
You can see that a resource was created.
Next, we’ll look at the Merge Request Pipeline.