发布于 2026-01-05 7 阅读
0

HashiCorp 的 Terraform 端到端 AWS 云基础设施自动化 什么是云计算?什么是 AWS?云自动化:你需要了解的内容及其重要性 什么是 Terraform?嗯……为什么要使用 Terraform?网站代码 Terraform 代码 HashiCorp 的 Terraform 端到端 AWS 云基础设施自动化

通过 Terraform 实现 HashiCorp 的端到端 AWS 云基础设施自动化

什么是云计算?

什么是AWS?

云自动化:你需要了解的内容及其重要性

Terraform是什么?

嗯……为什么要使用 Terraform?

网站代码

Terraform 代码

通过 Terraform 实现 HashiCorp 的端到端 AWS 云基础设施自动化

从……开始

什么是云计算?

“当被问及‘云’是什么时,大多数人首先想到的要么是真正的云,要么是天空,要么是与天气有关的东西。”

简而言之,云计算是指通过互联网(“云”)提供计算服务,包括服务器、存储、数据库、网络、软件、分析和智能等,从而实现更快的创新、更灵活的资源和规模经济。您通常只需为使用的云服务付费,这有助于降低运营成本、更高效地运行基础设施,并随着业务需求的变化进行扩展。

什么是AWS?

替代文字

亚马逊网络服务 (AWS)是全球最全面、应用最广泛的云平台,在全球数据中心提供超过 212 项功能齐全的服务。AWS 是亚马逊的子公司,以按需付费的方式向个人、公司和政府提供云计算平台和 API。

2020 年,AWS 包含 212 多项服务,包括计算、存储、网络、数据库、分析、应用程序服务、部署、管理、移动、开发人员工具和物联网工具。

云自动化:你需要了解的内容及其重要性

替代文字

云计算正以前所未有的方式迈向新的领域。随着越来越多的组织迁移到某种类型的云平台,服务提供商也在不断探索创建真正全自动云环境的方法。虽然我们尚未完全实现这一目标,但我们正在不断接近。

云自动化是一个统称,通常用来指代那些能够帮助我们减少部署和维护云端IT基础设施时所需人工投入的专用软件、工具和操作。简而言之,它就是以编程方式自动执行任务。

自动化之所以被广泛接受和使用,一个关键原因是自动化减少了部署一系列任务所需的人工工作量和干预。

云基础设施自动化最佳工具包括:

如今,Hashicorp Terraform 是各个组织中最广泛使用的实现基础设施即代码 (IaC) 的工具

IaC 工具大致分为四类:

  • 临时脚本
  • 配置管理工具
  • 服务器模板工具
  • 服务器配置工具

Terraform是什么?

替代文字

Terraform是由HashiCorp开发的开源“基础设施即代码”工具,用于安全高效地构建、变更和版本控制基础设施。Terraform 可以管理现有的常用服务提供商以及定制的内部解决方案。

Terraform 是一款声明式编码工具,它允许开发人员使用名为 HCL(HashiCorp 配置语言)的高级配置语言来描述运行应用程序所需的云端或本地基础设施的“最终状态”。然后,它会生成一个实现该最终状态的计划,并执行该计划来配置基础设施。

Terraform 支持众多公共和私有云基础设施提供商,例如Amazon Web Services (AWS)IBM Cloud(以前称为 Bluemix)阿里云Google Cloud PlatformDigitalOceanLinodeMicrosoft AzureOracle Cloud InfrastructureOVHScalewayVMware vSphereOpen Telekom Cloud,以及OpenNebulaOpenstack

嗯……为什么要使用 Terraform?

没错,听起来可能不太现实,我们竟然能在不了解任何云命令的情况下搭建起完整的云基础设施。但我保证,读完这篇文章后,你一定会领略到Terraform的真正威力。

任何云服务都拥有美观且动态的图形用户界面 (GUI) 门户,用户友好且易于使用。只需点击几下,即可访问并使用其上的任何服务。但如今,自动化已成为主流,而仅靠 GUI 无法实现自动化。

此外,如果我们已经在云端创建了一个基础设施,现在需要再次创建完全相同的基础设施,那么使用图形用户界面(GUI)会非常耗时,而且人工操作难免会遗漏一些细节。这时,基础设施即代码(IaC)就派上了用场。开发人员编写代码来创建基础设施,运行这段代码后,只需一条命令即可创建完整的基础设施;如果想要销毁该基础设施,也只需运行一条命令即可。

因此,我创建了一个强大的 Terraform 设置,以帮助您实现完整的端到端云基础设施自动化,在这里我选择了 AWS 作为云基础设施提供商。

在开始编写代码之前,我们需要做一些设置……

真正的刺激现在才开始!!

替代文字

  • 要使用 AWS 服务,您需要登录 AWS 控制台,为此您必须拥有 AWS 账户。
    点击此处创建新的 AWS 账户。

    • 注意:AWS 账户通常需要信用卡。但由于疫情影响,AWS推出了 Educate 服务,因此您或许无需信用卡即可注册账户。
  • AWS CLI已安装并添加到路径中

    • 配置您的 AWS CLI(稍后会详细介绍……)
  • Terraform已安装并添加到路径

  • 为了遵循最佳实践,我们来创建一个用户

    • 请妥善保存您的 AWS 凭证文件(您在创建新用户时获得的凭证文件)。
  • 快速配置 AWS CLI:

$ aws configure
AWS Access Key ID [None]: ###############
AWS Secret Access Key [None]: 
###############
Default region name [None]: us-west-2
Default output format [None]: json
Enter fullscreen mode Exit fullscreen mode

AWS CLI 将此信息存储在名为 default 的配置文件(一组设置)中。

现在让我们来设置项目的工作流程。

  • 创建允许端口 80 的密钥和安全组。
  • 启动EC2 实例
  • 在这个 EC2 实例中,使用我们创建的密钥安全组。
  • 启动一个卷(EBS)并将该卷挂载到/var/www/html
  • 开发者已将代码上传到GitHub 仓库,该仓库中还有一些图片。
  • 将 GitHub 仓库代码复制到 /var/www/html 目录
  • 创建S3 存储桶,并将 GitHub 仓库中的镜像复制/部署到该 S3 存储桶中,并将权限更改为公开可读。
  • 使用 S3 存储桶(包含图像)创建CloudFront,并使用 CloudFront URL 更新 /var/www/html 中的代码。
  • 创建EBS 快照

开始进行 Terraform 云基础设施自动化!

  • 首先,我们编写网站代码并将其推送到远程 GitHub 仓库;然后编写 .tf 代码,将网站代码克隆到远程 AWS 实例等等……
  • 我们想要部署的网站代码
  • 我们将编写 Terraform 代码来创建云基础设施。

网站代码

<!DOCTYPE html> 
<html> 

<head> 
    <title> 
        Slack Invitation Link - hrshmistry
    </title> 

    <!-- Style to create button -->
    <style> 
        .SLK { 
            background-color: white; 
            border: 3px solid black; 
            color: green;

            text-align: center; 
            display: inline-block; 
            font-size: 80px; 
            cursor: pointer; 
        } 
    </style> 
</head> 

<body > 
    <center style="font-size:70px;color:red;font-family:'Courier New'">Hybrid Multi-Cloud</center>
    <p align = "center"><img src="https://s3hrsh.s3.ap-south-1.amazonaws.com/cloud.jpg" width="300" height="300"></p>
    <center style="font-size:40px;color:blue;font-family:'Courier New'">Your Personal Slack Invitation Link</center>

    <!-- Adding link to the button on the onclick event -->
<center>
    <button  class="SLK"
    onclick="window.location.href = 'https://join.slack.com/t/hybridmulti-cloud/shared_invite/zt-etnyk2vm-gngGCm2hnk1VbOPR9nGpnw';"> 
        JOIN NOW
    </button>
</center> 
</body> 

</html>
Enter fullscreen mode Exit fullscreen mode

Terraform 代码

  • 提供者
#Describing Provider
provider "aws" {
  region     = "ap-south-1"
  profile    = "harsh"
}
Enter fullscreen mode Exit fullscreen mode
  • 变量
#Creating Variable for AMI Id
variable "ami_id" {
  type    = string
  default = "ami-0447a12f28fddb066"
}

#Creating Variable for AMI Type
variable "ami_type" {
  type    = string
  default = "t2.micro"
}

#Creating Variable for key
variable "EC2_Key" {
  type    = string
  default = "Task1Key"
}
Enter fullscreen mode Exit fullscreen mode
  • 钥匙对
#Creating tls_private_key using RSA algorithm 
resource "tls_private_key" "tls_key" {
  algorithm = "RSA"
  rsa_bits  = 4096
}

#Generating Key-Value Pair
resource "aws_key_pair" "generated_key" {
  depends_on = [
    tls_private_key.tls_key
  ]

  key_name   = var.EC2_Key
  public_key = tls_private_key.tls_key.public_key_openssh
}

#Saving Private Key PEM File
resource "local_file" "key-file" {
  depends_on = [
    tls_private_key.tls_key
  ]

  content  = tls_private_key.tls_key.private_key_pem
  filename = var.EC2_Key
}
Enter fullscreen mode Exit fullscreen mode
  • 安全组
resource "aws_security_group" "firewall" {
  depends_on = [
      aws_key_pair.generated_key
  ]

  name         = "firewall"
  description  = "allows ssh and httpd protocol"

  #Adding Rules to Security Group
  ingress {
    description = "SSH Port"
    from_port   = 22
    to_port     = 22
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }

  ingress {
    description = "HTTPD Port"
    from_port   = 80
    to_port     = 80
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  } 

  egress {
    from_port   = 0
    to_port     = 0
    protocol    = "-1"
    cidr_blocks = ["0.0.0.0/0"]
  }

  egress {
    from_port   = 0
    to_port     = 0
    protocol    = "-1"
    cidr_blocks = ["0.0.0.0/0"]
  }

  tags = {
    Name = "security-group-1"
  }
}
Enter fullscreen mode Exit fullscreen mode
  • 启动 EC2 实例
resource "aws_instance" "autos" {
  depends_on = [
      aws_security_group.firewall
  ]

  ami           = var.ami_id
  instance_type = var.ami_type
  key_name      = var.EC2_Key
  security_groups = ["${aws_security_group.firewall.name}"]

  connection {
    type     = "ssh"
    user     = "ec2-user"
    private_key = tls_private_key.tls_key.private_key_pem
    host     = aws_instance.autos.public_ip
  }

  provisioner "remote-exec" {
    inline = [
      "sudo yum install httpd php git -y",
      "sudo systemctl restart httpd",
      "sudo systemctl enable httpd"
    ]
  }

  tags = {
    Name = "autos"
    env  = "Production"
  }
}
Enter fullscreen mode Exit fullscreen mode
  • EBS卷
#Creating EBS volume and attaching it to EC2 Instance.
resource "aws_ebs_volume" "ebs" {
  availability_zone = aws_instance.autos.availability_zone
  size              = 1

  tags = {
    Name = "autos_ebs"
  }
}

/*
variable "volume_name" {
  type    = string
  default = "dh"
}
*/

resource "aws_volume_attachment" "ebs_att" {
  device_name = "/dev/sdh"
  volume_id   = aws_ebs_volume.ebs.id
  instance_id = aws_instance.autos.id
  force_detach = true
}

output "autos_public_ip" {
  value = aws_instance.autos.public_ip
}

resource "null_resource" "print_public_ip" {
  provisioner "local-exec" {
    command = "echo ${aws_instance.autos.public_ip} > autos_public_ip.txt"
  }
}
Enter fullscreen mode Exit fullscreen mode
  • 在 EC2 实例中挂载卷并克隆 GitHub
resource "null_resource" "mount_ebs_volume" {
  depends_on = [
    aws_volume_attachment.ebs_att
  ]

  connection {
    type     = "ssh"
    user     = "ec2-user"
    private_key = tls_private_key.tls_key.private_key_pem
    host     = aws_instance.autos.public_ip
  }

  provisioner "remote-exec" {
      inline = [
        "sudo mkfs.ext4 /dev/xvdh",
        "sudo mount /dev/xvdh /var/www/html",
        "sudo rm -rf /var/www/html",
        "sudo git clone https://github.com/hrshmistry/Code-Cloud.git /var/www/html/"
      ]
    }
}
Enter fullscreen mode Exit fullscreen mode
  • 创建 S3 存储桶
resource "aws_s3_bucket" "S3" {
  bucket = "autos-s3-bucket"
  acl    = "public-read"
}

#Putting Objects in S3 Bucket
resource "aws_s3_bucket_object" "S3_Object" {
  depends_on = [
    aws_s3_bucket.S3
  ]

  bucket = aws_s3_bucket.S3.bucket
  key    = "Cloud.JPG"
  source = "D:/LW/Hybrid-Multi-Cloud/Terraform/tera/task/Cloud.JPG"
  acl    = "public-read"
}
Enter fullscreen mode Exit fullscreen mode
  • 使用 S3 Bucket Origin 创建 CloutFront
locals {
  S3_Origin_Id = aws_s3_bucket.S3.id
}

resource "aws_cloudfront_distribution" "CloudFront" {
  depends_on = [
    aws_s3_bucket_object.S3_Object
  ]

  origin {
    domain_name = aws_s3_bucket.S3.bucket_regional_domain_name
    origin_id   = aws_s3_bucket.S3.id
    # OR origin_id   = local.S3_Origin_Id
  }

  enabled             = true
  is_ipv6_enabled     = true
  comment             = "S3 Web Distribution"

  default_cache_behavior {
    allowed_methods  = ["DELETE", "GET", "HEAD", "OPTIONS", "PATCH", "POST", "PUT"]
    cached_methods   = ["GET", "HEAD"]
    target_origin_id = aws_s3_bucket.S3.id
    # OR origin_id   = local.S3_Origin_Id

    forwarded_values {
      query_string = false

      cookies {
        forward = "none"
      }
    }

    viewer_protocol_policy = "allow-all"
    min_ttl                = 0
    default_ttl            = 3600
    max_ttl                = 86400
  }

  # Cache behavior with precedence 0
  ordered_cache_behavior {
    path_pattern     = "/content/immutable/*"
    allowed_methods  = ["GET", "HEAD", "OPTIONS"]
    cached_methods   = ["GET", "HEAD", "OPTIONS"]
    target_origin_id = aws_s3_bucket.S3.id
    # OR origin_id   = local.S3_Origin_Id

    forwarded_values {
      query_string = false
      headers      = ["Origin"]

      cookies {
        forward = "none"
      }
    }

    min_ttl                = 0
    default_ttl            = 86400
    max_ttl                = 31536000
    compress               = true
    viewer_protocol_policy = "redirect-to-https"
  }

  # Cache behavior with precedence 1
  ordered_cache_behavior {
    path_pattern     = "/content/*"
    allowed_methods  = ["GET", "HEAD", "OPTIONS"]
    cached_methods   = ["GET", "HEAD"]
    target_origin_id = aws_s3_bucket.S3.id
    # OR origin_id   = local.S3_Origin_Id

    forwarded_values {
      query_string = false
      cookies {
        forward = "none"
      }
    }

    min_ttl                = 0
    default_ttl            = 3600
    max_ttl                = 86400
    compress               = true
    viewer_protocol_policy = "redirect-to-https"
  }

  price_class = "PriceClass_200"

  restrictions {
    geo_restriction {
      restriction_type = "whitelist"
      locations        = ["IN"]
    }
  }

  tags = {
    Name        = "CF Distribution"
    Environment = "Production"
  }

  viewer_certificate {
    cloudfront_default_certificate = true
  }

  retain_on_delete = true
}
Enter fullscreen mode Exit fullscreen mode
  • 修改 HTML 代码并在其中添加图片 URL。
resource "null_resource" "CF_URL"  {
  depends_on = [
    aws_cloudfront_distribution.CloudFront
  ]

  connection {
    type     = "ssh"
    user     = "ec2-user"
    private_key = tls_private_key.tls_key.private_key_pem
    host     = aws_instance.autos.public_ip
  }

  provisioner "remote-exec" {
    inline = [
      "echo '<p align = 'center'>'",
      "echo '<img src='https://${aws_cloudfront_distribution.CloudFront.domain_name}/Cloud.JPG' width='100' height='100'>' | sudo tee -a /var/www/html/Slack.html",
      "echo '</p>'"
    ]
  }
}
Enter fullscreen mode Exit fullscreen mode
  • 创建 EBS 快照卷
resource "aws_ebs_snapshot" "ebs_snapshot" {
  depends_on = [
   null_resource.CF_URL
  ]

  volume_id = aws_ebs_volume.ebs.id

  tags = {
    Name = "ebs_snap"
  }
}
Enter fullscreen mode Exit fullscreen mode
  • 接入基础设施
resource "null_resource" "web-server-site-on-browser" {
  depends_on = [
    null_resource.CF_URL
  ]

  provisioner "local-exec" {
    command = "brave ${aws_instance.autos.public_ip}/Slack.html"
  }
}
Enter fullscreen mode Exit fullscreen mode
  • 完成 Terraform 代码后,只需一条命令即可部署整个云基础设施!
terraform apply -auto-approve
Enter fullscreen mode Exit fullscreen mode
  • 要摧毁整个云基础设施,
terraform destroy -auto-approve
Enter fullscreen mode Exit fullscreen mode

至此,我们完美地完成了通过 HashiCorp 的 Terraform 实现的端到端 AWS 云基础设施自动化!

🔗 LinkedIn帖子发布指南

  • 完整代码请访问下方我的GitHub仓库。

GitHub 标志 hrshmistry / Cloud-Automation-Terraform

通过 Terraform 实现 HashiCorp 的端到端 AWS 云基础设施自动化

通过 Terraform 实现 HashiCorp 的端到端 AWS 云基础设施自动化

GitHub GitHub 顶级语言

本项目包含的内容有……

  • 创建允许端口 80 的密钥和安全组。
  • 启动EC2 实例。
  • 在此 EC2 实例中,请使用我们创建的密钥安全组。
  • 启动一个卷(EBS),并将该卷挂载到/var/www/html。
  • 开发者已将代码上传到GitHub 仓库,该仓库中还有一些图片。
  • 将 GitHub 仓库代码复制到 /var/www/html 目录
  • 创建S3 存储桶,并将 GitHub 仓库中的图像复制/部署到 S3 存储桶中,并将权限更改为公开可读。
  • 使用 S3 存储桶(包含图像)创建CloudFront,并使用 CloudFront URL 更新 /var/www/html 中的代码。
  • 创建EBS 快照

点击此处查看完整文章。

前往 Dev.to Post

发推文的方式

LinkedIn帖子发布指南

支持这项工作

GitHub 关注者 GitHub 星标 GitHub 分支

赫尔希米斯特里图像
文章来源:https://dev.to/hrshmistry/end-to-end-aws-cloud-infrastruct-automation-through-terraform-b​​y-hashicorp-2gkl