IaC基础设施即代码:使用Terraform 连接 tencentcloud腾讯云 并创建后端COS

发布时间:2024年01月24日

目录

?一、实验

1.环境

2.tencentcloud腾讯云创建用户

3.Windows使用Terraform?连接 tencentcloud

4.Windows给Terraform项目添加tencentcloud腾讯云COS?(实现代码与资源分离)

二、问题

1.?Windows?terraform 初始化失败

2.Terraform 预览资源失败

3. Terraform初始化后端配置失败


?一、实验

1.环境

(1)主机

表1-1 主机

主机系统软件工具备注
jia

Windows?

Terraform 1.6.6VS Code、?PowerShell、?Chocolatey

2.tencentcloud腾讯云创建用户

(1)登录

用户列表 - 用户 - 访问管理 - 控制台 (tencent.com)

(2)查看

CAM访问管理-用户

(3)新建用户?

选中“可访问资源并接收消息”

(4)安全验证

(5)设置用户权限

(6)设置用户标签

(7)审阅信息和权限

(8)成功新建用户

(9)查看权限

(10)查看tentcloud provider 示例

Terraform Registry

USE PROVIDER? 示例

terraform {
  required_providers {
    tencentcloud = {
      source = "tencentcloudstack/tencentcloud"
      version = "1.81.69"
    }
  }
}

provider "tencentcloud" {
  # Configuration options
}

Example Usage? 示例

terraform {
  required_providers {
    tencentcloud = {
      source = "tencentcloudstack/tencentcloud"
    }
  }
}

# Configure the TencentCloud Provider
provider "tencentcloud" {
  secret_id  = "my-secret-id"
  secret_key = "my-secret-key"
  region     = "ap-guangzhou"
}

# Get availability zones
data "tencentcloud_availability_zones" "default" {
}

# Get availability images
data "tencentcloud_images" "default" {
  image_type = ["PUBLIC_IMAGE"]
  os_name    = "centos"
}

# Get availability instance types
data "tencentcloud_instance_types" "default" {
  cpu_core_count = 1
  memory_size    = 1
}

# Create a web server
resource "tencentcloud_instance" "web" {
  instance_name              = "web server"
  availability_zone          = data.tencentcloud_availability_zones.default.zones.0.name
  image_id                   = data.tencentcloud_images.default.images.0.image_id
  instance_type              = data.tencentcloud_instance_types.default.instance_types.0.instance_type
  system_disk_type           = "CLOUD_PREMIUM"
  system_disk_size           = 50
  allocate_public_ip         = true
  internet_max_bandwidth_out = 20
  security_groups            = [tencentcloud_security_group.default.id]
  count                      = 1
}

# Create security group
resource "tencentcloud_security_group" "default" {
  name        = "web accessibility"
  description = "make it accessible for both production and stage ports"
}

# Create security group rule allow web request
resource "tencentcloud_security_group_rule" "web" {
  security_group_id = tencentcloud_security_group.default.id
  type              = "ingress"
  cidr_ip           = "0.0.0.0/0"
  ip_protocol       = "tcp"
  port_range        = "80,8080"
  policy            = "accept"
}

# Create security group rule allow ssh request
resource "tencentcloud_security_group_rule" "ssh" {
  security_group_id = tencentcloud_security_group.default.id
  type              = "ingress"
  cidr_ip           = "0.0.0.0/0"
  ip_protocol       = "tcp"
  port_range        = "22"
  policy            = "accept"
}

(11)下载软件包

https://github.com/tencentcloudstack/terraform-provider-tencentcloud/releases

(12) 腾讯云查询地域和可用区

云服务器 地域和可用区-产品简介-文档中心-腾讯云 (tencent.com)

3.Windows使用Terraform?连接 tencentcloud

(1)验证版本

terraform -v 或 terraform --version

(2)创建主配置文件

main.tf

# Configure the TencentCloud Provider
provider "tencentcloud" {
  secret_id  = var.secret_id
  secret_key = var.secret_key
  region     = var.region
}

(3) 创建密钥配置文件

terraform.tfvars

secret_id = "XXXXX"
secret_key = "XXXXX"

(4)创建版本配置文件

versions.tf

terraform {
  required_providers {
    tencentcloud = {
      source  = "tencentcloudstack/tencentcloud"
      version = "1.81.69"
    }
  }
}

(5)创建变量配置文件

variables.tf

variable "secret_id" {
  type = string

}

variable "secret_key" {
  type = string
}

variable "region" {
  type      = string
  default   = "ap-nanjing"
  sensitive = true
}

(6)初始化

terraform init

(7)格式化代码

terraform fmt

(8)验证代码

terraform validate 

terraform validate -json

4.Windows给Terraform项目添加tencentcloud腾讯云COS?(实现代码与资源分离)

(1)修改主配置文件

main.tf ,添加如下代码

//获取用户的APP_ID
data "tencentcloud_user_info" "users" {}

output "app_id" {
  value = data.tencentcloud_user_info.users.app_id
}

(2)计划与预览

 terraform plan

成功拿到主账户id

(3)腾讯云开通COS服务

(4)修改主配置文件

main.tf ,添加如下代码

# bucket 需要加上主账号id
resource "tencentcloud_cos_bucket" "mycos" {
  bucket            = "tfbackend-${data.tencentcloud_user_info.users.app_id}"
  acl               = "private"
  versioning_enable = true
}

(5)计划与预览

 terraform plan

(6)申请资源

terraform apply

输入yes

(7)展示资源

terraform show

(8)登录腾讯云系统查看

存储桶

(9)创建后端存储配置文件

backend.tf

terraform {
  backend "cos" {
    secret_id = "XXXXX"
    secret_key = "XXXXX"
    region = "ap-nanjing"
    bucket = "tfbackend-1319237212"
    prefix = "global/backend"
  }
}

(10)?初始化

terraform init

yes ,系统上传配置文件到腾讯云COS

(11)登录腾讯云系统查看

①查看Bucket 列表

配置文件已上传

(12)创建输出配置文件

outputs.tf

output "bucket_name" {
  value = tencentcloud_cos_bucket.mycos.bucket
}

(13) 计划与预览

 terraform plan

成功拿到bucket的id

(14)查看项目目录

(15)删除项目配置文件

(16)再次查看项目目录

(17)查看版本

多了provider的仓库地址

terraform version

terraform -v

二、问题

1.?Windows?terraform 初始化失败

?(1)报错

(2)原因分析

国内用户在下载 Provider 时会遇到下载缓慢甚至下载失败的问题

(3)解决方法

Terraform CLI 自 0.13.2 版本起提供了设置网络镜像的功能。为解决以上问题,阿里云 Provider 提供了镜像服务以帮助国内用户快速下载。

① ?配置方案

创建.terraformrc 或terraform.rc配置文件,文件位置取决于主机的操作系统。
 
在 Windows 环境上,文件必须命名为terraform.rc,并放置在相关用户的%APPDATA%目录中。这个目录的物理位置取决于Windows 版本和系统配置;在 PowerShell 中使用 $env:APPDATA 可以找到其在系统上的位置。
 
在所有其他系统上,必须将该文件命名为.terraformrc,并直接放在相关用户的主目录中。
 
也可以使用TF_CLI_CONFIG_FILE环境变量指定 Terraform CLI 配置文件的位置,任何此类文件都应遵循命名模式*.tfrc。

?② 查看目录

echo $env:APPDATA

③ 进入目录

④在相关目录下创建terraform.rc文件

内容如下:

provider_installation {
  network_mirror {
    url = "https://mirrors.tencent.com/terraform/"
    // 限制只有腾讯云相关Provider, 从url中指定镜像源下载
    include = ["registry.terraform.io/tencentcloudstack/*"]   
  }
  direct {
    // 声明除了腾讯云相关Provider, 其它Provider依然从默认官方源下载
    exclude = ["registry.terraform.io/tencentcloudstack/*"]
  }
}

⑤ 成功

2.Terraform 预览资源失败

(1)报错

│ Error: [TencentCloudSDKError] Code=AuthFailure.UnauthorizedOperation, Message=You are not authorized to perform this operation. Check your CAM policies, and ensure that you are using the correct access keys. [[request id:c87b3e87-cec4-4909-95de-a240680cc207]you are not authorized to perform operation (cam:DescribeSubAccounts)
│ resource (*) has no permission
│ ], RequestId=c87b3e87-cec4-4909-95de-a240680cc207
│
│   with data.tencentcloud_user_info.users,
│   on main.tf line 9, in data "tencentcloud_user_info" "users":
│    9: data "tencentcloud_user_info" "users" {}

(2)原因分析

CAM权限不足。

(3)解决方法

CAM添加权限,添加AdministratorAccess?权限。

成功:

3. Terraform初始化后端配置失败

(1)报错

│ Error: Error inspecting states in the "local" backend:
│     GET https://tfbackend-1319237212.cos.ap-nanjing.myqcloud.com/?prefix=global/backend: 403 AccessDenied(Message: Access Denied., RequestId: NjViMDhlODVfY2Q5NTUzMWVfZTI1XzEwNmIxMGI=, TraceId: OGVmYzZiMmQzYjA2OWNhODk0NTRkMTBiOWVmMDAxODc0OWRkZjk0ZDM1NmI1M2E2MTRlY2MzZDhmNmI5MWI1OTBjYzE2MjAxN2M1MzJiOTdkZjMxMDVlYTZjN2FiMmI0ZjZmYzUxNDY4MmRmMTFjNjMyZjA4YjA1OTdjMDY0NmI=)
│
│ Prior to changing backends, Terraform inspects the source and destination
│ states to determine what kind of migration steps need to be taken, if any.
│ Terraform failed to load the states. The data in both the source and the
│ destination remain unmodified. Please resolve the above error and try again.

(2)原因分析

对象存储 访问 COS 时返回403错误码-故障处理-文档中心-腾讯云 (tencent.com)

匿名请求,向非公有读的对象发起不带签名的请求,会返回 "Access Denied."

(3)解决方法

后端配置文件添加密钥。

修改前:

?

修改后:

成功:

文章来源:https://blog.csdn.net/cronaldo91/article/details/135813965
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。