IaC基础设施即代码:使用Terraform 连接 alicloud阿里云

news2025/2/25 11:57:00

目录

一、实验

1.环境

2.alicloud阿里云创建用户

3.Linux使用Terraform 连接 alicloud

4.Windows使用Terraform 连接 alicloud

二、问题

1.Windows如何申明RAM 相关变量

2.Linux如何申明RAM 相关变量

3. Linux terraform 初始化失败

4.Linux terraform 计划与预览失败

5. Windows terraform 初始化失败

6. Windows terraform plan命令有哪些参数


一、实验

1.环境

(1)主机

表1-1 主机

主机系统软件工具备注
jia

Windows 

Terraform 1.6.6VS Code、 PowerShell
pipepointLinuxTerraform 1.6.6 Chocolatey

2.alicloud阿里云创建用户

(1)登录

RAM 访问控制 (aliyun.com)

(2)查看

RAM访问控制-用户

(3)创建用户 

选中“OpenAPI调用访问”

(4)安全验证

(5)完成创建

(6)添加权限

(7)选择权限,搜索“VPC”

(8)选择权限,搜索“ECS”

(9)授权成功

(10)查看alicloud provider 示例

Terraform Registry

USE PROVIDER  示例

terraform {
  required_providers {
    alicloud = {
      source = "aliyun/alicloud"
      version = "1.214.1"
    }
  }
}

provider "alicloud" {
  # Configuration options
}

Example Usage  示例

# Configure the Alicloud Provider
provider "alicloud" {
  access_key = "${var.access_key}"
  secret_key = "${var.secret_key}"
  region     = "${var.region}"
}

data "alicloud_instance_types" "c2g4" {
  cpu_core_count = 2
  memory_size    = 4
}

data "alicloud_images" "default" {
  name_regex  = "^ubuntu"
  most_recent = true
  owners      = "system"
}

# Create a web server
resource "alicloud_instance" "web" {
  image_id             = "${data.alicloud_images.default.images.0.id}"
  internet_charge_type = "PayByBandwidth"

  instance_type        = "${data.alicloud_instance_types.c2g4.instance_types.0.id}"
  system_disk_category = "cloud_efficiency"
  security_groups      = ["${alicloud_security_group.default.id}"]
  instance_name        = "web"
  vswitch_id           = "vsw-abc12345"
}

# Create security group
resource "alicloud_security_group" "default" {
  name        = "default"
  description = "default"
  vpc_id      = "vpc-abc12345"
}

3.Linux使用Terraform 连接 alicloud

(1)安装

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

安装yum-utils

添加REPO

安装Terraform

(2)验证版本

terraform version

(3)开启命令行补全

terraform -install-autocomplete

(4)创建项目

mkdir terraform

cd terraform/

(5)创建主配置文件

vim main.tf

  1 provider "alicloud" {
  2   access_key = var.access_key
  3   secret_key = var.secret_key
  4   region     = var.region
  5 }
  6 
  7 //VPC 专有网络
  8 resource "alicloud_vpc" "vpc" {
  9   vpc_name   = "tf_test"
 10   cidr_block = "172.16.0.0/12"
 11 }
 12 
 13 //switch 交换机
 14 resource "alicloud_vswitch" "vsw" {
 15   vpc_id     = alicloud_vpc.vpc.id
 16   cidr_block = "172.16.0.0/21"
 17   zone_id    = "cn-nanjing-a"
 18 }
 19 
 20 //security_group 安全组
 21 resource "alicloud_security_group" "group" {
 22   name                = "demo-group"
 23   vpc_id              = alicloud_vpc.vpc.id
 24   security_group_type = "normal" //普通类型
 25 }
 26 
 27 //security_group_rule 规则(80端口)
 28 resource "alicloud_security_group_rule" "allow_80_tcp" {
 29   type              = "ingress"
 30   ip_protocol       = "tcp"
 31   nic_type          = "intranet"
 32   policy            = "accept"
 33   port_range        = "80/80"
 34   priority          = 1
 35   security_group_id = alicloud_security_group.group.id
 36   cidr_ip           = "0.0.0.0/0"
 37 }
 38 
 39 //security_group_rule 规则(22端口)
 40 resource "alicloud_security_group_rule" "allow_22_tcp" {
 41   type              = "ingress"
 42   ip_protocol       = "tcp"
 43   nic_type          = "intranet"
 44   policy            = "accept"
 45   port_range        = "22/22"
 46   priority          = 1
 47   security_group_id = alicloud_security_group.group.id
 48   cidr_ip           = "0.0.0.0/0"
 49 }

(6)创建变量配置文件

vim variables.tf

  1 variable "access_key" { type = string }
  2 
  3 variable "secret_key" { type = string }
  4 
  5 variable "region" { type = string }

(7)创建版本配置文件

vim versions.tf

  1 terraform {
  2   required_version = "1.6.6"
  3   required_providers {
  4     alicloud = {
  5       source  = "aliyun/alicloud"
  6       version = "1.214.1"
  7     }
  8   }
  9 }
 10 

(8)初始化

terraform init

(9)申明RAM相关变量

export TF_VAR_access_key="XXXXX"
export TF_VAR_secret_key="XXXXX"
export TF_VAR_region="cn-nanjing"

(9)格式化代码

terraform fmt

(10)验证代码

terraform validate -json

(11)计划与预览

 terraform plan

(12)申请资源

terraform apply

输入yes

查看目录

ls

tree

(13)展示资源

terraform show

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

VPC

安全组

入方向规则

(15)销毁资源

terraform destroy

ls

输入yes

查看目录

4.Windows使用Terraform 连接 alicloud

(1)验证版本

terraform -v 或 terraform --version

(2)创建主配置文件

main.tf

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

variable "access_key" {
  description = "access_key"

}

variable "secret_key" {
  description = "secret_key"
}

variable "region" {
  description = "阿里云地域"
  type        = string
  default     = "cn-nanjing"
}



# Configure the Alicloud Provider
provider "alicloud" {
  access_key = var.access_key
  secret_key = var.secret_key
  region     = var.region
}

//VPC 专有网络
resource "alicloud_vpc" "vpc" {
  vpc_name   = "tf_test"
  cidr_block = "172.16.0.0/12"
}

//switch 交换机
resource "alicloud_vswitch" "vsw" {
  vpc_id     = alicloud_vpc.vpc.id
  cidr_block = "172.16.0.0/21"
  zone_id    = "cn-nanjing-a"
}

//security_group 安全组
resource "alicloud_security_group" "group" {
  name                = "demo-group"
  vpc_id              = alicloud_vpc.vpc.id
  security_group_type = "normal" //普通类型
}

//security_group_rule 规则(80端口)
resource "alicloud_security_group_rule" "allow_80_tcp" {
  type              = "ingress"
  ip_protocol       = "tcp"
  nic_type          = "intranet"
  policy            = "accept"
  port_range        = "80/80"
  priority          = 1
  security_group_id = alicloud_security_group.group.id
  cidr_ip           = "0.0.0.0/0"
}

//security_group_rule 规则(22端口)
resource "alicloud_security_group_rule" "allow_22_tcp" {
  type              = "ingress"
  ip_protocol       = "tcp"
  nic_type          = "intranet"
  policy            = "accept"
  port_range        = "22/22"
  priority          = 1
  security_group_id = alicloud_security_group.group.id
  cidr_ip           = "0.0.0.0/0"
}

(3) 创建变量配置文件

terraform.tfvars

access_key = "XXXXX"
secret_key = "XXXXX"

(4)初始化

terraform init

(5)格式化代码

terraform fmt

(6)验证代码

terraform validate -json

terraform validate 

(7)计划与预览

 terraform plan

(8)申请资源

terraform apply

输入yes

(9)展示资源

terraform show

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

VPC

安全组

入方向规则

(11)销毁资源

terraform destroy

输入yes

(12)查看版本

多了provider的仓库地址

terraform version

terraform -v

二、问题

1.Windows如何申明RAM 相关变量

(1)申明 (仅测试)

setx  TF_VAR_access_key  XXXXX
setx  TF_VAR_secret_key  XXXXX
setx  TF_VAR_region  cn-nanjing

(2)查看

regedit

用户变量:
计算机\HKEY_CURRENT_USER\Environment

系统变量:
计算机\HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Control\Session Manager\Environment

注册应用表:

用户变量:

系统变量:

2.Linux如何申明RAM 相关变量

(1)申明

export TF_VAR_access_key="XXXXX"
export TF_VAR_secret_key="XXXXX"
export TF_VAR_region="cn-nanjing"

3. Linux 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。

②  在home目录下创建.terraformrc文件,内容如下

provider_installation {
  network_mirror {
    url = "https://mirrors.aliyun.com/terraform/"
    // 限制只有阿里云相关 Provider 从国内镜像源下载
    include = ["registry.terraform.io/aliyun/alicloud", 
               "registry.terraform.io/hashicorp/alicloud",
              ]   
  }
  direct {
    // 声明除了阿里云相关Provider, 其它Provider保持原有的下载链路
    exclude = ["registry.terraform.io/aliyun/alicloud", 
               "registry.terraform.io/hashicorp/alicloud",
              ]  
  }
}

③ 新增配置文件

vim .terraformrc
cd terraform/

④ 成功

4.Linux terraform 计划与预览失败

(1)报错

(2)原因分析

环境变量引用失败

(3)解决方法

重新申明变量

export TF_VAR_access_key="XXXXX"
export TF_VAR_secret_key="XXXXX"
export TF_VAR_region="cn-nanjing"

成功:

5. 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.aliyun.com/terraform/"
    // 限制只有阿里云相关 Provider 从国内镜像源下载
    include = ["registry.terraform.io/aliyun/alicloud", 
               "registry.terraform.io/hashicorp/alicloud",
              ]   
  }
  direct {
    // 声明除了阿里云相关Provider, 其它Provider保持原有的下载链路
    exclude = ["registry.terraform.io/aliyun/alicloud", 
               "registry.terraform.io/hashicorp/alicloud",
              ]  
  }
}

⑤ 成功

6. Windows terraform plan命令有哪些参数

(1)语法

PS C:\Gocode\src\TERRAFORM> terraform plan -help                       
Usage: terraform [global options] plan [options]

  Generates a speculative execution plan, showing what actions Terraform
  would take to apply the current configuration. This command will not
  actually perform the planned actions.

  You can optionally save the plan to a file, which you can then pass to
  the "apply" command to perform exactly the actions described in the plan.

Plan Customization Options:

  The following options customize how Terraform will produce its plan. You
  can also use these options when you run "terraform apply" without passing
  it a saved plan, in order to plan and apply in a single command.

  -destroy            Select the "destroy" planning mode, which creates a plan
                      to destroy all objects currently managed by this
                      Terraform configuration instead of the usual behavior.

  -refresh-only       Select the "refresh only" planning mode, which checks
                      whether remote objects still match the outcome of the
                      most recent Terraform apply but does not propose any
                      actions to undo any changes made outside of Terraform.

  -refresh=false      Skip checking for external changes to remote objects
                      while creating the plan. This can potentially make
                      planning faster, but at the expense of possibly planning
                      against a stale record of the remote system state.

  -replace=resource   Force replacement of a particular resource instance using
                      its resource address. If the plan would've normally
                      produced an update or no-op action for this instance,
                      Terraform will plan to replace it instead. You can use
                      this option multiple times to replace more than one object.

  -target=resource    Limit the planning operation to only the given module,
                      resource, or resource instance and all of its
                      dependencies. You can use this option multiple times to
                      include more than one object. This is for exceptional
                      use only.

  -var 'foo=bar'      Set a value for one of the input variables in the root
                      module of the configuration. Use this option more than
                      once to set more than one variable.

  -var-file=filename  Load variable values from the given file, in addition
                      to the default files terraform.tfvars and *.auto.tfvars.
                      Use this option more than once to include more than one
                      variables file.

Other Options:

  -compact-warnings          If Terraform produces any warnings that are not
                             accompanied by errors, shows them in a more compact
                             form that includes only the summary messages.

  -detailed-exitcode         Return detailed exit codes when the command exits.
                             This will change the meaning of exit codes to:
                             0 - Succeeded, diff is empty (no changes)
                             1 - Errored
                             2 - Succeeded, there is a diff

  -generate-config-out=path  (Experimental) If import blocks are present in
                             configuration, instructs Terraform to generate HCL
                             for any imported resources not already present. The
                             configuration is written to a new file at PATH,
                             which must not already exist. Terraform may still
                             attempt to write configuration if the plan errors.

  -input=true                Ask for input for variables if not directly set.

  -lock=false                Don't hold a state lock during the operation. This
                             is dangerous if others might concurrently run
                             commands against the same workspace.

  -lock-timeout=0s           Duration to retry a state lock.

  -no-color                  If specified, output won't contain any color.

  -out=path                  Write a plan file to the given path. This can be
                             used as input to the "apply" command.

  -parallelism=n             Limit the number of concurrent operations. Defaults
                             to 10.

  -state=statefile           A legacy option used for the local backend only.
                             See the local backend's documentation for more
                             information.

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1383209.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

[ACM算法学习] 诱导排序与 SA-IS算法

学习自诱导排序与SA-IS算法 - riteme.site 为了简化一些操作,定义 # 是字典序最小的字符,其字典序小于字母集里任意字符,并且将其默认作为每个字符串的最后一个字符,即作 S[|S|] SA-IS 算法 SA-IS 算法是基于诱导排序这种思想。…

React入门 - 06(TodoList 列表数据的新增和删除)

本章内容 目录 一、实践一下 React 的列表渲染二、TodoList 新增功能三、列表循环的 key四、删除 上一节内容我们完成了输入框中可以自由输入内容,这一节我们继续 TodoList功能的完善:列表数据的新增和删除。 在开始之前,我们先介绍一下 Re…

java实现教务管理系统

git地址:https://gitee.com/myshort-term/school-management 1.系统简介 开发教务管理系统程序,设计了ems(EMSApp)、dao(AssignmentDAO、CourseDAO、DeptDAO、ScoreDAO、UserDAO、EmailDAO)、domain&#…

优雅草蜻蜓API大数据服务中心v1.0.4更新-加入蓝奏云直链解析·每日Bing·字数统计·今日油价·历史上的今天等接口

2024年1月13日优雅草蜻蜓API大数据服务中心v1.0.4更新-加入蓝奏云直链解析每日Bing字数统计今日油价历史上的今天等接口 优雅草api服务-大数据中心自12月29日推出以来截止2024年1月13日累计被调用次数为413次,共收录23个接口,截止前一日2024年1月12日当…

一元二次方程虚数解

对一元二次方程axbxc0 (a≠0)&#xff1b;若判别式△b-4ac<0,则方程无实根,虚数解为&#xff1a;x(-b i√(4ac-b))/(2a)。 只含有一个未知数&#xff08;一元&#xff09;&#xff0c;并且未知数项的最高次数是2&#xff08;二次&#xff09;的整式方程叫做一元二次方程[1] …

SpringCloud:微服务

文章目录 微服务服务架构演变单例架构&#xff08;集中式架构&#xff09;分布式架构 微服务SpringCloud 微服务 服务架构演变 单例架构&#xff08;集中式架构&#xff09; 单例架构&#xff1a; 将业务的所有功能集中在一个项目中开发&#xff0c;打成一个包部署 优点&…

CSS基础笔记-05layout

CSS基础笔记系列 《CSS基础笔记-01CSS概述》《CSS基础笔记-02动画》《CSS基础笔记-03选择器》《CSS基础笔记-04cascade-specificity-inheritance》 文章目录 CSS基础笔记系列什么是CSS布局布局方法normal flowflexboxgridfloats 总结 什么是CSS布局 CSS布局是指在页面中对元素…

信息质量要求

目录 \quad 会计信息质量要求 会计核算的信息质量要求是对会计核算提供信息的基本要求,是处理具体会计业务的基本依据&#xff0c;是在会计核算前提条件制约下进行会计核算的标准和质量要求。 \quad \quad 可靠性 也就是真实性, 要求会计记录以实际凭证为依据如实反映财务状况和…

Compileflow工作流引擎使用讲解

文章目录 1 Compileflow1.1 简介1.2 特点1.3 Compileflow插件下载1.4 main方法调用1.4.1 pom.xml1.4.2 新建bpm文件1.4.3 各个节点绑定方法1.4.4 测试方法 1.5 bpm各个标签说明1.5.1 BPM根节点1.5.2 全局变量1.5.3 开始节点: start1.5.4 结束节点: end1.5.5 自动节点: autoTask…

关于Quartz远程调用服务方法失败如何解决,@Inner详细介绍

1.单独在要调用服务的controller写上相关方法&#xff08;Inner(value true)要走aop&#xff0c;会检测是否有内部调用标识&#xff09;具体见下述 2. 编写Feign远程调用的接口&#xff0c;注意加上RequestHeader(SecurityConstants.FROM) String from。因为inner(value true…

带你拿捏SpringBoot自动装配的核心技术?模块装配(@EnableXXX注解+@Import)+ 条件装配(@ConditionalXXX)

文章目录 Profile激活指定配置文件主配置文件中指定激活的profile命令行激活设置虚拟机参数激活 profile控制不到的地方 Spring原生的条件装配注解ConditionalConditional接口讲解案例讲解 Spring Boot封装的条件装配注解ConditionalXXX自己实现ConditionalOnBeanSpringBoot 源…

【目标检测】评价指标:mAP概念及其计算方法(yolo源码/pycocotools)

本篇文章首先介绍目标检测任务中的关键评价指标mAP的概念&#xff1b;然后介绍其在yolo源码和pycocotools工具中的实现方法&#xff1b;最后比较两种mAP的计算方法的不同之处。 目标检测中的评价指标&#xff1a; mAP概念及其计算方法(yolo源码/pycocotools) 混淆矩阵概念及其…

6.2 声音编辑工具GoldWave5简介(7)

6.2.5其它常用功能 1&#xff0e;高低通 把录制的语音和背景音乐融合在一起时&#xff0c;可能会出现背景音乐音量过大&#xff0c;语音音量过小的现象&#xff0c;这时可以选择“低通”将背景音乐的音量降低一些。 (1)选择【效果】|【波波器】|【低通/高通】命令&#xff0…

开箱即用的企业级前后端分离【.NET Core6.0 Api + Vue 2.x + RBAC】权限框架-Blog.Core

前言 今天要给大家推荐一个开箱即用的企业级前后端分离【.NET Core6.0 Api Vue 2.x RBAC】权限框架&#xff08;提高生产效率&#xff0c;快速开发就选它&#xff09;&#xff1a;Blog.Core。 推荐原因 Blog.Core通过详细的文章和视频讲解&#xff0c;将知识点各个击破&…

2024-1-12 关于SVPWM的理解疑问

直流母线电压利用率是指逆变电路&#xff08;电机控制器&#xff09;所能输出的交流电压基波最大幅值U1m和直流母线电压之比。 电压利用率 SVPWM算法理解&#xff08;二&#xff09;——关于非零基本矢量幅值和线电压幅值的解释 因此我们在实际应用中提供的直流侧电压Udc&…

ssm基于Web的课堂管理系统设计与实现论文

目 录 目 录 I 摘 要 III ABSTRACT IV 1 绪论 1 1.1 课题背景 1 1.2 研究现状 1 1.3 研究内容 2 2 系统开发环境 3 2.1 vue技术 3 2.2 JAVA技术 3 2.3 MYSQL数据库 3 2.4 B/S结构 4 2.5 SSM框架技术 4 3 系统分析 5 3.1 可行性分析 5 3.1.1 技术可行性 5 3.1.2 操作可行性 5 3…

【Linux】 系统目录结构

进入到根目录 cd /ls目录名具体作用/存放系统系统相关的目录文件/boot放置linux系统内核文件和启动时用到的一些引导文件/home包含linux系统上各用户的主目录&#xff0c;子目录名称默认以该用户名命名/root系统管理员root的家目录/bin包含常用的命令文件&#xff08;如ls 等&a…

STM32 CAN学习(一)

STM32 CAN CAN协议简介 CAN是控制器局域网络(Controller Area Network)的简称&#xff0c;它是由研发和生产汽车电子产品著称的德国BOSCH公司开发的&#xff0c;并最终成为国际标准&#xff08;ISO11519&#xff09;&#xff0c;是国际上应用最广泛的现场总线之一。CAN总线协…

Qat++,轻量级开源C++ Web框架

目录 一.简介 二.编译Oat 1.环境 2.编译/安装 三.试用 1.创建一个 CMake 项目 2.自定义客户端请求响应 3.将请求Router到服务器 4.用浏览器验证 一.简介 Oat是一个面向C的现代Web框架 官网地址&#xff1a;https://oatpp.io github地址&#xff1a;https://github.co…