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

目录

一、实验

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.

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

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

关于高通Android 平台上qssi的介绍

1. QSSI 是 Qualcomm Single System Image 的缩写。 2. Android Q上开始支持QSSI。 3. QSSI 是用来编译system.img的 3.1 QSSI编译注意事项 lunch qssi ------ 编译system.img lunch target ------ 编译其余的image 3.2 有QSSI和没有QSSI的编译流程对比 没有QS…

YOLOv5独家原创改进:多层次特征融合(SDI)结合PConv、DualConv、GSConv,实现二次创新 | UNet v2最新论文

💡💡💡本文独家改进:多层次特征融合(SDI)高效结合DualConv、PConv、GSConv等实现二次创新 1)替代原始的Concat; 收录 YOLOv5原创自研 https://blog.csdn.net/m0_63774211/category_12511931.html 💡💡💡全网独家首发创新(原创),适合paper !!! 💡�…

Docker运行RabbitMQ并使用SpringAMQP操作

文章目录 一、RabbitMQ运行二、整合SpringAMQP1. 引入依赖 三、测试1. 消费者2. 生产者3. 运行 一、RabbitMQ运行 拉取docker镜像 docker pull rabbitmq:3-management基础运行命令 docker run \-e RABBITMQ_DEFAULT_USERrabbitmq \-e RABBITMQ_DEFAULT_PASSrabbitmq \--name…

Vue3 如何使用移动端调试工具vConsole

1、安装 pnpm i vconsole2、在src/utils下新建vconsole.ts,写入以下代码 // 这是移动端控制台调试工具,需要调试就打开,不用就注释 import vConsole from vconsole const vconsole new vConsole()3、src/main.ts 引入,需要调试就打开,&…

数据结构学习之链式栈应用的案例(最小栈)

实例要求: 设计一个支持入栈、出栈、取栈顶元素等操作,并能在常数时间内检索到最小元素的栈; 实现 MinStack 类: MinStack* minStackCreate() 初始化堆栈对象,即建栈; void minStackPush(MinStack* obj, int val) …

DICE模型的原理与推导、碳循环与气候变化、政策评估、不确定性分析与代码分析

目录 专题一:DICE模型的原理与推导 专题二:碳循环与气候变化 专题三:政策评估 专题四:不确定性分析与代码分析 更多应用 随着温室气体排放量的增大和温室效应的增强,全球气候变化问题受到日益的关注。我国政府庄严…

Linux驱动学习—IIC总线之FT5X06触摸驱动实验

1、实现触摸坐标值上报 流程图&#xff1a; 设备树如下&#xff1a; 触摸设备对应的设备树节点是&#xff1a; 读取坐标的寄存器&#xff1a; #include <linux/init.h> #include <linux/module.h> #include <linux/i2c.h> #include <linux/gpio.h> #i…

【排序篇3】快速排序、归并排序

目录 一、快速排序1.1 递归1.2 非递归 二、归并排序2.1 递归2.2 非递归 一、快速排序 1.1 递归 快速排序的递归采用二叉树的前序遍历的思路&#xff0c;单趟排序先确定好一个元素的位置&#xff0c;然后往后递归再确定其他子区域内的某个元素的位置&#xff0c;直到只有一个元…

隧道应用4-内网穿透EW的简单使用

与netsh端口映射内网类似&#xff0c;也是通过跳板机实现 EW官网地址&#xff1a;http://rootkiter.com/EarthWorm EW 是一套便携式的网络穿透工具&#xff0c;具有 SOCKS v5服务架设和端口转发两大核心功能&#xff0c;可在复杂网络环境下完成网络穿透。 注&#xff1a; 考虑…

【洛谷千题详解】P7072 [CSP-J2020] 直播获奖

输入样例&#xff1a; 10 60 200 300 400 500 600 600 0 300 200 100 输出样例&#xff1a; 200 300 400 400 400 500 400 400 300 300 #include<bits/stdc.h> using namespace std; int main() {int n,w,s,a[605]{0};cin>>n>>w;for(int i1;i<n;i){sca…

P1179 [NOIP2010 普及组] 数字统计————C++

目录 [NOIP2010 普及组] 数字统计题目描述输入格式输出格式样例 #1样例输入 #1样例输出 #1 样例 #2样例输入 #2样例输出 #2 提示 解题思路Code1Code2运行结果 [NOIP2010 普及组] 数字统计 题目描述 请统计某个给定范围 [ L , R ] [L, R] [L,R] 的所有整数中&#xff0c;数字…

使用集群提交作业步骤

首先&#xff0c;先在terminal中创建脚本 vi job.slurmvi命令&#xff1a;打开文件 文本内容为&#xff1a; #!/bin/bash #sbatch -j test #作业名为test&#xff0c;可以自定义 #sbatch -w,--nodelist<Node1> #提交到节点1跑代码 #sbatch -o test.out #屏幕上的输出文…

java客户端连接redis并设置序列化处理

1、导入依赖 <!--继承父依赖--> <parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.3.12.RELEASE</version><relativePath/> <!-- lookup paren…

css深度选择器 /deep/

一、/deep/的含义和使用 /deep/ 是一种 CSS 深度选择器&#xff0c;也被称为深度组合器或者阴影穿透组合器&#xff0c;主要用在 Web 组件样式封装中。 在 Vue.js 或者 Angular 中&#xff0c;使用了样式封装技术使得组件的样式不会影响到全局&#xff0c;也就是说组件内部的…

【漏洞复现】大华 DSS 数字监控系统 itcBulletin SQL 注入

漏洞描述 大华 DSS存在SQL注入漏洞,攻击者 pota/services/itcBuletin 路由发送特殊构造的数据包,利用报错注入获取数据库敏感信息。攻击者除了可以利用 SQL注入漏词获取数据库中的信息例如,管理员后台密码、站点的用户人人信息)之外,甚至在高权限的情况可向服务器中写入木…

Echarts图表如何利用formatter自定义tooltip的内容和样式

在展示多数据图表的时候 有的时候需要图例也展示出一些内容来&#xff0c;例如官方这样子&#xff1a;鼠标悬停的时候展示该点数据 但是&#xff0c;官方提供的样式有时不适用所有的开发场景 我的项目需要实现鼠标悬停在某一点的时候&#xff0c;只展示该条线的数据&#xff0…

异常处理注解 @ExceptionHandler

今天记录下 SpringBoot 中 ExceptionHandler 的使用。 场景 有一个员工表(employee)&#xff0c;且给表中的 username 属性设置了唯一性。 -- auto-generated definition create table employee (id bigint auto_increment comment 主键primary key,name va…

C++STL

STL基本概念 standard template library : 标准模板库STL从广义上可以分为&#xff1a; 容器(container) 算法(algorithm) 迭代器(iterator)。 容器和算法之间通过迭代器进行无缝连接。 STL几乎所有的代码都采用了模板类或者模板函数STL六大组件 STL的容器 STL的容器就是将运…

uniapp滑动页面切换和下拉刷新,触底加载更多(swiper + scroll-view)

因为官方文档乱七八糟的&#xff0c;所以自己来总结下 需求&#xff1a; 常见的上方tag标签切换&#xff0c;下方是页面&#xff0c;上面点击切换&#xff0c;下面页面也切换&#xff0c;下方列表有下拉刷新&#xff0c;触底加载更多 因为这两个组件都是固定高度的&#xff0c;…

maven管理使用

maven基本使用 一、简介二、配置文件三、项目结构maven基本标签实践(例子) 四、pom插件配置五、热部署六、maven 外部手动加载jar打包方式Maven上传私服或者本地 一、简介 基于Ant 的构建工具,Ant 有的功能Maven 都有,额外添加了其他功能.本地仓库:计算机中一个文件夹,自己定义…