Reputation: 3208
I'm utilizing gitlab's opentofu CICD component to good effect.. BUT noticing it'd be nice to keep my cloud credentials protected .. but smooth out the merge_request pipeline (which is not protected and fails on TF PLAN command)
Is there some good way to either protect the merge_request pipeline OR skip the tf plan stage?
variables:
TF_VAR_REGION: "sweden central"
TF_VAR_PROJECT_NAME: "myproject"
TF_VAR_ENVIRONMENT: "$CI_COMMIT_REF_NAME"
TF_STATE_NAME: ""
before_script:
- |
if [ "$CI_COMMIT_REF_NAME" == "main" ]; then
export TF_VAR_ENVIRONMENT="prd"
export TF_STATE_NAME="prd"
elif [ "$CI_COMMIT_REF_NAME" == "staging" ]; then
export TF_VAR_ENVIRONMENT="tst"
export TF_STATE_NAME="tst"
else
export TF_VAR_ENVIRONMENT="dev-${CI_COMMIT_REF_NAME,,}"
export TF_STATE_NAME="dev-${CI_COMMIT_REF_NAME,,}"
fi
include:
- template: Security/SAST.gitlab-ci.yml
- component: $CI_SERVER_FQDN/components/opentofu/[email protected]
inputs:
version: 0.25.0
root_dir: terraform
stages: [validate, test, build, deploy, cleanup]
As you can seee TF Plan fails on merge requets
OpenTofu has been successfully initialized!
Planning failed. OpenTofu encountered an error while generating this plan.
╷
│ Error: No valid credential sources found
│
│ with provider["registry.opentofu.org/hashicorp/aws"],
│ on provider.tf line 2, in provider "aws":
│ 2: provider "aws" {
│
│ Please see https://registry.terraform.io/providers/hashicorp/aws
│ for more information about providing credentials.
│
│ Error: failed to refresh cached credentials, no EC2 IMDS role found,
│ operation error ec2imds: GetMetadata, request canceled, context deadline
│ exceeded
│
╵
Upvotes: 0
Views: 121
Reputation: 1127
The terraform MR should be checked and tested before being merged in main branch, because main branch means real infra.
What would be the risk if the credentials are available to all MRs (branches)? The risk is changing the .gitlab-ci.yml
by some user and retrieve the credentials or applying something that is not in main branch. The solution would be protecting the gitlab-ci.yml
.
There are 3 solutions for this:
Push rules are pre-receive Git hooks. gitlab-ci.yml
can be added to it, and any push containing this file will be rejected.
.gitlab-ci.yml
from changeA .gitlab-ci.yml may contain rules to deploy an application to the production server. This deployment usually runs automatically after pushing a merge request. To prevent developers from changing the .gitlab-ci.yml, you can define it in a different repository. The configuration can reference a file in another project with a completely different set of permissions (similar to separating a project for deployments). In this scenario, the .gitlab-ci.yml is publicly accessible, but can only be edited by users with appropriate permissions in the other project.
and referencing it in your project:
include:
- project: 'gitlab-ci/models'
ref: 'v1.2.0' #optional
file:
- 'terraform.yml'
Upvotes: 0