使用 AWS 模拟器测试 Terraform
摘要
本文介绍了如何使用 AWS 新推出的 Emulator 工具——它能够忠实模拟 AWS API 端点——在将变更应用到真实环境之前,针对模拟的 AWS 基础设施测试 Terraform 计划,从而减少 CI/CD 工作流中失败的 apply 任务。
暂无内容
查看缓存全文
缓存时间: 2026/11/22 18:26
# 使用 AWS Emulator 测试 Terraform
来源:https://notes.hatedabamboo.me/terraform-tests-with-aws-emulator/
Terraform plan 通过了,显示一切正常,所有必要的资源变更都在预期之中。你执行 apply,然后……任务失败了,报出一个晦涩难懂的错误,说某个资源无法变更。你又开了一个 pull request 再试一次。结果可能又遇到了错误。是不是很熟悉?我打赌你一定遇到过。这种问题我遇到过太多次了,多到数不过来。但最近 AWS 发布(https://aws.amazon.com/about-aws/whats-new/2026/11/aws-emulator-now-available/)了一个名为 Emulator 的新工具,它可以模拟真实的 AWS API 端点。它应该非常适合处理这类问题!
标题图片
## 明确问题\#(https://notes.hatedabamboo.me/terraform-tests-with-aws-emulator/#defining-the-problem)
plan 和 apply 任务之间存在差异的问题在于:plan 根本无法针对真实基础设施模拟每一个实际的 API 调用。基于我们写入其中的静态声明——应用顺序、必要的参数、正确的配置值——它可以做出合理的推断。但这些模拟调用无法确切知道你在 AWS 中已经有一个名为 "my\-bucket\-asdasdasd" 的资源,或者你正试图在没有显式 "apply immediately" 标志的情况下将 PostgreSQL RDS 实例从版本 14 升级到版本 18。有人可能会说总可以在本地尝试 apply 变更,但这其实削弱了整个自动化流程的意义。那么答案是什么?
有多种工具可以模拟 AWS 服务,无论是部分模拟(https://github.com/guenter/aws-oss-alternatives)还是完全模拟(https://ministack.org/),但它们缺少的是对服务架构的真实了解。结构可能相似,但不够原汁原味,有时这种细微的差异会造成很大的问题。毕竟,如果有什么东西能比 AWS API 本身更接近 AWS API,那只能是一个短命的、临时的 AWS API 本身。
## AWS Emulator\#(https://notes.hatedabamboo.me/terraform-tests-with-aws-emulator/#aws-emulator)
AWS Emulator 的优势在于它是一个自包含的二进制文件(或 Docker 容器),可以在本地或 CI 工作流中使用。这意味着通常的 "Plan \> Apply" Terraform 工作流变成了 "Plan \> Apply 到模拟的 AWS 基础设施上以测试 plan \> Apply 到真正的 AWS 基础设施上"。这意味着任务时间会稍长一些,但如果你像我一样,apply 任务是在 PR 合并后对 `main` 分支的提交触发的,这就省去了你为了修复问题而专门创建一个新分支的麻烦。
### 在本地 AWS Emulator 上运行 Terraform\#(https://notes.hatedabamboo.me/terraform-tests-with-aws-emulator/#running-terraform-against-local-aws-emulator)
我们先从本地环境开始,看看如何将 AWS Emulator 与实际的 Terraform 代码结合使用。所有代码都在我的示例 GitHub 仓库中(https://github.com/hatedabamboo/terraform-tests-with-aws-emulator)。
首先是安装。你可以通过包管理器(https://docs.aws.amazon.com/emulator/latest/userguide/getting-started-linux.html)安装 aws\-emulator,也可以用 Docker 构建(https://docs.aws.amazon.com/emulator/latest/userguide/getting-started-docker.html)。我会使用 Docker,以免在系统中再安装一个包:
``
bash$ docker build -t aws-emulator .
$ docker images
IMAGE ID DISK USAGE CONTENT SIZE EXTRA
aws-emulator:latest 3c8fdb957b45 1.24GB 0B # 哇,这家伙真胖
$ docker run --rm -d -p 9297:9297 aws-emulator -a off
dcc416f234aaa3ec2966c9e8dcde7870f8d03057ec8a465cb8960617af82e501
$ docker logs dcc416f234aaa3ec2966c9e8dcde7870f8d03057ec8a465cb8960617af82e501
{"timestamp":"2026-11-12T14:51:16.261883Z","level":"INFO","fields":{"message":"aws-emulator emulator starting"},"target":"aws_emulator"}
This emulator collects usage and error telemetry: enabled (on by default; opt out any time); disable with EMULATOR_TELEMETRY=off or [telemetry] enabled = false in /home/emulator/.aws/emulator/config.toml
{"timestamp":"2026-11-12T14:51:16.270635Z","level":"INFO","fields":{"message":"emulator server information","endpoint_url":"https://127.0.0.1:9297","health_check_url":"https://127.0.0.1:9297/__admin/health","config_file":"/home/emulator/.aws/emulator/9297/config","ca_file":"/home/emulator/.aws/emulator/9297/ca.pem","java_truststore_file":"/home/emulator/.aws/emulator/9297/truststore.p12"},"target":"aws_emulator_server"}
{"timestamp":"2026-11-12T14:51:16.270655Z","level":"WARN","fields":{"message":"the emulator listens on 0.0.0.0, not loopback: other machines that can reach port 9297 can call it; bind 127.0.0.1 (-b 127.0.0.1) unless that is intended","bind_address":"0.0.0.0"},"target":"aws_emulator_server"}
{"timestamp":"2026-11-12T14:51:16.270659Z","level":"WARN","fields":{"message":"request authentication is off: the emulator accepts any request, signed or not; start it with -a on to require signatures","bind_address":"0.0.0.0"},"target":"aws_emulator_server"}
``
它启动并运行了!在上面的例子中,我让容器不受限制地运行(官方 AWS 文档建议设置内存和交换区限制:`--memory=2g --memory-swap=2g`,但在本地这样就够了)。我还禁用了授权(`-a off` 标志)以简化操作。
为了确认 aws\-emulator 已经启动并运行,我们来查询一下管理端点:
``
bash$ curl -sk https://127.0.0.1:9297/__admin/health
ok
``
好了,假的 AWS 上线了,让我们部署一些基础设施吧!
我为 Terraform 创建了一个示例 AWS 堆栈,并将在本文中使用它。首先,让 Terraform 配置为对接 aws\-emulator 而不是真实的 AWS API。`providers.tf` 看起来像这样:
``
hclprovider "aws" {
access_key = var.access_key
secret_key = var.secret_key
region = var.region
insecure = true # 模拟器使用自签名证书提供 HTTPS,跳过验证。
s3_use_path_style = true # 模拟器使用单个 IP 端点,将桶名放在路径中。
# 不要调用真实的 AWS 或实例元数据服务。
skip_credentials_validation = true
skip_metadata_api_check = true
skip_requesting_account_id = true
skip_region_validation = true
# 将所有服务发送到模拟器而不是 AWS。
endpoints {
ec2 = var.emulator_endpoint
lambda = var.emulator_endpoint
iam = var.emulator_endpoint
sts = var.emulator_endpoint
cloudwatch = var.emulator_endpoint
logs = var.emulator_endpoint
events = var.emulator_endpoint
sns = var.emulator_endpoint
}
default_tags {
tags = var.tags
}
}
``
真实基础设施与模拟环境的区别在于:我们设置了一堆标志来允许不安全的连接(也许关掉认证其实并没有更简单?),并且我们将配置中用到的每个服务的端点都指向了位于本地 Docker 容器中的模拟器端点:
``
hcl# variables.tf
variable "emulator_endpoint" {
description = "Base URL of the AWS Emulator"
type = string
default = "https://127.0.0.1:9297"
}
...
``
其余的配置和平时一样:资源、变量、模块(如果有的话)。就是你的项目里有什么就写什么。
让我们继续测试我们的配置。(我会省略完整的 terraform 输出,否则这篇文章会有三公里长)
``
bash$ cd terraform/
$ terraform init
Initializing the backend...
...
Terraform has been successfully initialized!
...
$ terraform plan
...
Plan: 15 to add, 0 to change, 0 to destroy.
Changes to Outputs:
+ alarm_name = "ttwae-lambda-errors"
+ event_rule_arn = (known after apply)
+ lambda_function_arn = (known after apply)
+ security_group_id = (known after apply)
+ sns_topic_arn = (known after apply)
+ subnet_id = (known after apply)
+ vpc_id = (known after apply)
``
Plan 成功了!这很好,但这并不是我们来这里的目的。不管怎样,这是个好兆头。现在进行真正的测试。
``
bash$ terraform apply --auto-approve
...
Apply complete! Resources: 15 added, 0 changed, 0 destroyed.
Outputs:
alarm_name = "ttwae-lambda-errors"
event_rule_arn = "arn:aws:events:us-east-1:000000000000:rule/ttwae-schedule"
lambda_function_arn = "arn:aws:lambda:us-east-1:000000000000:function:ttwae-worker"
security_group_id = "sg-00000000000000085"
sns_topic_arn = "arn:aws:sns:us-east-1:000000000000:ttwae-alarms"
subnet_id = "subnet-00000000000000089"
vpc_id = "vpc-00000000000000080"
``
Apply 也成功了!太棒了!
遗憾的是,运行中的 aws\-emulator 容器在日志中不会显示它收到了哪些 API 请求以及底层发生了什么,但我猜这个工具已经足够好了。
完成后,停止容器:
``
bash$ docker stop dcc416f234aaa3ec2966c9e8dcde7870f8d03057ec8a465cb8960617af82e501
``
使用 `--rm` 启动的容器在停止后会自动删除,所以不需要额外的清理工作。至于模拟器——它将状态保存在内存中,因此每次容器重启都会清除之前的所有操作记录和过期状态。
### 在 CI 流水线中运行 Terraform 对接 AWS Emulator\#(https://notes.hatedabamboo.me/terraform-tests-with-aws-emulator/#running-terraform-against-aws-emulator-in-ci-pipeline)
现在是真正的测试:我们能否将所需的逻辑封装到 CI 流水线中?让我们想想。
要在流水线中成功运行,我们需要几乎相同的一切,但会受到时间(越快越好,以及总体合理的超时时间)和资源的限制。
下面展示了在 aws\-emulator 上执行 `terraform apply` 的工作流。对于这个工作流,我决定尝试使用包管理器安装(构建器反正是临时的)以及正式的认证方式。包含实际成功运行的完整工作流可以在示例 GitHub 仓库中找到(https://github.com/hatedabamboo/terraform-tests-with-aws-emulator)。
``
yaml---
name: terraform-against-emulator
on:
push:
branches: [main]
permissions:
contents: read
jobs:
terraform:
runs-on: ubuntu-latest
env:
EMULATOR_PORT: "9297"
# 空的密钥使 provider 回退到模拟器写入的
# 共享凭据文件。insecure=false 通过 AWS_CA_BUNDLE
# 验证模拟器证书
TF_VAR_access_key: ""
TF_VAR_secret_key: ""
TF_VAR_insecure: "false"
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- name: Install the AWS Emulator
run: |
curl -fsSLo aws-emulator.deb \
https://downloads.aws.com/aws-emulator/packages/aws-emulator/LTS/latest/aws-emulator_amd64.deb
sudo apt-get install -y ./aws-emulator.deb
aws-emulator -v
- name: Start the emulator with signature checks on
run: |
nohup aws-emulator > /tmp/aws-emulator.log 2>&1 &
echo "Waiting for the emulator to answer..."
CA="$HOME/.aws/emulator/${EMULATOR_PORT}/ca.pem"
for i in $(seq 30); do
if [ -f "$CA" ] && curl -sf --cacert "$CA" \
"https://127.0.0.1:${EMULATOR_PORT}/__admin/health" >/dev/null; then
echo "Emulator is ready."
exit 0
fi
sleep 1
done
echo "Emulator did not become ready." >&2
cat /tmp/aws-emulator.log >&2
exit 1
- name: Point Terraform at the emulator credentials and certificate
run: |
DIR="$HOME/.aws/emulator/${EMULATOR_PORT}"
{
echo "AWS_SHARED_CREDENTIALS_FILE=$DIR/emulator_credentials"
echo "AWS_CONFIG_FILE=$DIR/config"
echo "AWS_CA_BUNDLE=$DIR/ca.pem"
echo "AWS_REGION=us-east-1"
echo "AWS_DEFAULT_REGION=us-east-1"
echo "AWS_EC2_METADATA_DISABLED=true"
echo "AWS_DISABLE_HOST_PREFIX_INJECTION=true"
} >> "$GITHUB_ENV"
- uses: hashicorp/setup-terraform@dfe3c3f87815947d99a8997f908cb6525fc44e9e # v4.0.1
with:
terraform_wrapper: false
- run: terraform -chdir=terraform init -input=false
- run: terraform -chdir=terraform validate
- run: terraform -chdir=terraform plan -input=false
- run: terraform -chdir=terraform apply -auto-approve -input=false
``
这是那个华丽的实际工作流文件的一个粗略摘录,概述了最重要的步骤:模拟器安装、terraform 配置、plan 和 apply。在示例 terraform 架构上,整个流水线耗时 1 分 25 秒,在我看来还不错,但还有改进空间:加一些缓存、把验证和格式检查留给本地钩子等等。
## 运行一个故意失败的 apply 任务\#(https://notes.hatedabamboo.me/terraform-tests-with-aws-emulator/#running-a-deliberately-failing-apply-job)
当别人写在网上的代码在你复制粘贴到本机后能直接运行,那当然是件好事。正因如此,我总是在发布文章之前亲自运行文中描述的流程——构建、测试、修复、重试。但只展示正面场景会让人们对这个工具产生虚假的信任感。
让我们故意搞点破坏。
在示例代码库中,我添加了一个变量,启用它时会使堆栈尝试部署一个声明有误的资源。它能通过 plan 任务,但会在 apply 时失败。
``
hclvariable "enable_failure_demo" {
description = "Create a DynamoDB table with an invalid name."
type = bool
default = false
}
``
在运行时将此变量设为 true 会破坏我们的堆栈。让我们看看:
``
bash$ cd terraform/
$ terraform init
Initializing the backend...
...
$ terraform plan -var 'enable_failure_demo=true'
...
Plan: 16 to add, 0 to change, 0 to destroy.
Changes to Outputs:
...
+ failure_demo_table_arn = (known after apply)
...
$ terraform apply -auto-approve -var 'enable_failure_demo=true'
...
╷
│ Error: creating AWS DynamoDB Table (ab): operation error DynamoDB: CreateTable, https response error StatusCode: 400, RequestID: 4TLD3XUB94783KNA4C76L8BEZ26UU8LS4IBN2IEKZJLAK4NMVTQ4, api error ValidationException: 1 validation error detected: Value 'ab' at 'tableName' failed to satisfy constraint: Member must have length greater than or equal to 3
│
│ with aws_dynamodb_table.bad_name[0],
│ on dynamodb.tf line 10, in resource "aws_dynamodb_table" "bad_name":
│ 10: resource "aws_dynamodb_table" "bad_name" {
│
``
这就是了。只有在面对实际 API 调用时才会出现的问题,在 plan 任务中根本发现不了。
对于完全这样的场景,模拟器的价值无可估量。
## 局限性与注意事项\#(https://notes.hatedabamboo.me/terraform-tests-with-aws-emulator/#limitations-and-considerations)
AWS Emulator 太棒了!我最近很少对新工具这么兴奋(主要是因为几乎所有的新工具都跟 AI 有关),但这个工具真的非常好,完美解决了我长期以来的痛点。
不过,它还远非完美。
首先,它无法有效地模拟 IAM 策略和权限检查。这很可惜,因为权限验证对于生产级别的安全性来说是如此关键的一步。希望这个工具能够继续发展,在未来的更新中加入这个功能。
其次,作为一个仍在开发中(\[1\])的工具,它的功能还相当有限。甚至在写这篇文章的过程中,我就遇到了好几次 `501 NotImplemented`。如果你的基础设施配置很庞大,包含很多特殊之处、奇怪的配置以及非常新的服务,这会让事情变得有点复杂。不过,AWS 发布新版本的频率相当高,而且他们对 Emulator 的局限性也相当坦诚(https://docs.aws.amazon.com/emulator/latest/userguide/fidelity.html),这很好。
最后但同样重要的是遥测数据。AWS 明确
相似文章
Fakecloud:用于集成测试的本地AWS云模拟器
Fakecloud是一个用于集成测试的本地AWS云模拟器,它支持在本地使用标准AWS客户端运行应用程序,并提供SDK以增强对105个服务的测试可见性。
使用 conftest 安全地自动应用 Terraform
本文介绍了如何使用 conftest(一个基于 Open Policy Agent 的策略即代码工具)安全地自动化 Terraform 自动应用,通过使用 Rego 策略确定性评估 Terraform 计划,从而消除人工审核瓶颈,同时保持可审计性。
@midudev:这个项目让你可以在本地免费使用 AWS。无需账户或技巧。非常适合练习。它叫做 Floci……
Floci 是一个免费、开源的本地 AWS 模拟器,通过 Docker 运行,提供 S3、Lambda、DynamoDB、RDS 等 69 个 AWS 服务,无需 AWS 账户或身份验证令牌,非常适合开发、测试和 CI。
Compiler Explorer 如何在 2026 年运行在 AWS 上
Matt Godbolt 解释了 Compiler Explorer 在 2026 年如何运行在 AWS 上,涵盖 CloudFront、负载均衡、自动扩展集群以及使用 Terraform 的基础设施即代码。
hashicorp/terraform
Terraform 是 HashiCorp 提供的一款基础设施即代码工具,用于安全高效地构建、变更和版本化管理基础设施。