是否可以使用 CloudFormation 重新创建 AWS 资源?

Is it possible to re-create AWS resources using CloudFormation?

假设 AWS 堆栈是使用 CloudFormation 创建的。 现在,其中一个资源已在 CloudFormation 之外修改。

1) 是否可以让 CloudFormation 专门创建这些资源?根据我的理解,我们不能这样做,因为 CloudFormation 不会识别差异,因此不会创建修改后的资源。我的观察是否正确?

2) 此外,如果在 CloudFormation 之外进行修改,我必须使用哪些选项才能将堆栈恢复到其原始状态?

很遗憾,您的两个问题的答案都是

  1. 如果在堆栈创建状态为 COMPLETE 后修改堆栈中的资源,CF 将无能为力,因为它不会跟踪对资源的修改
  2. 您别无选择,只能删除当前堆栈并创建一个新堆栈

首先,请注意,根据 AWS CloudFormation Best Practices

明确不鼓励 在 CloudFormation 之外修改 CloudFormation-created 资源

Manage All Stack Resources Through AWS CloudFormation

After you launch a stack, use the AWS CloudFormation console, API, or AWS CLI to update resources in your stack. Do not make changes to stack resources outside of AWS CloudFormation. Doing so can create a mismatch between your stack's template and the current state of your stack resources, which can cause errors if you update or delete the stack.

但是,如果您不小心修改了 CloudFormation-managed 资源并需要恢复,除了简单地删除和 re-creating 堆栈之外,您可能有一些有限的选择(这可能是不可接受的选项):

  1. CloudFormation 无法自动根据externally-modified资源的当前状态更新其内部状态。

    但是,根据具体的资源类型,在某些情况下,您可以在之后通过应用与资源当前状态匹配的堆栈更新来手动更新 CloudFormation。

  2. 同样,CloudFormation 不可能自动 将 externally-modified 资源恢复到其原始未修改的 CloudFormation 状态。

    但是,根据具体的资源类型,在某些情况下您可以:

    • 通过手动恢复资源将资源更新回其原始状态;
    • 通过应用堆栈更新来更新资源,将 CloudFormation 堆栈和托管资源都带到一个全新的状态,再次同步。

这是一种可能的破解方法,您可以在不删除整个堆栈的情况下使用。

  1. 从模板中删除意外删除的特定资源。
  2. 现在更新堆栈,使您帐户中的堆栈和资源同步。
  3. 将模板恢复到第 1 步之前的状态并再次更新,这将创建被意外删除的资源。