Terraform plan 和Terraform destroy 相关的状态文件是如何实现的?

How Terraform plan and Terraform destroy related to the state file?

terraform plandestroy 与状态文件有什么关系。

当 Terraform 执行 plan

一些基本解释:

A terraform plan 基本上根据地形 azurerm provider 验证您的代码以检查您的代码是否正确,是否满足 Azure API 的要求(例如使用正确的属性,类型等)。如果一切正常,它会执行干式 运行 并向您展示执行 terraform apply 时会发生什么。在这一点上,terraform 不知道 Azure 中存在什么或不存在什么,它只是干巴巴地 运行 给你一个想法。也就是说,即使你的terraform plan成功了,你的terraform apply也不一定会成功。

请记住,azurerm provider 更像是 Azure API 之上的包装器。它根据 Azure API.

的要求进行自己的验证

现在回答您的问题:

How does it know that the desired state in our manifest file is same as the current state of the resource in the azure portal? Is it by checking with the azurerm api directly or by referring to the state file?

对于 Terraform 创建的任何资源,Terraform 将always根据状态文件进行验证。它唯一一次检查 Azure API 是在它必须与资源交互时。

If it's referring the state file, how does the terraform plan get validated for the first time plan, while it doesn't yet have a state file (as it's only a terraform apply that will generate a state file?

参考基本解释。它可以追溯到 terraform plan 的工作方式。因为它是一个执行计划,所以它还不需要状态文件。状态文件仅保存在 Azure 中创建的内容或从 Azure 导入的内容的信息。它是有关实际现有资源的信息。 terraform plan 仅进行 dry-run/test/simple 验证,让您知道您的代码是否足以继续下一步:terraform apply.

Secondly, does the terraform destroy command has any reference to the our manifest file (desired configuration file), or will it just validate the state file with the current state (the resource actual status in the azure portal)

当 Terraform 对象保存在状态文件中时,它们会使用 Azure 资源 ID 耦合到 Azure 对象。类似于 planapplyterraform destroy 仍将使用状态文件作为其对现实世界(Azure 中的当前状态)的理解。如果从 Terraform 代码中删除 Terraform 对象,destroy 将对照状态文件进行交叉检查,并注意到该资源存在于状态文件中。由于它存在于状态文件中但正在从您的代码中删除,Terraform 随后将发送一个请求以销毁该资源。

看看下面您可以尝试的一些场景,这可能有助于您更好地理解。

场景 1

  1. 假设您从 Azure 门户.
  2. 创建了一个名为 ststorageaccount 的存储帐户
  3. 然后您继续编写 Terraform 代码以创建相同的存储帐户并执行 terraform plan。您会注意到执行计划不知道此存储帐户已经存在,并且执行计划显示尝试再次创建它。
  4. 由于计划是 'successful',因此您继续执行 terraform apply。您现在收到一条错误消息,指出存储帐户 ststorageaccount 已经存在并且需要导入到状态文件中。 terraform apply 阶段是 Terraform 的 azurerm provider 开始与 Azure API 交互以创建资源的阶段。 Azure API 知道 Azure 中的状态,会将该错误抛给 Terraform,然后再抛给你。
  5. 由于 Terraform 无法成功创建存储帐户,因此不会将其添加到状态文件中,而是要求您手动导入。

场景 2

  1. 您编写 Terraform 代码以在 South East Asia 区域创建特定资源。
  2. 您执行 terraform plan 并再次执行,因为 Terraform 仅根据 Terraform 的 azurerm provider 验证您的代码,这表明您执行计划成功。
  3. 您继续 terraform apply,但现在收到一条错误消息,指出区域错误,必须改为 SouthEastAsia(没有空格)。
  4. 发生这种情况是因为 Terraform azurerm provider 接受 South East Asia 而该特定资源的 Azure API 需要以不同方式编写区域。

所以您可以看到这两个案例显示了 terraform planterraform apply 的行为方式不同,因为它们在两个不同的 'planes'.

上工作