Terraform 入门

Set the instance name with a variable

Create a new file called variables.tf with a block defining a new instance_name variable in the learn-terraform-aws-instance directory.

$ touch variables.tf
variable "instance_name" {
  description = "Value of the Name tag for the EC2 instance"
  type        = string
  default     = "Ansible_mem"
}

variable "instance_ami" {
  description = "Value of the ami for the EC2 instance"
  type        = string
  default     = "ami-08a0d1e16fc3f61ea"
}

variable "instance_type" {
  description = "Value of the type for the EC2 instance"
  type        = string
  default     = "t2.micro"
}

variable "availability_zone" {
  description = "Value of the AZ for the EC2 instance"
  type        = string
  default     = "us-east-1b"
}

variable "vpc_security_group_ids" {
  description = "Value of the SG for the EC2 instance"
  type        = set(string)
  default     = ["sg-052590e460117f9ad"]
}

variable "key_name" {
  description = "Value of the SG for the EC2 instance"
  type        = string
  default     = "Ansible"
}

Output EC2 instance configuration

$ touch outputs.tf
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
}

main.tf

terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 4.16"
    }
  }

  required_version = ">= 1.2.0"
}

provider "aws" {
  region  = "us-east-1"
}

resource "aws_instance" "app_server" {
  count                      = 2
  ami               		= var.instance_ami
  instance_type     		= var.instance_type
  availability_zone 		= var.availability_zone
  vpc_security_group_ids     = var.vpc_security_group_ids
  key_name                   = var.key_name

  tags = {
     Name = "${var.instance_name}_${count.index+1}"
  }
}

参考 https://developer.hashicorp.com/terraform/tutorials/aws-get-started/infrastructure-as-code

posted @ 2024-06-13 14:10  goldtree358  阅读(31)  评论(0)    收藏  举报