Terraform资源生命周期详解
立即解锁
发布时间: 2025-08-14 01:29:38 阅读量: 9 订阅数: 12 


Terraform实战:从入门到精通
# Terraform资源生命周期详解
## 1. 资源创建
在Terraform中,创建本地文件资源的代码如下:
```go
func resourceLocalFileCreate(d *schema.ResourceData, _ interface{}) error {
content, err := resourceLocalFileContent(d)
if err != nil {
return err
}
destination := d.Get("filename").(string)
destinationDir := path.Dir(destination)
if _, err := os.Stat(destinationDir); err != nil {
dirPerm := d.Get("directory_permission").(string)
dirMode, _ := strconv.ParseInt(dirPerm, 8, 64)
if err := os.MkdirAll(destinationDir, os.FileMode(dirMode)); err != nil {
return err
}
}
filePerm := d.Get("file_permission").(string)
fileMode, _ := strconv.ParseInt(filePerm, 8, 64)
if err := ioutil.WriteFile(destination, []byte(content), os.FileMode(fileMode)); err != nil {
return err
}
checksum := sha1.Sum([]byte(content))
d.SetId(hex.EncodeToString(checksum[:]))
return nil
}
```
此代码的主要步骤如下:
1. 获取文件内容。
2. 检查目标目录是否存在,若不存在则创建。
3. 写入文件内容并设置文件权限。
4. 计算文件内容的哈希值并设置资源ID。
## 2. 执行无操作(No-Op)
当运行`terraform plan`时,Terraform会对状态文件中的每个资源调用`Read()`方法。若配置与远程系统无差异,将执行无操作(No-Op)。示例如下:
```bash
$ terraform plan
local_file.literature: Refreshing state... [id=907b35148fa2bce6c92cba32410c25b06d24e9af]
No changes. Infrastructure is up-to-date.
```
下面是Terraform生成执行计划时的流程图:
```mermaid
graph LR
classDef startend fill:#F5EBFF,stroke:#BE8FED,stroke-width:2px
classDef process fill:#E5F6FF,stroke:#73A6FF,stroke-width:2px
classDef decision fill:#FFF6CC,stroke:#FFBC52,stroke-width:2px
A([开始]):::startend --> B(读取配置):::process
B --> C{资源在状态中?}:::decision
C -->|是| D(读取状态):::process
C -->|否| E(创建资源):::process
D --> F{有更改?}:::decision
F -->|是| G(输出计划):::process
F -->|否| H(无操作):::process
G --> I{是否为销毁计划?}:::decision
I -->|是| J(删除资源):::process
I -->|否| K(更新资源):::process
J --> L([结束]):::startend
K --> L
H --> L
```
## 3. 资源读取
以下是执行`Read()`操作的代码:
```go
func resourceLocalFileRead(d *schema.ResourceData, _ interface{}) error {
// If the output file doesn't exist, mark the resource for creation.
outputPath := d.Get("filename").(string)
if _, err := os.Stat(outputPath); os.IsNotExist(err) {
d.SetId("")
return nil
}
// Verify that the content of the destination file matches the content we
// expect. Otherwise, the file might have been modified externally and we
// must reconcile.
outputContent, err := ioutil.ReadFile(outputPath)
if err != nil {
return err
}
outputChecksum := sha1.Sum([]byte(outputContent))
if hex.EncodeToString(outputChecksum[:]) != d.Id() {
d.SetId("")
return nil
}
return nil
}
```
该代码的主要逻辑为:
1. 检查输出文件是否存在,若不存在则标记资源待创建。
2. 验证文件内容是否与预期一致,若不一致则标记资源待处理。
## 4. 更新本地文件资源
### 4.1 更新配置
更新`main.tf`代码如下:
```hcl
terraform {
required_version = ">= 0.15"
required_providers {
local = {
source = "hashicorp/local"
version = "~> 2.0"
}
}
}
resource "local_file" "literature" {
filename = "art_of_war.txt"
content = <<-EOT
Sun Tzu said: The art of war is of vital importance to the State.
It is a matter of life and death, a road either to safety or to
ruin. Hence it is a subject of inquiry which can on no account be
neglected.
The art of war, then, is governed by five constant factors, to be
taken into account in one's deliberations, when seeking to
determine the conditions obtaining in the field.
These are: (1) The Moral Law; (2) Heaven; (3) Earth; (4) The
Commander; (5) Method and discipline.
EOT
}
```
### 4.2 查看执行计划
运行`terraform plan`查看执行计划:
```bash
$ terraform plan
local_file.literature: Refreshing state... [id=907b35148fa2bce6c92cba32410c25b06d24e9af]
Terraform used the selected providers to generate the following execution
plan.
Resource actions are indicated with the following symbols:
-/+ destroy and then create replacement
Terraform will perform the following actions:
# local_file.literature must be replaced
-/+ resource "local_file" "literature" {
~ content = <<-EOT # forces replacement
Sun Tzu said: The art of war is of vital importance to the State.
It is a matter of life and death, a ro
```
0
0
复制全文
相关推荐










