使用terraform 来创建GCP的instance template 和基于它的vm

本文详细介绍了如何使用Terraform在GoogleCloudPlatform(GCP)上创建实例模板和基于模板的VM,包括使用`google_compute_instance_template`和`google_compute_instance_from_template`资源。着重展示了如何配置实例模板以及如何覆盖模板默认设置以满足特定需求。

本人在上一篇的文章中已经介绍了如何去创建 google cloud的 vm 的image 和 instance template了
url:
快速构建自定义配置好的VM - 使用GCP instance-template 和 custom-image

但是里面的操作是基于gcloud CLI的。

在实际项目上, 我们对google cloud infra的change 更常有的是terraform。 这里也简单介绍下如何利用terraform去创建vm instance template 和对应的vm

下面的内容都是参考自官方terraform 文档:
https://registry.terraform.io/providers/hashicorp/google/latest/docs/resources/compute_instance_from_template




创建 实例模板 vm instance template

首先在terraform的vm module里新建1个tf 文件 instance_template.tf, 其实terraform的module folder 内是支持把内容写在多个文件的, 比起单一的main.tf 来讲更加容易管理
在这里插入图片描述

接下来就简单了, 我们可以把vm module原来了定义vm的代码块抄过来, 只是下面的部分需要注意修改:

resource "google_compute_instance_template" "vm-template-vpc0-subnet0-e2-small-tomcat" {
   
   
  name         = "vm-template-vpc0-subnet0-e2-small-tomcat"
  machine_type = "e2-small"

  disk {
   
   
    source_image = "https://compute.googleapis.com/compute/v1/projects/jason-hsbc/global/images/e2-small-tomcat-image"
    auto_delete  = true
    disk_size_gb = 20
    boot         = true
  }

  network_interface {
   
   
    network =  var.vpc0
    subnetwork =  var.vpc0_subnet0    
  }

 service_account {
   
   
    email  = "vm-common@jason-hsbc.iam.gserviceaccount.com"
    scopes = ["https://www.googleapis.com/auth/cloud-platform"]
  }

  # https://registry.terraform.io/providers/hashicorp/google/latest/docs/resources/compute_instance#provisioning_model
  # to reduce cost
  scheduling {
   
    
    automatic_restart = false # Scheduling must have preemptible be false when AutomaticRestart is true.
    provisioning_model = "SPOT"
    preemptible         = true
    instance_termination_action = "STOP"
  }

  can_ip_forward = false
}

注意修改的部分:

  1. resource 是google_compute_instance_template 而不是 google_compute_instance
  2. source image 记得改成你自定义的image, 如果你需要预安装配置某些软件的话(jdk/tomcat…)

当执行玩terraform 一套命令后(init/plan/apply) , 1个新的vm instance template 就会被创建vm-template-vpc0-subnet0-e2-small-tomcat

[
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

nvd11

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值