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 = 2memory_size    = 4
}data "alicloud_images" "default" {name_regex  = "^ubuntu"most_recent = trueowners      = "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-utilssudo yum-config-manager --add-repo https://rpm.releases.hashicorp.com/RHEL/hashicorp.reposudo yum -y install terraform

安装yum-utils

添加REPO

安装Terraform

(2)验证版本

terraform version

(3)开启命令行补全

terraform -install-autocomplete

(4)创建项目

mkdir terraformcd terraform/

(5)创建主配置文件

vim main.tf

  1 provider "alicloud" {2   access_key = var.access_key3   secret_key = var.secret_key4   region     = var.region5 }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.id16   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.id24   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          = 135   security_group_id = alicloud_security_group.group.id36   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          = 147   security_group_id = alicloud_security_group.group.id48   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

查看目录

lstree

(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        = stringdefault     = "cn-nanjing"
}# Configure the Alicloud Provider
provider "alicloud" {access_key = var.access_keysecret_key = var.secret_keyregion     = 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.idcidr_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.idsecurity_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          = 1security_group_id = alicloud_security_group.group.idcidr_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          = 1security_group_id = alicloud_security_group.group.idcidr_ip           = "0.0.0.0/0"
}

(3) 创建变量配置文件

terraform.tfvars

access_key = "XXXXX"
secret_key = "XXXXX"

(4)初始化

terraform init

(5)格式化代码

terraform fmt

(6)验证代码

terraform validate -jsonterraform validate 

(7)计划与预览

 terraform plan

(8)申请资源

terraform apply

输入yes

(9)展示资源

terraform show

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

VPC

安全组

入方向规则

(11)销毁资源

terraform destroy

输入yes

(12)查看版本

多了provider的仓库地址

terraform versionterraform -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 Terraformwould take to apply the current configuration. This command will notactually perform the planned actions.You can optionally save the plan to a file, which you can then pass tothe "apply" command to perform exactly the actions described in the plan.Plan Customization Options:The following options customize how Terraform will produce its plan. Youcan also use these options when you run "terraform apply" without passingit a saved plan, in order to plan and apply in a single command.-destroy            Select the "destroy" planning mode, which creates a planto destroy all objects currently managed by thisTerraform configuration instead of the usual behavior.-refresh-only       Select the "refresh only" planning mode, which checkswhether remote objects still match the outcome of themost recent Terraform apply but does not propose anyactions to undo any changes made outside of Terraform.-refresh=false      Skip checking for external changes to remote objectswhile creating the plan. This can potentially makeplanning faster, but at the expense of possibly planningagainst a stale record of the remote system state.-replace=resource   Force replacement of a particular resource instance usingits resource address. If the plan would've normallyproduced an update or no-op action for this instance,Terraform will plan to replace it instead. You can usethis 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 itsdependencies. You can use this option multiple times toinclude more than one object. This is for exceptionaluse only.-var 'foo=bar'      Set a value for one of the input variables in the rootmodule of the configuration. Use this option more thanonce to set more than one variable.-var-file=filename  Load variable values from the given file, in additionto the default files terraform.tfvars and *.auto.tfvars.Use this option more than once to include more than onevariables file.Other Options:-compact-warnings          If Terraform produces any warnings that are notaccompanied by errors, shows them in a more compactform 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 - Errored2 - Succeeded, there is a diff-generate-config-out=path  (Experimental) If import blocks are present inconfiguration, instructs Terraform to generate HCLfor any imported resources not already present. Theconfiguration is written to a new file at PATH,which must not already exist. Terraform may stillattempt 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. Thisis dangerous if others might concurrently runcommands 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 beused as input to the "apply" command.-parallelism=n             Limit the number of concurrent operations. Defaultsto 10.-state=statefile           A legacy option used for the local backend only.See the local backend's documentation for moreinformation.

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

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

相关文章

【LeetCode: 57. 插入区间+分类讨论+模拟】

🚀 算法题 🚀 🌲 算法刷题专栏 | 面试必备算法 | 面试高频算法 🍀 🌲 越难的东西,越要努力坚持,因为它具有很高的价值,算法就是这样✨ 🌲 作者简介:硕风和炜,…

blender 导入到 Marvelous Designer

1) 将模型的所有部分合并为一个单独的mesh 2) 先调整计量单位: 3)等比缩放,身高调整到180cm左右 4)应用当前scale 首先,选中你要修改的物体,然后按下Ctrl-A键,打开应用…

CSAPP - bomblab 作弊方式2: gdb jump 命令, 以及修改 jne 为 nop 指令

CSAPP - bomblab 作弊方式2: gdb jump 命令, 以及修改 jne 为 nop 指令 厌倦了在 gdb 中一步步顺序执行 bomb 可执行程序。为什么不能自行控制程序的执行呢?跳到特定的函数去执行,又或者把原本要执行的指令改掉,gdb 里…

【Machine Learning】Other Stuff

本笔记基于清华大学《机器学习》的课程讲义中有关机器学习的此前未提到的部分,基本为笔者在考试前一两天所作的Cheat Sheet。内容较多,并不详细,主要作为复习和记忆的资料。 Robust Machine Learning Attack: PGD max ⁡ δ ∈ Δ L o s s (…

linux环境下安装postgresql

PostgreSQL: Linux downloads (Red Hat family)postgresql官网 PostgreSQL: Linux downloads (Red Hat family) 环境: centos7 postgresql14 选择版本 执行启动命令 配置远程连接文件 vi /var/lib/pqsql/14/data/postgresql.conf 这里将listen_addresses值由lo…

力扣399. 除法求值

广度优先搜索 思路: 题目梳理 输入信息里包含 A / B val;输入一堆 A / B 需要求出它们的比值;以操作数为节点,构建权重图,节点对应了关联节点及其比值;可以进行简单的处理,将代数变量映射为整…

【位运算】【二分查找】【C++算法】100160价值和小于等于 K 的最大数字

作者推荐 【动态规划】【字符串】扰乱字符串 本文涉及的基础知识点 二分查找算法合集 位运算 LeetCode100160. 价值和小于等于 K 的最大数字 给你一个整数 k 和一个整数 x 。 令 s 为整数 num 的下标从1 开始的二进制表示。我们说一个整数 num 的 价值 是满足 i % x 0 且…

数据分析---SQL(3)

目录 IF和CASE WHEN的区别IF函数示例CASE WHEN示例如何求字段整体的标准差和均值什么是笛卡尔积笛卡尔积通常的使用场景是什么rank、dense rank、row number的区别rank函数示例dense rank函数示例row number函数示例什么是窗口函数除了rank之外还有哪些窗口函数IF和CASE WHEN的…

阿里云ingress配置时间超时的参数

一、背景 在使用阿里云k8s集群的时候,内网API网关,刚开始是用的是Nginx,后面又搭建了ingress。 区别于nginx配置,ingress又该怎么设置参数呢?比如http超时时间等等。 本文会先梳理nginx是如何配置,再对比…

优雅的删除链表元

王有志,一个分享硬核Java技术的互金摸鱼侠加入Java人的提桶跑路群:共同富裕的Java人 在数据结构:链表中,我们实现了链表的删除方法,但代码看起来并不“优雅”,那么今天我们就来尝试使用多种方法&#xff0c…

Halcon 3D相关算子(二)

(1) moments_object_model_3d( : : ObjectModel3D, MomentsToCalculate : Moments) 功能:计算3D对象模型的平均值或中心二阶矩。要计算3D物体模型点的平均值,在MomentsToCalculate中选择mean_points;如果要计算二阶中心矩,则选择…

windows安装conda环境,开发openai应用准备,运行第一个ai程序

文章目录 前言一、windows创建openai开发环境二、国内代理方式访问openai的方法(简单方法)三、测试运行第一个openai程序总结 前言 作者开发第一个openai应用的环境准备、第一个openai程序调用成功,做个记录,希望帮助新来的你。 …

如何处理Uniapp中的异步请求?

在Uniapp中处理异步请求有以下几种方法: 使用 uni.request 方法发送异步请求,该方法返回一个 Promise 对象,可以使用 then 方法处理请求成功的回调,使用 catch 方法处理请求失败的回调。 uni.request({url: http://api.example.…

鸿蒙系统ArkTs语法入门

鸿蒙系统ArkTs的ts语法入门 前言1. 变量声明2. 数据类型2.1 基本数据类型2.2 复杂数据类型2.3 联合类型2.4 空类型和未定义类型 3. 函数3.1 匿名函数和箭头函数 4. 类和接口类的访问权限接口类的继承内部类 7. 结构体参考材料 前言 每个语言都有控制流语句就不写测试代码了。a…

31 树的存储结构一

无法直接用数组表示树的逻辑结构,但是可以设计结构体数组对节点间的关系进行描述:【如表】 这样做的问题: 可以利用 组织链表 parent指针: 注意:树结点在 组织链表 中的位置不代表树的任何逻辑关系 树的架构图&#xf…

从0开始学Git指令(3)

从0开始学Git指令 因为网上的git文章优劣难评,大部分没有实操展示,所以打算自己从头整理一份完整的git实战教程,希望对大家能够起到帮助! 远程仓库 Git是分布式版本控制系统,同一个Git仓库,可以分布到不…

ubuntu主机开启ssh服务,ubuntu通过ssh访问主机

1.ubuntu通过ssh访问主机 要在Ubuntu上通过SSH(Secure Shell)访问另一台主机,您需要确保几件事情: 目标主机上的SSH服务器:确保您要访问的主机上安装并运行了SSH服务器(例如OpenSSH服务器)。 …

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

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

服务器出现500、502、503错误的原因以及解决方法

服务器我们经常会遇到访问不了的情况有的时候是因为我们服务器被入侵了所以访问不了&#xff0c;有的时候是因为出现了服务器配置问题&#xff0c;或者软硬件出现问题导致的无法访问的问题&#xff0c;这时候会出现500、502、503等错误代码。基于以上问题我们第一步可以先重启服…

Chapter 7 类和对象的特性(上篇)

目的&#xff1a;认识类&#xff0c;对面向对象产生认识 &#x1f4ca;&#x1f4ca;&#x1f4ca;&#x1f4ca;&#x1f4ca;&#x1f4ca;&#x1f4ca;&#x1f4ca;&#x1f4ca;&#x1f4ca;&#x1f4ca;&#x1f4ca;&#x1f4ca;&#x1f4ca;&#x1f4ca;&#x1…