Terraform 扩展

2024-04-10 23:12
文章标签 扩展 terraform

本文主要是介绍Terraform 扩展,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

Terraform 扩展

Terraform Meta-Arguments 元参数

  • count 创建相似的资源
  • for_each 创建相似的资源
  • depends_on 定义资源或者模块的依赖
  • provider 定义provider选项
  • lifecycle 资源的生命周期行为
参数使用范围备注
countresource module适用于创建多个相似的资源,使用索引count.index作为参数引用。如果资源存在区别,建议使用 for_each
for_eachresource modulefor_each 它只能用于set(string) 或者map(string)
depends_onresource module处理 Terraform 无法自动推断的资源或模块之间的依赖关系
providerresource module在资源中定义供应商,通常是 . ,模块中,如果子模块未定义providers则继承父模块
lifecycleresource module生命周期行为定义

Count 创建资源副本

  • count = num数值类型, 可以通过 length() 计算数量;
  • count.index 索引来遍历列表

示例: 创建三条 DNS 记录

  • devops1.evescn.com
  • devops2.evescn.com
  • devops3.evescn.com
Terraform 配置
## count.tflocals {zone = "evescn.com"records = ["devops1","devops2","devops3"]
}resource "alicloud_dns_record" "record" {count = length(local.records)name        = local.zonehost_record = local.records[count.index]type        = "A"value       = "192.168.1.1"
}
## count.tflocals {zone = "evescn.com"records = ["devops1","devops2","devops3"]
}resource "alicloud_dns_record" "record" {count = length(local.records)name        = local.zonehost_record = local.records[count.index]type        = "A"value       = "192.168.1.1"
}
创建 DNS 解析
evescn@evescndeMacBook-Pro count % terraform initInitializing the backend...Initializing provider plugins...
- Finding hashicorp/alicloud versions matching "1.164.0"...
- Installing hashicorp/alicloud v1.164.0...
- Installed hashicorp/alicloud v1.164.0 (signed by HashiCorp)Terraform has been successfully initialized!evescn@evescndeMacBook-Pro count % terraform fmt 
count.tfevescn@evescndeMacBook-Pro count % terraform validate
Success! The configuration is valid.evescn@evescndeMacBook-Pro count % terraform plan    Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following symbols:+ createTerraform will perform the following actions:# alicloud_dns_record.record[0] will be created+ resource "alicloud_dns_record" "record" {+ host_record = "devops1"+ id          = (known after apply)+ locked      = (known after apply)+ name        = "evescn.com"+ routing     = "default"+ status      = (known after apply)+ ttl         = 600+ type        = "A"+ value       = "192.168.1.1"}# alicloud_dns_record.record[1] will be created+ resource "alicloud_dns_record" "record" {+ host_record = "devops2"+ id          = (known after apply)+ locked      = (known after apply)+ name        = "evescn.com"+ routing     = "default"+ status      = (known after apply)+ ttl         = 600+ type        = "A"+ value       = "192.168.1.1"}# alicloud_dns_record.record[2] will be created+ resource "alicloud_dns_record" "record" {+ host_record = "devops3"+ id          = (known after apply)+ locked      = (known after apply)+ name        = "evescn.com"+ routing     = "default"+ status      = (known after apply)+ ttl         = 600+ type        = "A"+ value       = "192.168.1.1"}Plan: 3 to add, 0 to change, 0 to destroy.evescn@evescndeMacBook-Pro count % terraform apply --auto-approveTerraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following symbols:+ createTerraform will perform the following actions:# alicloud_dns_record.record[0] will be created+ resource "alicloud_dns_record" "record" {+ host_record = "devops1"+ id          = (known after apply)+ locked      = (known after apply)+ name        = "evescn.com"+ routing     = "default"+ status      = (known after apply)+ ttl         = 600+ type        = "A"+ value       = "192.168.1.1"}# alicloud_dns_record.record[1] will be created+ resource "alicloud_dns_record" "record" {+ host_record = "devops2"+ id          = (known after apply)+ locked      = (known after apply)+ name        = "evescn.com"+ routing     = "default"+ status      = (known after apply)+ ttl         = 600+ type        = "A"+ value       = "192.168.1.1"}# alicloud_dns_record.record[2] will be created+ resource "alicloud_dns_record" "record" {+ host_record = "devops3"+ id          = (known after apply)+ locked      = (known after apply)+ name        = "evescn.com"+ routing     = "default"+ status      = (known after apply)+ ttl         = 600+ type        = "A"+ value       = "192.168.1.1"}Plan: 3 to add, 0 to change, 0 to destroy.
alicloud_dns_record.record[1]: Creating...
alicloud_dns_record.record[0]: Creating...
alicloud_dns_record.record[2]: Creating...
alicloud_dns_record.record[0]: Creation complete after 1s [id=843289465596745728]
alicloud_dns_record.record[1]: Creation complete after 1s [id=843289465605112832]
alicloud_dns_record.record[2]: Creation complete after 1s [id=843289465619789824]Apply complete! Resources: 3 added, 0 changed, 0 destroyed.

删除 devops2 记录,会成功运行?

locals {zone    = "evescn.com"# records = ["devops1", "devops2", "devops3"]records = ["devops1", "devops3"]
}resource "alicloud_dns_record" "record" {count       = length(local.records)name        = local.zonehost_record = local.records[count.index]type        = "A"value       = "192.168.1.1"
}

 执行部署

evescn@evescndeMacBook-Pro count % terraform plan                
alicloud_dns_record.record[0]: Refreshing state... [id=843289465596745728]
alicloud_dns_record.record[2]: Refreshing state... [id=843289465619789824]
alicloud_dns_record.record[1]: Refreshing state... [id=843289465605112832]Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following symbols:~ update in-place- destroyTerraform will perform the following actions:# alicloud_dns_record.record[1] will be updated in-place~ resource "alicloud_dns_record" "record" {~ host_record = "devops2" -> "devops3"id          = "843289465605112832"name        = "evescn.com"# (7 unchanged attributes hidden)}# alicloud_dns_record.record[2] will be destroyed# (because index [2] is out of range for count)- resource "alicloud_dns_record" "record" {- host_record = "devops3" -> null- id          = "843289465619789824" -> null- locked      = false -> null- name        = "evescn.com" -> null- priority    = 0 -> null- routing     = "default" -> null- status      = "ENABLE" -> null- ttl         = 600 -> null- type        = "A" -> null- value       = "192.168.1.1" -> null}Plan: 0 to add, 1 to change, 1 to destroy.evescn@evescndeMacBook-Pro count % terraform apply --auto-approve
alicloud_dns_record.record[1]: Refreshing state... [id=843289465605112832]
alicloud_dns_record.record[0]: Refreshing state... [id=843289465596745728]
alicloud_dns_record.record[2]: Refreshing state... [id=843289465619789824]Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following symbols:~ update in-place- destroyTerraform will perform the following actions:# alicloud_dns_record.record[1] will be updated in-place~ resource "alicloud_dns_record" "record" {~ host_record = "devops2" -> "devops3"id          = "843289465605112832"name        = "evescn.com"# (7 unchanged attributes hidden)}# alicloud_dns_record.record[2] will be destroyed# (because index [2] is out of range for count)- resource "alicloud_dns_record" "record" {- host_record = "devops3" -> null- id          = "843289465619789824" -> null- locked      = false -> null- name        = "evescn.com" -> null- priority    = 0 -> null- routing     = "default" -> null- status      = "ENABLE" -> null- ttl         = 600 -> null- type        = "A" -> null- value       = "192.168.1.1" -> null}Plan: 0 to add, 1 to change, 1 to destroy.
alicloud_dns_record.record[2]: Destroying... [id=843289465619789824]
alicloud_dns_record.record[1]: Modifying... [id=843289465605112832]
alicloud_dns_record.record[2]: Destruction complete after 1s
╷
│ Error: [ERROR] terraform-provider-alicloud/alicloud/resource_alicloud_dns_record.go:138: Resource 843289465605112832 UpdateDomainRecord Failed!!! [SDK alibaba-cloud-sdk-go ERROR]:
│ SDK.ServerError
│ ErrorCode: DomainRecordDuplicate
│ Recommend: https://api.aliyun.com/troubleshoot?q=DomainRecordDuplicate&product=Alidns
│ RequestId: 17F3D4A1-6E02-5F4E-AEA0-C04C583B9A9E
│ Message: The DNS record already exists.
│ RespHeaders: map[Access-Control-Allow-Origin:[*] Access-Control-Expose-Headers:[*] Connection:[keep-alive] Content-Length:[246] Content-Type:[application/json;charset=utf-8] Date:[Wed, 02 Aug 2023 03:39:11 GMT] Keep-Alive:[timeout=25] X-Acs-Request-Id:[17F3D4A1-6E02-5F4E-AEA0-C04C583B9A9E] X-Acs-Trace-Id:[df248ca1dac580f3e90c12bf599c4e1a]]
│ 
│   with alicloud_dns_record.record[1],
│   on count.tf line 7, in resource "alicloud_dns_record" "record":
│    7: resource "alicloud_dns_record" "record" {
│ 

从 terraform 看,程序执行的操作步骤如下:

  • update: server2 > server3
  • destroy: server3

但是在执行过程中 count = length(local.records) 命令获取不了 [2] 这个下标程序出错,看看 DNS 解析记录

for_each 创建资源副本 

  • for_each = set(string) map(string)

  • for_each 只能用于 set(string) 或者 map(string),可以使用 toset 转换 list 为 set 数据

  • for_each = set(string)

    • each.key = each.value
  • for_each = map(string)

    • each.key = key
    • each.value = value

示例: 创建三条 DNS 记录

  • devops1.evescn.com
  • devops2.evescn.com
  • devops3.evescn.com
Terraform 配置
## version.tfterraform {required_version = ">=1.1.9"required_providers {alicloud = {source  = "hashicorp/alicloud"version = "1.164.0"}}
}# Configure the Alicloud Provider
provider "alicloud" {access_key = "xxxxxxxx"secret_key = "xxxxxxxx"
}
## for_each.tflocals {zone = "evescn.com"# records = ["devops1", "devops2", "devops3"]records = ["devops1", "devops3"]
}resource "alicloud_dns_record" "eachrecord" {for_each    = toset(local.records)name        = local.zonehost_record = each.valuetype        = "A"value       = "192.168.1.1"
}
创建 DNS 解析
evescn@evescndeMacBook-Pro for_each % terraform initInitializing the backend...Initializing provider plugins...
- Finding hashicorp/alicloud versions matching "1.164.0"...
- Installing hashicorp/alicloud v1.164.0...
- Installed hashicorp/alicloud v1.164.0 (signed by HashiCorp)Terraform has been successfully initialized!evescn@evescndeMacBook-Pro for_each % terraform fmt 
for_each.tfevescn@evescndeMacBook-Pro for_each % terraform validate
Success! The configuration is valid.evescn@evescndeMacBook-Pro for_each % terraform apply   Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following symbols:+ createTerraform will perform the following actions:# alicloud_dns_record.eachrecord["devops1"] will be created+ resource "alicloud_dns_record" "eachrecord" {+ host_record = "devops1"+ id          = (known after apply)+ locked      = (known after apply)+ name        = "evescn.com"+ routing     = "default"+ status      = (known after apply)+ ttl         = 600+ type        = "A"+ value       = "192.168.1.1"}# alicloud_dns_record.eachrecord["devops2"] will be created+ resource "alicloud_dns_record" "eachrecord" {+ host_record = "devops2"+ id          = (known after apply)+ locked      = (known after apply)+ name        = "evescn.com"+ routing     = "default"+ status      = (known after apply)+ ttl         = 600+ type        = "A"+ value       = "192.168.1.1"}# alicloud_dns_record.eachrecord["devops3"] will be created+ resource "alicloud_dns_record" "eachrecord" {+ host_record = "devops3"+ id          = (known after apply)+ locked      = (known after apply)+ name        = "evescn.com"+ routing     = "default"+ status      = (known after apply)+ ttl         = 600+ type        = "A"+ value       = "192.168.1.1"}Plan: 3 to add, 0 to change, 0 to destroy.Do you want to perform these actions?Terraform will perform the actions described above.Only 'yes' will be accepted to approve.Enter a value: yesalicloud_dns_record.eachrecord["devops1"]: Creating...
alicloud_dns_record.eachrecord["devops2"]: Creating...
alicloud_dns_record.eachrecord["devops3"]: Creating...
alicloud_dns_record.eachrecord["devops2"]: Creation complete after 0s [id=843317481926367232]
alicloud_dns_record.eachrecord["devops3"]: Creation complete after 0s [id=843317481928446976]
alicloud_dns_record.eachrecord["devops1"]: Creation complete after 0s [id=843317481953598464]Apply complete! Resources: 3 added, 0 changed, 0 destroyed.

 删除 devops2 记录,重新执行

## for_each.tflocals {zone = "evescn.com"# records = ["devops1", "devops2", "devops3"]records = ["devops1", "devops3"]
}resource "alicloud_dns_record" "eachrecord" {for_each    = toset(local.records)name        = local.zonehost_record = each.valuetype        = "A"value       = "192.168.1.1"
}

 执行部署

evescn@evescndeMacBook-Pro for_each % terraform apply
alicloud_dns_record.eachrecord["devops2"]: Refreshing state... [id=843317481926367232]
alicloud_dns_record.eachrecord["devops3"]: Refreshing state... [id=843317481928446976]
alicloud_dns_record.eachrecord["devops1"]: Refreshing state... [id=843317481953598464]Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following symbols:- destroyTerraform will perform the following actions:# alicloud_dns_record.eachrecord["devops2"] will be destroyed# (because key ["devops2"] is not in for_each map)- resource "alicloud_dns_record" "eachrecord" {- host_record = "devops2" -> null- id          = "843317481926367232" -> null- locked      = false -> null- name        = "evescn.com" -> null- priority    = 0 -> null- routing     = "default" -> null- status      = "ENABLE" -> null- ttl         = 600 -> null- type        = "A" -> null- value       = "192.168.1.1" -> null}Plan: 0 to add, 0 to change, 1 to destroy.Do you want to perform these actions?Terraform will perform the actions described above.Only 'yes' will be accepted to approve.Enter a value: yesalicloud_dns_record.eachrecord["devops2"]: Destroying... [id=843317481926367232]
alicloud_dns_record.eachrecord["devops2"]: Destruction complete after 0sApply complete! Resources: 0 added, 0 changed, 1 destroyed.

dynamic 动态的内联块

  • dynamic : 定义动态资源块,后面是 label, 默认为生成的语句块名称;
  • for_each : 要进行迭代循环的对象(map、list、set);
  • iterator : 临时的变量名称,如果未定义则使用 label 即 ports ;
  • content : 要生成的语句块的内容部分;
dynamic "label" {# 支持 map list set 等数据for_each = map | list | set iterator = iterator_namecontent {key = iterator_name.value}
}
dynamic "ports" {for_each = local.jenkins_portscontent {internal = ports.value.internalexternal = ports.value.externalip       = "0.0.0.0"protocol = "tcp"}
}

Docker 中的 ports{}

resource "docker_container" "jenkins" {ports {internal = 8080external = 8080ip       = "0.0.0.0"protocol = "tcp"}ports {internal = 50000external = 50000ip       = "0.0.0.0"protocol = "tcp"}
}

定义一个local变量;使用dynamic动态内联块
for_each遍历资源;ports.value引用遍历的资源

locals {jenkins_ports = [{internal = 8080external = 8080},{internal = 50000external = 50000}]
}resource "docker_container" "jenkins" {// 使用dynamic来实现动态dynamic "ports" {for_each = local.jenkins_portscontent {internal = ports.value.internalexternal = ports.value.externalip       = "0.0.0.0"protocol = "tcp"}}

depends_on 依赖关系

处理 资源或模块之间的依赖关系。

resource "docker_image" "jenkins" {name         = "jenkins/jenkins:2.332.2-centos7-jdk8"force_remove = falsekeep_locally = true
}resource "docker_container" "jenkins" {image      = docker_image.jenkins.namename       = "jenkins-demo"# 依赖 docker_image 资源depends_on = [docker_image.jenkins]
}

provider 自定义供应商

resource 覆盖资源中的 provider

例如:分别在 cn-beijing 和 cn-shanghai 区域分别创建1个实例。

provider "alicloud" {alias  = "north"region = "cn-beijing"access_key = "AKIR"secret_key = "MJy5JXmZn"
}provider "alicloud" {region     = "cn-shanghai"access_key = "AK5R"secret_key = "MJy5JX6HIqmZn"
}resource "alicloud_instance" "ecs_demo_north" {provider      = alicloud.north...
}resource "alicloud_instance" "ecs_demo" {...
}

module 默认子模块继承根模块的provider;

  • provider = map()
  • key: provider名称
  • value: <provider>.<alias>
provider "alicloud" {alias  = "north"region = "cn-beijing"
}provider "alicloud" {region = "cn-shanghai"
}module "example" { source = "./example"# module 中的 provider 配置providers = { alicloud = alicloud.north}
}

lifecycle 生命周期

标记资源不被删除或者销毁前创建新的资源;

lifecycle {xxx
}
  • create_before_destroy 先创建新的对象,再销毁旧的对象;
  • prevent_destroy 防止资源被销毁;
  • ignore_changes 忽略资源的差异;
  • replace_triggered_by 当指定的资源修改后替换当前资源;
  • precondition postcondition 条件检查
lifecycle {create_before_destroy = true# prevent_destroy = trueignore_changes = [tags, instance_name]replace_triggered_by = [alicloud_vpc.vpc.vpc_name]
}

这篇关于Terraform 扩展的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/892416

相关文章

csu 1446 Problem J Modified LCS (扩展欧几里得算法的简单应用)

这是一道扩展欧几里得算法的简单应用题,这题是在湖南多校训练赛中队友ac的一道题,在比赛之后请教了队友,然后自己把它a掉 这也是自己独自做扩展欧几里得算法的题目 题意:把题意转变下就变成了:求d1*x - d2*y = f2 - f1的解,很明显用exgcd来解 下面介绍一下exgcd的一些知识点:求ax + by = c的解 一、首先求ax + by = gcd(a,b)的解 这个

科研绘图系列:R语言扩展物种堆积图(Extended Stacked Barplot)

介绍 R语言的扩展物种堆积图是一种数据可视化工具,它不仅展示了物种的堆积结果,还整合了不同样本分组之间的差异性分析结果。这种图形表示方法能够直观地比较不同物种在各个分组中的显著性差异,为研究者提供了一种有效的数据解读方式。 加载R包 knitr::opts_chunk$set(warning = F, message = F)library(tidyverse)library(phyl

Spring框架5 - 容器的扩展功能 (ApplicationContext)

private static ApplicationContext applicationContext;static {applicationContext = new ClassPathXmlApplicationContext("bean.xml");} BeanFactory的功能扩展类ApplicationContext进行深度的分析。ApplicationConext与 BeanF

PHP7扩展开发之数组处理

前言 这次,我们将演示如何在PHP扩展中如何对数组进行处理。要实现的PHP代码如下: <?phpfunction array_concat ($arr, $prefix) {foreach($arr as $key => $val) {if (isset($prefix[$key]) && is_string($val) && is_string($prefix[$key])) {$arr[

PHP7扩展开发之字符串处理

前言 这次,我们来看看字符串在PHP扩展里面如何处理。 示例代码如下: <?phpfunction str_concat($prefix, $string) {$len = strlen($prefix);$substr = substr($string, 0, $len);if ($substr != $prefix) {return $prefix." ".$string;} else

PHP7扩展开发之类型处理

前言 这次,我们将演示如何在PHP扩展中如何对类型进行一些操作。如,判断变量类型。要实现的PHP代码如下: <?phpfunction get_size ($value) {if (is_string($value)) {return "string size is ". strlen($value);} else if (is_array($value)) {return "array si

PHP7扩展开发之依赖其他扩展

前言 有的时候,我们的扩展要依赖其他扩展。比如,我们PHP的mysqli扩展就依赖mysqlnd扩展。这中情况下,我们怎么使用其他扩展呢?这个就是本文讲述的内容。 我们新建立一个扩展,名字叫 demo_dep , 依赖之前的say扩展。 在demo_dep扩展中,我们实现demo_say方法。这个方法调用say扩展的say方法。 代码 基础代码 确保say扩展的头文件正确安装到了php

PHP7扩展开发之函数方式使用lib库

前言 首先说下什么是lib库。lib库就是一个提供特定功能的一个文件。可以把它看成是PHP的一个文件,这个文件提供一些函数方法。只是这个lib库是用c或者c++写的。 使用lib库的场景。一些软件已经提供了lib库,我们就没必要再重复实现一次。如,原先的mysql扩展,就是使用mysql官方的lib库进行的封装。 在本文,我们将建立一个简单的lib库,并在扩展中进行封装调用。 代码 基础

PHP7扩展开发之对象方式使用lib库

前言 上一篇文章,我们使用的是函数方式调用lib库。这篇文章我们将使用对象的方式调用lib库。调用代码如下: <?php $hello = new hello(); $result = $hello->get(); var_dump($result); ?> 我们将在扩展中实现hello类。hello类中将依赖lib库。 代码 基础代码 这个扩展,我们将在say扩展上增加相关代码。sa

PHP7扩展开发之流操作

前言 啥是流操作?简单来讲就是对一些文件,网络的IO操作。PHP已经把这些IO操作,封装成流操作。这节,我们将使用PHP扩展实现一个目录遍历的功能。PHP示例代码如下: <?phpfunction list_dir($dir) {if (is_dir($dir) === false) {return;} $dh = opendir($dir);if ($dh == false) {ret