Repository navigation
Feat/terraform cd - #4222
Feat/terraform cd#4222yang1993buaa wants to merge 13 commits into
Conversation
- Add TKE Serverless (EKS) cluster with Kubernetes Provider - Add VPC, subnets, security groups - Add managed PostgreSQL and Redis - Add K8s Deployment with rolling update on image tag change - Add K8s Service with CLB LoadBalancer - Add GitHub Actions CD workflow (tag push -> build -> terraform apply) - Add Terraform state backend on Tencent COS - Update .gitignore for Terraform sensitive files
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
WalkthroughAdds Terraform-based infrastructure and Kubernetes app manifests for Tencent Cloud, plus two GitHub Actions workflows: a tag-triggered build-and-deploy to TCR + Terraform apply, and a PR-focused Terraform validation workflow. Also adds docs, tflint config, example tfvars, and a .gitignore merge-conflict insertion. Changes
Sequence Diagram(s)sequenceDiagram
participant GH as GitHub Actions
participant Repo as Repository
participant TCR as Tencent TCR
participant TF as Terraform
participant COS as Tencent COS
participant Tencent as Tencent Cloud
participant K8s as Kubernetes
GH->>Repo: trigger (tag push / workflow_dispatch / pull_request)
GH->>Repo: checkout code
alt Tag push or manual deploy
GH->>Repo: build Docker image (image_tag/version)
GH->>TCR: push image (version, latest)
GH->>TF: terraform init/plan/apply (COS backend)
TF->>COS: read/write state
TF->>Tencent: provision VPC, DB, Redis, TKE resources
TF->>K8s: deploy Deployment/Service using pushed image
TF->>GH: emit outputs (app_url, app_image)
else PR validation
GH->>TF: run terraform fmt -check & validate
GH->>TF: run tflint
GH->>TF: terraform plan (app_image_tag=plan-check)
TF-->>GH: plan output (comment on PR)
end
Estimated code review effort🎯 4 (Complex) | ⏱️ ~50 minutes Poem
🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 inconclusive)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 8
🧹 Nitpick comments (7)
infra/terraform/README.md (2)
96-107: Add language identifier to file structure code block.Per static analysis hint (MD040), fenced code blocks should have a language specified.
♻️ Proposed fix
-``` +```text infra/terraform/ ├── versions.tf # Terraform/Provider 版本 + COS backend🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@infra/terraform/README.md` around lines 96 - 107, The README.md's fenced file-tree block lacks a language identifier causing MD040; update the opening fence for the code block in README.md to include a language token (e.g., change the triple backticks to "```text") so the file-structure block is annotated; locate the block that begins with the tree listing (the block shown in the diff) and add the language identifier to the opening fence only.
7-25: Add language identifier to fenced code block.Per static analysis, fenced code blocks should have a language specified. For ASCII diagrams, use
textorplaintext.♻️ Proposed fix
-``` +```text GitHub (tag push) │🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@infra/terraform/README.md` around lines 7 - 25, The fenced ASCII diagram code block in the Terraform README lacks a language identifier; update the opening fence from ``` to ```text (or ```plaintext) for the ASCII diagram so static analysis recognizes it as a plaintext block—locate the ASCII diagram block (the GitHub/TKE/Tencent 云 resource diagram) and add the language token to the opening fence..github/workflows/terraform-validate.yml (2)
93-95: Consider pinning TFLint version for reproducible CI.Using
tflint_version: latestcan cause inconsistent behavior across runs if TFLint releases a new version with different rules or behaviors.♻️ Proposed fix
- name: Setup TFLint uses: terraform-linters/setup-tflint@v4 with: - tflint_version: latest + tflint_version: "0.53.0" # Pin to specific version🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In @.github/workflows/terraform-validate.yml around lines 93 - 95, The workflow currently sets tflint_version: latest which can cause nondeterministic CI; update the job to pin a specific TFLint release by replacing tflint_version: latest with a concrete version string (e.g., "0.45.0") and, if desired, also pin the action by changing uses: terraform-linters/setup-tflint@v4 to a specific tag or SHA; ensure the chosen version is tested and documented in the workflow so runs are reproducible.
113-116: Environment variablesTENCENTCLOUD_SECRET_ID/KEYare redundant.The secrets are passed via
-vararguments in the plan step (lines 132-133). The environment variables on lines 114-115 appear unused by the Terraform provider since the provider is configured viavar.secret_idandvar.secret_keyinprovider.tf.♻️ Remove unused environment variables
defaults: run: working-directory: ${{ env.TF_WORKING_DIR }} - env: - TENCENTCLOUD_SECRET_ID: ${{ secrets.TENCENTCLOUD_SECRET_ID }} - TENCENTCLOUD_SECRET_KEY: ${{ secrets.TENCENTCLOUD_SECRET_KEY }} steps: - uses: actions/checkout@v4🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In @.github/workflows/terraform-validate.yml around lines 113 - 116, Remove the unused environment variables TENCENTCLOUD_SECRET_ID and TENCENTCLOUD_SECRET_KEY from the GitHub Actions job since the Terraform provider is configured via input variables var.secret_id and var.secret_key (passed through the plan step's -var arguments); update the workflow to only rely on the existing -var usage in the plan/apply steps (or, if you intend to use env creds, wire the provider to read the env vars instead), ensuring you reference the Terraform variables var.secret_id and var.secret_key and the plan step that supplies them when making the change.infra/terraform/network.tf (1)
13-27: Single availability zone — consider multi-AZ for production high availability.Both subnets are placed in
var.availability_zone. For production workloads, consider spreading across multiple AZs to survive zone failures. This is acceptable for initial deployment but worth noting for future improvements.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@infra/terraform/network.tf` around lines 13 - 27, The two subnet resources (tencentcloud_subnet.app and tencentcloud_subnet.db) are both using the same var.availability_zone which creates a single-AZ deployment; modify these resources to accept or compute different availability zones (e.g., var.availability_zones list or a count/map) and assign distinct AZs to each subnet so that app and db subnets are placed in separate availability zones for multi-AZ high availability, updating any variable definitions and references accordingly.infra/terraform/versions.tf (1)
4-17: Consider tighter provider version constraints for production stability.Using
>=allows any future major version, which could introduce breaking changes. For production infrastructure, consider using pessimistic constraints (~>) to allow patch/minor updates while preventing major version jumps.♻️ Proposed fix for version constraints
required_providers { tencentcloud = { source = "tencentcloudstack/tencentcloud" - version = ">= 1.81.0" + version = "~> 1.81" } kubernetes = { source = "hashicorp/kubernetes" - version = ">= 2.25.0" + version = "~> 2.25" } random = { source = "hashicorp/random" - version = ">= 3.6.0" + version = "~> 3.6" } }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@infra/terraform/versions.tf` around lines 4 - 17, The provider version constraints using ">=" are too permissive; update each provider entry in the required_providers block (tencentcloud, kubernetes, random) to use pessimistic constraints instead (e.g., change version = ">= 1.81.0" to version = "~> 1.81.0", ">= 2.25.0" to "~> 2.25.0", and ">= 3.6.0" to "~> 3.6.0") so minor/patch updates are allowed but major version jumps are prevented..github/workflows/deploy-tencent.yml (1)
104-110: PreferTF_VAR_*env vars over passing secrets on the CLI.These values end up on the Terraform command line. GitHub masks the secret values in logs, but keeping them out of argv is still safer and cleaner. Move the sensitive inputs into job env and only keep the non-secret
app_image_tagon the CLI.Suggested refactor
env: # Terraform 通过环境变量读取腾讯云凭证 TENCENTCLOUD_SECRET_ID: ${{ secrets.TENCENTCLOUD_SECRET_ID }} TENCENTCLOUD_SECRET_KEY: ${{ secrets.TENCENTCLOUD_SECRET_KEY }} + TF_VAR_secret_id: ${{ secrets.TENCENTCLOUD_SECRET_ID }} + TF_VAR_secret_key: ${{ secrets.TENCENTCLOUD_SECRET_KEY }} + TF_VAR_tcr_namespace: ${{ secrets.TCR_NAMESPACE }} + TF_VAR_db_password: ${{ secrets.DB_PASSWORD }} + TF_VAR_session_secret: ${{ secrets.SESSION_SECRET }} @@ terraform plan -no-color -input=false \ -var="app_image_tag=${{ needs.build.outputs.version }}" \ - -var="secret_id=${{ secrets.TENCENTCLOUD_SECRET_ID }}" \ - -var="secret_key=${{ secrets.TENCENTCLOUD_SECRET_KEY }}" \ - -var="tcr_namespace=${{ secrets.TCR_NAMESPACE }}" \ - -var="db_password=${{ secrets.DB_PASSWORD }}" \ - -var="session_secret=${{ secrets.SESSION_SECRET }}" \ -out=tfplan🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In @.github/workflows/deploy-tencent.yml around lines 104 - 110, Move sensitive Terraform inputs off the CLI by exporting them as TF_VAR_* environment variables in the job environment and only pass the non-secret app_image_tag via -var on the terraform plan command; specifically, set environment variables TF_VAR_secret_id, TF_VAR_secret_key, TF_VAR_tcr_namespace, TF_VAR_db_password, and TF_VAR_session_secret from the corresponding GitHub secrets (secrets.TENCENTCLOUD_SECRET_ID, secrets.TENCENTCLOUD_SECRET_KEY, secrets.TCR_NAMESPACE, secrets.DB_PASSWORD, secrets.SESSION_SECRET) and remove those -var="..." entries from the terraform plan invocation while keeping -var="app_image_tag=${{ needs.build.outputs.version }}" in the terraform plan call.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In @.github/workflows/deploy-tencent.yml:
- Around line 116-127: The verification step currently swallows terraform errors
by using `terraform output -raw ... || echo ""` so it always posts "Deploy
Complete"; modify the step to poll for non-empty `APP_URL` and `IMAGE` (from
`terraform output -raw app_url` and `terraform output -raw app_image`) for a
bounded period (e.g., loop with sleep and a configurable timeout/retries), and
if either value remains empty after the timeout exit with a non-zero status so
the job fails; upon success, write the values to `GITHUB_STEP_SUMMARY` as
before.
In @.github/workflows/terraform-validate.yml:
- Around line 140-176: The current "Comment Plan on PR" step reads a raw plan
file (plan_output.txt) which may contain sensitive values; update the workflow
so the plan is created with "terraform plan -out=tfplan" and then run "terraform
show -no-color tfplan" to produce the output file you read (planPath) so
Terraform's sensitivity markers are respected, and additionally implement a
simple redaction pass before posting (e.g., scan the plan string for known
sensitive patterns like access_key, secret, token, password, private_key and
replace values with "[REDACTED]") — update the step that writes/reads plan
(variables planPath and the code that sets plan) to use the tfplan->show flow
and perform the redaction before truncation and composing the comment (keeping
the existing maxLen/truncation and use of steps.plan.outcome).
In @.gitignore:
- Line 35: Remove the infra/terraform/.terraform.lock.hcl entry from .gitignore
and add/commit the actual infra/terraform/.terraform.lock.hcl file to the repo
so Terraform's dependency lock file is tracked; update the git index (git rm
--cached if needed) and ensure future changes to the lockfile are committed to
keep provider versions consistent.
In `@infra/terraform/app.tf`:
- Around line 49-50: The SQL_DSN is interpolating var.db_password directly which
breaks if the password contains URL-sensitive characters; update the
interpolation in the SQL_DSN value to URL-encode the password (e.g., use
Terraform's urlencode function) so that var.db_password is passed as
urlencode(var.db_password) when constructing the DSN that includes
tencentcloud_postgresql_instance.main.private_access_ip and
.private_access_port.
- Around line 13-16: The public_lb block on the tencentcloud_eks_cluster
resource currently uses allow_from_cidrs = ["0.0.0.0/0"]; change this to accept
a constrained list of CIDRs (e.g., GitHub Actions egress ranges plus your admin
office IPs) and parameterize it via a new variable (e.g., variable
"api_allowed_cidrs" in variables.tf) instead of hardcoding; update the
tencentcloud_eks_cluster.public_lb.allow_from_cidrs to reference
var.api_allowed_cidrs and add a sensible default/validation in variables.tf to
prevent accidental wide-open values.
- Around line 237-242: The LoadBalancer service port block exposing name="https"
with port=443 and target_port=3000 is incorrect because TLS is not terminated;
either remove this port block (delete the port with name "https", port 443,
target_port 3000) or implement TLS termination on the CLB by configuring a CLB
HTTPS listener with a valid certificate and forwarding to the backend on port
3000 (keep the port block but ensure CLB TLS termination is configured). Ensure
the chosen fix is applied consistently wherever the port block with name "https"
is defined.
In `@infra/terraform/network.tf`:
- Around line 43-54: The VPC-wide permissive rule in the ingress list
("ACCEPT#10.0.0.0/16#ALL#ALL") should be replaced with least-privilege rules:
remove that all-ports allow and add explicit ingress entries for only the
required internal ports (for example add "ACCEPT#10.0.0.0/16#TCP#3000" for app
traffic and any specific TCP/UDP ports used for health checks or inter-service
APIs), keep the external HTTP/HTTPS rules and the final DROP rule; update the
ingress array definition so only those explicit 10.0.0.0/16 entries exist
instead of the broad ALL rule.
In `@infra/terraform/outputs.tf`:
- Around line 16-19: The output output "app_load_balancer_ip" currently indexes
kubernetes_service.app.status[0].load_balancer[0].ingress[0].ip directly which
can fail if the LoadBalancer/ingress isn't yet assigned; update the output to
use Terraform's try() around that lookup (e.g.,
try(kubernetes_service.app.status[0].load_balancer[0].ingress[0].ip, null)) so
the initial apply doesn't error and the value remains null until populated;
apply the same try() pattern to any other outputs that reference
kubernetes_service.app.status[0].load_balancer[0].ingress[0].ip.
---
Nitpick comments:
In @.github/workflows/deploy-tencent.yml:
- Around line 104-110: Move sensitive Terraform inputs off the CLI by exporting
them as TF_VAR_* environment variables in the job environment and only pass the
non-secret app_image_tag via -var on the terraform plan command; specifically,
set environment variables TF_VAR_secret_id, TF_VAR_secret_key,
TF_VAR_tcr_namespace, TF_VAR_db_password, and TF_VAR_session_secret from the
corresponding GitHub secrets (secrets.TENCENTCLOUD_SECRET_ID,
secrets.TENCENTCLOUD_SECRET_KEY, secrets.TCR_NAMESPACE, secrets.DB_PASSWORD,
secrets.SESSION_SECRET) and remove those -var="..." entries from the terraform
plan invocation while keeping -var="app_image_tag=${{
needs.build.outputs.version }}" in the terraform plan call.
In @.github/workflows/terraform-validate.yml:
- Around line 93-95: The workflow currently sets tflint_version: latest which
can cause nondeterministic CI; update the job to pin a specific TFLint release
by replacing tflint_version: latest with a concrete version string (e.g.,
"0.45.0") and, if desired, also pin the action by changing uses:
terraform-linters/setup-tflint@v4 to a specific tag or SHA; ensure the chosen
version is tested and documented in the workflow so runs are reproducible.
- Around line 113-116: Remove the unused environment variables
TENCENTCLOUD_SECRET_ID and TENCENTCLOUD_SECRET_KEY from the GitHub Actions job
since the Terraform provider is configured via input variables var.secret_id and
var.secret_key (passed through the plan step's -var arguments); update the
workflow to only rely on the existing -var usage in the plan/apply steps (or, if
you intend to use env creds, wire the provider to read the env vars instead),
ensuring you reference the Terraform variables var.secret_id and var.secret_key
and the plan step that supplies them when making the change.
In `@infra/terraform/network.tf`:
- Around line 13-27: The two subnet resources (tencentcloud_subnet.app and
tencentcloud_subnet.db) are both using the same var.availability_zone which
creates a single-AZ deployment; modify these resources to accept or compute
different availability zones (e.g., var.availability_zones list or a count/map)
and assign distinct AZs to each subnet so that app and db subnets are placed in
separate availability zones for multi-AZ high availability, updating any
variable definitions and references accordingly.
In `@infra/terraform/README.md`:
- Around line 96-107: The README.md's fenced file-tree block lacks a language
identifier causing MD040; update the opening fence for the code block in
README.md to include a language token (e.g., change the triple backticks to
"```text") so the file-structure block is annotated; locate the block that
begins with the tree listing (the block shown in the diff) and add the language
identifier to the opening fence only.
- Around line 7-25: The fenced ASCII diagram code block in the Terraform README
lacks a language identifier; update the opening fence from ``` to ```text (or
```plaintext) for the ASCII diagram so static analysis recognizes it as a
plaintext block—locate the ASCII diagram block (the GitHub/TKE/Tencent 云
resource diagram) and add the language token to the opening fence.
In `@infra/terraform/versions.tf`:
- Around line 4-17: The provider version constraints using ">=" are too
permissive; update each provider entry in the required_providers block
(tencentcloud, kubernetes, random) to use pessimistic constraints instead (e.g.,
change version = ">= 1.81.0" to version = "~> 1.81.0", ">= 2.25.0" to "~>
2.25.0", and ">= 3.6.0" to "~> 3.6.0") so minor/patch updates are allowed but
major version jumps are prevented.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 4c039b89-f37d-454c-98d3-3aadae2e45e8
📒 Files selected for processing (13)
.github/workflows/deploy-tencent.yml.github/workflows/terraform-validate.yml.gitignoreinfra/terraform/.tflint.hclinfra/terraform/README.mdinfra/terraform/app.tfinfra/terraform/database.tfinfra/terraform/network.tfinfra/terraform/outputs.tfinfra/terraform/provider.tfinfra/terraform/terraform.tfvars.exampleinfra/terraform/variables.tfinfra/terraform/versions.tf
| - name: Verify deployment | ||
| run: | | ||
| APP_URL=$(terraform output -raw app_url 2>/dev/null || echo "") | ||
| IMAGE=$(terraform output -raw app_image 2>/dev/null || echo "") | ||
|
|
||
| echo "### 🚀 Deploy Complete" >> "$GITHUB_STEP_SUMMARY" | ||
| echo "" >> "$GITHUB_STEP_SUMMARY" | ||
| echo "| Item | Value |" >> "$GITHUB_STEP_SUMMARY" | ||
| echo "|------|-------|" >> "$GITHUB_STEP_SUMMARY" | ||
| echo "| **Version** | \`${{ needs.build.outputs.version }}\` |" >> "$GITHUB_STEP_SUMMARY" | ||
| echo "| **Image** | \`${IMAGE}\` |" >> "$GITHUB_STEP_SUMMARY" | ||
| echo "| **URL** | ${APP_URL} |" >> "$GITHUB_STEP_SUMMARY" |
There was a problem hiding this comment.
Make the verification step fail when deployment outputs never appear.
Right now every terraform output error is swallowed and the step still publishes Deploy Complete. A CLB provisioning failure or empty output becomes a false green release. Poll for a non-empty URL/image and exit non-zero on timeout.
Suggested fix
- name: Verify deployment
run: |
- APP_URL=$(terraform output -raw app_url 2>/dev/null || echo "")
- IMAGE=$(terraform output -raw app_image 2>/dev/null || echo "")
+ APP_URL=""
+ IMAGE=""
+ for _ in {1..30}; do
+ APP_URL=$(terraform output -raw app_url 2>/dev/null || true)
+ IMAGE=$(terraform output -raw app_image 2>/dev/null || true)
+ [[ -n "$APP_URL" && -n "$IMAGE" ]] && break
+ sleep 10
+ done
+
+ [[ -n "$APP_URL" && -n "$IMAGE" ]] || {
+ echo "Deployment outputs not ready after waiting."
+ exit 1
+ }
echo "### 🚀 Deploy Complete" >> "$GITHUB_STEP_SUMMARY"🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In @.github/workflows/deploy-tencent.yml around lines 116 - 127, The
verification step currently swallows terraform errors by using `terraform output
-raw ... || echo ""` so it always posts "Deploy Complete"; modify the step to
poll for non-empty `APP_URL` and `IMAGE` (from `terraform output -raw app_url`
and `terraform output -raw app_image`) for a bounded period (e.g., loop with
sleep and a configurable timeout/retries), and if either value remains empty
after the timeout exit with a non-zero status so the job fails; upon success,
write the values to `GITHUB_STEP_SUMMARY` as before.
|
|
||
| # Terraform | ||
| infra/terraform/.terraform/ | ||
| infra/terraform/.terraform.lock.hcl |
There was a problem hiding this comment.
🧩 Analysis chain
🌐 Web query:
Should terraform.lock.hcl be committed to git?
💡 Result:
Yes, the .terraform.lock.hcl file should be committed to Git. Official HashiCorp documentation explicitly states: "You should include this file in your version control repository so that you can discuss potential changes to your external dependencies via code review." This ensures consistent provider versions across team members and environments, preventing unexpected upgrades during terraform init. Multiple recent sources (up to 2026) confirm this best practice, including recommendations to generate multi-platform hashes using terraform providers lock for cross-OS teams and to update via terraform init -upgrade before committing changes. Do not add it to .gitignore; instead, ignore .terraform/ directory and .tfstate files.
Citations:
- 1: https://developer.hashicorp.com/terraform/language/files/dependency-lock
- 2: https://developer.hashicorp.com/terraform/tutorials/configuration-language/provider-versioning
- 3: https://devops-daily.com/posts/should-terraform-lock-be-in-your-gitignore
- 4: https://oneuptime.com/blog/post/2026-02-23-how-to-handle-terraform-lock-hcl-in-version-control/view
- 5: https://stackoverflow.com/questions/67963719/should-terraform-lock-hcl-be-included-in-the-gitignore-file
- 6: https://blog.rishabkumar.com/terraform-lock-hcl-to-gitignore-or-commit
Remove .terraform.lock.hcl from .gitignore.
The Terraform dependency lock file must be committed to version control. HashiCorp's official documentation explicitly recommends this to ensure consistent provider versions across all team members and environments, preventing unexpected upgrades during terraform init.
♻️ Proposed fix
# Terraform
infra/terraform/.terraform/
-infra/terraform/.terraform.lock.hcl
infra/terraform/terraform.tfvars
infra/terraform/terraform.tfstate*
infra/terraform/tfplan
infra/terraform/*.backup📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| infra/terraform/.terraform.lock.hcl | |
| # Terraform | |
| infra/terraform/.terraform/ | |
| infra/terraform/terraform.tfvars | |
| infra/terraform/terraform.tfstate* | |
| infra/terraform/tfplan | |
| infra/terraform/*.backup |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In @.gitignore at line 35, Remove the infra/terraform/.terraform.lock.hcl entry
from .gitignore and add/commit the actual infra/terraform/.terraform.lock.hcl
file to the repo so Terraform's dependency lock file is tracked; update the git
index (git rm --cached if needed) and ensure future changes to the lockfile are
committed to keep provider versions consistent.
| data = { | ||
| SQL_DSN = "postgresql://root:${var.db_password}@${tencentcloud_postgresql_instance.main.private_access_ip}:${tencentcloud_postgresql_instance.main.private_access_port}/new_api?sslmode=require" |
There was a problem hiding this comment.
URL-encode the database password inside the DSN.
If var.db_password contains @, :, #, /, or similar characters, this connection string becomes invalid even though the password itself is valid. Encode the password before interpolating it into the URL.
Suggested fix
- SQL_DSN = "postgresql://root:${var.db_password}@${tencentcloud_postgresql_instance.main.private_access_ip}:${tencentcloud_postgresql_instance.main.private_access_port}/new_api?sslmode=require"
+ SQL_DSN = "postgresql://root:${urlencode(var.db_password)}@${tencentcloud_postgresql_instance.main.private_access_ip}:${tencentcloud_postgresql_instance.main.private_access_port}/new_api?sslmode=require"🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@infra/terraform/app.tf` around lines 49 - 50, The SQL_DSN is interpolating
var.db_password directly which breaks if the password contains URL-sensitive
characters; update the interpolation in the SQL_DSN value to URL-encode the
password (e.g., use Terraform's urlencode function) so that var.db_password is
passed as urlencode(var.db_password) when constructing the DSN that includes
tencentcloud_postgresql_instance.main.private_access_ip and
.private_access_port.
| port { | ||
| name = "https" | ||
| port = 443 | ||
| target_port = 3000 | ||
| protocol = "TCP" | ||
| } |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
# First, let's look at the structure of the infra/terraform directory
find infra/terraform -type f -name "*.tf" | head -20Repository: QuantumNous/new-api
Length of output: 252
🏁 Script executed:
# Now let's examine the specific file around the mentioned lines
cat -n infra/terraform/app.tf | sed -n '220,260p'Repository: QuantumNous/new-api
Length of output: 575
🏁 Script executed:
# Let's also search for TLS, certificate, and ingress configurations in the terraform files
rg -i "tls|certificate|ingress|ssl" infra/terraform/ --type tf -A 3 -B 1Repository: QuantumNous/new-api
Length of output: 2082
🏁 Script executed:
# Search for Kubernetes Ingress resources
rg -i "kubernetes_ingress|kind.*ingress" infra/terraform/ --type tf -A 5 -B 2Repository: QuantumNous/new-api
Length of output: 45
🏁 Script executed:
# Get the full app.tf file to see all resource definitions
wc -l infra/terraform/app.tfRepository: QuantumNous/new-api
Length of output: 89
🏁 Script executed:
# Examine the app.tf file structure to see all resource types
rg "^resource " infra/terraform/app.tfRepository: QuantumNous/new-api
Length of output: 270
🏁 Script executed:
# Read the entire app.tf file to check for any TLS configuration in deployment
cat -n infra/terraform/app.tfRepository: QuantumNous/new-api
Length of output: 7540
Remove port 443 or implement TLS termination at the CLB level.
Port 443 is exposed by the LoadBalancer service but forwards directly to port 3000 without TLS termination. The application listens only on HTTP (port 3000), so HTTPS clients attempting to connect will fail with TLS handshake errors. Either remove the port 443 mapping or configure TLS termination at the TencentCloud CLB layer.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@infra/terraform/app.tf` around lines 237 - 242, The LoadBalancer service port
block exposing name="https" with port=443 and target_port=3000 is incorrect
because TLS is not terminated; either remove this port block (delete the port
with name "https", port 443, target_port 3000) or implement TLS termination on
the CLB by configuring a CLB HTTPS listener with a valid certificate and
forwarding to the backend on port 3000 (keep the port block but ensure CLB TLS
termination is configured). Ensure the chosen fix is applied consistently
wherever the port block with name "https" is defined.
| ingress = [ | ||
| # VPC 内部全放通 | ||
| "ACCEPT#10.0.0.0/16#ALL#ALL", | ||
| # HTTP | ||
| "ACCEPT#0.0.0.0/0#TCP#80", | ||
| # HTTPS | ||
| "ACCEPT#0.0.0.0/0#TCP#443", | ||
| # 应用端口(CLB 健康检查需要) | ||
| "ACCEPT#10.0.0.0/16#TCP#3000", | ||
| # 拒绝其他 | ||
| "DROP#0.0.0.0/0#ALL#ALL", | ||
| ] |
There was a problem hiding this comment.
VPC-internal "allow all" rule is overly permissive.
Line 45 allows all traffic within the VPC (ACCEPT#10.0.0.0/16#ALL#ALL), which means any compromised workload can access any other service on any port. Consider applying least-privilege by only allowing the specific ports needed (e.g., 3000 for app-to-app, specific ports for health checks).
🛡️ Suggested more restrictive rules
ingress = [
- # VPC 内部全放通
- "ACCEPT#10.0.0.0/16#ALL#ALL",
# HTTP
"ACCEPT#0.0.0.0/0#TCP#80",
# HTTPS
"ACCEPT#0.0.0.0/0#TCP#443",
- # 应用端口(CLB 健康检查需要)
+ # 应用端口(VPC 内部 + CLB 健康检查)
"ACCEPT#10.0.0.0/16#TCP#3000",
# 拒绝其他
"DROP#0.0.0.0/0#ALL#ALL",
]📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| ingress = [ | |
| # VPC 内部全放通 | |
| "ACCEPT#10.0.0.0/16#ALL#ALL", | |
| # HTTP | |
| "ACCEPT#0.0.0.0/0#TCP#80", | |
| # HTTPS | |
| "ACCEPT#0.0.0.0/0#TCP#443", | |
| # 应用端口(CLB 健康检查需要) | |
| "ACCEPT#10.0.0.0/16#TCP#3000", | |
| # 拒绝其他 | |
| "DROP#0.0.0.0/0#ALL#ALL", | |
| ] | |
| ingress = [ | |
| # HTTP | |
| "ACCEPT#0.0.0.0/0#TCP#80", | |
| # HTTPS | |
| "ACCEPT#0.0.0.0/0#TCP#443", | |
| # 应用端口(VPC 内部 + CLB 健康检查) | |
| "ACCEPT#10.0.0.0/16#TCP#3000", | |
| # 拒绝其他 | |
| "DROP#0.0.0.0/0#ALL#ALL", | |
| ] |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@infra/terraform/network.tf` around lines 43 - 54, The VPC-wide permissive
rule in the ingress list ("ACCEPT#10.0.0.0/16#ALL#ALL") should be replaced with
least-privilege rules: remove that all-ports allow and add explicit ingress
entries for only the required internal ports (for example add
"ACCEPT#10.0.0.0/16#TCP#3000" for app traffic and any specific TCP/UDP ports
used for health checks or inter-service APIs), keep the external HTTP/HTTPS
rules and the final DROP rule; update the ingress array definition so only those
explicit 10.0.0.0/16 entries exist instead of the broad ALL rule.
| output "app_load_balancer_ip" { | ||
| description = "new-api 服务的 CLB 公网 IP(部署后可通过此 IP 访问)" | ||
| value = kubernetes_service.app.status[0].load_balancer[0].ingress[0].ip | ||
| } |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
find . -name "outputs.tf" -path "*/terraform/*" -type fRepository: QuantumNous/new-api
Length of output: 91
🏁 Script executed:
cat -n ./infra/terraform/outputs.tfRepository: QuantumNous/new-api
Length of output: 1572
🏁 Script executed:
grep -n "kubernetes_service" ./infra/terraform/outputs.tf
rg "kubernetes_service\.app" ./infra/terraform/ --no-headingRepository: QuantumNous/new-api
Length of output: 470
🏁 Script executed:
fd "\.tf$" ./infra/terraform/ -type f | head -20Repository: QuantumNous/new-api
Length of output: 233
🏁 Script executed:
fd "\.tf$" ./infra/terraform/Repository: QuantumNous/new-api
Length of output: 266
🏁 Script executed:
rg "kubernetes_service\.app" ./infra/terraform/app.tf -A 10 -B 2Repository: QuantumNous/new-api
Length of output: 45
🏁 Script executed:
grep -rn "resource.*kubernetes_service" ./infra/terraform/Repository: QuantumNous/new-api
Length of output: 129
🏁 Script executed:
sed -n '211,250p' ./infra/terraform/app.tfRepository: QuantumNous/new-api
Length of output: 800
Guard the LoadBalancer outputs until ingress is assigned.
Both outputs directly access kubernetes_service.app.status[0].load_balancer[0].ingress[0].ip without guards. Since Kubernetes LoadBalancer provisioning is asynchronous, the IP may not be allocated on the first apply, causing an "Invalid index" error. Wrap these lookups with try() to allow the initial apply to succeed and let the workflow poll separately.
Suggested hardening
output "app_load_balancer_ip" {
description = "new-api 服务的 CLB 公网 IP(部署后可通过此 IP 访问)"
- value = kubernetes_service.app.status[0].load_balancer[0].ingress[0].ip
+ value = try(kubernetes_service.app.status[0].load_balancer[0].ingress[0].ip, "")
}
@@
output "app_url" {
description = "应用访问地址"
- value = "http://${kubernetes_service.app.status[0].load_balancer[0].ingress[0].ip}"
+ value = try("http://${kubernetes_service.app.status[0].load_balancer[0].ingress[0].ip}", "")
}🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@infra/terraform/outputs.tf` around lines 16 - 19, The output output
"app_load_balancer_ip" currently indexes
kubernetes_service.app.status[0].load_balancer[0].ingress[0].ip directly which
can fail if the LoadBalancer/ingress isn't yet assigned; update the output to
use Terraform's try() around that lookup (e.g.,
try(kubernetes_service.app.status[0].load_balancer[0].ingress[0].ip, null)) so
the initial apply doesn't error and the value remains null until populated;
apply the same try() pattern to any other outputs that reference
kubernetes_service.app.status[0].load_balancer[0].ingress[0].ip.
- Replace deprecated tencentcloud_eks_cluster with tencentcloud_kubernetes_cluster + serverless node pool - Remove unsupported tencentcloud_postgresql_database resource - Fix Redis charge_type: POSTPAID_BY_HOUR -> POSTPAID - Fix Kubernetes provider config (remove unsupported kube_config_raw) - Upgrade K8s resources to v1 (namespace_v1, secret_v1, deployment_v1, service_v1) - Replace deprecated security_group_lite_rule with security_group_rule_set - Fix terraform fmt alignment issues
There was a problem hiding this comment.
Actionable comments posted: 3
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@infra/terraform/database.tf`:
- Line 11: The app is being configured to connect with the Postgres superuser by
wiring root_password (var.db_password) into the runtime SQL_DSN; create a
dedicated least-privileged application role and secret instead: add a new DB
user/password variable (e.g., var.app_db_password), provision a non-superuser
role and grant only needed schemas/tables/privileges (instead of using
root_password), store the app credential separately from the admin/root secret,
and update the SQL_DSN to use the new app role and secret (replace references to
root_password/var.db_password and the 'root' user in SQL_DSN with the new app
user).
- Around line 32-40: The tencentcloud_redis_instance resource
(tencentcloud_redis_instance.main) is created without AUTH; add an immutable
generated password and enable it by setting the instance password attribute
(e.g., create a random_password resource like redis_password and reference it in
tencentcloud_redis_instance.main.password), store that password in a Kubernetes
Secret and update the consumer (the app deployment that currently uses a
passwordless Redis URL) to read the secret instead of embedding credentials, and
ensure any Terraform outputs or templates expose only the secret name (not
plaintext) so pods mount the secret for REDIS_URL/REDIS_PASSWORD.
- Around line 24-27: Add a Terraform provisioner to automate creating the
new_api database: create a null_resource (e.g., null_resource.db_bootstrap) with
a depends_on pointing at the resource that creates the DB host (the instance
resource that provisions Postgres), and add a provisioner block (local-exec or
remote-exec) that runs a safe psql command to create the DB if missing (use psql
with a pre-check like "SELECT 1 FROM pg_database WHERE datname='new_api';" and
run "CREATE DATABASE new_api;" only when absent). Ensure the null_resource uses
triggers or connection settings to run only after the instance is ready and
include secrets via variables (DB_HOST/PORT/USER/PASSWORD) so the provisioner
will be idempotent and tied to the instance lifecycle.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: a0024ace-8310-4b2f-ba0d-ac1549c3752f
📒 Files selected for processing (6)
infra/terraform/app.tfinfra/terraform/database.tfinfra/terraform/network.tfinfra/terraform/outputs.tfinfra/terraform/provider.tfinfra/terraform/variables.tf
✅ Files skipped from review due to trivial changes (2)
- infra/terraform/network.tf
- infra/terraform/variables.tf
🚧 Files skipped from review as they are similar to previous changes (3)
- infra/terraform/provider.tf
- infra/terraform/outputs.tf
- infra/terraform/app.tf
| vpc_id = tencentcloud_vpc.main.id | ||
| subnet_id = tencentcloud_subnet.db.id | ||
| engine_version = "15.0" | ||
| root_password = var.db_password |
There was a problem hiding this comment.
Avoid provisioning app access through PostgreSQL root credentials.
Line 11 provisions the admin credential, and infra/terraform/app.tf (Line 63) uses root in SQL_DSN. This gives the runtime app superuser-level privileges. Use a dedicated least-privileged application role and separate secret instead.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@infra/terraform/database.tf` at line 11, The app is being configured to
connect with the Postgres superuser by wiring root_password (var.db_password)
into the runtime SQL_DSN; create a dedicated least-privileged application role
and secret instead: add a new DB user/password variable (e.g.,
var.app_db_password), provision a non-superuser role and grant only needed
schemas/tables/privileges (instead of using root_password), store the app
credential separately from the admin/root secret, and update the SQL_DSN to use
the new app role and secret (replace references to root_password/var.db_password
and the 'root' user in SQL_DSN with the new app user).
| # 注意:tencentcloud_postgresql_database 资源不受 Provider 支持 | ||
| # 数据库 new_api 需要在首次部署后手动创建,或通过 provisioner 执行: | ||
| # CREATE DATABASE new_api; | ||
| # new-api 应用在启动时如果数据库不存在会自动创建表结构(GORM AutoMigrate) |
There was a problem hiding this comment.
🧩 Analysis chain
🌐 Web query:
For the Terraform provider tencentcloudstack/tencentcloud, does a resource exist to create PostgreSQL databases (for example tencentcloud_postgresql_database or equivalent), and from which provider version is it supported?
💡 Result:
No, the Terraform provider tencentcloudstack/tencentcloud does not have a resource to create PostgreSQL databases (such as tencentcloud_postgresql_database or equivalent). The available PostgreSQL resources are for managing instances (tencentcloud_postgresql_instance), read-only instances (tencentcloud_postgresql_readonly_instance), accounts (tencentcloud_postgresql_account), network access, and operations like backups and read-only groups, but none for creating user databases within an instance. Databases in PostgreSQL are typically managed via direct SQL commands (CREATE DATABASE) after connecting to the instance.
Citations:
- 1: https://registry.terraform.io/providers/tencentcloudstack/tencentcloud/1.82.8/docs/resources/postgresql_instance
- 2: https://registry.terraform.io/providers/tencentcloudstack/tencentcloud/1.81.33/docs/resources/postgresql_instance
- 3: https://library.tf/providers/tencentcloudstack/tencentcloud/latest/docs/data-sources/postgresql_db_versions
- 4: https://registry.terraform.io/providers/tencentcloudstack/tencentcloud/latest/docs/resources/postgresql_instance
- 5: https://github.com/tencentcloudstack/terraform-provider-tencentcloud
- 6: https://registry.terraform.io/providers/tencentcloudstack/tencentcloud/latest/docs
- 7: https://registry.terraform.io/providers/huaweicloud/huaweicloud/latest/docs/resources/rds_pg_database
🏁 Script executed:
# Search for provisioner blocks and database initialization logic
rg -A 5 -B 2 "provisioner|CREATE DATABASE|new_api" infra/terraform/database.tfRepository: QuantumNous/new-api
Length of output: 385
🏁 Script executed:
# Check full content of database.tf to see complete context
wc -l infra/terraform/database.tfRepository: QuantumNous/new-api
Length of output: 93
🏁 Script executed:
# Look for any init/bootstrap scripts referenced
fd -e sh -e sql -e py infra/terraform/ | head -20Repository: QuantumNous/new-api
Length of output: 432
🏁 Script executed:
# Read full database.tf file
cat -n infra/terraform/database.tfRepository: QuantumNous/new-api
Length of output: 1806
🏁 Script executed:
# Search for provisioner blocks across infra directory
rg "provisioner" infra/Repository: QuantumNous/new-api
Length of output: 137
🏁 Script executed:
# Look for any bootstrap or init scripts
fd --full-path . infra/terraform/ -type f | rg -E "\.(sh|sql|py|tf)$"Repository: QuantumNous/new-api
Length of output: 630
Automate database bootstrap—provisioner option is documented but not implemented.
The TencentCloud provider does not support tencentcloud_postgresql_database resources. However, lines 24-27 mention using a provisioner to automate database creation but this is never implemented in the code. The stack currently requires manual CREATE DATABASE new_api execution, breaking idempotency and creating drift during rebuilds. Implement the provisioner or use a local-exec block to bootstrap the database during instance creation (GORM AutoMigrate handles only table structures, not the database itself).
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@infra/terraform/database.tf` around lines 24 - 27, Add a Terraform
provisioner to automate creating the new_api database: create a null_resource
(e.g., null_resource.db_bootstrap) with a depends_on pointing at the resource
that creates the DB host (the instance resource that provisions Postgres), and
add a provisioner block (local-exec or remote-exec) that runs a safe psql
command to create the DB if missing (use psql with a pre-check like "SELECT 1
FROM pg_database WHERE datname='new_api';" and run "CREATE DATABASE new_api;"
only when absent). Ensure the null_resource uses triggers or connection settings
to run only after the instance is ready and include secrets via variables
(DB_HOST/PORT/USER/PASSWORD) so the provisioner will be idempotent and tied to
the instance lifecycle.
| resource "tencentcloud_redis_instance" "main" { | ||
| name = "new-api-redis" | ||
| availability_zone = var.availability_zone | ||
| type_id = 2 # Redis 主从版 | ||
| mem_size = var.redis_mem_size | ||
| vpc_id = tencentcloud_vpc.main.id | ||
| subnet_id = tencentcloud_subnet.db.id | ||
| security_groups = [tencentcloud_security_group.db.id] | ||
| charge_type = "POSTPAID" |
There was a problem hiding this comment.
Enable Redis authentication; network isolation alone is not enough.
This resource is consumed by infra/terraform/app.tf (Line 64) using a passwordless Redis URL. Any compromised workload in the VPC could access Redis directly. Enable Redis AUTH and inject credentials via Kubernetes Secret.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@infra/terraform/database.tf` around lines 32 - 40, The
tencentcloud_redis_instance resource (tencentcloud_redis_instance.main) is
created without AUTH; add an immutable generated password and enable it by
setting the instance password attribute (e.g., create a random_password resource
like redis_password and reference it in
tencentcloud_redis_instance.main.password), store that password in a Kubernetes
Secret and update the consumer (the app deployment that currently uses a
passwordless Redis URL) to read the secret instead of embedding credentials, and
ensure any Terraform outputs or templates expose only the secret name (not
plaintext) so pods mount the secret for REDIS_URL/REDIS_PASSWORD.
Plan job doesn't need remote COS backend connection during PR checks. Use placeholder values for variables since we only validate config syntax.
…ilable - Add pull_request_target event to allow secrets access for fork PRs - Skip plan job when TENCENTCLOUD_SECRET_ID is empty - Checkout PR head SHA for pull_request_target safety
PostgreSQL root_password validation requires letters+numbers+special chars. When secrets are not injected (fork PR limitation), use compliant defaults.
51fdfc5 to
2b6f1df
Compare
📝 变更描述 / Description
添加cd代码逻辑;
🚀 变更类型 / Type of change
🔗 关联任务 / Related Issue
✅ 提交前检查项 / Checklist
Bug fix,我已提交或关联对应 Issue,且不会将设计取舍、预期不一致或理解偏差直接归类为 bug。📸 运行证明 / Proof of Work
(请在此粘贴截图、关键日志或测试报告,以证明变更生效)
Summary by CodeRabbit
Infrastructure & Deployment
Documentation