纯实操,无详细说明。

目录

安装 Terraform 1 2

$ wget -O- https://apt.releases.hashicorp.com/gpg | sudo gpg --dearmor -o /usr/share/keyrings/hashicorp-archive-keyring.gpg
$ 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
$ sudo apt update && sudo apt install terraform
$ terraform -help
$ terraform -install-autocomplete

安装 AWS CLI 3

$ curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"
$ unzip awscliv2.zip
$ sudo ./aws/install
$ aws --version
$ which aws
$ ls -l /usr/local/bin/aws

AWS IAM 用户凭证

$ export AWS_ACCESS_KEY_ID=AKABC************123
$ export AWS_SECRET_ACCESS_KEY=XYZ**********************************789

Terraform 配置

$ mkdir terraform-on-aws
$ cd terraform-on-aws
$ touch terraform.tf main.tf variables.tf outputs.tf

下面是一个基础的、简单的、且完整的示例:


terraform {
  required_version = ">= 1.3.7"

  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = ">= 4.37.0"
    }
  }
}

provider "aws" {
  region  = "ap-northeast-1"
}

resource "aws_instance" "app_server" {
  ami           = "ami-0bba69335379e17f8"
  instance_type = "t2.micro"

  tags = {
    Name = var.instance_name
  }
}

variable "instance_name" {
  description = "Value of the Name tag for the EC2 instance"
  type        = string
  default     = "ExampleAppServerInstance"
}

output "instance_id" {
  description = "ID of the EC2 instance"
  value       = aws_instance.app_server.id
}

output "instance_public_ip" {
  description = "Public IP address of the EC2 instance"
  value       = aws_instance.app_server.public_ip
}

初始化目录

$ terraform init

格式化和验证配置

$ terraform fmt
$ terraform validate

创建基础设施

$ terraform apply

检查状态

$ terraform show
$ terraform state list

检查输出值

$ terraform output

销毁基础设施

$ terraform destroy