首页 > 系统相关 >Terraform实践--腾讯云、首都云、VMware

Terraform实践--腾讯云、首都云、VMware

时间:2022-11-28 17:00:32浏览次数:61  
标签:vsphere terraform -- vm virtual Terraform provider id VMware

Terraform实践

目录

简介

Terraform是一个IT基础架构自动化编排工具,可以用代码来管理维护 IT 资源。Terraform的命令行接口(CLI)提供一种简单机制,并对其进行版本控制。它编写了描述云资源拓扑的配置文件中的基础结构,例如虚拟机、存储帐户和网络接口。

优势

    • 将基础结构部署到多个云
    • 自动化管理基础结构
    • 降低开发成本

工作流程

img

安装

登录 Terraform官网 下载适用于你的操作系统的程序包

Ubauntu/Debian安装

wget -O- https://apt.releases.hashicorp.com/gpg | gpg --dearmor | sudo tee /usr/share/keyrings/hashicorp-archive-keyring.gpg
echo "deb [signed-by=/usr/share/keyrings/hashicorp-archive-keyring.gpg] https://apt.releases.hashicorp.com $(lsb_release -cs) main" | sudo tee /etc/apt/sources.list.d/hashicorp.list
sudo apt update && sudo apt install terraform

Centos安装

sudo yum install -y yum-utils
sudo yum-config-manager --add-repo https://rpm.releases.hashicorp.com/RHEL/hashicorp.repo
sudo yum -y install terraform

对接案例

腾讯云

参考文档:TencentCloud Providerterraform文档cloud-terraform-快速实践腾讯云控制台
配置腾讯云provider文件
登录腾讯云,在访问管理中选择API秘钥管理

img

img

指定terraform版本
[root@test-lwj-150-64 cloud-terraform]# terraform12_5 --version
Terraform v0.12.5
+ provider.tencentcloud v1.56.2

Your version of Terraform is out of date! The latest version
is 1.3.5. You can update by downloading from www.terraform.io/downloads.html
在新目录下创建 provider.tf 文件,填入秘钥和区域信息
[root@test-lwj-150-64 cloud-terraform]# cat provider.tf
provider "tencentcloud" {
        secret_id  = "AK******************"
        secret_key = "Wo******************"
        region     = "ap-shanghai"
    }
执行terraform init初始化Terraform
[root@test-lwj-150-64 cloud-terraform]# terraform init

Initializing the backend...

Initializing provider plugins...

The following providers do not have any version constraints in configuration,
so the latest version was installed.

To prevent automatic upgrades to new major versions that may contain breaking
changes, it is recommended to add version = "..." constraints to the
corresponding provider blocks in configuration, with the constraint strings
suggested below.

* provider.tencentcloud: version = "~> 1.56"

Terraform has been successfully initialized!

You may now begin working with Terraform. Try running "terraform plan" to see
any changes that are required for your infrastructure. All Terraform commands
should now work.

If you ever set or change modules or backend configuration for Terraform,
rerun this command to reinitialize your working directory. If you forget, other
commands will detect it and remind you to do so if necessary.
编辑资源
[root@test-lwj-150-64 cloud-terraform]# cat cvm.tf
resource "tencentcloud_instance" "cvm_test" {
        # 实例名称
        instance_name = "cvm-test"
        # 可用区
        availability_zone = "ap-shanghai-2"
        # 镜像id
        image_id = "img-57j4snjh"
        # 实例类型
        instance_type = "S5.MEDIUM2"
        # 磁盘类型
        system_disk_type = "CLOUD_PREMIUM"
        # 安全组 可参考腾讯安全组
        security_groups = [
            "sg-5aw0ubdu"
        ]
        # VPC ID 参考:腾讯云-上海私有网络
        vpc_id = "vpc-4d8eaoy0"
        # 子网ID
        subnet_id = "subnet-53rip33v"
        # 默认自动分配公网IP
        allocate_public_ip = true
        # 最大带宽输出
        internet_max_bandwidth_out = 50
        # 数量
        count = 1
    }
部署腾讯云资源
# 下载腾讯云provider依赖包
[root@test-lwj-150-64 cloud-terraform]# terraform12_5 init

Initializing the backend...

Initializing provider plugins...

The following providers do not have any version constraints in configuration,
so the latest version was installed.

To prevent automatic upgrades to new major versions that may contain breaking
changes, it is recommended to add version = "..." constraints to the
corresponding provider blocks in configuration, with the constraint strings
suggested below.

* provider.tencentcloud: version = "~> 1.56"

Terraform has been successfully initialized!

You may now begin working with Terraform. Try running "terraform plan" to see
any changes that are required for your infrastructure. All Terraform commands
should now work.

If you ever set or change modules or backend configuration for Terraform,
rerun this command to reinitialize your working directory. If you forget, other
commands will detect it and remind you to do so if necessary.

# 开始创建资源
[root@test-lwj-150-64 cloud-terraform]# terraform apply

An execution plan has been generated and is shown below.
Resource actions are indicated with the following symbols:
  + create

Terraform will perform the following actions:

  # tencentcloud_instance.cvm_test[0] will be created
  + resource "tencentcloud_instance" "cvm_test" {
      + allocate_public_ip                      = false
      + availability_zone                       = "ap-shanghai-5"
      + create_time                             = (known after apply)
      + disable_monitor_service                 = false
      + disable_security_service                = false
      + expired_time                            = (known after apply)
      + force_delete                            = false
      + id                                      = (known after apply)
      + image_id                                = "img-57j4snjh"
      + instance_charge_type                    = "POSTPAID_BY_HOUR"
      + instance_charge_type_prepaid_renew_flag = (known after apply)
      + instance_name                           = "cvm-test"
      + instance_status                         = (known after apply)
      + instance_type                           = "S5.MEDIUM2"
      + internet_charge_type                    = (known after apply)
      + internet_max_bandwidth_out              = (known after apply)
      + key_name                                = (known after apply)
      + private_ip                              = (known after apply)
      + project_id                              = 0
      + public_ip                               = (known after apply)
      + running_flag                            = true
      + security_groups                         = [
          + "sg-5aw0ubdu",
        ]
      + subnet_id                               = "subnet-53rip33v"
      + system_disk_id                          = (known after apply)
      + system_disk_size                        = 50
      + system_disk_type                        = "CLOUD_PREMIUM"
      + vpc_id                                  = "vpc-4d8eaoy0"

      + data_disks {
          + data_disk_id           = (known after apply)
          + data_disk_size         = (known after apply)
          + data_disk_snapshot_id  = (known after apply)
          + data_disk_type         = (known after apply)
          + delete_with_instance   = (known after apply)
          + encrypt                = (known after apply)
          + throughput_performance = (known after apply)
        }
    }

Plan: 1 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: yes

tencentcloud_instance.cvm_test[0]: Creating...
tencentcloud_instance.cvm_test[0]: Still creating... [10s elapsed]
tencentcloud_instance.cvm_test[0]: Still creating... [20s elapsed]
tencentcloud_instance.cvm_test[0]: Still creating... [30s elapsed]
tencentcloud_instance.cvm_test[0]: Creation complete after 34s [id=ins-avgx70a7]

Apply complete! Resources: 1 added, 0 changed, 0 destroyed.

首都云

参考文档:terraform-provider-cdscds-api首都云控制台
下载首都云terraform-provider
$ git clone https://github.com/capitalonline/terraform-provider-cds.git
$ cd terraform-provider-cds
$ go get
$ go build -o terraform-provider-cds
$ mkdir ~/.terraform.d/plugins/
$ mv terraform-provider-cds ~/.terraform.d/plugins/
获取首都云密钥

img

img

img

编辑首都云密钥
[root@test-lwj-150-64 terraform-provider-cds]# cd terraform-provider-cds/
[root@test-lwj-150-64 terraform-provider-cds]# cat sn.sh
#!/usr/bin/env bash
export CDS_SECRET_ID=4a698**************
export CDS_SECRET_KEY=606a8**************
export CDS_REGION=CN_Shanghai_C
[root@test-lwj-150-64 terraform-provider-cds]# source sn.sh
需要手动创建以下.terraform目录结构,注意1.4.4版本应该跟你当前provider一直,可以通过versions.tf进行查看
[root@test-lwj-150-64 cds_instance]# tree -a
.
|-- .main.tf.swp
|-- .terraform
|   `-- providers
|       `-- terraform.capitalonline.net
|           `-- capitalonline
|               `-- cds
|                   `-- 1.4.4
|                       `-- linux_amd64 -> /root/.terraform.d/plugins/terraform.capitalonline.net/capitalonline/cds/1.4.4/linux_amd64
|-- .terraform.lock.hcl
|-- main.tf
|-- terraform.log
|-- terraform.tfstate
|-- terraform.tfstate.backup
|-- variables.tf
`-- versions.tf
参数说明
[root@test-lwj-150-64 cds_instance]# cat main.tf
// create instance
resource "cds_instance" "my_instance2" {
  # 实例名称
  instance_name = "test_zz_04"
  # 可用区,可以参考cds-api-可用区说明文档
  region_id     = "CN_Shanghai_C"
  # 镜像ID,可以参考CDS-GUI控制台-镜像管理
  image_id      = "16c64418-cb49-11ec-90e9-da10a5128739"
  # 实例类型说明可以参考cds-api文档:
  instance_type = "CCS.C3CL"
  # CPU
  cpu           = 2
  # 内存
  ram           = 4
  # VDC-ID 可参考CDS-GUI控制台-虚拟数据中心VDC列表
  vdc_id        = "545a90f1-f140-4cb6-b866-dd4ca3e2437a"
  # 给服务器添加公钥信息
  public_key = file("/home/guest/.ssh/test.pub")
  # 自定义服务器密码
  password  = "Huanle.2021"
  # 自定义镜像密码
  image_password = "Huanle.2022"
  # 实例预期运行状态
  operate_instance_status = "run"
  # 公网IP分配
  public_ip = "auto"
  # 私网IP分配;private_id:参数如何获取可参考下图
  private_ip {
    private_id="34c024da-a1a5-11eb-b808-9602cbfa07f9"
    address= "auto"
  }
  # 系统磁盘
  system_disk = {
    type = var.system_disk_type
    size = 100
    iops = 5
  }

}
部分参数如何获取
private_id参数获取

以当前例子获取VDC的私网ID:虚拟数据中心-VDC:office-上海C ID:545a90f1-f140-4cb6-b866-dd4ca3e2437a

  1. 点击对应VDC的【更多】按钮

img

  1. 开启页面【检查】,快捷键F12

  2. 点击【私网管理】

img

  1. 查看【pipe_segment/】请求参数中有pipe_id就是我们需要的private_id

img

interface_id参数获取

以当前为例:

img

部署首都云
[root@test-lwj-150-64 cds_instance]# terraform apply
cds_instance.my_instance2: Refreshing state... [id=d3d7389b-2660-4925-8e7c-383db2d66769]

No changes. Your infrastructure matches the configuration.

Terraform has compared your real infrastructure against your configuration and found no differences, so no changes are needed.

Apply complete! Resources: 0 added, 0 changed, 0 destroyed.

VMware

参考文档: Vsphere-Terraform-Providers
准备Terraform工作目录
[root@lwj-local-103 terraform-vsphere-standalone]# cat variables.tf
#====================#
# vCenter connection #
#====================#

variable "vsphere_user" {
  description = "vSphere user name"
}

variable "vsphere_password" {
  description = "vSphere password"
}

variable "vsphere_vcenter" {
  description = "vCenter server FQDN or IP"
}

variable "vsphere_unverified_ssl" {
  description = "Is the vCenter using a self signed certificate (true/false)"
}

variable "vsphere_datacenter" {
  description = "vSphere datacenter"
}

variable "vsphere_cluster" {
  description = "vSphere cluster"
  default     = ""
}

#=========================#
# vSphere virtual machine #
#=========================#

variable "vm_datastore" {
  description = "Datastore used for the vSphere virtual machines"
}

variable "vm_network" {
  description = "Network used for the vSphere virtual machines"
}

variable "vm_template" {
  description = "Template used to create the vSphere virtual machines"
}

variable "vm_linked_clone" {
  description = "Use linked clone to create the vSphere virtual machine from the template (true/false). If you would like to use the linked clone feature, your template need to have one and only one snapshot"
  default = "false"
}

variable "vm_ip" {
  description = "Ip used for the vSpgere virtual machine"
}

variable "vm_netmask" {
  description = "Netmask used for the vSphere virtual machine (example: 24)"
}

variable "vm_gateway" {
  description = "Gateway for the vSphere virtual machine"
}

variable "vm_dns" {
  description = "DNS for the vSphere virtual machine"
}

variable "vm_domain" {
  description = "Domain for the vSphere virtual machine"
}

variable "vm_cpu" {
  description = "Number of vCPU for the vSphere virtual machines"
}

variable "vm_ram" {
  description = "Amount of RAM for the vSphere virtual machines (example: 2048)"
}

variable "vm_name" {
  description = "The name of the vSphere virtual machines and the hostname of the machine"
}
准备variables.tf文件
准备terraform.tfvars文件
[root@lwj-local-103 terraform-vsphere-standalone]# cat terraform.tfvars
#===============================================================================
# VMware vSphere configuration
#===============================================================================

# vCenter IP or FQDN #
vsphere_vcenter = "0.0.0.0"

# vSphere username used to deploy the infrastructure #
vsphere_user = "******"

vsphere_password = "********"

# Skip the verification of the vCenter SSL certificate (true/false) #
vsphere_unverified_ssl = "true"

# vSphere datacenter name where the infrastructure will be deployed #
vsphere_datacenter = "Datacenter"

# vSphere cluster name where the infrastructure will be deployed #
# 集群名
vsphere_cluster = "compute_cluster01"

#===============================================================================
# Virtual machine parameters
#===============================================================================

# The name of the virtual machine #
vm_name = "trf-test01"

# The datastore name used to store the files of the virtual machine #
# 数据中心
vm_datastore = "datastore_160_1_02"

# The vSphere network name used by the virtual machine #
vm_network = "VM Network"

# The netmask used to configure the network card of the virtual machine (example: 24) #
vm_netmask = "24"

# The network gateway used by the virtual machine #
vm_gateway = "10.0.160.254"

# The DNS server used by the virtual machine #
vm_dns = "192.168.0.1"

# The domain name used by the virtual machine #
vm_domain = ""

# The vSphere template the virtual machine is based on #
vm_template = "centos7-temp"

# Use linked clone (true/false)
vm_linked_clone = "false"

# The number of vCPU allocated to the virtual machine #
vm_cpu = 2

# The amount of RAM allocated to the virtual machine #
vm_ram = 2048

vm_disk_size = 40

# The IP address of the virtual machine #
vm_ip = "10.0.160.19"
准备vsphere-standalone.tf文件
[root@lwj-local-103 terraform-vsphere-standalone]# cat vsphere-standalone.tf
#===============================================================================
# vSphere Provider
#===============================================================================

provider "vsphere" {
  version        = "1.11.0"
  vsphere_server = "${var.vsphere_vcenter}"
  user           = "${var.vsphere_user}"
  password       = "${var.vsphere_password}"

  allow_unverified_ssl = "${var.vsphere_unverified_ssl}"
}

#===============================================================================
# vSphere Data
#===============================================================================

data "vsphere_datacenter" "dc" {
  name = "${var.vsphere_datacenter}"
}

data "vsphere_compute_cluster" "cluster" {
  name          = "${var.vsphere_cluster}"
  datacenter_id = "${data.vsphere_datacenter.dc.id}"
}

data "vsphere_datastore" "datastore" {
  name          = "${var.vm_datastore}"
  datacenter_id = "${data.vsphere_datacenter.dc.id}"
}

data "vsphere_network" "network" {
  name          = "${var.vm_network}"
  datacenter_id = "${data.vsphere_datacenter.dc.id}"
}

data "vsphere_virtual_machine" "template" {
  name          = "${var.vm_template}"
  datacenter_id = "${data.vsphere_datacenter.dc.id}"
}

#===============================================================================
# vSphere Resources
#===============================================================================

resource "vsphere_virtual_machine" "standalone" {
  name             = "${var.vm_name}"
  resource_pool_id = "${data.vsphere_compute_cluster.cluster.resource_pool_id}"
  datastore_id     = "${data.vsphere_datastore.datastore.id}"

  num_cpus = "${var.vm_cpu}"
  memory   = "${var.vm_ram}"
  guest_id = "${data.vsphere_virtual_machine.template.guest_id}"

  network_interface {
    network_id   = "${data.vsphere_network.network.id}"
    adapter_type = "${data.vsphere_virtual_machine.template.network_interface_types[0]}"
  }

  disk {
    label            = "${var.vm_name}.vmdk"
    size             = "${data.vsphere_virtual_machine.template.disks.0.size}"
    eagerly_scrub    = "${data.vsphere_virtual_machine.template.disks.0.eagerly_scrub}"
    thin_provisioned = "${data.vsphere_virtual_machine.template.disks.0.thin_provisioned}"
  }

  clone {
    template_uuid = "${data.vsphere_virtual_machine.template.id}"
    linked_clone  = "${var.vm_linked_clone}"

    customize {
      timeout = "20"

      linux_options {
        host_name = "${var.vm_name}"
        domain    = "${var.vm_domain}"
      }

      network_interface {
        ipv4_address = "${var.vm_ip}"
        ipv4_netmask = "${var.vm_netmask}"
      }

      ipv4_gateway    = "${var.vm_gateway}"
      dns_server_list = ["${var.vm_dns}"]
    }
  }
}

标签:vsphere,terraform,--,vm,virtual,Terraform,provider,id,VMware
From: https://www.cnblogs.com/louwj/p/16932654.html

相关文章

  • 使用第三方IQKeyboardManager处理键盘问题
    这个库的下载地址:https://github.com/hackiftekhar/IQKeyboardManagerIQKeyboardManager的初始化当IQKeyboardManager初始化的时候,它做了这么几件事情:1.监听有关键盘的......
  • Python|批量获取Mapbox等时圈shapefile格式数据
    直接获取Mapbox出行圈数据Mapbox地图网站有个IsochoneAPI接口IsochroneAPI|Playground|Mapbox,可以快速获得等时圈数据。获取accesstoken打开Mapbox网站Maps,geoc......
  • React中性能优化的方案
    shouldComponentUpdate控制组件自身或子组件是否需要更新,尤其在子组件非常多的情况下,需要进行优化。PureComponentPureComponent会帮你比较新Props跟旧的Props,......
  • 小新学Java13-【线程池、Lambda表达式】
    一、等待唤醒机制1.1线程间通信概念:多个线程在处理同一个资源,但是处理的动作(线程的任务)却不相同。1.2等待唤醒机制什么是等待唤醒机制?这是多个线程间的一种协作机......
  • VS 使用本机IP调试项目
    获取本机ip地址win+r打开《运行》输入cmd回车输入ipconfig即可查看到ipv4地址  配置IP 右键iis服务器,选择显示所有应用程序  点击项目名即可显示配置这一选......
  • tcp连接
    服务器端packagemainimport( "fmt" "net" "strings")funcHandleConnect(connnet.Conn){ deferconn.Close() addr:=conn.RemoteAddr() fmt.Println(a......
  • Java基础运算符
    JAVA基础运算符算数运算符:+,-,*,/,%,++,--//二元运算符//Ctrl+D赋值当前行到下一行inta=10;intb=20;intc=25;......
  • 非常强大的第三方授权登录的工具类库!
    非常强大的第三方授权登录的工具类库!关注什么是JustAuth?JustAuth,如你所见,它仅仅是一个第三方授权登录的工具类库,它可以让我们脱离繁琐的第三方登录SDK,让登录变得So......
  • yum失效couldnot resolve host: mirrorlist.centos.org
    参考https://blog.csdn.net/qq_38224386/article/details/114592661今天虚拟机安装完CentOS系统后,安装网络的时候yum-yinstallnet-tools紧接着问题来了:Couldnotr......
  • mybatis快速xml技巧
    1.查询2.条件查询参数传递[封装]方式三种......