Terraform Detecting Drift
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 apply
s, 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.TypeList
, schema.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的更多相关文章
- terraform plugin 版本以及changlog 规范
文章来自官方文章,转自:https://www.terraform.io/docs/extend/best-practices/versioning.html 里面包含了版本命名的规范,以及chang ...
- 论文阅读(Xiang Bai——【CVPR2012】Detecting Texts of Arbitrary Orientations in Natural Images)
Xiang Bai--[CVPR2012]Detecting Texts of Arbitrary Orientations in Natural Images 目录 作者和相关链接 方法概括 方法细 ...
- **stack smashing detecting**
stack smashing aborted 堆 猛烈撞击 流失 我在使用数据时写了 tmp_row = row + pos[num1][[0]; tmp_col = col + pos[num1][ ...
- 论文阅读之 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 ...
- Detecting diabetic retinopathy in eye images
Detecting diabetic retinopathy in eye images The past almost four months I have been competing in a ...
- 1.6.7 Detecting Languages During Indexing
1. Detecting Languages During Indexing 在索引的时候,solr可以使用langid UpdateRequestProcessor来识别语言,然后映射文本到特定语言 ...
- 如何使用 Docker、ECS、Terraform 重建基础架构?
早期 Segment 基础架构普遍组合在一起.我们通过 AWS 界面设定实例,使用许多闲散的 AMI,并且采用三种不同的部署方式. 然而随着商业的飞速发展,工程师团队的规模不断扩大,基础架构的复杂度也 ...
- 关于terraform的状态管理
我们想在aws创建3台主机,使用ansible和terraform都是可以实现的. 用ansible可能是这样子的: - ec2: count: 10 image: ami-40d281120 ins ...
- ansible+packer+terraform在aws上布署web服务器
各工具所扮演的角色 ansible: 配合packer生成安装有apache的基础镜像 packer: 生成amazon AMI terraform: 以packer生成的镜像为基础,布署web服务器 ...
随机推荐
- sas 选择一段日期,和一定周期,生成日期序列和周期序列
工作需要,得选择一段日期,和一定周期,生成日期序列和周期序列.暂时用七天为一个周期 data d; format date date9.; do date='04mar2018'd to'05may2 ...
- java泛型讲解
原文: https://blog.csdn.net/briblue/article/details/76736356 泛型,一个孤独的守门者. 大家可能会有疑问,我为什么叫做泛型是一个守门者.这其实是 ...
- 6.2 C++ string类型字符串的连接
参考:http://www.weixueyuan.net/view/6391.html 总结: 对于string类型变量,我们可以直接用“+”或者“+=”进行字符串的连接,操作符非常方便. 用“+”风 ...
- 2.8 C++参数初始化表
参考:http://www.weixueyuan.net/view/6340.html 总结: 参数初始化表可以为任何数据成员进行初始化. 初始化const成员变量的唯一方法只有利用参数初始化表. 通 ...
- Spring异步调用注解@Async的使用
1.pom依赖 <dependency> <groupId>org.springframework</groupId> <artifactId>spri ...
- Linux文件系统命令 rm
命令名:rm 功能:删除某一个文件或者目录 eg: renjg@renjg-HP-Compaq-Pro--MT:~/WorkSpace$ ls BM3 gf k8s minicom_download ...
- UVALive - 6434 (贪心)
题目链接:https://vjudge.net/problem/UVALive-6434 题意:给你n个数字,要你把这n个数字分成m组,每一组的消耗值定义为改组最大值和最小值之差,要求这m组的消耗值总 ...
- <Flume><Source Code><Flume源码阅读笔记>
Overview source采集的日志首先会传入ChannelProcessor, 在其内首先会通过Interceptors进行过滤加工,然后通过ChannelSelector选择channel. ...
- 通过调整浏览器UA设置欺骗限制上网
先上图片, 通过调整浏览器UA,欺骗识别,原来这个WIFI是只能手机端使用的,打开IE F12,进行如上图所示,进行修改,正常输入手机号,获取验证码,登陆后,即可上网了.虽然显示的是400,但实际 ...
- wx小程序功能总结
注:1. 微信默认的宽度为750rpx , 不会变化. 2.bindtap 绑定触摸事件,可冒泡 catchtap 绑定触摸事件,不可冒泡 1.唤出系统菜单 2.上传图片 showSelection( ...