转自:https://www.terraform.io/docs/extend/best-practices/detecting-drift.html 这篇文章主要说明了对于资源如何处理
read&&create,可以让我们了解如何进行状态管理 

One of the core challenges of infrastructure as code is keeping an up-to-date record of all deployed infrastructure and their properties. Terraform manages this by maintaining state information in a single file, called the state file.

Terraform uses declarative configuration files to define the infrastructure resources to provision. This configuration serves as the target source of truth for what exists on the backend API. Changes to Infrastructure outside of Terraform will be detected as deviation by Terraform and shown as a diff in future runs of terraform plan. This type of change is referred to as "drift", and its detection is an important responsibility of Terraform in order to inform users of changes in their infrastructure. Here are a few techniques for developers to ensure drift is detected.

»Capture all state in READ

A provider's READ method is where state is synchronized from the remote API to Terraform state. It's essential that all attributes defined in the schema are recorded and kept up-to-date in state. Consider this provider code:

// resource_example_simple.gopackageexamplefuncresourceExampleSimple()*schema.Resource{return&schema.Resource{Read:resourceExampleSimpleRead,Create:resourceExampleSimpleCreate,Schema:map[string]*schema.Schema{"name":{Type:schema.TypeString,Required:true,ForceNew:true,},"type":{Type:schema.TypeString,Optional:true,},},}}funcresourceExampleSimpleRead(d*schema.ResourceData,metainterface{})error{client:=meta.(*ProviderApi).clientresource,_:=client.GetResource(d.Id())d.Set("name",resource.Name)d.Set("type",resource.Type)returnnil}

As defined in the schema, the type attribute is optional, now consider this config:

# config.tf
resource "simple" "ex" {
name = "example"
}

Even though type is omitted from the config, it is vital that we record it into state in the READ function, as the backend API could set it to a default value. To illustrate the importance of capturing all state consider a configuration that interpolates the optional value into another resource:

resource "simple" "ex" {
name = "example"
} resource "another" "ex" {
name = "${simple.ex.type}"
}

»Update state after modification

A provider's CREATE and UPDATE functions will create or modify resources on the remote API. APIs might perform things like provide default values for unspecified attributes (as described in the above example config/provider code), or normalize inputs (lower or upper casing all characters in a string). The end result is a backend API containing modified versions of values that Terraform has in its state locally. Immediately after creation or updating of a resource, Terraform will have a stale state, which will result in a detected deviation on subsequent plan or applys, as Terraform refreshes its state and wants to reconcile the diff. Because of this, it is standard practice to call READ at the end of all modifications to synchronize immediately and avoid that diff.

funcresourceExampleSimpleRead(d*schema.ResourceData,metainterface{})error{client:=meta.(*ProviderApi).clientresource,_:=client.GetResource(d.Id())d.Set("name",resource.Name)d.Set("type",resource.Type)returnnil}funcresourceExampleSimpleCreate(d*schema.ResourceData,metainterface{})error{client:=meta.(*ProviderApi).clientname:=d.Get("name").(string)client.CreateResource(name)d.SetId(name)returnresourceExampleSimpleRead(d,meta)}

»Error checking aggregate types

Terraform schema is defined using primitive types and aggregate types. The preceding examples featured primitive types which don't require error checking. Aggregate types on the other hand, schema.TypeListschema.TypeSet, and schema.TypeMap, are converted to key/value pairs when set into state. As a result the Set method must be error checked, otherwise Terraform will think it's operation was successful despite having broken state. The same can be said for error checking API responses.

# config.tf
resource "simple" "ex" {
name = "example"
type = "simple"
tags = {
name = "example"
}
}
// resource_example_simple.gopackageexamplefuncresourceExampleSimple()*schema.Resource{return&schema.Resource{Read:resourceExampleSimpleRead,Create:resourceExampleSimpleCreate,Schema:map[string]*schema.Schema{"name":{Type:schema.TypeString,Required:true,ForceNew:true,},"type":{Type:schema.TypeString,Optional:true,},"tags":{Type:schema.TypeMap,Optional:true,},},}}funcresourceExampleSimpleRead(d*schema.ResourceData,metainterface{})error{client:=meta.(*ProviderApi).clientresource,err:=client.GetResource(d.Id())iferr!=nil{returnfmt.Errorf("error getting resource %s: %s",d.Id(),err)}d.Set("name",resource.Name)d.Set("type",resource.Type)iferr:=d.Set("tags",resource.TagMap);err!=nil{returnfmt.Errorf("error setting tags for resource %s: %s",d.Id(),err)}returnnil}

»Use Schema Helper methods

As mentioned, remote APIs can often perform mutations to the attributes of a resource outside of Terraform's control. Common examples include data containing uppercase letters and being normalized to lowercase, or complex defaults being set for unset attributes. These situations expectedly result in drift, but can be reconciled by using Terraform's schema functions, such as DiffSuppressFunc or DefaultFunc

 
 
 
 

Terraform Detecting Drift的更多相关文章

  1. terraform plugin 版本以及changlog 规范

    文章来自官方文章,转自:https://www.terraform.io/docs/extend/best-practices/versioning.html 里面包含了版本命名的规范,以及chang ...

  2. 论文阅读(Xiang Bai——【CVPR2012】Detecting Texts of Arbitrary Orientations in Natural Images)

    Xiang Bai--[CVPR2012]Detecting Texts of Arbitrary Orientations in Natural Images 目录 作者和相关链接 方法概括 方法细 ...

  3. **stack smashing detecting**

    stack smashing aborted 堆 猛烈撞击 流失 我在使用数据时写了 tmp_row = row + pos[num1][[0]; tmp_col = col + pos[num1][ ...

  4. 论文阅读之 DECOLOR: Moving Object Detection by Detecting Contiguous Outliers in the Low-Rank Representation

    DECOLOR: Moving Object Detection by Detecting Contiguous Outliers in the Low-Rank Representation Xia ...

  5. Detecting diabetic retinopathy in eye images

    Detecting diabetic retinopathy in eye images The past almost four months I have been competing in a  ...

  6. 1.6.7 Detecting Languages During Indexing

    1. Detecting Languages During Indexing 在索引的时候,solr可以使用langid UpdateRequestProcessor来识别语言,然后映射文本到特定语言 ...

  7. 如何使用 Docker、ECS、Terraform 重建基础架构?

    早期 Segment 基础架构普遍组合在一起.我们通过 AWS 界面设定实例,使用许多闲散的 AMI,并且采用三种不同的部署方式. 然而随着商业的飞速发展,工程师团队的规模不断扩大,基础架构的复杂度也 ...

  8. 关于terraform的状态管理

    我们想在aws创建3台主机,使用ansible和terraform都是可以实现的. 用ansible可能是这样子的: - ec2: count: 10 image: ami-40d281120 ins ...

  9. ansible+packer+terraform在aws上布署web服务器

    各工具所扮演的角色 ansible: 配合packer生成安装有apache的基础镜像 packer: 生成amazon AMI terraform: 以packer生成的镜像为基础,布署web服务器 ...

随机推荐

  1. Jenkins详细安装与构建部署使用教程

    版权声明:本文为博主林炳文Evankaka原创文章,转载请注明出处http://blog.csdn.net/evankaka   目录(?)[+]   Jenkins是一个开源软件项目,旨在提供一个开 ...

  2. 【转载三】Grafana系列教程–Grafana的配置及运行

    本篇文章,就让我们来了解下,Grafana的简单配置及运行. 详细的配置我们后面会讲,本篇文章只对其配置做一个简单了解,主要是让大家了解Grafana的配置及启动的过程及方法. 更多Grafana问题 ...

  3. CentOS7安装配置Amanda

    参考: https://wenku.baidu.com/view/881e0c998e9951e79a892759.html yum  -y  install  amanda* http://blog ...

  4. 用servlet实现用户登录案例

    以下实现登录窗口 Login.jsp <!--Login.jsp--> <%@ page language="java" import="java.ut ...

  5. CSS颜色

    CSS 颜色 可以用以下方法来规定 CSS 中的颜色: ·        十六进制色 十六进制值使用三个双位数来编写,并以 # 符号开头. ·        RGB 颜色 o   所有浏览器都支持 R ...

  6. Core Java 面经

    1  面向对象的特征有哪些方面? (1)抽象,抽象就是忽略与当前目标无关的部分,抽象包含两个方面,一是过程抽象,一是数据 (2)继承,是Java中允许和鼓励类重用的思想的体现,, 它提供了一种方式,可 ...

  7. JavaWeb:c3p0配置问题java.lang.NoClassDefFoundError: com/mchange/v2/ser/Indirector

    错误显示 java.lang.NoClassDefFoundError: com/mchange/v2/ser/Indirector at dbdemo.JdbcUtils.<clinit> ...

  8. localStorage的使用记录

    // 存数据 var str = JSON.stringify(back); localStorage.setItem("options", str); // 取数据 var op ...

  9. springsecurity的remember me

    基于持久化的token的方法 实现原理:将生成的 token 存入 cookie 中并发送到客户端浏览器,待到下次用户访问系统时,系统将直接从客户端 cookie 中读取 token 进行认证. 实现 ...

  10. mysql储存引擎

    Mysql数据库常用存储引擎 数据库存储引擎:是数据库底层软件组织,数据库管理系统(DBMS)使用数据引擎进行创建.查询.更新和删除数据.不同的存储引擎提供不同的存储机制.索引技巧.锁定水平等功能,使 ...