也许可以使用一句神奇的话语,方便快速地优化你的Terraform计划
当使用 Terraform 管理的资源增多时,tfstate 文件会变得庞大。由于 Terraform 计划会变得越来越慢,而我在等待过程中会去看 Twitter,结果忘记了自己到底在做什么。这是一个常见情况。
在这种情况下,基本的解决方法是将tfstate适度地分割为较小的单位,虽然可以修改tfstate,但有些麻烦。
然而,可能还有更简单快捷的技巧可以实现加速。
那个魔法的词就是“并行”。默认情况下,它以10个并行来运行,但可以进行修改。
最佳值因调用API和网络配置等因素而异,因此需要根据情况来确定。
一般来说,如果处理的资源很多,增加并行度可能会提高速度。
首先,为了进行比较,我们将测量原始状态下的执行时间。
$ time terraform plan
terraform plan 14.48s user 4.79s system 27% cpu 1:09.17 total
大概需要花费1分钟左右。尝试将并发度提升至30,看看结果如何。
$ time terraform plan --parallelism=30
terraform plan --parallelism=30 13.82s user 4.10s system 57% cpu 30.962 total
太厉害了,只用了大约30秒就完成了。仅仅这一步就实现了2倍速度提升。太好了!
由于每次都指定很麻烦,你可以将其设置为环境变量TF_CLI_ARGS_plan。
$ export TF_CLI_ARGS_plan="--parallelism=30"
$ time terraform plan
terraform plan 13.88s user 3.98s system 56% cpu 31.868 total
应用环境变量也有效果啊。
对于apply操作,使用环境变量 TF_CLI_ARGS_apply。
在不同情况下,最佳并行程度会有所不同,但这很简单,所以试一试不会有任何损失。
我偶然在看Terraform的问题时发现,
其实这根本不是什么神奇的词语,而是在官方文档中普普通通地写着呢。
它还在命令的帮助文档里,为什么之前我怎么都没有注意到呢。
参考资料:
– https://github.com/hashicorp/terraform/issues/18974
– https://www.terraform.io/docs/commands/plan.html
– https://www.terraform.io/docs/configuration/environment-variables.html#tf_cli_args-and-tf_cli_args_name
参考来源:
– https://github.com/hashicorp/terraform/issues/18974
– https://www.terraform.io/docs/commands/plan.html
– https://www.terraform.io/docs/configuration/environment-variables.html#tf_cli_args-and-tf_cli_args_name