terraform 入门(三):改变、销毁 基础设施

730 阅读2分钟

本篇笔记参考官方教程

作者学习环境:VMware虚拟机,centos7。

本笔记继上一篇笔记学习。目的是将AMI 更改为 Ubuntu,并销毁创建的基础设施

1.寻找新的AMI ID

在此链接中找到region=us-east-1的新的AMI ID,筛选public images,复制任一AMI ID,将main.tf文件中的ami =数据修改。AWS 提供商知道它在创建实例后无法更改其 AMI,因此 Terraform 将销毁旧实例并创建一个新实例。(需要筛选条件设置为Platform = Ubuntu,Source = amazon。我这样设置的原因是“AMI 更改为 Ubuntu”、source本来是没有设置条件的,apply后报错,看了一下之前AMI ID的source是amazon/ ,所以我也这样设置了。真正原因待查)

2.应用更改

更改配置后,执行terraform apply后,需要关注的:

$ terraform apply
aws_instance.app_server: Refreshing state... [id=i-01e03375ba238b384]

An execution plan has been generated and is shown below.
Resource actions are indicated with the following symbols:
-/+ destroy and then create replacement

Terraform will perform the following actions:

  # aws_instance.app_server must be replaced
-/+ resource "aws_instance" "app_server" {
      ~ ami                          = "ami-830c94e3" -> "ami-08d70e59c07c61a3a" # forces replacement
      ~ arn                          = "arn:aws:ec2:us-west-2:561656980159:instance/i-01e03375ba238b384" -> (known after apply)
##...

前缀 -/+ 表示 Terraform 将销毁并重新创建资源,而不是在此基础更新它。 Terraform 可以就地更新某些属性(以 ~ 前缀表示),但更改 EC2 实例的 AMI 需要重新创建它。 Terraform 会为您处理这些细节,执行计划会显示 Terraform 将执行的操作。

此外,执行计划显示 AMI 更改是迫使 Terraform 替换实例的原因。使用此信息,您可以调整您的更改以避免必要时进行破坏性更新。

terraform show 打印出与此实例关联的新值。

3.销毁

一旦不再需要基础设施,可以将其销毁以减少安全风险和成本。 例如,可以从服务中删除生产环境,或管理短期环境,如构建或测试系统。 除了构建和修改基础设施之外,Terraform 还可以破坏或重新创建它管理的基础设施。

使用terraform destroy 会终止 Terraform 项目管理的资源,这个命令是相反的terraform apply,因为它终止了在你的 Terraform 状态中指定的所有资源。它不会破坏在其他地方运行且不受当前 Terraform 项目管理的资源。

$ terraform destroy
An execution plan has been generated and is shown below.
Resource actions are indicated with the following symbols:
  - destroy

Terraform will perform the following actions:

  # aws_instance.app_server will be destroyed
  - resource "aws_instance" "app_server" {
      - ami                          = "ami-08d70e59c07c61a3a" -> null
      - arn                          = "arn:aws:ec2:us-west-2:561656980159:instance/i-0fd4a35969bd21710" -> null
##...

Plan: 0 to add, 0 to change, 1 to destroy.

Do you really want to destroy all resources?
  Terraform will destroy all your managed infrastructure, as shown above.
  There is no undo. Only 'yes' will be accepted to confirm.

  Enter a value:

-前缀表示实例将被销毁。与 apply 一样,Terraform 会显示其执行计划并等待批准,然后再进行任何更改。确定销毁资源的顺序。在这种情况下,Terraform 识别出没有其他依赖项的单个实例,因此它销毁了该实例。在具有多个资源的更复杂的情况下,Terraform 将按照适当的顺序销毁它们以尊重依赖关系。