Terraform 脚本

问题描述 投票:0回答:1

使用terraform创建了EC2实例,现在我想修改实例类型而无需手动干预。它应该使用包装脚本自动更改。

示例我使用 terraform 启动了一个 AWS ec2 实例,其基本配置包括实例类型、实例数量等。但是,当我想将实例计数从 1 更改为 2 或更改我通过编辑 terraform 代码手动执行的任何配置时。

  1. 我想通过wrappr脚本自动化该阶段

主要.tf

terraform {
  required_providers {
    aws = {
      source = "hashicorp/aws"
    }
  }
}

resource "aws_instance" "" {
  ami           = var.ami
  instance_type = var.instance_type

  network_interface {
    network_interface_id = var.network_interface_id
    device_index         = 0
  }
  credit_specification {
    cpu_credits = "unlimited"
  }
}

变种.tf

variable "network_interface_id" {
  type    = string
  default = "network_id_from_aws"
}

variable "ami" {
  type    = string
  default = "ami-005e54dee72cc1d00"
}

variable "instance_type" {
  type    = string
  default = "t2.micro"
}

这里我想修改“实例类型”t2。微型到 t2.large。 自动无需手动进入 var.tf 文件

amazon-web-services shell terraform
1个回答
1
投票

如果我正确理解你的问题:

您希望拥有一个不想更改的 Terraform 脚本,即使您想更改基础设施中的某些内容(例如实例计数、机器类型等)也是如此。

对于此用例,您可以简单地从 Terraform plan/apply 中、通过创建自定义 *.tfvars 文件或使用

TF_VAR_*
环境变量来为变量提供值(更多信息请参见:https://developer. hashcorp.com/terraform/language/values/variables#variable-definition-precedence)。

例如,对于如下所示的脚本:

terraform {
  required_providers {
    aws = {
      source = "hashicorp/aws"
    }
  }
}
resource "aws_instance" "myinstance" {
  count         = var.instance_count
  ami           = var.ami
  instance_type = var.instance_type

  network_interface {
    network_interface_id = var.network_interface_id
    device_index         = 0
  }

  credit_specification {
    cpu_credits = "unlimited"
  }
}

# Var.tf
variable "network_interface_id" {
  type    = string
  default = "network_id_from_aws"
}

variable "ami" {
  type    = string
  default = "ami-005e54dee72cc1d00"
}

variable "instance_type" {
  type    = string
  default = "t2.micro"
}

variable "instance_count" {
  type   = number
  defult = 1
}

我会将此行添加到我的包装脚本中(假设它是从我的 CI 管道运行的 bash 脚本)

terraform plan -var instance_count=2 -var instance_type=t2.large

或者,我会根据脚本输入动态创建一个

*.tfvars
文件


但是,如果您想做的不止于此,请考虑 Terraform 是一项 IaaC 技术。您可能希望 Terraform 脚本尽可能接近现实(云环境中的脚本)。

© www.soinside.com 2019 - 2024. All rights reserved.