mirror of
https://gitlab.sarex.io/infra/terraform-contour-mirror.git
synced 2026-12-03 16:11:36 +03:00
++ stand contract env
This commit is contained in:
parent
183240224f
commit
49437054e6
99
.gitea/workflows/contract.yml
Normal file
99
.gitea/workflows/contract.yml
Normal file
@ -0,0 +1,99 @@
|
||||
name: contract
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
push:
|
||||
branches: [main]
|
||||
|
||||
env:
|
||||
INFRA_ENV: ${{ vars.INFRA_ENV }}
|
||||
STACKS: ${{ vars.STACKS }}
|
||||
PG_ADMIN_HOST: ${{ vars.PG_ADMIN_HOST }}
|
||||
PG_ADMIN_PORT: ${{ vars.PG_ADMIN_PORT }}
|
||||
PG_ADMIN_USER: ${{ vars.PG_ADMIN_USER }}
|
||||
MINIO_ENDPOINT: ${{ vars.MINIO_ENDPOINT }}
|
||||
KAFKA_BOOTSTRAP: ${{ vars.KAFKA_BOOTSTRAP }}
|
||||
KAFKA_TLS_ENABLED: ${{ vars.KAFKA_TLS_ENABLED }}
|
||||
KAFKA_SASL_MECHANISM: ${{ vars.KAFKA_SASL_MECHANISM }}
|
||||
RABBITMQ_ENDPOINT: ${{ vars.RABBITMQ_ENDPOINT }}
|
||||
SKIP_POSTGRES_ADMIN: ${{ vars.SKIP_POSTGRES_ADMIN }}
|
||||
SKIP_KAFKA_ADMIN: ${{ vars.SKIP_KAFKA_ADMIN }}
|
||||
SKIP_MINIO_ADMIN: ${{ vars.SKIP_MINIO_ADMIN }}
|
||||
UNIT_ORDER: namespace vault-secrets database s3 rabbitmq kafka-topics valkey-users clickhouse secrets contracts
|
||||
|
||||
jobs:
|
||||
apply:
|
||||
runs-on: ${{ vars.RUNNER_LABEL || 'incluster' }}
|
||||
container:
|
||||
image: ${{ vars.RUNNER_IMAGE || 'cr.yandex/crp3ccidau046kdj8g9q/contour/terraform-terragrunt-offline:v9.11' }}
|
||||
env:
|
||||
TF_STATE_S3_ENDPOINT: ${{ secrets.TF_STATE_S3_ENDPOINT }}
|
||||
TF_STATE_S3_BUCKET: ${{ secrets.TF_STATE_S3_BUCKET }}
|
||||
TF_STATE_S3_REGION: us-east-1
|
||||
S3_ACCESS_KEY: ${{ secrets.S3_ACCESS_KEY }}
|
||||
S3_SECRET_KEY: ${{ secrets.S3_SECRET_KEY }}
|
||||
VAULT_ADDR: ${{ secrets.VAULT_ADDR }}
|
||||
VAULT_TOKEN: ${{ secrets.VAULT_TOKEN }}
|
||||
KUBE_CONTEXT: ${{ secrets.KUBE_CONTEXT }}
|
||||
KUBECONFIG_B64: ${{ secrets.KUBECONFIG_B64 }}
|
||||
KUBECONFIG: /workspace/.kube/config
|
||||
GIT_AUTH_TOKEN: ${{ github.token }}
|
||||
TG_TF_PATH: terraform
|
||||
TG_NON_INTERACTIVE: "true"
|
||||
steps:
|
||||
- name: Checkout
|
||||
run: |
|
||||
set -eu
|
||||
REPO_URL="${GITHUB_SERVER_URL%/}/${GITHUB_REPOSITORY}.git"
|
||||
rm -rf ./* ./.git 2>/dev/null || true
|
||||
git init -q .
|
||||
git remote add origin "$REPO_URL"
|
||||
git -c http.extraHeader="Authorization: token ${GIT_AUTH_TOKEN}" fetch -q --depth=1 origin "${GITHUB_SHA}"
|
||||
git checkout -q -f FETCH_HEAD
|
||||
echo "commit ${GITHUB_SHA}"
|
||||
git log -1 --format='%s'
|
||||
|
||||
- name: Kubeconfig
|
||||
run: |
|
||||
set -eu
|
||||
mkdir -p /workspace/.kube
|
||||
echo "$KUBECONFIG_B64" | base64 -d > /workspace/.kube/config
|
||||
chmod 600 /workspace/.kube/config
|
||||
|
||||
- name: Secret values
|
||||
env:
|
||||
SOPS_AGE_KEY: ${{ secrets.SOPS_AGE_KEY_CONTOUR }}
|
||||
run: |
|
||||
set -eu
|
||||
src="environments/${INFRA_ENV}/secrets.yaml"
|
||||
if grep -q '^sops:' "$src"; then
|
||||
sops --decrypt "$src" > /tmp/infra-secret-values.yaml
|
||||
else
|
||||
cp "$src" /tmp/infra-secret-values.yaml
|
||||
fi
|
||||
echo "INFRA_SECRET_VALUES_FILE=/tmp/infra-secret-values.yaml" >> "$GITHUB_ENV"
|
||||
|
||||
- name: Apply units
|
||||
run: |
|
||||
set -eu
|
||||
export PLATFORM_CODE_DIR="$PWD/vendor/terraform-platform"
|
||||
export INFRA_CONFIG_ROOT="$PWD"
|
||||
map=""
|
||||
for m in vendor/modules/*; do
|
||||
name="$(basename "$m")"
|
||||
map="${map:+$map,}git::ssh://git@gitlab.sarex.io/infra/terraform-modules/${name}.git=$PWD/vendor/modules"
|
||||
done
|
||||
export TG_SOURCE_MAP="$map"
|
||||
. ./scripts/load_admin_creds.sh
|
||||
base="live-contract/${INFRA_ENV}"
|
||||
units=""
|
||||
for u in ${STACKS:-$UNIT_ORDER}; do
|
||||
[ -f "$base/$u/terragrunt.hcl" ] && units="$units $u"
|
||||
done
|
||||
echo "units:$units"
|
||||
for u in $units; do
|
||||
echo "::group::$u"
|
||||
(cd "$base/$u" && terragrunt run -- apply -auto-approve -input=false)
|
||||
echo "::endgroup::"
|
||||
done
|
||||
rm -f /tmp/infra-secret-values.yaml
|
||||
123
ci/build-slice.py
Normal file
123
ci/build-slice.py
Normal file
@ -0,0 +1,123 @@
|
||||
#!/usr/bin/env python3
|
||||
import argparse
|
||||
import base64
|
||||
import io
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
import tarfile
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
GITLAB = "https://gitlab.sarex.io"
|
||||
PLATFORM_REPO = "infra/terraform-platform"
|
||||
MODULES_GROUP = "infra/terraform-modules"
|
||||
SHARED_FILES = (".gitea/workflows/contract.yml", "scripts/load_admin_creds.sh")
|
||||
|
||||
|
||||
class SliceError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def list_contours(repo: Path) -> list[str]:
|
||||
return sorted(p.parent.name for p in repo.glob("live-contract/*/env.hcl"))
|
||||
|
||||
|
||||
def code_ref(repo: Path, contour: str) -> str:
|
||||
text = (repo / "live-contract" / contour / "env.hcl").read_text()
|
||||
m = re.search(r'code_ref\s*=\s*"([^"]+)"', text)
|
||||
if not m:
|
||||
raise SliceError(f"no code_ref in live-contract/{contour}/env.hcl")
|
||||
return m.group(1)
|
||||
|
||||
|
||||
def module_versions(platform_dir: Path) -> dict[str, str]:
|
||||
text = (platform_dir / "versions.hcl").read_text()
|
||||
block = re.search(r"module_versions\s*=\s*\{(.*?)\n\s*\}", text, re.S)
|
||||
if not block:
|
||||
raise SliceError("no module_versions in terraform-platform versions.hcl")
|
||||
return dict(re.findall(r'^\s*([a-z0-9-]+)\s*=\s*"([^"]+)"', block.group(1), re.M))
|
||||
|
||||
|
||||
def infrastructure_yaml(contour: str) -> str:
|
||||
return f"current_environment: {contour}\nenvironments:\n {contour}: {{}}\n"
|
||||
|
||||
|
||||
def git_env(token: str | None) -> dict:
|
||||
env = {**os.environ, "GIT_TERMINAL_PROMPT": "0"}
|
||||
if token:
|
||||
basic = base64.b64encode(f"gitlab-ci-token:{token}".encode()).decode()
|
||||
env.update({"GIT_CONFIG_COUNT": "1", "GIT_CONFIG_KEY_0": "http.extraHeader", "GIT_CONFIG_VALUE_0": f"Authorization: Basic {basic}"})
|
||||
return env
|
||||
|
||||
|
||||
def fetch_tree(source: str, ref: str, dest: Path, token: str | None) -> dict[str, bytes]:
|
||||
r = subprocess.run(["git", "clone", "--quiet", "--depth", "1", "--branch", ref, source, str(dest)], capture_output=True, text=True, env=git_env(token))
|
||||
if r.returncode != 0:
|
||||
raise SliceError(f"git clone {source.split('@')[-1]}@{ref}: {r.stderr.strip()}")
|
||||
files = subprocess.run(["git", "-C", str(dest), "ls-files", "-z"], capture_output=True, check=True).stdout.split(b"\0")
|
||||
return {f.decode(): (dest / f.decode()).read_bytes() for f in files if f}
|
||||
|
||||
|
||||
def tracked(repo: Path, paths: list[str]) -> dict[str, bytes]:
|
||||
out = subprocess.run(["git", "-C", str(repo), "ls-files", "-z", "--", *paths], capture_output=True, check=True).stdout.split(b"\0")
|
||||
return {f.decode(): (repo / f.decode()).read_bytes() for f in out if f}
|
||||
|
||||
|
||||
def collect(repo: Path, contour: str, source_base: str, token: str | None) -> tuple[dict[str, bytes], dict[str, str]]:
|
||||
files = tracked(repo, [f"live-contract/{contour}", f"environments/{contour}", *SHARED_FILES])
|
||||
missing = [p for p in SHARED_FILES if p not in files]
|
||||
if missing:
|
||||
raise SliceError(f"missing {', '.join(missing)}")
|
||||
if not any(p.startswith(f"environments/{contour}/") for p in files):
|
||||
raise SliceError(f"no environments/{contour}")
|
||||
files["infrastructure.yaml"] = infrastructure_yaml(contour).encode()
|
||||
ref = code_ref(repo, contour)
|
||||
pins = {"terraform-platform": ref}
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
platform = Path(tmp) / "platform"
|
||||
for path, data in fetch_tree(f"{source_base}/{PLATFORM_REPO}.git", ref, platform, token).items():
|
||||
files[f"vendor/terraform-platform/{path}"] = data
|
||||
for name, version in sorted(module_versions(platform).items()):
|
||||
for path, data in fetch_tree(f"{source_base}/{MODULES_GROUP}/{name}.git", version, Path(tmp) / name, token).items():
|
||||
if path.startswith("tests/"):
|
||||
continue
|
||||
files[f"vendor/modules/{name}/{path}"] = data
|
||||
pins[name] = version
|
||||
return files, pins
|
||||
|
||||
|
||||
def write_tar(files: dict[str, bytes], out: Path) -> None:
|
||||
buf = io.BytesIO()
|
||||
with tarfile.open(fileobj=buf, mode="w", format=tarfile.PAX_FORMAT) as tar:
|
||||
for name in sorted(files):
|
||||
info = tarfile.TarInfo(name)
|
||||
info.size = len(files[name])
|
||||
info.mode = 0o755 if name.endswith(".sh") else 0o644
|
||||
info.mtime = 0
|
||||
info.uid = info.gid = 0
|
||||
info.uname = info.gname = ""
|
||||
tar.addfile(info, io.BytesIO(files[name]))
|
||||
out.write_bytes(buf.getvalue())
|
||||
|
||||
|
||||
def main() -> int:
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("contour")
|
||||
ap.add_argument("--repo", default=".")
|
||||
ap.add_argument("--out", required=True)
|
||||
ap.add_argument("--source-base", default=GITLAB, help="base URL or local directory holding infra/terraform-platform and infra/terraform-modules")
|
||||
args = ap.parse_args()
|
||||
try:
|
||||
files, pins = collect(Path(args.repo).resolve(), args.contour, args.source_base, os.environ.get("CI_JOB_TOKEN"))
|
||||
write_tar(files, Path(args.out))
|
||||
except SliceError as e:
|
||||
print(f"slice {args.contour}: {e}", file=sys.stderr)
|
||||
return 1
|
||||
print(f"slice {args.contour}: {len(files)} files, " + ", ".join(f"{k} {v}" for k, v in pins.items()))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
17
environments/stand/environment.yaml
Normal file
17
environments/stand/environment.yaml
Normal file
@ -0,0 +1,17 @@
|
||||
name: stand
|
||||
state:
|
||||
bucket: tfstate
|
||||
endpoint: http://minio.storage.svc.cluster.local:9000
|
||||
region: us-east-1
|
||||
backends:
|
||||
postgresql:
|
||||
kind: incluster
|
||||
host: pg-host.storage.svc.cluster.local
|
||||
port: 5432
|
||||
s3:
|
||||
kind: incluster
|
||||
endpoint: http://minio.storage.svc.cluster.local:9000
|
||||
kafka:
|
||||
kind: incluster
|
||||
rabbitmq:
|
||||
cluster: default
|
||||
1
environments/stand/namespaces.yaml
Normal file
1
environments/stand/namespaces.yaml
Normal file
@ -0,0 +1 @@
|
||||
namespaces: {}
|
||||
17
environments/stand/secrets.yaml
Normal file
17
environments/stand/secrets.yaml
Normal file
@ -0,0 +1,17 @@
|
||||
environments:
|
||||
stand:
|
||||
vault:
|
||||
enabled: true
|
||||
kv_mount: secrets
|
||||
path_prefix: vault
|
||||
kubernetes_auth_backend: kubernetes
|
||||
features:
|
||||
create_regcred: false
|
||||
create_smtp_auth: false
|
||||
create_django_auth: false
|
||||
create_rsa_keys: false
|
||||
create_infra_secrets: false
|
||||
create_infra_policies: true
|
||||
create_infra_roles: true
|
||||
create_app_policies: false
|
||||
create_app_roles: false
|
||||
4
live-contract/stand/env.hcl
Normal file
4
live-contract/stand/env.hcl
Normal file
@ -0,0 +1,4 @@
|
||||
locals {
|
||||
environment = "stand"
|
||||
code_ref = "v0.30.0"
|
||||
}
|
||||
7
live-contract/stand/vault-secrets/terragrunt.hcl
Normal file
7
live-contract/stand/vault-secrets/terragrunt.hcl
Normal file
@ -0,0 +1,7 @@
|
||||
include "root" {
|
||||
path = "${get_env("PLATFORM_CODE_DIR", "")}/terragrunt/root.hcl"
|
||||
}
|
||||
|
||||
include "unit" {
|
||||
path = "${get_env("PLATFORM_CODE_DIR", "")}/terragrunt/units/vault-secrets.hcl"
|
||||
}
|
||||
Loading…
Reference in New Issue
Block a user