Skip to content
Snippets Groups Projects
Unverified Commit 548f5a4c authored by Timo Furrer's avatar Timo Furrer
Browse files

Add initial copies from terraform-images and minimal pipeline

parent 2c68fb95
No related branches found
No related tags found
No related merge requests found
# include:
# # include the component located in the current project from the current SHA
# - component: gitlab.com/$CI_PROJECT_PATH/full-pipeline@$CI_COMMIT_SHA
# inputs:
# stage: build
#
# stages: [build, test, release]
stages:
- build
.versions:
parallel:
matrix:
- OPENTOFU_VERSION: '1.6'
- OPENTOFU_VERSION: '1.6.0-rc1'
variables:
# OpenTofu image build variables:
DOCKER_DIND_IMAGE: "docker:24.0.7-dind"
PLATFORMS: linux/amd64,linux/arm64
BASE_IMAGE: "alpine:3.18.4"
GITLAB_OPENTOFU_IMAGE_NAME: "$CI_REGISTRY_IMAGE/internal/gitlab-opentofu-$OPENTOFU_VERSION:$CI_COMMIT_SHA"
gitlab-opentofu-image:
extends: .versions
stage: build
services:
- "$DOCKER_DIND_IMAGE"
image: "$DOCKER_DIND_IMAGE"
before_script:
# See note on the `build terraform` job about this image
- docker run --rm --privileged tonistiigi/binfmt
# Registry auth
- docker login -u "$CI_REGISTRY_USER" -p "$CI_REGISTRY_PASSWORD" "$CI_REGISTRY"
script:
- docker buildx create --use
# NOTE: we disable provenance for now
# because it causes troubles with the registry and older clients.
# See
# - https://gitlab.com/gitlab-org/terraform-images/-/issues/104
# - https://gitlab.com/gitlab-org/terraform-images/-/merge_requests/184#note_1328485943
- docker buildx build
--platform "$PLATFORMS"
--build-arg BASE_IMAGE=$BASE_IMAGE
--build-arg OPENTOFU_VERSION=$OPENTOFU_VERSION
--file Dockerfile
--tag "$GITLAB_OPENTOFU_IMAGE_NAME"
--provenance=false
--push
.
# Check if `component-job` is added.
# This example job could also test that the included component works as expected.
# You can inspect data generated by the component, use GitLab API endpoints, or third-party tools.
# ensure-job-added:
# stage: test
# image: badouralix/curl-jq
# script:
# - |
# route="https://gitlab.com/api/v4/projects/$CI_PROJECT_ID/pipelines/$CI_PIPELINE_ID/jobs"
# count=`curl --silent --header "PRIVATE-TOKEN: $API_TOKEN" $route | jq 'map(select(.name | contains("component-job"))) | length'`
# if [ "$count" != "1" ]; then
# exit 1
# fi
# If the pipeline is for a new tag with a semantic version, and all previous jobs succeed,
# create the release.
# create-release:
# stage: release
# image: registry.gitlab.com/gitlab-org/release-cli:latest
# rules:
# - if: $CI_COMMIT_TAG =~ /\d+/
# script: echo "Creating release $CI_COMMIT_TAG"
# release:
# tag_name: $CI_COMMIT_TAG
# description: "Release $CI_COMMIT_TAG of components repository $CI_PROJECT_PATH"
ARG BASE_IMAGE
FROM $BASE_IMAGE
ARG OPENTOFU_VERSION
RUN apk add --no-cache \
curl \
gcompat \
git \
idn2-utils \
jq \
openssh \
cosign
# Install OpenTofu using the installer script in standalone mode
# see https://opentofu.org/docs/intro/install/standalone
# We may want to switch to installing manually from GitHub and verifying signature
RUN curl --proto '=https' --tlsv1.2 -fsSL https://get.opentofu.org/install-opentofu.sh -o install-opentofu.sh && \
chmod +x install-opentofu.sh && \
OPENTOFU_VERSION=${OPENTOFU_VERSION} ./install-opentofu.sh --install-method standalone && \
rm ./install-opentofu.sh && \
tofu --version
WORKDIR /
COPY assets/gitlab-opentofu.sh /usr/bin/gitlab-opentofu
RUN chmod +x /usr/bin/gitlab-opentofu
# Override ENTRYPOINT
ENTRYPOINT []
# OpenTofu
# WIP: OpenTofu
This OpenTofu CI/CD component is still work in progress.
## Getting started
To make it easy for you to get started with GitLab, here's a list of recommended next steps.
Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)!
## Add your files
- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files
- [ ] [Add files using the command line](https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command:
```
cd existing_repo
git remote add origin https://gitlab.com/components/opentofu.git
git branch -M main
git push -uf origin main
```
## Integrate with your tools
- [ ] [Set up project integrations](https://gitlab.com/components/opentofu/-/settings/integrations)
## Collaborate with your team
- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/)
- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html)
- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically)
- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/)
- [ ] [Set auto-merge](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html)
## Test and Deploy
Use the built-in continuous integration in GitLab.
- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/index.html)
- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing (SAST)](https://docs.gitlab.com/ee/user/application_security/sast/)
- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html)
- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/)
- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html)
***
# Editing this README
When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thanks to [makeareadme.com](https://www.makeareadme.com/) for this template.
## Suggestions for a good README
Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information.
## Name
Choose a self-explaining name for your project.
## Description
Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors.
## Badges
On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge.
## Visuals
Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method.
## Installation
Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection.
## Usage
Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README.
## Support
Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc.
## Roadmap
If you have ideas for releases in the future, it is a good idea to list them in the README.
## Contributing
State if you are open to contributions and what your requirements are for accepting them.
For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self.
You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser.
## Authors and acknowledgment
Show your appreciation to those who have contributed to the project.
## License
For open source projects, say how it is licensed.
## Project status
If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers.
See https://gitlab.com/groups/gitlab-org/-/epics/12401
#!/bin/sh -e
# ATTENTION: this script is yet JUST A COPY of https://gitlab.com/gitlab-org/terraform-images/-/blob/master/src/bin/gitlab-terraform.sh
# with some VERY MINIMAL MODIFICATIONS.
# It definitely needs cleanup in the future.
if [ "${DEBUG_OUTPUT}" = "true" ]; then
set -x
fi
# Helpers
# Evaluate if this script is being sourced or executed directly.
# See https://stackoverflow.com/a/28776166
sourced=0
if [ -n "$ZSH_VERSION" ]; then
case $ZSH_EVAL_CONTEXT in *:file) sourced=1;; esac
elif [ -n "$KSH_VERSION" ]; then
# shellcheck disable=SC2296
[ "$(cd -- "$(dirname -- "$0")" && pwd -P)/$(basename -- "$0")" != "$(cd -- "$(dirname -- "${.sh.file}")" && pwd -P)/$(basename -- "${.sh.file}")" ] && sourced=1
elif [ -n "$BASH_VERSION" ]; then
(return 0 2>/dev/null) && sourced=1
else # All other shells: examine $0 for known shell binary filenames.
# Detects `sh` and `dash`; add additional shell filenames as needed.
case ${0##*/} in sh|-sh|dash|-dash) sourced=1;; esac
fi
JQ_PLAN='
(
[.resource_changes[]?.change.actions?] | flatten
) | {
"create":(map(select(.=="create")) | length),
"update":(map(select(.=="update")) | length),
"delete":(map(select(.=="delete")) | length)
}
'
# If TF_USERNAME is unset then default to GITLAB_USER_LOGIN
TF_USERNAME="${TF_USERNAME:-${GITLAB_USER_LOGIN}}"
# If TF_PASSWORD is unset then default to gitlab-ci-token/CI_JOB_TOKEN
if [ -z "${TF_PASSWORD}" ]; then
TF_USERNAME="gitlab-ci-token"
TF_PASSWORD="${CI_JOB_TOKEN}"
fi
# If TF_ADDRESS is unset but TF_STATE_NAME is provided, then default to GitLab backend in current project
if [ -n "${TF_STATE_NAME}" ]; then
TF_ADDRESS="${TF_ADDRESS:-${CI_API_V4_URL}/projects/${CI_PROJECT_ID}/terraform/state/${TF_STATE_NAME}}"
fi
# If TF_ROOT is set then use the -chdir option
if [ -n "${TF_ROOT}" ]; then
abs_tf_root=$(cd "${CI_PROJECT_DIR}"; realpath "${TF_ROOT}")
TF_CHDIR_OPT="-chdir=${abs_tf_root}"
default_tf_plan_cache="${abs_tf_root}/plan.cache"
default_tf_plan_json="${abs_tf_root}/plan.json"
fi
# If TF_PLAN_CACHE is not set then use either the plan.cache file within TF_ROOT if set, or plan.cache in CWD
if [ -z "${TF_PLAN_CACHE}" ]; then
TF_PLAN_CACHE="${default_tf_plan_cache:-plan.cache}"
fi
# If TF_PLAN_JSON is not set then use either the plan.json file within TF_ROOT if set, or plan.json in CWD
if [ -z "${TF_PLAN_JSON}" ]; then
TF_PLAN_JSON="${default_tf_plan_json:-plan.json}"
fi
# Set variables for the HTTP backend to default to TF_* values
export TF_HTTP_ADDRESS="${TF_HTTP_ADDRESS:-${TF_ADDRESS}}"
export TF_HTTP_LOCK_ADDRESS="${TF_HTTP_LOCK_ADDRESS:-${TF_ADDRESS}/lock}"
export TF_HTTP_LOCK_METHOD="${TF_HTTP_LOCK_METHOD:-POST}"
export TF_HTTP_UNLOCK_ADDRESS="${TF_HTTP_UNLOCK_ADDRESS:-${TF_ADDRESS}/lock}"
export TF_HTTP_UNLOCK_METHOD="${TF_HTTP_UNLOCK_METHOD:-DELETE}"
export TF_HTTP_USERNAME="${TF_HTTP_USERNAME:-${TF_USERNAME}}"
export TF_HTTP_PASSWORD="${TF_HTTP_PASSWORD:-${TF_PASSWORD}}"
export TF_HTTP_RETRY_WAIT_MIN="${TF_HTTP_RETRY_WAIT_MIN:-5}"
# Expose Gitlab specific variables to terraform since no -tf-var is available
# Usable in the .tf file as variable "CI_JOB_ID" { type = string } etc
export TF_VAR_CI_JOB_ID="${TF_VAR_CI_JOB_ID:-${CI_JOB_ID}}"
export TF_VAR_CI_COMMIT_SHA="${TF_VAR_CI_COMMIT_SHA:-${CI_COMMIT_SHA}}"
export TF_VAR_CI_JOB_STAGE="${TF_VAR_CI_JOB_STAGE:-${CI_JOB_STAGE}}"
export TF_VAR_CI_PROJECT_ID="${TF_VAR_CI_PROJECT_ID:-${CI_PROJECT_ID}}"
export TF_VAR_CI_PROJECT_NAME="${TF_VAR_CI_PROJECT_NAME:-${CI_PROJECT_NAME}}"
export TF_VAR_CI_PROJECT_NAMESPACE="${TF_VAR_CI_PROJECT_NAMESPACE:-${CI_PROJECT_NAMESPACE}}"
export TF_VAR_CI_PROJECT_PATH="${TF_VAR_CI_PROJECT_PATH:-${CI_PROJECT_PATH}}"
export TF_VAR_CI_PROJECT_URL="${TF_VAR_CI_PROJECT_URL:-${CI_PROJECT_URL}}"
# Use terraform automation mode (will remove some verbose unneeded messages)
export TF_IN_AUTOMATION=true
DEFAULT_TF_CONFIG_PATH="$HOME/.terraformrc"
# Set a Terraform CLI Configuration File
if [ -z "${TF_CLI_CONFIG_FILE}" ] && [ -f "${DEFAULT_TF_CONFIG_PATH}" ]; then
export TF_CLI_CONFIG_FILE="${DEFAULT_TF_CONFIG_PATH}"
fi
terraform_authenticate_private_registry() {
# From Terraform 1.2.0 and later (or all versions of OpenTofu), we can use TF_TOKEN_your_domain_name to authenticate to registry.
# The credential environment variable has the following requirements:
# - Domain names containing non-ASCII characters are converted to their punycode equivalent with an ACE prefix
# - Periods are encoded as underscores
# - Hyphens are encoded as double underscores
# For more info, see https://www.terraform.io/cli/config/config-file#environment-variable-credentials
if [ "${CI_SERVER_PROTOCOL}" = "https" ] && [ -n "${CI_SERVER_HOST}" ]; then
tf_token_var_name=TF_TOKEN_$(idn2 "${CI_SERVER_HOST}" | sed 's/\./_/g' | sed 's/-/__/g')
# If TF_TOKEN_ for the Gitlab domain is not set then use the CI_JOB_TOKEN
if [ -z "$(eval "echo \${${tf_token_var_name}:-}")" ]; then
export "${tf_token_var_name}"="${CI_JOB_TOKEN}"
fi
fi
}
# If TF_IMPLICIT_INIT is not set, we set it to `true`.
# If set to `true` it will call `terraform init` prior
# to calling the wrapper `terraform` commands.
TF_IMPLICIT_INIT=${TF_IMPLICIT_INIT:-true}
terraform_init() {
# If TF_INIT_NO_RECONFIGURE is not set to 'true',
# a `-reconfigure` flag is added to the `terraform init` command.
if [ "$TF_INIT_NO_RECONFIGURE" != 'true' ]; then
tf_init_reconfigure_flag='-reconfigure'
fi
# We want to allow word splitting here for TF_INIT_FLAGS
# shellcheck disable=SC2086
tofu "${TF_CHDIR_OPT}" init "${@}" -input=false ${tf_init_reconfigure_flag} ${TF_INIT_FLAGS}
}
# If this script is executed and not sourced, a terraform command is ran.
# Otherwise, nothing happens and the sourced shell can use the defined variables
# and helper functions exposed by this script.
if [ $sourced -eq 0 ]; then
# Authenticate to private registry
terraform_authenticate_private_registry
case "${1}" in
"apply")
$TF_IMPLICIT_INIT && terraform_init
tofu "${TF_CHDIR_OPT}" "${@}" -input=false "${TF_PLAN_CACHE}"
;;
"destroy")
$TF_IMPLICIT_INIT && terraform_init
tofu "${TF_CHDIR_OPT}" "${@}" -auto-approve
;;
"fmt")
tofu "${TF_CHDIR_OPT}" "${@}" -check -diff -recursive
;;
"init")
# shift argument list „one to the left“ to not call 'terraform init init'
shift
terraform_init "${@}"
;;
"plan")
$TF_IMPLICIT_INIT && terraform_init
tofu "${TF_CHDIR_OPT}" "${@}" -input=false -out="${TF_PLAN_CACHE}"
;;
"plan-json")
tofu "${TF_CHDIR_OPT}" show -json "${TF_PLAN_CACHE}" | \
jq -r "${JQ_PLAN}" \
> "${TF_PLAN_JSON}"
;;
"validate")
$TF_IMPLICIT_INIT && terraform_init -backend=false
tofu "${TF_CHDIR_OPT}" "${@}"
;;
--)
shift
tofu "${TF_CHDIR_OPT}" "${@}"
;;
*)
tofu "${TF_CHDIR_OPT}" "${@}"
;;
esac
else
# This variable can be used if the script is sourced
# shellcheck disable=SC2034
TF_GITLAB_SOURCED=true
fi
spec:
inputs:
stage_validate:
default: 'validate'
description: 'Defines the validate stage'
stage_test:
default: 'test'
description: 'Defines the test stage'
stage_build:
default: 'build'
description: 'Defines the build stage'
stage_deploy:
default: 'deploy'
description: 'Defines the deploy stage'
stage_cleanup:
default: 'cleanup'
description: 'Defines the cleanup stage'
enable_destroy_job:
default: false
description: 'Weather the destroy job should be created'
---
.default:
image:
name: "$CI_TEMPLATE_REGISTRY_HOST/gitlab-org/terraform-images/stable:latest"
cache:
key: "${TF_ROOT}"
paths:
- ${TF_ROOT}/.terraform/
variables:
TF_ROOT: ${CI_PROJECT_DIR} # The relative path to the root directory of the Terraform project
TF_STATE_NAME: default # The name of the state file used by the GitLab Managed Terraform state backend
fmt:
extends: .default
stage: $[[ inputs.stage_validate ]]
needs: []
script:
- gitlab-opentofu fmt
allow_failure: true
rules:
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
- if: $CI_OPEN_MERGE_REQUESTS # Don't add it to a *branch* pipeline if it's already in a merge request pipeline.
when: never
- if: $CI_COMMIT_BRANCH # If there's no open merge request, add it to a *branch* pipeline instead.
validate:
extends: .default
stage: $[[ inputs.stage_validate ]]
script:
- gitlab-opentofu validate
rules:
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
- if: $CI_OPEN_MERGE_REQUESTS # Don't add it to a *branch* pipeline if it's already in a merge request pipeline.
when: never
- if: $CI_COMMIT_BRANCH # If there's no open merge request, add it to a *branch* pipeline instead.
plan:
extends: .default
stage: $[[ inputs.stage_build ]]
script:
- gitlab-opentofu plan
- gitlab-opentofu plan-json
environment:
name: ${TF_STATE_NAME}
action: prepare
resource_group: ${TF_STATE_NAME}
artifacts:
# Terraform's cache files can include secrets which can be accidentally exposed.
# Please exercise caution when utilizing secrets in your Terraform infrastructure and
# consider limiting access to artifacts or take other security measures to protect sensitive information.
#
# The next line, which disables public access to pipeline artifacts, is not available on GitLab.com.
# See: https://docs.gitlab.com/ee/ci/yaml/#artifactspublic
public: false
paths:
- ${TF_ROOT}/plan.cache
reports:
terraform: ${TF_ROOT}/plan.json
rules:
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
- if: $CI_OPEN_MERGE_REQUESTS # Don't add it to a *branch* pipeline if it's already in a merge request pipeline.
when: never
- if: $CI_COMMIT_BRANCH # If there's no open merge request, add it to a *branch* pipeline instead.
apply:
extends: .default
stage: $[[ inputs.stage_deploy ]]
script:
- gitlab-opentofu apply
environment:
name: $TF_STATE_NAME
action: start
resource_group: ${TF_STATE_NAME}
rules:
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH && $TF_AUTO_DEPLOY == "true"
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
when: manual
destroy:
extends: .default
stage: $[[ inputs.stage_destroy ]]
script:
- gitlab-opentofu destroy
resource_group: ${TF_STATE_NAME}
when: manual
rules:
- if: $[[ inputs.enable_destroy_job ]]
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment