ToB企服应用市场:ToB评测及商务社交产业平台

标题: 史上最全 Terraform 入门教程,助你无坑入门! [打印本页]

作者: 瑞星    时间: 2024-10-28 13:13
标题: 史上最全 Terraform 入门教程,助你无坑入门!
在云盘算的浪潮中,底子设施管理变得越来越复杂。如何高效地配置和管理云资源,成为了每个开发者和运维工程师必须面临的挑战。Terraform,作为一种强大的底子设施即代码(IaC)工具,为我们提供了一种简便而有效的解决方案。
在这篇博客中,我将深入探究Terraform的功能与使用场景,资助你理解其在云资源管理中的紧张性。同时,我会详细先容Terraform的安装步骤,以便你能快速上手。
这篇博客特别适合入门级读者,内容细致易懂,确保即使是初学者也能顺利跟随。我将通过实际操作,使用Terraform在AWS上创建各种底子设施资源,包括VPC、子网、路由表、网关、安全组、EC2实例、EBS卷和弹性IP(EIP)。别的,我还将分享如何创建EKS的IAM脚色,定义EKS的Terraform配置文件,以及如何配置EKS Node Group的IAM脚色和节点组,一步一步创建EKS集群。
每个Terraform文件都将配有细致的表明,让你清晰理解每一行代码的意义和作用。无论你是云盘算新手照旧希望提拔技能的专业人士,这篇博客都将为你提供实用的指导和深入的见解,资助你轻松迈入Terraform的世界。让我们一起开始这段充满乐趣的学习之旅吧!
一、Terraform 简介

1. 特性与使用场景

Terraform 是一个开源的底子设施即代码(Infrastructure as Code, IaC)工具,由 HashiCorp 开发。它允许用户通过配置文件以编程方式管理云底子设施、物理设备以及其他服务的资源。以下是 Terraform 的一些关键特性和使用场景:
底子设施即代码

Terraform 使用简单的声明性配置语言(HCL,HashiCorp Configuration Language),使用户可以或许定义和管理他们的底子设施。这种方式带来了多个优势:
多云支持

Terraform 支持多种云服务提供商,包括 AWS、Azure、Google Cloud、阿里云等,用户可以在一个配置文件中同时管理不同云环境的资源。这种多云管理能力带来了如下好处:
状态管理

Terraform 会维护一个关于当前底子设施状态的文件(状态文件),以便在后续的变更中跟踪和管理资源的状态。状态管理的优势包括:
资源依靠管理

Terraform 可以或许自动处理资源之间的依靠关系,确保在创建或修改资源时,按照正确的顺序进行操作。这减少了手动处理依靠的复杂性,提高了自动化程度。详细来说:
可扩展性

Terraform 提供了丰富的插件和模块,用户可以通过自定义模块来扩展 Terraform 的功能,实现更复杂的底子设施架构。可扩展性的特点包括:
跨团队协作

Terraform 的配置文件可以与 Git 等版本控制系统团结使用,支持团队协作。团队协作的优势包括:
使用场景

总之,Terraform 是一个强大且机动的工具,可以或许资助开发团队以代码的方式高效管理云底子设施,提拔运维效率和机动性。通过 Terraform,用户可以或许在多云环境中实现自动化和尺度化,适应快速变化的业务需求。
2. Terraform 工作原理和工作流程

Terraform 是一个底子设施即代码(IaC)工具,通过以下几个步骤来管理底子设施:
通过这些步骤,Terraform 可以或许以一致性和可猜测的方式管理和部署底子设施,使用户在整个底子设施生命周期中保持对资源的控制和管理。
3. Terraform基本使用概念

3.1 Provider

3.2  Terraform状态文件

3.3 Terraform配置文件

3.4 变量文件

3.5 输出文件

二、环境准备

1. 安装 Terraform

请根据自己的操作系统参考 https://developer.hashicorp.com/terraform/install,本文之列出常见的操作系统安装方式。
macOS
  1. brew tap hashicorp/tap
  2. brew install hashicorp/tap/terraform
复制代码
Windows

https://releases.hashicorp.com/terraform/1.9.8/terraform_1.9.8_windows_amd64.zip
Ubuntu/Debian
  1. wget -O- https://apt.releases.hashicorp.com/gpg | sudo gpg --dearmor -o /usr/share/keyrings/hashicorp-archive-keyring.gpg
  2. echo "deb [signed-by=/usr/share/keyrings/hashicorp-archive-keyring.gpg] https://apt.releases.hashicorp.com $(lsb_release -cs) main" | sudo tee /etc/apt/sources.list.d/hashicorp.list
  3. sudo apt update && sudo apt install terraform
复制代码
CentOS/RHEL
  1. sudo yum install -y yum-utils
  2. sudo yum-config-manager --add-repo https://rpm.releases.hashicorp.com/RHEL/hashicorp.repo
  3. sudo yum -y install terraform
复制代码
2. 配置 AWS CLI

确保配置的访问密钥拥有足够的权限。
详情可参考:https://www.cnblogs.com/Sunzz/p/18432935
2.1. 创建~/.aws/config文件

内容如下:
  1. [default]
  2. region = us-west-1
复制代码
其中region请根据你的实际情况进行修改即可
2.2 创建 ~/.aws/credentials文件

内容如下:
  1. [default]
  2. aws_access_key_id = AKIA2LXD....
  3. aws_secret_access_key = ZvQllpYL.....
复制代码
转载请著名原文地址:https://www.cnblogs.com/Sunzz/p/18498915
3. 初始化terraform

3.1 创建variables.tf文件

variables.tf用来存多次用到的变量
内容如下:
  1. variable "aws_region" {
  2.   default = "us-west-1"
  3. }
复制代码
定义了使用的区域,这里使用us-west-1,请根据你的实际情况进行修改。
3.2 创建provider.tf 文件

配置定义了 Terraform 使用的 providers
  1. terraform {
  2.   required_providers {
  3.     aws = {
  4.       source  = "hashicorp/aws"
  5.       version = "~> 4.0"
  6.     }
  7.   }
  8. }
  9. provider "aws" {
  10.   region = var.aws_region
  11. }
复制代码
表明

3.3 初始化

初始化过程中会用到国外的一些网络资源,由于众所周知的原因,下载的时间可能出现一些问题,这里发起直接使用你的工具即可。
根据实际情况修改ip和端口
  1. export https_proxy=http://127.0.0.1:7890
  2. export http_proxy=http://127.0.0.1:7890
复制代码
  1. terraform init
复制代码
输出如下:
  1. Initializing the backend...
  2. Initializing provider plugins...
  3. - Finding hashicorp/aws versions matching ">= 4.0.0"...
  4. - Installing hashicorp/aws v5.72.1...
  5. - Installed hashicorp/aws v5.72.1 (signed by HashiCorp)
  6. Terraform has created a lock file .terraform.lock.hcl to record the provider
  7. selections it made above. Include this file in your version control repository
  8. so that Terraform can guarantee to make the same selections by default when
  9. you run "terraform init" in the future.
  10. Terraform has been successfully initialized!
  11. You may now begin working with Terraform. Try running "terraform plan" to see
  12. any changes that are required for your infrastructure. All Terraform commands
  13. should now work.
  14. If you ever set or change modules or backend configuration for Terraform,
  15. rerun this command to reinitialize your working directory. If you forget, other
  16. commands will detect it and remind you to do so if necessary.
复制代码
 
三、创建aws 网络资源

本文每次创建之前我都会先创建对应资源的tf文件,一种资源一个tf文件,好比所有的ec2都放在一个ec2.tf文件中。
然后都会执行 terraform plan -out=tf.plan 来预演一下执行结果,防止出错。
terraform plan -out=tf.plan 是一个“预演”工具。它不会真的去创建或改动资源,而是天生一个详细的计划,告诉我们“假如执行,会做哪些详细更改”。这个计划可以保存成一个文件(好比这里的 tf.plan),如许我们可以先检查它,确保没问题后,再真正去执行。这不仅减少了出错的时机,还让我们随时知道哪些资源会被创建、修改或删除。
1. 创建vpc

编写vpc.tf文件
  1. resource "aws_vpc" "tf_vpc" {
  2.   cidr_block = "10.10.0.0/16"
  3.   enable_dns_hostnames = true
  4.   enable_dns_support   = true
  5.   tags = {
  6.     Name = "tf-vpc"
  7.   }
  8. }
复制代码
表明:

预执行
  1. terraform plan -out=tf.plan
复制代码
terraform plan
  1.  terraform plan -out=tf.plan
  2. Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the
  3. following symbols:
  4.   + create
  5. Terraform will perform the following actions:
  6.   # aws_vpc.tf_vpc will be created
  7.   + resource "aws_vpc" "tf_vpc" {
  8.       + arn                                  = (known after apply)
  9.       + cidr_block                           = "10.10.0.0/16"
  10.       + default_network_acl_id               = (known after apply)
  11.       + default_route_table_id               = (known after apply)
  12.       + default_security_group_id            = (known after apply)
  13.       + dhcp_options_id                      = (known after apply)
  14.       + enable_dns_hostnames                 = true
  15.       + enable_dns_support                   = true
  16.       + enable_network_address_usage_metrics = (known after apply)
  17.       + id                                   = (known after apply)
  18.       + instance_tenancy                     = "default"
  19.       + ipv6_association_id                  = (known after apply)
  20.       + ipv6_cidr_block                      = (known after apply)
  21.       + ipv6_cidr_block_network_border_group = (known after apply)
  22.       + main_route_table_id                  = (known after apply)
  23.       + owner_id                             = (known after apply)
  24.       + tags                                 = {
  25.           + "Name" = "tf-vpc"
  26.         }
  27.       + tags_all                             = {
  28.           + "Name" = "tf-vpc"
  29.         }
  30.     }
  31. Plan: 1 to add, 0 to change, 0 to destroy.
  32. ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
  33. Saved the plan to: tf.plan
  34. To perform exactly these actions, run the following command to apply:
  35.     terraform apply "tf.plan"
复制代码
创建vpc
  1. terraform apply tf.plan
  2. aws_vpc.tf_vpc: Creating...
  3. aws_vpc.tf_vpc: Still creating... [10s elapsed]
  4. aws_vpc.tf_vpc: Creation complete after 13s [id=vpc-0f2e1cdca0cf5a306]
复制代码
转载请著名原文地址:https://www.cnblogs.com/Sunzz/p/18498915
2. 创建子网

新建变量

给variables.tf添加如下内容:
  1. variable "az_1" {
  2.   description = "Availability Zone for the first subnet"
  3.   type        = string
  4.   default     = "us-west-1a"
  5. }
  6. variable "az_2" {
  7.   description = "Availability Zone for the second subnet"
  8.   type        = string
  9.   default     = "us-west-1b"
  10. }
复制代码
表明:

variable "az_1/2":
定义子网配置的subnet.tf文件
  1. # 定义第一个子网 tf-subnet01 (10.10.1.0/24, 使用变量指定可用区)
  2. resource "aws_subnet" "tf_subnet01" {
  3.   vpc_id            = aws_vpc.tf_vpc.id
  4.   cidr_block        = "10.10.1.0/24"
  5.   availability_zone = var.az_1  # 使用变量代替硬编码的可用区
  6.   tags = {
  7.     Name = "tf-subnet01"
  8.   }
  9. }
  10. # 定义第二个子网 tf-subnet02 (10.10.2.0/24, 使用变量指定可用区)
  11. resource "aws_subnet" "tf_subnet02" {
  12.   vpc_id            = aws_vpc.tf_vpc.id
  13.   cidr_block        = "10.10.2.0/24"
  14.   availability_zone = var.az_2
  15.   tags = {
  16.     Name = "tf-subnet02"
  17.   }
  18. }
复制代码
表明:

预执行
  1. terraform plan -out=tf.plan
复制代码
terraform plan
  1.  terraform plan -out=tf.plan
  2. aws_vpc.tf_vpc: Refreshing state... [id=vpc-0f2e1cdca0cf5a306]
  3. Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the
  4. following symbols:
  5.   + create
  6. Terraform will perform the following actions:
  7.   # aws_subnet.tf_subnet01 will be created
  8.   + resource "aws_subnet" "tf_subnet01" {
  9.       + arn                                            = (known after apply)
  10.       + assign_ipv6_address_on_creation                = false
  11.       + availability_zone                              = "us-west-1a"
  12.       + availability_zone_id                           = (known after apply)
  13.       + cidr_block                                     = "10.10.1.0/24"
  14.       + enable_dns64                                   = false
  15.       + enable_resource_name_dns_a_record_on_launch    = false
  16.       + enable_resource_name_dns_aaaa_record_on_launch = false
  17.       + id                                             = (known after apply)
  18.       + ipv6_cidr_block_association_id                 = (known after apply)
  19.       + ipv6_native                                    = false
  20.       + map_public_ip_on_launch                        = false
  21.       + owner_id                                       = (known after apply)
  22.       + private_dns_hostname_type_on_launch            = (known after apply)
  23.       + tags                                           = {
  24.           + "Name" = "tf-subnet01"
  25.         }
  26.       + tags_all                                       = {
  27.           + "Name" = "tf-subnet01"
  28.         }
  29.       + vpc_id                                         = "vpc-0f2e1cdca0cf5a306"
  30.     }
  31.   # aws_subnet.tf_subnet02 will be created
  32.   + resource "aws_subnet" "tf_subnet02" {
  33.       + arn                                            = (known after apply)
  34.       + assign_ipv6_address_on_creation                = false
  35.       + availability_zone                              = "us-west-1b"
  36.       + availability_zone_id                           = (known after apply)
  37.       + cidr_block                                     = "10.10.2.0/24"
  38.       + enable_dns64                                   = false
  39.       + enable_resource_name_dns_a_record_on_launch    = false
  40.       + enable_resource_name_dns_aaaa_record_on_launch = false
  41.       + id                                             = (known after apply)
  42.       + ipv6_cidr_block_association_id                 = (known after apply)
  43.       + ipv6_native                                    = false
  44.       + map_public_ip_on_launch                        = false
  45.       + owner_id                                       = (known after apply)
  46.       + private_dns_hostname_type_on_launch            = (known after apply)
  47.       + tags                                           = {
  48.           + "Name" = "tf-subnet02"
  49.         }
  50.       + tags_all                                       = {
  51.           + "Name" = "tf-subnet02"
  52.         }
  53.       + vpc_id                                         = "vpc-0f2e1cdca0cf5a306"
  54.     }
  55. Plan: 2 to add, 0 to change, 0 to destroy.
  56. ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
  57. Saved the plan to: tf.plan
  58. To perform exactly these actions, run the following command to apply:
  59.     terraform apply "tf.plan"
复制代码
创建子网
  1. terraform apply "tf.plan"
复制代码
  1. terraform apply "tf.plan"
  2. aws_subnet.tf_subnet01: Creating...
  3. aws_subnet.tf_subnet02: Creating...
  4. aws_subnet.tf_subnet01: Creation complete after 2s [id=subnet-08f8e4b2c62e27989]
  5. aws_subnet.tf_subnet02: Creation complete after 2s [id=subnet-019490723ad3e940a]
  6. Apply complete! Resources: 2 added, 0 changed, 0 destroyed.
复制代码
3.创建网关

创建定义网关的internet_gateway.tf文件
  1. resource "aws_internet_gateway" "tf_igw" {
  2.   vpc_id = aws_vpc.tf_vpc.id
  3.   tags = {
  4.     Name = "tf-igw"
  5.   }
  6. }
复制代码
表明

预执行
  1. terraform plan -out=tf.plan
复制代码
tf plan
  1.  Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the
  2. following symbols:
  3.   + create
  4. Terraform will perform the following actions:
  5.   # aws_internet_gateway.tf_igw will be created
  6.   + resource "aws_internet_gateway" "tf_igw" {
  7.       + arn      = (known after apply)
  8.       + id       = (known after apply)
  9.       + owner_id = (known after apply)
  10.       + tags     = {
  11.           + "Name" = "tf-igw"
  12.         }
  13.       + tags_all = {
  14.           + "Name" = "tf-igw"
  15.         }
  16.       + vpc_id   = "vpc-0f2e1cdca0cf5a306"
  17.     }
  18. Plan: 1 to add, 0 to change, 0 to destroy.
  19. ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
  20. Saved the plan to: tf.plan
  21. To perform exactly these actions, run the following command to apply:
  22.     terraform apply "tf.plan"
复制代码
执行创建网关
  1. terraform apply "tf.plan"
复制代码
输出如下:
  1. aws_internet_gateway.tf_igw: Creating...
  2. aws_internet_gateway.tf_igw: Creation complete after 2s [id=igw-08ec2f3357e8725df]
  3. Apply complete! Resources: 1 added, 0 changed, 0 destroyed.
复制代码
4. 创建路由表

定义route_table.tf
  1. resource "aws_route_table" "tf_route_table" {
  2.   vpc_id = aws_vpc.tf_vpc.id
  3.   route {
  4.     cidr_block = "0.0.0.0/0"
  5.     gateway_id = aws_internet_gateway.tf_igw.id
  6.   }
  7.   tags = {
  8.     Name = "tf-route-table"
  9.   }
  10. }
复制代码
表明

预执行创建路由表

terraform plan
  1.  terraform plan -out=tf.plan
  2. Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the
  3. following symbols:
  4.   + create
  5. Terraform will perform the following actions:
  6.   # aws_route_table.tf_route_table will be created
  7.   + resource "aws_route_table" "tf_route_table" {
  8.       + arn              = (known after apply)
  9.       + id               = (known after apply)
  10.       + owner_id         = (known after apply)
  11.       + propagating_vgws = (known after apply)
  12.       + route            = [
  13.           + {
  14.               + cidr_block                 = "0.0.0.0/0"
  15.               + gateway_id                 = "igw-08ec2f3357e8725df"
  16.                 # (12 unchanged attributes hidden)
  17.             },
  18.         ]
  19.       + tags             = {
  20.           + "Name" = "tf-route-table"
  21.         }
  22.       + tags_all         = {
  23.           + "Name" = "tf-route-table"
  24.         }
  25.       + vpc_id           = "vpc-0f2e1cdca0cf5a306"
  26.     }
  27. Plan: 1 to add, 0 to change, 0 to destroy.
  28. ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
  29. Saved the plan to: tf.plan
  30. To perform exactly these actions, run the following command to apply:
  31.     terraform apply "tf.plan"
复制代码
执行创建路由表
  1. terraform apply "tf.plan"
复制代码
输出如下:
  1. aws_route_table.tf_route_table: Creating...
  2. aws_route_table.tf_route_table: Creation complete after 3s [id=rtb-0ae4b29ae8d6881ed]
  3. Apply complete! Resources: 1 added, 0 changed, 0 destroyed.
复制代码
5. 关联路由表和子网

创建route_table_association.tf
  1. # 关联子网和路由表
  2. resource "aws_route_table_association" "tf_route_table_association_01" {
  3.   subnet_id      = aws_subnet.tf_subnet01.id
  4.   route_table_id = aws_route_table.tf_route_table.id
  5. }
  6. resource "aws_route_table_association" "tf_route_table_association_02" {
  7.   subnet_id      = aws_subnet.tf_subnet02.id
  8.   route_table_id = aws_route_table.tf_route_table.id
  9. }
复制代码
表明

预执行 terraform plan -out=tf.plan

检察代码
  1.   terraform plan -out=tf.plan
  2.   
  3. Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the
  4. following symbols:
  5.   + create
  6. Terraform will perform the following actions:
  7.   # aws_route_table_association.tf_route_table_association_01 will be created
  8.   + resource "aws_route_table_association" "tf_route_table_association_01" {
  9.       + id             = (known after apply)
  10.       + route_table_id = "rtb-0ae4b29ae8d6881ed"
  11.       + subnet_id      = "subnet-08f8e4b2c62e27989"
  12.     }
  13.   # aws_route_table_association.tf_route_table_association_02 will be created
  14.   + resource "aws_route_table_association" "tf_route_table_association_02" {
  15.       + id             = (known after apply)
  16.       + route_table_id = "rtb-0ae4b29ae8d6881ed"
  17.       + subnet_id      = "subnet-019490723ad3e940a"
  18.     }
  19. Plan: 2 to add, 0 to change, 0 to destroy.
  20. ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
  21. Saved the plan to: tf.plan
  22. To perform exactly these actions, run the following command to apply:
  23.     terraform apply "tf.plan"
  24. 转载请著名原文地址:https://www.cnblogs.com/Sunzz/p/18498915
复制代码
执行关联
  1. terraform apply "tf.plan"
复制代码
输出如下:
  1. aws_route_table_association.tf_route_table_association_01: Creating...
  2. aws_route_table_association.tf_route_table_association_02: Creating...
  3. aws_route_table_association.tf_route_table_association_01: Creation complete after 1s [id=rtbassoc-0999e44cc1cfb7f09]
  4. aws_route_table_association.tf_route_table_association_02: Creation complete after 1s [id=rtbassoc-0190cb61bd5850d86]
  5. Apply complete! Resources: 2 added, 0 changed, 0 destroyed.
复制代码
四、创建ec2

1. 创建密钥对

天生密钥对
  1. ssh-keygen -t rsa -b 4096 -f ~/.ssh/tf-keypair
复制代码
创建key_pair.tf文件
  1. resource "aws_key_pair" "tf-keypair" {
  2.   key_name   = "tf-keypair"
  3.   public_key = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQC42p8Ly5xXtaQPbBoKiVVSuU0HKhK38I5DtPhijhZrVZmhRpW5yD6pbCXmFLnIFTFNb....."
  4. }
复制代码
表明:
预执行
  1. terraform plan -out=tf.plan
复制代码
terraform plan
  1.  terraform plan -out=tf.plan
  2. aws_vpc.tf_vpc: Refreshing state... [id=vpc-0f2e1cdca0cf5a306]
  3. aws_subnet.tf_subnet01: Refreshing state... [id=subnet-08f8e4b2c62e27989]
  4. aws_subnet.tf_subnet02: Refreshing state... [id=subnet-019490723ad3e940a]
  5. Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the
  6. following symbols:
  7.   + create
  8. Terraform will perform the following actions:
  9.   # aws_key_pair.tf-keypair will be created
  10.   + resource "aws_key_pair" "tf-keypair" {
  11.       + arn             = (known after apply)
  12.       + fingerprint     = (known after apply)
  13.       + id              = (known after apply)
  14.       + key_name        = "tf-keypair"
  15.       + key_name_prefix = (known after apply)
  16.       + key_pair_id     = (known after apply)
  17.       + key_type        = (known after apply)
  18.       + public_key      = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQC42p8Ly5xXtaQPbBoKiVVSuU0HKhK38ua0arfBYQF++/QFRJZ7+/fmeES7P0+//+vKjWnwdf67BIu0RyoA+MFpztYn58hDKdAmSeEXCpp4cOojgFmgnf1+p3MdaOvnT379YT....."
  19.       + tags_all        = (known after apply)
  20.     }
  21. Plan: 1 to add, 0 to change, 0 to destroy.
  22. ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
  23. Saved the plan to: tf.plan
  24. To perform exactly these actions, run the following command to apply:
  25.     terraform apply "tf.plan"
复制代码
执行创建密钥对
  1. terraform apply "tf.plan"
复制代码
结果如下:
  1. aws_key_pair.tf-keypair: Creating...
  2. aws_key_pair.tf-keypair: Creation complete after 1s [id=tf-keypair]
  3. Apply complete! Resources: 1 added, 0 changed, 0 destroyed.
复制代码
2.创建安全组

创建security_group.tf文件
  1. resource "aws_security_group" "tf_security_group" {
  2.   name        = "tf-security-group"
  3.   description = "Security group for allowing specific inbound traffic"
  4.   vpc_id      = aws_vpc.tf_vpc.id
  5.   # ICMP (ping) 入站规则
  6.   ingress {
  7.     from_port   = -1
  8.     to_port     = -1
  9.     protocol    = "icmp"
  10.     cidr_blocks = ["0.0.0.0/0"]
  11.     description = "Allow ICMP (ping) traffic"
  12.   }
  13.   # SSH (22) 入站规则
  14.   ingress {
  15.     from_port   = 22
  16.     to_port     = 22
  17.     protocol    = "tcp"
  18.     cidr_blocks = ["0.0.0.0/0"]
  19.     description = "Allow SSH traffic"
  20.   }
  21.   # HTTP (80) 入站规则
  22.   ingress {
  23.     from_port   = 80
  24.     to_port     = 80
  25.     protocol    = "tcp"
  26.     cidr_blocks = ["0.0.0.0/0"]
  27.     description = "Allow HTTP traffic"
  28.   }
  29.   # HTTPS (443) 入站规则
  30.   ingress {
  31.     from_port   = 443
  32.     to_port     = 443
  33.     protocol    = "tcp"
  34.     cidr_blocks = ["0.0.0.0/0"]
  35.     description = "Allow HTTPS traffic"
  36.   }
  37.   # 默认出站规则:允许所有出站流量
  38.   egress {
  39.     from_port   = 0
  40.     to_port     = 0
  41.     protocol    = "-1"
  42.     cidr_blocks = ["0.0.0.0/0"]
  43.     description = "Allow all outbound traffic"
  44.   }
  45.   tags = {
  46.     Name = "tf-security-group"
  47.   }
  48. }
复制代码
表明
预执行
  1. terraform plan -out=tf.plan
复制代码
terraform plan
  1.  terraform plan -out=tf.plan
  2. aws_key_pair.tf-keypair: Refreshing state... [id=tf-keypair]
  3. aws_vpc.tf_vpc: Refreshing state... [id=vpc-0f2e1cdca0cf5a306]
  4. aws_subnet.tf_subnet01: Refreshing state... [id=subnet-08f8e4b2c62e27989]
  5. aws_subnet.tf_subnet02: Refreshing state... [id=subnet-019490723ad3e940a]
  6. Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the
  7. following symbols:
  8.   + create
  9. Terraform will perform the following actions:
  10.   # aws_security_group.tf_security_group will be created
  11.   + resource "aws_security_group" "tf_security_group" {
  12.       + arn                    = (known after apply)
  13.       + description            = "Security group for allowing specific inbound traffic"
  14.       + egress                 = [
  15.           + {
  16.               + cidr_blocks      = [
  17.                   + "0.0.0.0/0",
  18.                 ]
  19.               + description      = "Allow all outbound traffic"
  20.               + from_port        = 0
  21.               + ipv6_cidr_blocks = []
  22.               + prefix_list_ids  = []
  23.               + protocol         = "-1"
  24.               + security_groups  = []
  25.               + self             = false
  26.               + to_port          = 0
  27.             },
  28.         ]
  29.       + id                     = (known after apply)
  30.       + ingress                = [
  31.           + {
  32.               + cidr_blocks      = [
  33.                   + "0.0.0.0/0",
  34.                 ]
  35.               + description      = "Allow HTTP traffic"
  36.               + from_port        = 80
  37.               + ipv6_cidr_blocks = []
  38.               + prefix_list_ids  = []
  39.               + protocol         = "tcp"
  40.               + security_groups  = []
  41.               + self             = false
  42.               + to_port          = 80
  43.             },
  44.           + {
  45.               + cidr_blocks      = [
  46.                   + "0.0.0.0/0",
  47.                 ]
  48.               + description      = "Allow HTTPS traffic"
  49.               + from_port        = 443
  50.               + ipv6_cidr_blocks = []
  51.               + prefix_list_ids  = []
  52.               + protocol         = "tcp"
  53.               + security_groups  = []
  54.               + self             = false
  55.               + to_port          = 443
  56.             },
  57.           + {
  58.               + cidr_blocks      = [
  59.                   + "0.0.0.0/0",
  60.                 ]
  61.               + description      = "Allow ICMP (ping) traffic"
  62.               + from_port        = -1
  63.               + ipv6_cidr_blocks = []
  64.               + prefix_list_ids  = []
  65.               + protocol         = "icmp"
  66.               + security_groups  = []
  67.               + self             = false
  68.               + to_port          = -1
  69.             },
  70.           + {
  71.               + cidr_blocks      = [
  72.                   + "0.0.0.0/0",
  73.                 ]
  74.               + description      = "Allow SSH traffic"
  75.               + from_port        = 22
  76.               + ipv6_cidr_blocks = []
  77.               + prefix_list_ids  = []
  78.               + protocol         = "tcp"
  79.               + security_groups  = []
  80.               + self             = false
  81.               + to_port          = 22
  82.             },
  83.         ]
  84.       + name                   = "tf-security-group"
  85.       + name_prefix            = (known after apply)
  86.       + owner_id               = (known after apply)
  87.       + revoke_rules_on_delete = false
  88.       + tags                   = {
  89.           + "Name" = "tf-security-group"
  90.         }
  91.       + tags_all               = {
  92.           + "Name" = "tf-security-group"
  93.         }
  94.       + vpc_id                 = "vpc-0f2e1cdca0cf5a306"
  95.     }
  96. Plan: 1 to add, 0 to change, 0 to destroy.
  97. ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
  98. Saved the plan to: tf.plan
  99. To perform exactly these actions, run the following command to apply:
  100.     terraform apply "tf.plan"
复制代码
执行创建安全组
  1. terraform apply "tf.plan"
复制代码
输出如下:
  1. terraform apply "tf.plan"
  2. aws_security_group.tf_security_group: Creating...
  3. aws_security_group.tf_security_group: Creation complete after 5s [id=sg-0907b4ae2d4bd9592]
  4. Apply complete! Resources: 1 added, 0 changed, 0 destroyed.
复制代码
3.创建ec2

先定义ami内容,方便后边作用变量直接使用,编辑variables.tf新增如下内容。这里使用了amazon linux和ubuntu 24.04的镜像
修改variables.tf
  1. variable "amazon_linux_ami" {
  2.   description = "AMI ID for Amazon Linux"
  3.   type        = string
  4.   default     = "ami-0cf4e1fcfd8494d5b"  # 替换为你的Amazon Linux AMI ID
  5. }
  6. variable "ubuntu_ami" {
  7.   description = "AMI ID for Ubuntu"
  8.   type        = string
  9.   default     = "ami-0da424eb883458071"  # 替换为你的Ubuntu 24.04 AMI ID
  10. }
复制代码
创建ec2.tf文件
  1. # 第一个 EC2 实例
  2. resource "aws_instance" "tf-ec2-01" {
  3.   ami           = var.amazon_linux_ami
  4.   instance_type = "t2.micro"
  5.   subnet_id     = aws_subnet.tf_subnet01.id
  6.   key_name      = aws_key_pair.tf-keypair.key_name
  7.   vpc_security_group_ids = [aws_security_group.tf_security_group.id]
  8.   root_block_device {
  9.     volume_size = 10
  10.   }
  11.   tags = {
  12.     Name = "tf-ec2-01"
  13.   }
  14. }
  15. # 第二个 EC2 实例
  16. resource "aws_instance" "tf-ec2-02" {
  17.   ami           = var.ubuntu_ami
  18.   instance_type = "t2.micro"
  19.   subnet_id     = aws_subnet.tf_subnet02.id
  20.   key_name      = aws_key_pair.tf-keypair.key_name
  21.   vpc_security_group_ids = [aws_security_group.tf_security_group.id]
  22.   root_block_device {
  23.     volume_size = 10
  24.   }
  25.   tags = {
  26.     Name = "tf-ec2-02"
  27.   }
  28. }
复制代码
配置阐明

转载请著名原文地址:https://www.cnblogs.com/Sunzz/p/18498915
预执行
  1. terraform plan -out=tf.plan
复制代码
terraform plan
  1. terraform plan -out=tf.plan
  2. aws_key_pair.tf-keypair: Refreshing state... [id=tf-keypair]
  3. aws_vpc.tf_vpc: Refreshing state... [id=vpc-0f2e1cdca0cf5a306]
  4. aws_subnet.tf_subnet02: Refreshing state... [id=subnet-019490723ad3e940a]
  5. aws_subnet.tf_subnet01: Refreshing state... [id=subnet-08f8e4b2c62e27989]
  6. aws_security_group.tf_security_group: Refreshing state... [id=sg-0907b4ae2d4bd9592]
  7. Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the
  8. following symbols:
  9.   + create
  10. Terraform will perform the following actions:
  11.   # aws_instance.tf-ec2-01 will be created
  12.   + resource "aws_instance" "tf-ec2-01" {
  13.       + ami                                  = "ami-0cf4e1fcfd8494d5b"
  14.       + arn                                  = (known after apply)
  15.       + associate_public_ip_address          = (known after apply)
  16.       + availability_zone                    = (known after apply)
  17.       + cpu_core_count                       = (known after apply)
  18.       + cpu_threads_per_core                 = (known after apply)
  19.       + disable_api_stop                     = (known after apply)
  20.       + disable_api_termination              = (known after apply)
  21.       + ebs_optimized                        = (known after apply)
  22.       + get_password_data                    = false
  23.       + host_id                              = (known after apply)
  24.       + host_resource_group_arn              = (known after apply)
  25.       + iam_instance_profile                 = (known after apply)
  26.       + id                                   = (known after apply)
  27.       + instance_initiated_shutdown_behavior = (known after apply)
  28.       + instance_state                       = (known after apply)
  29.       + instance_type                        = "t2.micro"
  30.       + ipv6_address_count                   = (known after apply)
  31.       + ipv6_addresses                       = (known after apply)
  32.       + key_name                             = "tf-keypair"
  33.       + monitoring                           = (known after apply)
  34.       + outpost_arn                          = (known after apply)
  35.       + password_data                        = (known after apply)
  36.       + placement_group                      = (known after apply)
  37.       + placement_partition_number           = (known after apply)
  38.       + primary_network_interface_id         = (known after apply)
  39.       + private_dns                          = (known after apply)
  40.       + private_ip                           = (known after apply)
  41.       + public_dns                           = (known after apply)
  42.       + public_ip                            = (known after apply)
  43.       + secondary_private_ips                = (known after apply)
  44.       + security_groups                      = (known after apply)
  45.       + source_dest_check                    = true
  46.       + subnet_id                            = "subnet-08f8e4b2c62e27989"
  47.       + tags                                 = {
  48.           + "Name" = "tf-ec2-01"
  49.         }
  50.       + tags_all                             = {
  51.           + "Name" = "tf-ec2-01"
  52.         }
  53.       + tenancy                              = (known after apply)
  54.       + user_data                            = (known after apply)
  55.       + user_data_base64                     = (known after apply)
  56.       + user_data_replace_on_change          = false
  57.       + vpc_security_group_ids               = [
  58.           + "sg-0907b4ae2d4bd9592",
  59.         ]
  60.       + capacity_reservation_specification (known after apply)
  61.       + cpu_options (known after apply)
  62.       + ebs_block_device (known after apply)
  63.       + enclave_options (known after apply)
  64.       + ephemeral_block_device (known after apply)
  65.       + maintenance_options (known after apply)
  66.       + metadata_options (known after apply)
  67.       + network_interface (known after apply)
  68.       + private_dns_name_options (known after apply)
  69.       + root_block_device {
  70.           + delete_on_termination = true
  71.           + device_name           = (known after apply)
  72.           + encrypted             = (known after apply)
  73.           + iops                  = (known after apply)
  74.           + kms_key_id            = (known after apply)
  75.           + throughput            = (known after apply)
  76.           + volume_id             = (known after apply)
  77.           + volume_size           = 10
  78.           + volume_type           = (known after apply)
  79.         }
  80.     }
  81.   # aws_instance.tf-ec2-02 will be created
  82.   + resource "aws_instance" "tf-ec2-02" {
  83.       + ami                                  = "ami-0da424eb883458071"
  84.       + arn                                  = (known after apply)
  85.       + associate_public_ip_address          = (known after apply)
  86.       + availability_zone                    = (known after apply)
  87.       + cpu_core_count                       = (known after apply)
  88.       + cpu_threads_per_core                 = (known after apply)
  89.       + disable_api_stop                     = (known after apply)
  90.       + disable_api_termination              = (known after apply)
  91.       + ebs_optimized                        = (known after apply)
  92.       + get_password_data                    = false
  93.       + host_id                              = (known after apply)
  94.       + host_resource_group_arn              = (known after apply)
  95.       + iam_instance_profile                 = (known after apply)
  96.       + id                                   = (known after apply)
  97.       + instance_initiated_shutdown_behavior = (known after apply)
  98.       + instance_state                       = (known after apply)
  99.       + instance_type                        = "t2.micro"
  100.       + ipv6_address_count                   = (known after apply)
  101.       + ipv6_addresses                       = (known after apply)
  102.       + key_name                             = "tf-keypair"
  103.       + monitoring                           = (known after apply)
  104.       + outpost_arn                          = (known after apply)
  105.       + password_data                        = (known after apply)
  106.       + placement_group                      = (known after apply)
  107.       + placement_partition_number           = (known after apply)
  108.       + primary_network_interface_id         = (known after apply)
  109.       + private_dns                          = (known after apply)
  110.       + private_ip                           = (known after apply)
  111.       + public_dns                           = (known after apply)
  112.       + public_ip                            = (known after apply)
  113.       + secondary_private_ips                = (known after apply)
  114.       + security_groups                      = (known after apply)
  115.       + source_dest_check                    = true
  116.       + subnet_id                            = "subnet-019490723ad3e940a"
  117.       + tags                                 = {
  118.           + "Name" = "tf-ec2-02"
  119.         }
  120.       + tags_all                             = {
  121.           + "Name" = "tf-ec2-02"
  122.         }
  123.       + tenancy                              = (known after apply)
  124.       + user_data                            = (known after apply)
  125.       + user_data_base64                     = (known after apply)
  126.       + user_data_replace_on_change          = false
  127.       + vpc_security_group_ids               = [
  128.           + "sg-0907b4ae2d4bd9592",
  129.         ]
  130.       + capacity_reservation_specification (known after apply)
  131.       + cpu_options (known after apply)
  132.       + ebs_block_device (known after apply)
  133.       + enclave_options (known after apply)
  134.       + ephemeral_block_device (known after apply)
  135.       + maintenance_options (known after apply)
  136.       + metadata_options (known after apply)
  137.       + network_interface (known after apply)
  138.       + private_dns_name_options (known after apply)
  139.       + root_block_device {
  140.           + delete_on_termination = true
  141.           + device_name           = (known after apply)
  142.           + encrypted             = (known after apply)
  143.           + iops                  = (known after apply)
  144.           + kms_key_id            = (known after apply)
  145.           + throughput            = (known after apply)
  146.           + volume_id             = (known after apply)
  147.           + volume_size           = 10
  148.           + volume_type           = (known after apply)
  149.         }
  150.     }
  151. Plan: 2 to add, 0 to change, 0 to destroy.
  152. ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
  153. Saved the plan to: tf.plan
  154. To perform exactly these actions, run the following command to apply:
  155.     terraform apply "tf.plan"
复制代码
执行创建ec2
  1. terraform apply "tf.plan"
复制代码
 输出:
  1. aws_instance.tf-ec2-01: Creating...
  2. aws_instance.tf-ec2-02: Creating...
  3. aws_instance.tf-ec2-02: Still creating... [10s elapsed]
  4. aws_instance.tf-ec2-01: Still creating... [10s elapsed]
  5. aws_instance.tf-ec2-01: Creation complete after 16s [id=i-0f8d63e600d93f6b0]
  6. aws_instance.tf-ec2-02: Creation complete after 16s [id=i-0888d477cdf36aea0]
  7. Apply complete! Resources: 2 added, 0 changed, 0 destroyed.
复制代码
4.创建ebs

新增ebs.tf文化
  1. resource "aws_ebs_volume" "ebs_ec2_01" {
  2.   availability_zone = var.az_1  # 使用变量代替硬编码的可用区
  3.   size              = 20
  4.   type              = "gp3"
  5.   tags = {
  6.     Name = "ebs-ec2-01"
  7.   }
  8. }
  9. resource "aws_ebs_volume" "ebs_ec2_02" {
  10.   availability_zone = var.az_2
  11.   size              = 20
  12.   type              = "gp3"
  13.   tags = {
  14.     Name = "ebs-ec2-02"
  15.   }
  16. }
复制代码
表明

预执行
  1. terraform plan -out=tf.plan
复制代码
terraform plan
  1.  terraform plan -out=tf.plan
  2. aws_key_pair.tf-keypair: Refreshing state... [id=tf-keypair]
  3. aws_vpc.tf_vpc: Refreshing state... [id=vpc-0f2e1cdca0cf5a306]
  4. aws_subnet.tf_subnet02: Refreshing state... [id=subnet-019490723ad3e940a]
  5. aws_subnet.tf_subnet01: Refreshing state... [id=subnet-08f8e4b2c62e27989]
  6. aws_security_group.tf_security_group: Refreshing state... [id=sg-0907b4ae2d4bd9592]
  7. aws_instance.tf-ec2-02: Refreshing state... [id=i-0888d477cdf36aea0]
  8. aws_instance.tf-ec2-01: Refreshing state... [id=i-0f8d63e600d93f6b0]
  9. Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the
  10. following symbols:
  11.   + create
  12. Terraform will perform the following actions:
  13.   # aws_ebs_volume.ebs_ec2_01 will be created
  14.   + resource "aws_ebs_volume" "ebs_ec2_01" {
  15.       + arn               = (known after apply)
  16.       + availability_zone = "us-west-1a"
  17.       + encrypted         = (known after apply)
  18.       + final_snapshot    = false
  19.       + id                = (known after apply)
  20.       + iops              = (known after apply)
  21.       + kms_key_id        = (known after apply)
  22.       + size              = 20
  23.       + snapshot_id       = (known after apply)
  24.       + tags              = {
  25.           + "Name" = "ebs-ec2-01"
  26.         }
  27.       + tags_all          = {
  28.           + "Name" = "ebs-ec2-01"
  29.         }
  30.       + throughput        = (known after apply)
  31.       + type              = "gp3"
  32.     }
  33.   # aws_ebs_volume.ebs_ec2_02 will be created
  34.   + resource "aws_ebs_volume" "ebs_ec2_02" {
  35.       + arn               = (known after apply)
  36.       + availability_zone = "us-west-1b"
  37.       + encrypted         = (known after apply)
  38.       + final_snapshot    = false
  39.       + id                = (known after apply)
  40.       + iops              = (known after apply)
  41.       + kms_key_id        = (known after apply)
  42.       + size              = 20
  43.       + snapshot_id       = (known after apply)
  44.       + tags              = {
  45.           + "Name" = "ebs-ec2-02"
  46.         }
  47.       + tags_all          = {
  48.           + "Name" = "ebs-ec2-02"
  49.         }
  50.       + throughput        = (known after apply)
  51.       + type              = "gp3"
  52.     }
  53. Plan: 2 to add, 0 to change, 0 to destroy.
  54. ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
  55. Saved the plan to: tf.plan
  56. To perform exactly these actions, run the following command to apply:
  57.     terraform apply "tf.plan"
复制代码
执行创建ebs
  1. terraform apply "tf.plan"
复制代码
输出如下:
  1. terraform apply "tf.plan"
  2. aws_ebs_volume.ebs_ec2_02: Creating...
  3. aws_ebs_volume.ebs_ec2_01: Creating...
  4. aws_ebs_volume.ebs_ec2_02: Still creating... [10s elapsed]
  5. aws_ebs_volume.ebs_ec2_01: Still creating... [10s elapsed]
  6. aws_ebs_volume.ebs_ec2_01: Creation complete after 12s [id=vol-0aac9f1302376328a]
  7. aws_ebs_volume.ebs_ec2_02: Creation complete after 12s [id=vol-06bd472f44eadaf02]
  8. Apply complete! Resources: 2 added, 0 changed, 0 destroyed.
复制代码
5.将 EBS 磁盘附加到 EC2 

新增ebs_attachment.tf文件
  1. resource "aws_volume_attachment" "attach_ebs_to_ec2_01" {
  2.   device_name = "/dev/xvdh"                # 设备名称,可根据需求更改
  3.   volume_id   = aws_ebs_volume.ebs_ec2_01.id
  4.   instance_id = aws_instance.tf-ec2-01.id
  5. }
  6. resource "aws_volume_attachment" "attach_ebs_to_ec2_02" {
  7.   device_name = "/dev/xvdh"
  8.   volume_id   = aws_ebs_volume.ebs_ec2_02.id
  9.   instance_id = aws_instance.tf-ec2-02.id
  10. }
复制代码
表明

预执行
  1. terraform plan -out=tf.plan
复制代码
terraform plan
  1.  terraform plan -out=tf.plan
  2. aws_ebs_volume.ebs_ec2_02: Refreshing state... [id=vol-06bd472f44eadaf02]
  3. aws_vpc.tf_vpc: Refreshing state... [id=vpc-0f2e1cdca0cf5a306]
  4. aws_ebs_volume.ebs_ec2_01: Refreshing state... [id=vol-0aac9f1302376328a]
  5. aws_key_pair.tf-keypair: Refreshing state... [id=tf-keypair]
  6. aws_subnet.tf_subnet02: Refreshing state... [id=subnet-019490723ad3e940a]
  7. aws_subnet.tf_subnet01: Refreshing state... [id=subnet-08f8e4b2c62e27989]
  8. aws_security_group.tf_security_group: Refreshing state... [id=sg-0907b4ae2d4bd9592]
  9. aws_instance.tf-ec2-01: Refreshing state... [id=i-0f8d63e600d93f6b0]
  10. aws_instance.tf-ec2-02: Refreshing state... [id=i-0888d477cdf36aea0]
  11. Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the
  12. following symbols:
  13.   + create
  14. Terraform will perform the following actions:
  15.   # aws_volume_attachment.attach_ebs_to_ec2_01 will be created
  16.   + resource "aws_volume_attachment" "attach_ebs_to_ec2_01" {
  17.       + device_name = "/dev/xvdh"
  18.       + id          = (known after apply)
  19.       + instance_id = "i-0f8d63e600d93f6b0"
  20.       + volume_id   = "vol-0aac9f1302376328a"
  21.     }
  22.   # aws_volume_attachment.attach_ebs_to_ec2_02 will be created
  23.   + resource "aws_volume_attachment" "attach_ebs_to_ec2_02" {
  24.       + device_name = "/dev/xvdh"
  25.       + id          = (known after apply)
  26.       + instance_id = "i-0888d477cdf36aea0"
  27.       + volume_id   = "vol-06bd472f44eadaf02"
  28.     }
  29. Plan: 2 to add, 0 to change, 0 to destroy.
  30. ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
  31. Saved the plan to: tf.plan
  32. To perform exactly these actions, run the following command to apply:
  33.     terraform apply "tf.plan"
复制代码
执行附加磁盘
  1. terraform apply "tf.plan"
复制代码
输出:
  1. aws_volume_attachment.attach_ebs_to_ec2_01: Creating...
  2. aws_volume_attachment.attach_ebs_to_ec2_02: Creating...
  3. aws_volume_attachment.attach_ebs_to_ec2_02: Still creating... [10s elapsed]
  4. aws_volume_attachment.attach_ebs_to_ec2_01: Still creating... [10s elapsed]
  5. aws_volume_attachment.attach_ebs_to_ec2_01: Still creating... [20s elapsed]
  6. aws_volume_attachment.attach_ebs_to_ec2_02: Still creating... [20s elapsed]
  7. aws_volume_attachment.attach_ebs_to_ec2_02: Still creating... [30s elapsed]
  8. aws_volume_attachment.attach_ebs_to_ec2_01: Still creating... [30s elapsed]
  9. aws_volume_attachment.attach_ebs_to_ec2_02: Creation complete after 33s [id=vai-439503465]
  10. aws_volume_attachment.attach_ebs_to_ec2_01: Creation complete after 33s [id=vai-1312740159]
  11. Apply complete! Resources: 2 added, 0 changed, 0 destroyed.
复制代码
6. 创建eip和关联eip到ec2实例

 新增eip.tf文件
  1. # 为 tf-ec2-01 创建 EIP
  2. resource "aws_eip" "tf_eip_01" {
  3.   vpc = true
  4.   tags = {
  5.     Name = "tf-eip-01"
  6.   }
  7. }
  8. # 为 tf-ec2-02 创建 EIP
  9. resource "aws_eip" "tf_eip_02" {
  10.   vpc = true
  11.   tags = {
  12.     Name = "tf-eip-02"
  13.   }
  14. }
复制代码
表明

新增eip_association.tf文件
  1. # 关联 EIP 到 tf-ec2-01 实例
  2. resource "aws_eip_association" "tf_eip_association_01" {
  3.   instance_id   = aws_instance.tf-ec2-01.id
  4.   allocation_id = aws_eip.tf_eip_01.id
  5. }
  6. # 关联 EIP 到 tf-ec2-02 实例
  7. resource "aws_eip_association" "tf_eip_association_02" {
  8.   instance_id   = aws_instance.tf-ec2-02.id
  9.   allocation_id = aws_eip.tf_eip_02.id
  10. }
复制代码
表明

预执行

terraform plan -out=tf.plan
terraform plan
  1. terraform plan -out=tf.plan
  2. aws_key_pair.tf-keypair: Refreshing state... [id=tf-keypair]
  3. aws_ebs_volume.ebs_ec2_01: Refreshing state... [id=vol-0aac9f1302376328a]
  4. aws_ebs_volume.ebs_ec2_02: Refreshing state... [id=vol-06bd472f44eadaf02]
  5. aws_vpc.tf_vpc: Refreshing state... [id=vpc-0f2e1cdca0cf5a306]
  6. aws_internet_gateway.tf_igw: Refreshing state... [id=igw-08ec2f3357e8725df]
  7. aws_subnet.tf_subnet02: Refreshing state... [id=subnet-019490723ad3e940a]
  8. aws_subnet.tf_subnet01: Refreshing state... [id=subnet-08f8e4b2c62e27989]
  9. aws_security_group.tf_security_group: Refreshing state... [id=sg-0907b4ae2d4bd9592]
  10. aws_route_table.tf_route_table: Refreshing state... [id=rtb-0ae4b29ae8d6881ed]
  11. aws_instance.tf-ec2-01: Refreshing state... [id=i-0f8d63e600d93f6b0]
  12. aws_instance.tf-ec2-02: Refreshing state... [id=i-0888d477cdf36aea0]
  13. aws_route_table_association.tf_route_table_association_02: Refreshing state... [id=rtbassoc-0190cb61bd5850d86]
  14. aws_route_table_association.tf_route_table_association_01: Refreshing state... [id=rtbassoc-0999e44cc1cfb7f09]
  15. aws_volume_attachment.attach_ebs_to_ec2_01: Refreshing state... [id=vai-1312740159]
  16. aws_volume_attachment.attach_ebs_to_ec2_02: Refreshing state... [id=vai-439503465]
  17. Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the
  18. following symbols:
  19.   + create
  20. Terraform will perform the following actions:
  21.   # aws_eip.tf_eip_01 will be created
  22.   + resource "aws_eip" "tf_eip_01" {
  23.       + allocation_id        = (known after apply)
  24.       + association_id       = (known after apply)
  25.       + carrier_ip           = (known after apply)
  26.       + customer_owned_ip    = (known after apply)
  27.       + domain               = (known after apply)
  28.       + id                   = (known after apply)
  29.       + instance             = (known after apply)
  30.       + network_border_group = (known after apply)
  31.       + network_interface    = (known after apply)
  32.       + private_dns          = (known after apply)
  33.       + private_ip           = (known after apply)
  34.       + public_dns           = (known after apply)
  35.       + public_ip            = (known after apply)
  36.       + public_ipv4_pool     = (known after apply)
  37.       + tags                 = {
  38.           + "Name" = "tf-eip-01"
  39.         }
  40.       + tags_all             = {
  41.           + "Name" = "tf-eip-01"
  42.         }
  43.       + vpc                  = true
  44.     }
  45.   # aws_eip.tf_eip_02 will be created
  46.   + resource "aws_eip" "tf_eip_02" {
  47.       + allocation_id        = (known after apply)
  48.       + association_id       = (known after apply)
  49.       + carrier_ip           = (known after apply)
  50.       + customer_owned_ip    = (known after apply)
  51.       + domain               = (known after apply)
  52.       + id                   = (known after apply)
  53.       + instance             = (known after apply)
  54.       + network_border_group = (known after apply)
  55.       + network_interface    = (known after apply)
  56.       + private_dns          = (known after apply)
  57.       + private_ip           = (known after apply)
  58.       + public_dns           = (known after apply)
  59.       + public_ip            = (known after apply)
  60.       + public_ipv4_pool     = (known after apply)
  61.       + tags                 = {
  62.           + "Name" = "tf-eip-02"
  63.         }
  64.       + tags_all             = {
  65.           + "Name" = "tf-eip-02"
  66.         }
  67.       + vpc                  = true
  68.     }
  69.   # aws_eip_association.tf_eip_association_01 will be created
  70.   + resource "aws_eip_association" "tf_eip_association_01" {
  71.       + allocation_id        = (known after apply)
  72.       + id                   = (known after apply)
  73.       + instance_id          = "i-0f8d63e600d93f6b0"
  74.       + network_interface_id = (known after apply)
  75.       + private_ip_address   = (known after apply)
  76.       + public_ip            = (known after apply)
  77.     }
  78.   # aws_eip_association.tf_eip_association_02 will be created
  79.   + resource "aws_eip_association" "tf_eip_association_02" {
  80.       + allocation_id        = (known after apply)
  81.       + id                   = (known after apply)
  82.       + instance_id          = "i-0888d477cdf36aea0"
  83.       + network_interface_id = (known after apply)
  84.       + private_ip_address   = (known after apply)
  85.       + public_ip            = (known after apply)
  86.     }
  87. Plan: 4 to add, 0 to change, 0 to destroy.
  88. ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
  89. Saved the plan to: tf.plan
  90. To perform exactly these actions, run the following command to apply:
  91.     terraform apply "tf.plan"
复制代码
执行创建eip和关联ec2
  1. terraform apply "tf.plan"
复制代码
结果如下:
  1. aws_eip.tf_eip_02: Creating...
  2. aws_eip.tf_eip_01: Creating...
  3. aws_eip.tf_eip_01: Creation complete after 2s [id=eipalloc-0a9cdbc84013614f5]
  4. aws_eip.tf_eip_02: Creation complete after 2s [id=eipalloc-0ed1c932d9a7a305a]
  5. aws_eip_association.tf_eip_association_01: Creating...
  6. aws_eip_association.tf_eip_association_02: Creating...
  7. aws_eip_association.tf_eip_association_02: Creation complete after 1s [id=eipassoc-0b517a49d76639054]
  8. aws_eip_association.tf_eip_association_01: Creation complete after 1s [id=eipassoc-0e0359ad952266802]
  9. Apply complete! Resources: 4 added, 0 changed, 0 destroyed.
复制代码
转载请著名原文地址:https://www.cnblogs.com/Sunzz/p/18498915
7.通过控制后台检察创建的结果

通过控制台可以看到,实例名字、范例、可用区、公网IP、安全组、密钥、磁盘等都是符合我们在tf中定义的。

再直接登录到服务器上看下,确保网络、安全组都是可用的
  1. ssh ec2-user@52.9.19.52 -i ~/.ssh/tf-keypair
复制代码

五、创建EKS

1. 创建EKS所需的网络资源

创建eks所用的子网并关联路由表文件

eks_subnets.tf内容如下
  1. resource "aws_subnet" "tf_eks_subnet1" {
  2.   vpc_id            = aws_vpc.tf_vpc.id
  3.   cidr_block        = "10.10.81.0/24"
  4.   availability_zone = var.az_1
  5.   map_public_ip_on_launch = true
  6.   tags = {
  7.     Name = "tf_eks_subnet1"
  8.   }
  9. }
  10. resource "aws_subnet" "tf_eks_subnet2" {
  11.   vpc_id            = aws_vpc.tf_vpc.id
  12.   cidr_block        = "10.10.82.0/24"
  13.   availability_zone = var.az_2
  14.   map_public_ip_on_launch = true
  15.   tags = {
  16.     Name = "tf_eks_subnet2"
  17.   }
  18. }
  19. # 将路由表关联到子网tf_eks_subnet1
  20. resource "aws_route_table_association" "tf_eks_subnet1_association" {
  21.   subnet_id      = aws_subnet.tf_eks_subnet1.id
  22.   route_table_id = aws_route_table.tf_route_table.id
  23. }
  24. # 将路由表关联到子网tf_eks_subnet2
  25. resource "aws_route_table_association" "tf_eks_subnet2_association" {
  26.   subnet_id      = aws_subnet.tf_eks_subnet2.id  
  27.   route_table_id = aws_route_table.tf_route_table.id
  28. }
复制代码
表明

 
预创建
  1. terraform plan -out=tf.plan
复制代码
tf plan
  1.  Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following
  2. symbols:
  3.   + create
  4. Terraform will perform the following actions:
  5.   # aws_route_table_association.tf_eks_subnet1_association will be created
  6.   + resource "aws_route_table_association" "tf_eks_subnet1_association" {
  7.       + id             = (known after apply)
  8.       + route_table_id = "rtb-0ae4b29ae8d6881ed"
  9.       + subnet_id      = (known after apply)
  10.     }
  11.   # aws_route_table_association.tf_eks_subnet2_association will be created
  12.   + resource "aws_route_table_association" "tf_eks_subnet2_association" {
  13.       + id             = (known after apply)
  14.       + route_table_id = "rtb-0ae4b29ae8d6881ed"
  15.       + subnet_id      = (known after apply)
  16.     }
  17.   # aws_subnet.tf_eks_subnet1 will be created
  18.   + resource "aws_subnet" "tf_eks_subnet1" {
  19.       + arn                                            = (known after apply)
  20.       + assign_ipv6_address_on_creation                = false
  21.       + availability_zone                              = "us-west-1a"
  22.       + availability_zone_id                           = (known after apply)
  23.       + cidr_block                                     = "10.10.81.0/24"
  24.       + enable_dns64                                   = false
  25.       + enable_resource_name_dns_a_record_on_launch    = false
  26.       + enable_resource_name_dns_aaaa_record_on_launch = false
  27.       + id                                             = (known after apply)
  28.       + ipv6_cidr_block_association_id                 = (known after apply)
  29.       + ipv6_native                                    = false
  30.       + map_public_ip_on_launch                        = true
  31.       + owner_id                                       = (known after apply)
  32.       + private_dns_hostname_type_on_launch            = (known after apply)
  33.       + tags                                           = {
  34.           + "Name" = "tf_eks_subnet1"
  35.         }
  36.       + tags_all                                       = {
  37.           + "Name" = "tf_eks_subnet1"
  38.         }
  39.       + vpc_id                                         = "vpc-0f2e1cdca0cf5a306"
  40.     }
  41.   # aws_subnet.tf_eks_subnet2 will be created
  42.   + resource "aws_subnet" "tf_eks_subnet2" {
  43.       + arn                                            = (known after apply)
  44.       + assign_ipv6_address_on_creation                = false
  45.       + availability_zone                              = "us-west-1b"
  46.       + availability_zone_id                           = (known after apply)
  47.       + cidr_block                                     = "10.10.82.0/24"
  48.       + enable_dns64                                   = false
  49.       + enable_resource_name_dns_a_record_on_launch    = false
  50.       + enable_resource_name_dns_aaaa_record_on_launch = false
  51.       + id                                             = (known after apply)
  52.       + ipv6_cidr_block_association_id                 = (known after apply)
  53.       + ipv6_native                                    = false
  54.       + map_public_ip_on_launch                        = true
  55.       + owner_id                                       = (known after apply)
  56.       + private_dns_hostname_type_on_launch            = (known after apply)
  57.       + tags                                           = {
  58.           + "Name" = "tf_eks_subnet2"
  59.         }
  60.       + tags_all                                       = {
  61.           + "Name" = "tf_eks_subnet2"
  62.         }
  63.       + vpc_id                                         = "vpc-0f2e1cdca0cf5a306"
  64.     }
  65. Plan: 4 to add, 0 to change, 0 to destroy.
  66. ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
  67. Saved the plan to: tf.plan
  68. To perform exactly these actions, run the following command to apply:
  69.     terraform apply "tf.plan"
复制代码
创建子网
  1. terraform apply "tf.plan"
复制代码
输出如下:
  1. aws_subnet.tf_eks_subnet2: Creating...
  2. aws_subnet.tf_eks_subnet1: Creating...
  3. aws_subnet.tf_eks_subnet1: Still creating... [10s elapsed]
  4. aws_subnet.tf_eks_subnet2: Still creating... [10s elapsed]
  5. aws_subnet.tf_eks_subnet2: Creation complete after 13s [id=subnet-0a30534a829758774]
  6. aws_route_table_association.tf_eks_subnet2_association: Creating...
  7. aws_subnet.tf_eks_subnet1: Creation complete after 13s [id=subnet-01b5d98060f0063ef]
  8. aws_route_table_association.tf_eks_subnet1_association: Creating...
  9. aws_route_table_association.tf_eks_subnet1_association: Creation complete after 1s [id=rtbassoc-08fef5fee4d037035]
  10. aws_route_table_association.tf_eks_subnet2_association: Creation complete after 1s [id=rtbassoc-0ec12dc9868d6316a]
  11. Apply complete! Resources: 4 added, 0 changed, 0 destroyed.
复制代码
2. 创建EKS安全组

eks_security_group.tf
这里放开所有只是为了演示,请勿用在生产环境中
  1. resource "aws_security_group" "eks_allow_all" {
  2.   name        = "eks_allow_all"
  3.   description = "Security group that allows all inbound and outbound traffic"
  4.   vpc_id      = aws_vpc.tf_vpc.id
  5.   // 允许所有入站流量
  6.   ingress {
  7.     from_port   = 0
  8.     to_port     = 0
  9.     protocol    = "-1"  // -1 表示所有协议
  10.     cidr_blocks = ["0.0.0.0/0"]  // 允许来自所有 IP 的流量
  11.   }
  12.   // 允许所有出站流量
  13.   egress {
  14.     from_port   = 0
  15.     to_port     = 0
  16.     protocol    = "-1"  // -1 表示所有协议
  17.     cidr_blocks = ["0.0.0.0/0"]  // 允许流量发送到所有 IP
  18.   }
  19. }
复制代码
表明

入站规则(ingress)

出站规则(egress)

预创建
  1. terraform plan -out=tf.plan
复制代码
tf plan
  1.  Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following
  2. symbols:
  3.   + create
  4. Terraform will perform the following actions:
  5.   # aws_security_group.eks_allow_all will be created
  6.   + resource "aws_security_group" "eks_allow_all" {
  7.       + arn                    = (known after apply)
  8.       + description            = "Security group that allows all inbound and outbound traffic"
  9.       + egress                 = [
  10.           + {
  11.               + cidr_blocks      = [
  12.                   + "0.0.0.0/0",
  13.                 ]
  14.               + from_port        = 0
  15.               + ipv6_cidr_blocks = []
  16.               + prefix_list_ids  = []
  17.               + protocol         = "-1"
  18.               + security_groups  = []
  19.               + self             = false
  20.               + to_port          = 0
  21.                 # (1 unchanged attribute hidden)
  22.             },
  23.         ]
  24.       + id                     = (known after apply)
  25.       + ingress                = [
  26.           + {
  27.               + cidr_blocks      = [
  28.                   + "0.0.0.0/0",
  29.                 ]
  30.               + from_port        = 0
  31.               + ipv6_cidr_blocks = []
  32.               + prefix_list_ids  = []
  33.               + protocol         = "-1"
  34.               + security_groups  = []
  35.               + self             = false
  36.               + to_port          = 0
  37.                 # (1 unchanged attribute hidden)
  38.             },
  39.         ]
  40.       + name                   = "eks_allow_all"
  41.       + name_prefix            = (known after apply)
  42.       + owner_id               = (known after apply)
  43.       + revoke_rules_on_delete = false
  44.       + tags_all               = (known after apply)
  45.       + vpc_id                 = "vpc-0f2e1cdca0cf5a306"
  46.     }
  47. Plan: 1 to add, 0 to change, 0 to destroy.
  48. ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
  49. Saved the plan to: tf.plan
  50. To perform exactly these actions, run the following command to apply:
  51.     terraform apply "tf.plan"
复制代码
创建安全组
  1. terraform apply "tf.plan"
复制代码
输出如下:
  1. aws_security_group.eks_allow_all: Creating...
  2. aws_security_group.eks_allow_all: Creation complete after 7s [id=sg-0db88cd4ca4b95099]
  3. Apply complete! Resources: 1 added, 0 changed, 0 destroyed.
复制代码
3. 创建 EKS 集群 IAM 脚色

创建eks_iam_roles.tf文件
  1. data "aws_iam_policy_document" "assume_role" {
  2.   statement {
  3.     effect = "Allow"
  4.     principals {
  5.       type        = "Service"
  6.       identifiers = ["eks.amazonaws.com"]
  7.     }
  8.     actions = ["sts:AssumeRole"]
  9.   }
  10. }
  11. resource "aws_iam_role" "eks-cluster" {
  12.   name               = "eks-cluster"
  13.   assume_role_policy = data.aws_iam_policy_document.assume_role.json
  14. }
  15. resource "aws_iam_role_policy_attachment" "eks-cluster-AmazonEKSClusterPolicy" {
  16.   policy_arn = "arn:aws:iam::aws:policy/AmazonEKSClusterPolicy"
  17.   role       = aws_iam_role.eks-cluster.name
  18. }
  19. resource "aws_iam_role_policy_attachment" "eks-cluster-AmazonEKSVPCResourceController" {
  20.   policy_arn = "arn:aws:iam::aws:policy/AmazonEKSVPCResourceController"
  21.   role       = aws_iam_role.eks-cluster.name
  22. }
复制代码
表明

这段代码定义了一个 IAM 脚色及其权限策略,用于 Amazon EKS 集群的创建和管理。以下是详细表明:
数据源部分

IAM 脚色部分

IAM 脚色策略附件

预创建
  1. terraform plan -out=tf.plan
复制代码
tf plan
  1.  Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following
  2. symbols:
  3.   + create
  4. Terraform will perform the following actions:
  5.   # aws_iam_role.eks-cluster will be created
  6.   + resource "aws_iam_role" "eks-cluster" {
  7.       + arn                   = (known after apply)
  8.       + assume_role_policy    = jsonencode(
  9.             {
  10.               + Statement = [
  11.                   + {
  12.                       + Action    = "sts:AssumeRole"
  13.                       + Effect    = "Allow"
  14.                       + Principal = {
  15.                           + Service = "eks.amazonaws.com"
  16.                         }
  17.                       + Sid       = ""
  18.                     },
  19.                 ]
  20.               + Version   = "2012-10-17"
  21.             }
  22.         )
  23.       + create_date           = (known after apply)
  24.       + force_detach_policies = false
  25.       + id                    = (known after apply)
  26.       + managed_policy_arns   = (known after apply)
  27.       + max_session_duration  = 3600
  28.       + name                  = "eks-cluster"
  29.       + name_prefix           = (known after apply)
  30.       + path                  = "/"
  31.       + role_last_used        = (known after apply)
  32.       + tags_all              = (known after apply)
  33.       + unique_id             = (known after apply)
  34.       + inline_policy (known after apply)
  35.     }
  36.   # aws_iam_role_policy_attachment.eks-cluster-AmazonEKSClusterPolicy will be created
  37.   + resource "aws_iam_role_policy_attachment" "eks-cluster-AmazonEKSClusterPolicy" {
  38.       + id         = (known after apply)
  39.       + policy_arn = "arn:aws:iam::aws:policy/AmazonEKSClusterPolicy"
  40.       + role       = "eks-cluster"
  41.     }
  42.   # aws_iam_role_policy_attachment.eks-cluster-AmazonEKSVPCResourceController will be created
  43.   + resource "aws_iam_role_policy_attachment" "eks-cluster-AmazonEKSVPCResourceController" {
  44.       + id         = (known after apply)
  45.       + policy_arn = "arn:aws:iam::aws:policy/AmazonEKSVPCResourceController"
  46.       + role       = "eks-cluster"
  47.     }
  48. Plan: 3 to add, 0 to change, 0 to destroy.
  49. ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
  50. Saved the plan to: tf.plan
  51. To perform exactly these actions, run the following command to apply:
  52.     terraform apply "tf.plan"
复制代码
创建eks iam role
  1. terraform apply "tf.plan"
复制代码
输出如下:
  1. aws_iam_role.eks-cluster: Creating...
  2. aws_iam_role.eks-cluster: Creation complete after 2s [id=eks-cluster]
  3. aws_iam_role_policy_attachment.eks-cluster-AmazonEKSVPCResourceController: Creating...
  4. aws_iam_role_policy_attachment.eks-cluster-AmazonEKSClusterPolicy: Creating...
  5. aws_iam_role_policy_attachment.eks-cluster-AmazonEKSVPCResourceController: Creation complete after 1s [id=eks-cluster-20241027124651622300000001]
  6. aws_iam_role_policy_attachment.eks-cluster-AmazonEKSClusterPolicy: Creation complete after 1s [id=eks-cluster-20241027124651968900000002]
  7. Apply complete! Resources: 3 added, 0 changed, 0 destroyed.
复制代码
4. 创建EKS集群

编写eks_cluster.tf文件
  1. resource "aws_eks_cluster" "tf-eks" {
  2.   name     = "tf-eks"
  3.   version  = var.eks_version  # 指定 EKS 版本
  4.   role_arn = aws_iam_role.eks-cluster.arn
  5.   vpc_config {
  6.     subnet_ids = [
  7.           aws_subnet.tf_eks_subnet1.id,
  8.           aws_subnet.tf_eks_subnet2.id
  9.         ]
  10.     security_group_ids      = [aws_security_group.eks_allow_all.id]    # 引用之前创建的安全组
  11.     endpoint_public_access  = true     # 公有访问
  12.     endpoint_private_access = true     # 私有访问
  13.     public_access_cidrs = ["0.0.0.0/0"] # 允许从任何地方访问
  14.   }
  15. #  # 启用日志
  16. #  enabled_cluster_log_types = [
  17. #           "api",
  18. #           "audit",
  19. #           "authenticator",
  20. #           "controllerManager",
  21. #           "scheduler",
  22. #  ]
  23.   depends_on = [
  24.     aws_iam_role_policy_attachment.eks-cluster-AmazonEKSClusterPolicy,
  25.     aws_iam_role_policy_attachment.eks-cluster-AmazonEKSVPCResourceController,
  26.   ]
  27. }
复制代码
参数表明

预创建
  1. terraform plan -out=tf.plan
复制代码
tf plan
  1.  Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following
  2. symbols:
  3.   + create
  4. Terraform will perform the following actions:
  5.   # aws_eks_cluster.tf-eks will be created
  6.   + resource "aws_eks_cluster" "tf-eks" {
  7.       + arn                   = (known after apply)
  8.       + certificate_authority = (known after apply)
  9.       + cluster_id            = (known after apply)
  10.       + created_at            = (known after apply)
  11.       + endpoint              = (known after apply)
  12.       + id                    = (known after apply)
  13.       + identity              = (known after apply)
  14.       + name                  = "tf-eks"
  15.       + platform_version      = (known after apply)
  16.       + role_arn              = "arn:aws:iam::xxxxxxxx:role/eks-cluster"
  17.       + status                = (known after apply)
  18.       + tags_all              = (known after apply)
  19.       + version               = "1.31"
  20.       + kubernetes_network_config (known after apply)
  21.       + vpc_config {
  22.           + cluster_security_group_id = (known after apply)
  23.           + endpoint_private_access   = true
  24.           + endpoint_public_access    = true
  25.           + public_access_cidrs       = [
  26.               + "0.0.0.0/0",
  27.             ]
  28.           + security_group_ids        = [
  29.               + "sg-0db88cd4ca4b95099",
  30.             ]
  31.           + subnet_ids                = [
  32.               + "subnet-01b5d98060f0063ef",
  33.               + "subnet-0a30534a829758774",
  34.             ]
  35.           + vpc_id                    = (known after apply)
  36.         }
  37.     }
  38. Plan: 1 to add, 0 to change, 0 to destroy.
  39. ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
  40. Saved the plan to: tf.plan
  41. To perform exactly these actions, run the following command to apply:
  42.     terraform apply "tf.plan"
复制代码
创建
  1. terraform apply "tf.plan"
复制代码
输出如下:
  1. aws_eks_cluster.tf-eks: Creating...
  2. aws_eks_cluster.tf-eks: Still creating... [10s elapsed]
  3. aws_eks_cluster.tf-eks: Still creating... [20s elapsed]
  4. aws_eks_cluster.tf-eks: Still creating... [30s elapsed]
  5. ......
  6. .......
  7. aws_eks_cluster.tf-eks: Still creating... [7m21s elapsed]
  8. aws_eks_cluster.tf-eks: Still creating... [7m31s elapsed]
  9. aws_eks_cluster.tf-eks: Creation complete after 7m35s [id=tf-eks]
  10. Apply complete! Resources: 1 added, 0 changed, 0 destroyed.
复制代码
5. 创建Node Group IAM

创建tf文件

eks_node_group_iam.tf
  1. resource "aws_iam_role" "eks-nodegroup-role" {
  2.   name = "eks-nodegroup-role"
  3.   assume_role_policy = jsonencode({
  4.     Statement = [{
  5.       Action = "sts:AssumeRole"
  6.       Effect = "Allow"
  7.       Principal = {
  8.         Service = "ec2.amazonaws.com"
  9.       }
  10.     }]
  11.     Version = "2012-10-17"
  12.   })
  13. }
  14. resource "aws_iam_role_policy_attachment" "eks-nodegroup-role-AmazonEKSWorkerNodePolicy" {
  15.   policy_arn = "arn:aws:iam::aws:policy/AmazonEKSWorkerNodePolicy"
  16.   role       = aws_iam_role.eks-nodegroup-role.name
  17. }
  18. resource "aws_iam_role_policy_attachment" "eks-nodegroup-role-AmazonEKS_CNI_Policy" {
  19.   policy_arn = "arn:aws:iam::aws:policy/AmazonEKS_CNI_Policy"
  20.   role       = aws_iam_role.eks-nodegroup-role.name
  21. }
  22. resource "aws_iam_role_policy_attachment" "eks-nodegroup-role-AmazonEC2ContainerRegistryReadOnly" {
  23.   policy_arn = "arn:aws:iam::aws:policy/AmazonEC2ContainerRegistryReadOnly"
  24.   role       = aws_iam_role.eks-nodegroup-role.name
  25. }
复制代码
表明

这段代码定义了一个 IAM 脚色,用于 Amazon EKS 节点组,并附加了必要的权限策略。以下是详细表明:
IAM 脚色定义

IAM 脚色策略附件

预创建
  1. terraform plan -out=tf.plan
复制代码
tf plan
  1.  Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following
  2. symbols:
  3.   + create
  4. Terraform will perform the following actions:
  5.   # aws_iam_role.eks-nodegroup-role will be created
  6.   + resource "aws_iam_role" "eks-nodegroup-role" {
  7.       + arn                   = (known after apply)
  8.       + assume_role_policy    = jsonencode(
  9.             {
  10.               + Statement = [
  11.                   + {
  12.                       + Action    = "sts:AssumeRole"
  13.                       + Effect    = "Allow"
  14.                       + Principal = {
  15.                           + Service = "ec2.amazonaws.com"
  16.                         }
  17.                     },
  18.                 ]
  19.               + Version   = "2012-10-17"
  20.             }
  21.         )
  22.       + create_date           = (known after apply)
  23.       + force_detach_policies = false
  24.       + id                    = (known after apply)
  25.       + managed_policy_arns   = (known after apply)
  26.       + max_session_duration  = 3600
  27.       + name                  = "eks-nodegroup-role"
  28.       + name_prefix           = (known after apply)
  29.       + path                  = "/"
  30.       + role_last_used        = (known after apply)
  31.       + tags_all              = (known after apply)
  32.       + unique_id             = (known after apply)
  33.       + inline_policy (known after apply)
  34.     }
  35.   # aws_iam_role_policy_attachment.eks-nodegroup-role-AmazonEC2ContainerRegistryReadOnly will be created
  36.   + resource "aws_iam_role_policy_attachment" "eks-nodegroup-role-AmazonEC2ContainerRegistryReadOnly" {
  37.       + id         = (known after apply)
  38.       + policy_arn = "arn:aws:iam::aws:policy/AmazonEC2ContainerRegistryReadOnly"
  39.       + role       = "eks-nodegroup-role"
  40.     }
  41.   # aws_iam_role_policy_attachment.eks-nodegroup-role-AmazonEKSWorkerNodePolicy will be created
  42.   + resource "aws_iam_role_policy_attachment" "eks-nodegroup-role-AmazonEKSWorkerNodePolicy" {
  43.       + id         = (known after apply)
  44.       + policy_arn = "arn:aws:iam::aws:policy/AmazonEKSWorkerNodePolicy"
  45.       + role       = "eks-nodegroup-role"
  46.     }
  47.   # aws_iam_role_policy_attachment.eks-nodegroup-role-AmazonEKS_CNI_Policy will be created
  48.   + resource "aws_iam_role_policy_attachment" "eks-nodegroup-role-AmazonEKS_CNI_Policy" {
  49.       + id         = (known after apply)
  50.       + policy_arn = "arn:aws:iam::aws:policy/AmazonEKS_CNI_Policy"
  51.       + role       = "eks-nodegroup-role"
  52.     }
  53. Plan: 4 to add, 0 to change, 0 to destroy.
  54. ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
  55. Saved the plan to: tf.plan
  56. To perform exactly these actions, run the following command to apply:
  57.     terraform apply "tf.plan"
复制代码
创建node group iam
  1. terraform apply "tf.plan"
复制代码
输出:
  1. aws_iam_role.eks-nodegroup-role: Creating...
  2. aws_iam_role.eks-nodegroup-role: Creation complete after 2s [id=eks-nodegroup-role]
  3. aws_iam_role_policy_attachment.eks-nodegroup-role-AmazonEKS_CNI_Policy: Creating...
  4. aws_iam_role_policy_attachment.eks-nodegroup-role-AmazonEC2ContainerRegistryReadOnly: Creating...
  5. aws_iam_role_policy_attachment.eks-nodegroup-role-AmazonEKSWorkerNodePolicy: Creating...
  6. aws_iam_role_policy_attachment.eks-nodegroup-role-AmazonEC2ContainerRegistryReadOnly: Creation complete after 1s [id=eks-nodegroup-role-20241027130604526800000001]
  7. aws_iam_role_policy_attachment.eks-nodegroup-role-AmazonEKS_CNI_Policy: Creation complete after 1s [id=eks-nodegroup-role-20241027130604963000000002]
  8. aws_iam_role_policy_attachment.eks-nodegroup-role-AmazonEKSWorkerNodePolicy: Creation complete after 2s [id=eks-nodegroup-role-20241027130605372700000003]
  9. Apply complete! Resources: 4 added, 0 changed, 0 destroyed.
复制代码
转载请著名原文地址:https://www.cnblogs.com/Sunzz/p/18498915
6. 创建Node Group

定义eks_node_group.tf文件
  1. resource "aws_eks_node_group" "node_group1" {
  2.   cluster_name    = aws_eks_cluster.tf-eks.name
  3.   node_group_name = "node_group1"
  4.   ami_type        = "AL2_x86_64"
  5.   capacity_type   = "ON_DEMAND"
  6.   disk_size       = 20
  7.   instance_types   = ["t3.medium"]
  8.   node_role_arn   = aws_iam_role.eks-nodegroup-role.arn
  9.   subnet_ids = [
  10.       aws_subnet.tf_eks_subnet1.id,
  11.       aws_subnet.tf_eks_subnet2.id
  12.     ]
  13.   scaling_config {
  14.     desired_size = 1
  15.     max_size     = 2
  16.     min_size     = 1
  17.   }
  18.   update_config {
  19.     max_unavailable = 1
  20.   }
  21.   depends_on = [
  22.     aws_iam_role_policy_attachment.eks-nodegroup-role-AmazonEKSWorkerNodePolicy,
  23.     aws_iam_role_policy_attachment.eks-nodegroup-role-AmazonEKS_CNI_Policy,
  24.     aws_iam_role_policy_attachment.eks-nodegroup-role-AmazonEC2ContainerRegistryReadOnly,
  25.   ]
  26. #  remote_access {
  27. #    ec2_ssh_key = aws_key_pair.tf-keypair.key_name
  28. #    source_security_group_ids = [
  29. #           aws_security_group.tf_security_group.id
  30. #    ]
  31. #  }
  32. }
  33. resource "aws_eks_node_group" "node_group2" {
  34.   cluster_name    = aws_eks_cluster.tf-eks.name
  35.   node_group_name = "node_group2"
  36.   ami_type        = "AL2_x86_64"
  37.   capacity_type   = "ON_DEMAND"
  38.   disk_size       = 20
  39.   instance_types  = ["t3.medium"]
  40.   node_role_arn   = aws_iam_role.eks-nodegroup-role.arn
  41.   subnet_ids = [
  42.       aws_subnet.tf_eks_subnet1.id,
  43.       aws_subnet.tf_eks_subnet2.id
  44.     ]
  45.   scaling_config {
  46.     desired_size = 1
  47.     max_size     = 2
  48.     min_size     = 1
  49.   }
  50.   update_config {
  51.     max_unavailable = 1
  52.   }
  53.   depends_on = [
  54.     aws_iam_role_policy_attachment.eks-nodegroup-role-AmazonEKSWorkerNodePolicy,
  55.     aws_iam_role_policy_attachment.eks-nodegroup-role-AmazonEKS_CNI_Policy,
  56.     aws_iam_role_policy_attachment.eks-nodegroup-role-AmazonEC2ContainerRegistryReadOnly,
  57.   ]
  58. #  remote_access {
  59. #    ec2_ssh_key = aws_key_pair.tf-keypair.key_name
  60. #    source_security_group_ids = [
  61. #           aws_security_group.tf_security_group.id
  62. #    ]
  63. #  }
  64. }
复制代码
表明

EKS 节点组定义

扩展和更新配置

依靠关系

远程访问配置(被注释掉)

预创建
  1. terraform plan -out=tf.plan
复制代码
tf plan
  1.  Terraform will perform the following actions:
  2.   # aws_eks_node_group.node_group1 will be created
  3.   + resource "aws_eks_node_group" "node_group1" {
  4.       + ami_type               = "AL2_x86_64"
  5.       + arn                    = (known after apply)
  6.       + capacity_type          = "ON_DEMAND"
  7.       + cluster_name           = "tf-eks"
  8.       + disk_size              = 20
  9.       + id                     = (known after apply)
  10.       + instance_types         = [
  11.           + "t3.medium",
  12.         ]
  13.       + node_group_name        = "node_group1"
  14.       + node_group_name_prefix = (known after apply)
  15.       + node_role_arn          = "arn:aws:iam::xxxxxx:role/eks-nodegroup-role"
  16.       + release_version        = (known after apply)
  17.       + resources              = (known after apply)
  18.       + status                 = (known after apply)
  19.       + subnet_ids             = [
  20.           + "subnet-01b5d98060f0063ef",
  21.           + "subnet-0a30534a829758774",
  22.         ]
  23.       + tags_all               = (known after apply)
  24.       + version                = (known after apply)
  25.       + scaling_config {
  26.           + desired_size = 1
  27.           + max_size     = 2
  28.           + min_size     = 1
  29.         }
  30.       + update_config {
  31.           + max_unavailable = 1
  32.         }
  33.     }
  34.   # aws_eks_node_group.node_group2 will be created
  35.   + resource "aws_eks_node_group" "node_group2" {
  36.       + ami_type               = "AL2_x86_64"
  37.       + arn                    = (known after apply)
  38.       + capacity_type          = "ON_DEMAND"
  39.       + cluster_name           = "tf-eks"
  40.       + disk_size              = 20
  41.       + id                     = (known after apply)
  42.       + instance_types         = [
  43.           + "t3.medium",
  44.         ]
  45.       + node_group_name        = "node_group2"
  46.       + node_group_name_prefix = (known after apply)
  47.       + node_role_arn          = "arn:aws:iam::xxxxx:role/eks-nodegroup-role"
  48.       + release_version        = (known after apply)
  49.       + resources              = (known after apply)
  50.       + status                 = (known after apply)
  51.       + subnet_ids             = [
  52.           + "subnet-01b5d98060f0063ef",
  53.           + "subnet-0a30534a829758774",
  54.         ]
  55.       + tags_all               = (known after apply)
  56.       + version                = (known after apply)
  57.       + scaling_config {
  58.           + desired_size = 1
  59.           + max_size     = 2
  60.           + min_size     = 1
  61.         }
  62.       + update_config {
  63.           + max_unavailable = 1
  64.         }
  65.     }
  66. Plan: 2 to add, 0 to change, 0 to destroy.
  67. ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
  68. Saved the plan to: tf.plan
  69. To perform exactly these actions, run the following command to apply:
  70.     terraform apply "tf.plan"
复制代码
创建Node Group
  1. terraform apply "tf.plan"
复制代码
输出如下:
  1. aws_eks_node_group.node_group2: Creating...
  2. aws_eks_node_group.node_group1: Creating...
  3. aws_eks_node_group.node_group1: Still creating... [10s elapsed]
  4. ......
  5. aws_eks_node_group.node_group1: Creation complete after 1m41s [id=tf-eks:node_group1]
  6. aws_eks_node_group.node_group2: Still creating... [1m50s elapsed]
  7. aws_eks_node_group.node_group2: Creation complete after 1m52s [id=tf-eks:node_group2]
  8. Apply complete! Resources: 2 added, 0 changed, 0 destroyed.
复制代码
7. 获取EKS信息

新增eks_output.tf

[code]# 输出 EKS 集群的名称output "eks_cluster_name" {  value = aws_eks_cluster.tf-eks.name  description = "The name of the EKS cluster"}# 输出 EKS 集群的 ARN(Amazon Resource Name)output "eks_cluster_arn" {  value = aws_eks_cluster.tf-eks.arn  description = "The ARN of the EKS cluster"}# 输出 EKS 集群的 API 服务器端点output "eks_cluster_endpoint" {  value = aws_eks_cluster.tf-eks.endpoint  description = "The endpoint of the EKS cluster"}# 输出 EKS 集群的当前状态output "eks_cluster_status" {  value = aws_eks_cluster.tf-eks.status  description = "The status of the EKS cluster"}# 输出与 EKS 集群关联的 VPC IDoutput "eks_cluster_vpc_id" {  value = aws_eks_cluster.tf-eks.vpc_config[0].vpc_id  description = "The VPC ID associated with the EKS cluster"}# 输出与 EKS 集群关联的安全组 IDoutput "eks_cluster_security_group_ids" {  value = aws_eks_cluster.tf-eks.vpc_config[0].cluster_security_group_id  description = "The security group IDs associated with the EKS cluster"}# 输出用于访问 EKS 集群的 kubeconfig 配置output "kubeconfig" {  value =




欢迎光临 ToB企服应用市场:ToB评测及商务社交产业平台 (https://dis.qidao123.com/) Powered by Discuz! X3.4