IaC基础设施即代码:Terraform 通过后端使用 alicloud的OSS 实现资源管理

发布时间:2024年01月16日

目录

一、实验

1.环境

2.Windows创建Terraform后端项目

3.Windows实例化Terraform后端项目

3.Windows给Terraform项目添加alicloud阿里云OSS (实现代码与资源分离)

4.Windows给Terraform项目添加封装的模块

5.Terraform通过后端使用 alicloud阿里云OSS 实现资源管理

二、问题

1.后端存储的锁机制如何实现

2.Terraform申请资源失败(NotEnoughBalance)

3.Terraform申请资源失败(ResourceNotAvailable)

4.Terraform初始资源失败(Backend configuration changed)

5.Terraform初始资源失败(provider)

6.Terraform删除资源失败(the instance name?)

7.?Terraform申请资源失败(Exists)

8. 阿里云Tablestore未开通

9.Terraform申请资源失败(AccessDenied)

10.阿里云OSS未开通

11.Terraform删除资源失败


一、实验

1.环境

(1)主机

表1-1 主机

主机系统软件工具备注
jia

Windows?

Terraform 1.6.6VS Code、?PowerShell、?Chocolatey
pipepointLinuxTerraform 1.6.6SSH

2.Windows创建Terraform后端项目

(1)创建项目

terraform-backend-dev

(2)创建目录envirments存放实例的配置文件

查看目录

(3)创建实例的主配置文件

main.tf

# Configure the Alicloud Provider 默认供应商
provider "alicloud" {
  access_key = var.access_key
  secret_key = var.secret_key
  region     = "cn-hangzhou"
}

# OSS
resource "alicloud_oss_bucket" "bucket-backenddev" {
  bucket = "tf-backenddev"
  acl    = "private"
}

#tablestore
resource "alicloud_ots_instance" "tftabledev" {
  name        = "tftabledev"
  description = "terraform tablestore"
  accessed_by = "Any"
  tags = {
    Created = "TF"
    For     = "Building table"
  }
}


resource "alicloud_ots_table" "basic" {
  instance_name                 = alicloud_ots_instance.tftabledev.name
  table_name                    = "tf_devops"
  time_to_live                  = -1
  max_version                   = 1
  deviation_cell_version_in_sec = 1

  primary_key {
    name = "LockID"
    type = "String"
  }
}

(3)创建实例的变量配置文件

variables.tf

variable "access_key" {
  description = "access_key"

}

variable "secret_key" {
  description = "secret_key"
}

variable "region" {
  type        = string
  description = "region name"
  default     = "cn-hangzhou"
  sensitive   = true
}

(4)创建实例的版本配置文件

terraform {
  required_version = "1.6.6"
  required_providers {
    alicloud = {
      source  = "hashicorp/alicloud"
      version = "1.214.1"
    }
  }
}

(5)?创建实例的输出配置文件

outputs.tf

output "bucket_name" {
  value = alicloud_oss_bucket.bucket-devops.bucket
}

output "table_name" {
  value = alicloud_ots_table.default.table_name
}

output "myecs_public_ip" {
  value = module.myecs.ecs_ip
}

(6)创建实例的密钥配置文件

terraform.tfvars

access_key = "XXXXX"
secret_key = "XXXXX"

3.Windows实例化Terraform后端项目

(1)初始化

terraform init

(2)格式化代码

terraform fmt
 
terraform fmt -recursive

(3)验证代码

terraform validate 

(4)计划与预览

 terraform plan

(5)申请资源

terraform apply

输入yes

(6)展示资源

terraform show

(10)登录阿里云系统查看

①查看Bucket 列表

②?查看Tablestore

确认公网信息

数据表列表

3.Windows给Terraform项目添加alicloud阿里云OSS (实现代码与资源分离)

(1)创建实例的后端配置文件

backend.tf

(2)初始化

terraform init

yes,系统上传配置文件到阿里云OSS


?

(3)查看目录

(4)登录阿里云系统查看

①查看Bucket 列表

配置文件已上传

②?查看Tablestore

数据详情

详情

(6)删除项目配置文件

?(5)申请资源

terraform apply

无资源变化

4.Windows给Terraform项目添加封装的模块

(1)添加模块modules

查看目录

(2)模块内容

内容与本人上一篇博客基本相同(参考)

IaC基础设施即代码:Terraform 通过模块封装实现 alicloud 资源管理-CSDN博客

单独修改地域为 cn-hangzhou,修改可用区为cn-hangzhou-j 。

(3)给dev主配置文件添加内容

查看目录

修改main.tf,添加如下内容

locals {
  region         = "cn-hangzhou-j"
  vpc_cidr_block = "172.16.0.0/12"
  vsw_cidr_block = "172.16.0.0/21"
  vpc_name       = "myvpc"
}

module "myvpc" {
  // 模块代码路径
  source         = "../../modules/vpc"
  vpc_cidr_block = local.vpc_cidr_block
  vsw_cidr_block = local.vsw_cidr_block
  vpc_name       = local.vpc_name
}

module "mysecgroup" {
  source = "../../modules/secgroup"
  //引用VPC模块的输出变量
  vpc_id = module.myvpc.vpc_id
}

module "myecs" {
  // 模块代码路径
  source = "../../modules/ecs"
  region = local.region
  //引用VPC模块的输出变量
  vsw_id      = module.myvpc.vsw_id
  secgroup_id = module.mysecgroup.secgroup_id
}

module "mydns" {
  source     = "../../modules/dns"
  dns_record = "maojing"
  ecs_ip     = module.myecs.ecs_ip
}

5.Terraform通过后端使用 alicloud阿里云OSS 实现资源管理

(1)?初始化

terraform init

(2)??计划与预览

 terraform plan

(3)?申请资源

terraform apply

yes

(4)登录阿里云系统查看

①查看ECS实例

②域名解析

③ 实例详情

④ 监控

⑤ 安全组

⑥云盘⑦弹性网卡

(5)远程登录实例

?① ?查看公网IP

② 远程连接

③ 立即登录

④ 登录实例

⑤ 登录成功

⑥查看IP

(12)远程操作实例

① ?Linux主机远程连接实例

 ssh root@118.178.240.67

② 给实例安装nginx

yum -y install nginx

③ 给实例启动服务并监听端口

systemctl start nginx

netstat -anlpt | grep 80

④ 解析域名

 dig maojing.maojing.site

(13)浏览器访问

①公网地址访问

http://118.178.240.67/

② 查看解析设置

③ 域名访问

http://maojing.maojing.site/

(14)销毁资源

terraform destroy

输入yes

Tablestore资源删除比较慢 (释放中)

用时大约8分钟完成删除

(15)查看项目完整目录

(16)登录阿里云系统查看

ECS实例已删除

Tablestore实例已删除

二、问题

1.后端存储的锁机制如何实现

(1)原理

(2)测试

terraform生产资源时另开一台终端进行生成资源,出现报错 Error acquiring the state lock,说明锁机制生效,限制1人操作apply去生成资源,当lockID 不存在时,才会在后端存储OSS写入配置文件。操作完成,释放lockID。

PS C:\Gocode\src\terraform-backend-dev\envirments\dev> terraform apply
?
│ Error: Error acquiring the state lock
│
│ Error message: invoking PutRow got an error: &tablestore.OtsError{Code:"OTSConditionCheckFail", Message:"Condition check failed.", RequestId:"00060f0d-9145-0e51-2d6e-280a01e05409"}
│ Lock Info:
│   ID:        734c1f77-fc30-20aa-7485-0961594e4829
│   Path:      tf-backenddev/dev/terraform-dev.tfstate
│   Operation: OperationTypeApply
│   Who:       DESKTOP-Q4AS5US\Jia@DESKTOP-Q4AS5US
│   Version:   1.6.6
│   Created:   2024-01-16 10:26:39.6694316 +0000 UTC
│   Info:
│
│
│ Terraform acquires a state lock to protect the state from being written
│ by multiple users at the same time. Please resolve the issue above and try
│ again. For most commands, you can disable locking with the "-lock=false"
│ flag, but this is not recommended.

2.Terraform申请资源失败(NotEnoughBalance)

(1)报错

│ Error: [ERROR] terraform-provider-alicloud/alicloud/resource_alicloud_instance.go:952: Resource alicloud_instance RunInstances Failed!!! [SDK alibaba-cloud-sdk-go ERROR]:
│ SDKError:
│    StatusCode: 403
│    Code: InvalidAccountStatus.NotEnoughBalance
│    Message: code: 403, Your account does not have enough balance. request id: 5835DFEE-E670-5993-8C32-7F5D90BD8D90
│    Data: {"Code":"InvalidAccountStatus.NotEnoughBalance","HostId":"ecs-unit-share.cn-hangzhou.aliyuncs.com","Message":"Your account does not have enough balance.","Recommend":"https://api.aliyun.com/troubleshoot?q=InvalidAccountStatus.NotEnoughBalance\u0026product=Ecs\u0026requestId=5835DFEE-E670-5993-8C32-7F5D90BD8D90","RequestId":"5835DFEE-E670-5993-8C32-7F5D90BD8D90"}
│
│
│   with module.myecs.alicloud_instance.myecs,
│   on ..\..\modules\ecs\main.tf line 17, in resource "alicloud_instance" "myecs":
│   17: resource "alicloud_instance" "myecs" {

(2)原因分析

https://api.aliyun.com/document/Ecs/2014-05-26/errorCode

(3)解决方法

① 通过计算最低成本补充余额

3.Terraform申请资源失败(ResourceNotAvailable)

(1)报错

│ Error: [ERROR] terraform-provider-alicloud/alicloud/resource_alicloud_vswitch.go:151: Resource alicloud_vswitch CreateVSwitch Failed!!! [SDK alibaba-cloud-sdk-go ERROR]:
│ SDKError:
│    StatusCode: 400
│    Code: ResourceNotAvailable
│    Message: code: 400, Resource you requested is not available in this region or zone. request id: B71C5B23-BC46-5A40-8958-75AE3A50F980
│    Data: {"Code":"ResourceNotAvailable","HostId":"vpc.aliyuncs.com","Message":"Resource you requested is not available in this region or zone.","Recommend":"https://api.aliyun.com/troubleshoot?q=ResourceNotAvailable\u0026product=Vpc\u0026requestId=B71C5B23-BC46-5A40-8958-75AE3A50F980","RequestId":"B71C5B23-BC46-5A40-8958-75AE3A50F980"}
│
│
│   with module.myvpc.alicloud_vswitch.vsw,
│   on ..\..\modules\vpc\main.tf line 8, in resource "alicloud_vswitch" "vsw":
│    8: resource "alicloud_vswitch" "vsw" {

(2)原因分析

选择的地域中,没有相应的VPC资源,即有可能这个地域中的VPC配置类型,没货或不存在。

(3)解决方法

因为Tablestore在杭州的region,所以查看杭州可用区(H 、I、J、K可用)

修改可用区为 hangzhou-j

4.Terraform初始资源失败(Backend configuration changed)

(1) 报错

│ Error: Backend configuration changed
│
│ A change in the backend configuration has been detected, which may require migrating existing state.
│
│ If you wish to attempt automatic migration of the state, use "terraform init -migrate-state".
│ If you wish to store the current configuration with no changes to the state, use "terraform init -reconfigure".

(2)原因分析

配置文件变更或移除

(3)解决方法

重新初始化

terraform init -reconfigure

5.Terraform初始资源失败(provider)

(1)报错

│ Error: Duplicate provider configuration
│
│   on main.tf line 40:
│   40: provider "alicloud" {
│
│ A default (non-aliased) provider configuration for "alicloud" was already given at main.tf:2,1-20. If multiple configurations are required, set the "alias" argument for alternative configurations.
?

(2)原因分析

系统只能有1个默认的供应商provider,其他同名的需要起别名?"alias"

(3)解决方法

起别名。

# Configure the Alicloud Provider 默认供应商
provider "alicloud" {
  access_key = var.access_key
  secret_key = var.secret_key
  region     = "cn-hangzhou"
}

provider "alicloud" {
  alias  = "nanjing"
  access_key = var.access_key
  secret_key = var.secret_key
  region     = "cn-nanjing"
}

6.Terraform删除资源失败(the instance name?)

(1)报错

│ Error: the instance name must consist of a~z, A~Z, 0~9 and a hyphen (-), the first character must be a letter and the last character cannot be a hyphen (-), the legal length range is 3~16 bytes
│ 
│   with alicloud_ots_instance.terraform_table,
│   on main.tf line 15, in resource "alicloud_ots_instance" "terraform_table":
│   15: resource "alicloud_ots_instance" "terraform_table" {
│
?
PS C:\Gocode\src\terraform-backend-demo\envirments\dev> terraform apply  
?
│ Error: the instance name must consist of a~z, A~Z, 0~9 and a hyphen (-), the first character must be a letter and the last character cannot be a hyphen (-), the legal length range is 3~16 bytes
│
│   with alicloud_ots_instance.terraform_table,
│   on main.tf line 15, in resource "alicloud_ots_instance" "terraform_table":
│   15: resource "alicloud_ots_instance" "terraform_table" {

(2)原因分析

实例名称不规范

(3)解决方法

按规范,修改实例名称。

7.?Terraform申请资源失败(Exists)

(1)报错

│ Error: [ERROR] terraform-provider-alicloud/alicloud/resource_alicloud_ots_instance.go:73:
│ [ERROR] terraform-provider-alicloud/alicloud/service_alicloud_ots.go:962: Resource tablestore /v2/openapi/createinstance Failed!!! [SDK alibaba-cloud-sdk-go ERROR]:
│ SDKError:
│    StatusCode: 409
│    Code: Exists
│    Message: code: 409, 资源已经存在 request id: 6763D7F0-BE22-5475-B92D-53D12798AA7A
│    Data: {"Code":"Exists","Message":"资源已经存在","RequestId":"6763D7F0-BE22-5475-B92D-53D12798AA7A","_headers":{"access-control-allow-origin":"*","access-control-expose-headers":"*","connection":"keep-alive","content-length":"99","content-type":"application/json;charset=utf-8","date":"Tue, 16 Jan 2024 05:50:35 GMT","keep-alive":"timeout=25","x-acs-request-id":"6763D7F0-BE22-5475-B92D-53D12798AA7A","x-acs-trace-id":"36ad93c4c65f1e4f12f6adcebdb4be3e"}}
│
│
│   with alicloud_ots_instance.tftable,
│   on main.tf line 15, in resource "alicloud_ots_instance" "tftable":
│   15: resource "alicloud_ots_instance" "tftable" {
│

(2)原因分析

"alicloud_ots_instance"? ots实例重名或名称不可用

(3)解决方法

修改ots实例名称。

8. 阿里云Tablestore未开通

(1)报错

(2)原因分析

需要开通服务。

(3)解决方法

开通服务

成功:

9.Terraform申请资源失败(AccessDenied)

(1)报错

(2)原因分析

官网:

如何通过RAM Policy为RAM用户授权_表格存储(Tablestore)-阿里云帮助中心 (aliyun.com)

RAM无OTS、OSS权限。

(3)解决方法

① RAM用户添加OTS、OSS权限。

搜索OTS

搜索OSS

授权成功

10.阿里云OSS未开通

(1)报错

(2)原因分析

需要开通服务。

(3)解决方法

开通服务

成功:

进入:

11.Terraform删除资源失败

(1)报错

│ Error: [ERROR] terraform-provider-alicloud/alicloud/resource_alicloud_oss_bucket.go:1703: Resource tf-backenddev DeleteBucket Failed!!! [SDK aliyun-oss-go-sdk ERROR]:
│ oss: service returned error: StatusCode=409, ErrorCode=BucketNotEmpty, ErrorMessage="The bucket has objects. Please delete them first.", RequestId=65A66A257CF84234346A2B88, Ec=0015-00000301
│
│
?
?
│ Error: Error releasing the state lock
│
│ Error message: failed to retrieve lock info: OTSAuthFailed The instance is not running. 00060f0e-a627-1dec-1c17-2a0a0222224d
│
│ Terraform acquires a lock when accessing your state to prevent others
│ running Terraform to potentially modify the state at the same time. An
│ error occurred while releasing this lock. This could mean that the lock
│ did or did not release properly. If the lock didn't release properly,
│ Terraform may not be able to run future commands since it'll appear as if
│ the lock is held.
│
│ In this scenario, please call the "force-unlock" command to unlock the
│ state manually. This is a very dangerous operation since if it is done
│ erroneously it could result in two people modifying state at the same time.
│ Only call this command if you're certain that the unlock above failed and
│ that no one else is holding a lock.

(2)原因分析

官网:

删除不再需要的存储空间以免产生额外费用_对象存储(OSS)-阿里云帮助中心 (aliyun.com)

未删除Bucket的所有文件(Object)

?(3)解决方法

① 删除所有文件(Object)

② 确定

③移除

④ 完成

⑤ 选中左侧列表最后的“删除Bucket”再点击右侧的“立即删除”

⑥ 确定删除

⑦ 删除成功

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