Terraform 文件能够通过语法检查,并不意味着部署后的资源配置符合安全要求。Trivy 的配置扫描会解析基础设施代码,把可求出的资源属性与规则比较,在部署前找出可疑配置。使用它的关键不只是执行一次命令,还要知道扫描用了哪些变量、遗漏了哪些未知值,以及报告到底检查了误配置、秘密还是依赖漏洞。
来源与版本:根据 Aqua Security / Trivy 项目维护的 Terraform scanning 教程、config 命令参考、filesystem 命令参考与Terraform 覆盖范围合并译解。原指定链接的 /v0.75/ 路径本次无法读取,已改读同一官方站点 /docs/v0.75/ 四页完整正文,均在 2026-10-05 返回 HTTP 200。页面没有可确认的个人作者署名。本文未实际安装 Trivy、扫描仓库或生成 Terraform Plan。

config 检查的是什么
官方教程把 Terraform 扫描放在 trivy config 下。这个入口也能检查 CloudFormation、Dockerfile、Kubernetes 清单和 Helm Chart 等配置。扫描目录可以混合多种文件,Trivy 根据文件类型选择相应分析器和规则。
规则检查大致有三种情况:显式配置满足要求,检查通过;显式配置违反要求,检查失败;某项配置没有写出来,Trivy 可能依据资源默认行为判断,因此仍可能报出问题。“没有配置”不等于“没有风险”,例如资源的默认值本身可能不符合你希望的限制。
trivy config ./
Terraform 分析器会递归搜索扫描目录中的文件,尝试求值变量、导入和引用。扫描根目录需要谨慎选择:目录太小,共享文件可能无法解析;目录太大,又可能把无关环境或不该进入报告的敏感配置一起纳入。
原教程提到 tfsec 的扫描工作逐步集中到 Trivy,并提供一个演示仓库。下面保留这个准备路径,但改用 HTTPS 地址,并补全进入克隆目录的步骤;这是相对原命令的编辑修正。仓库名和目录来自原教程,本文没有运行其中的配置,也未审计整个演示仓库。
git clone https://github.com/Cloud-Native-Security/trivy-demo.git
cd trivy-demo/bad_iac/terraform
trivy config ./
这里是故意包含问题的练习配置。使用扫描器阅读它,不应顺手对这些配置执行部署。安装 Trivy 时应从官方安装说明选择适合的平台,并记录 trivy --version 和实际使用的规则版本;本文的命令依据 0.75 文档,不能自动保证适用于所有历史或未来版本。
先确定变量,再看检查结果
同一份 HCL 在开发环境与生产环境中可能使用不同变量。只扫描默认值,可能评估了并不存在的部署配置。--tf-vars 可以让 Trivy 使用指定变量文件覆盖 HCL 默认值:
trivy config --tf-vars terraform.tfvars ./
trivy config --tf-vars dev.terraform.tfvars ./infrastructure/tf
文件名不是环境的可靠标识。审查时应记录配置提交、变量文件来源,以及所扫描的环境。不要把含密码、令牌或私钥的真实变量文件放进公开示例;报告也可能暴露资源名称、路径和配置值,应该按项目的访问范围保存。
变量文件只能解决已提供的输入,不能让静态分析器获得所有云端状态。涉及数据源、计算属性或外部文件的限制,仍要单独核对。
把报告用于阅读、归档和自动化
默认表格适合在终端阅读。JSON 适合程序处理,SARIF 可交给支持该格式的代码审查与安全结果界面。--format 与短选项 -f 等价;--output 与 -o 指定保存位置:
trivy config --format json --output report.json ./
trivy config --format sarif --output report.sarif ./
这些命令生成的是相应格式的报告,不会自动上传报告,也不会自动禁止部署。输出文件名已存在时可能被覆盖,应使用本次作业自己的目录。本文没有运行这些命令,也未生成扫描结果。
可以按严重性筛选显示结果:
trivy config --severity CRITICAL,MEDIUM ./
trivy config --tf-vars terraform.tfvars --severity CRITICAL,MEDIUM --format json --output report.json ./
这里修正了原教程的参数空格:原页写成 CRITICAL, MEDIUM,未经引号保护的空格会被命令行拆成额外参数;本文写为 CRITICAL,MEDIUM。这个列表严格表示“严重”和“中等”两级,不包含 HIGH,也不表示“中等及以上”。若目标是拦截高危与严重问题,应明确写出 HIGH,CRITICAL。可选等级还包括 UNKNOWN、LOW;CLI 默认显示全部列出的等级。
误配置、秘密和漏洞是不同扫描范围
trivy config 不默认进行秘密和漏洞检测。Terraform 里即使写入了令牌,单看配置检查也不能据此断言“没有泄露”。按原教程,可以显式启用文件系统扫描器中的秘密与误配置检查:
trivy fs --scanners secret,misconfig ./
这条命令并没有选择 vuln,因此不能把其结果描述为完成了依赖漏洞扫描。0.75 的 filesystem CLI 默认扫描器是 vuln,secret;显式传入 --scanners 后,应按所选列表解释范围。Terraform 秘密检测针对文件中的原始文本,不会像 Terraform 求值那样特殊处理变量和引用。
原文把 config 描述为 fs 的配置扫描入口。实际操作时,读者更需要区分两个命令的扫描器范围,而不是假设它们输出的安全结论完全相同。命令参数允许做什么,与本次是否真正启用了该能力,是两回事。
自定义检查要当作规则代码维护
内置规则覆盖通用实践,组织也可能需要自己的约束。原教程把自定义检查引向 Rego 文档;0.75 CLI 参考提供了 --config-check、--config-data 和 --check-namespaces 等入口,用于选择规则文件、辅助数据和命名空间。
添加规则时应记录规则来源和版本,并为自己的允许、拒绝场景准备样例。本文没有编造一条未经语义核验的 Rego 规则,也没有宣称内置规则能完整表达任何组织的安全策略。使用忽略文件、内联 # trivy:ignore 或 --ignore-policy 时,应写明原因、责任人和复核期限;忽略某项发现只是改变报告处理方式,不会修复资源。
远程模块让“静态扫描”也可能访问网络
Terraform 覆盖范围文档明确说明:误配置扫描遇到远程模块,会下载模块;下载默认开启,而且不能通过 CLI 关闭。配置作者可以选择模块源地址,所以扫描不可信配置可能使扫描环境访问作者指定的主机,包括环境能够到达的内部服务。
应在受控环境中扫描,只放行可信模块仓库与注册服务,阻断云实例元数据端点和敏感内网。不要把云端凭据、个人目录或生产网络访问权限直接带入扫描环境。这里的防护针对文档确认的实际网络行为,不是把所有本地文本扫描都假定为完全离线。
可以先在自己控制的环境中执行 terraform init,把下载好的 .terraform/modules 随配置一起提供。Trivy 会重用可加载的模块缓存,但缺少模块或加载失败时仍可能继续下载。因此缓存不是完整的网络隔离措施。
trivy config --tf-exclude-downloaded-modules ./configs
上面的选项只会把下载模块中的发现标为忽略:模块仍然被下载和求值。它既不是“禁止联网”,也不是“信任第三方模块”的证明。--offline-scan、跳过规则更新等其他选项也不能被擅自解释为这个远程模块下载行为的关闭开关。
扫描 Plan,能补充信息但不能消除所有盲区
Trivy 支持 Terraform HCL、JSON 配置、Plan 快照及其 JSON 表示。若已经有受控流程生成的 Plan,可以直接检查快照,或将其导出成 JSON 再扫描:
trivy config tfplan
terraform show -json tfplan > tfplan.json
trivy config tfplan.json
原文的生成步骤是 terraform plan --out tfplan,前提是 terraform init 和 plan 本身能够成功。本文没有执行这些步骤。plan 不等于纯文本解析:它可能初始化或调用 provider、访问远程后端和数据源;特定配置还可能涉及外部程序。对不可信配置,应先审核所引用组件和外部数据逻辑,并在隔离环境中准备所需输入。这里没有提供 terraform apply 或销毁资源命令。
Plan 和 terraform show -json 的结果可能包含敏感值。不要因为原 HCL 将变量标为 sensitive,就把导出的 JSON 当作可以公开的脱敏文件。
静态分析还有以下具体限制:
- 文件读取边界:Trivy 把扫描根目录作为信任边界,
file()、filebase64()等不能读取边界以外的路径。只扫描envs/production/时,引用../shared/可能求值失败。可从仓库根目录扫描,再用--skip-dirs排除不相关环境;但也应重新确认扩大后的扫描范围。 - 数据源与 computed 属性:Trivy 不执行 provider 查询,无法还原依赖外部云状态的 data 块,也无法提前得到创建后才知道的 ID、IP 或 DNS 等值。表达式可能保持 unknown,或者通过
try等逻辑落到默认值,导致误报或漏报。 - Plan JSON 的引用:Terraform 的 Plan 在某些
for_each、count表达式中没有保留足够的资源引用信息。例如使用相同集合迭代创建 S3 bucket 和 ACL,再通过aws_s3_bucket.this[each.key].id关联时,分析器可能无法建立规则所需的关系。扫描 Plan 并不保证比扫描 HCL 在所有检查上都更完整。
把检查放进 CI/CD 时,明确失败条件
原教程列出 GitHub Actions、CircleCI、GitLab、Travis 等集成方向。无论平台是什么,至少要保留扫描输入版本、工具与规则版本、完整报告以及例外理由。严重性筛选适合门禁,但最好同时保存未筛选报告,避免低等级或未知等级问题在长期积累后无人注意。
下面是基于 0.75 CLI 的编辑新增门禁示例:只对高危和严重发现返回非零结果。它不是原教程提供的完整流水线,也未经运行测试。
trivy config --tf-vars terraform.tfvars --severity HIGH,CRITICAL --exit-code 1 --format json --output report.json ./
脚本还要区分“规则发现问题”与“扫描器运行失败”。扫描进程退出为零、报告为空或某条规则通过,都不能推导出实际云资源安全。部署权限检查、运行时配置审计以及人员复核仍然有自己的位置。
静态审查结论与归属
本次核对了四页全文及所用 CLI 参数,修正了严重性列表空格和演示仓库工作目录,明确区分了扫描器范围、下载模块与忽略模块发现,说明了 Plan 的敏感值和网络/程序执行前提。没有执行任何克隆、扫描、初始化、Plan 或部署命令;没有生成“扫描通过”的结论。示例命令没有硬编码秘密,未发现命令拼接注入,但实际项目输入、扫描器配置及第三方组件仍需独立审核。
归属与许可:原教程与参考文档由 Aqua Security / Trivy 项目维护。项目仓库 Apache License 2.0 许可正文见本文下方,此项代码许可不被当作任意第三方图像的授权。图示为未完纪原创,正文为中文翻译、合并与明确标注的编辑补充。
Apache License 2.0
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.












暂无评论内容