环境CentOS7.9
1. 下载安装terraform
打开https://www.terraform.io/downloads.html,复制下载地址

wget https://releases.hashicorp.com/terraform/0.15.4/terraform_0.15.4_linux_amd64.zip
解压后,移动到/bin目录
unzip terraform_0.15.4_linux_amd64.zip
mv terraform /bin/
2. 配置awscli(这里默认已经配置好aws AMI access key)
安装awscli
yum install awscli -y
配置awscli,输入id,key,地区和输出格式信息
aws configure
AWS Access Key ID [****************65UO]: ^C
[root@192-168-64-138 aws]# aws configure
AWS Access Key ID [****************65UO]:
AWS Secret Access Key [****************iOBH]:
Default region name [ap-northeast-2]:
Default output format [json]:
3. 编写main.tf文件
以下main.tf文件对于t2.micro是完全适用得,需要自己修改region,vpc_security_group_ids,subnet_id
aws自有ami镜像获取方式如下:
aws ec2 describe-images --owners self amazon
#mkdir aws
#cd aws
#vim main.tf
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 3.27"
}
}
required_version = ">= 0.14.9"
}
provider "aws" {
profile = "default"
region = "ap-northeast-2"
}
resource "aws_instance" "app_server" {
ami = "ami-0005600074f3aa4be"
instance_type = "t2.micro"
vpc_security_group_ids=["sg-066b80c1d6a8d170c"]
subnet_id="subnet-0a792e831feab123a"
tags = {
Name = "ExampleAppServerInstance"
}
}
4. 开始创建
首先需要init目录
#terraform init
Initializing the backend...
Initializing provider plugins...
- Reusing previous version of hashicorp/aws from the dependency lock file
- Using previously-installed hashicorp/aws v3.42.0
Terraform has been successfully initialized!
You may now begin working with Terraform. Try running "terraform plan" to see
any changes that are required for your infrastructure. All Terraform commands
should now work.
If you ever set or change modules or backend configuration for Terraform,
rerun this command to reinitialize your working directory. If you forget, other
commands will detect it and remind you to do so if necessary.
会看到目录下安装了aws的provider模块
创建
#terraform apply
Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following symbols:
+ create
Terraform will perform the following actions:
# aws_instance.app_server will be created
+ resource "aws_instance" "app_server" {
+ ami = "ami-0005600074f3aa4be"
+ arn = (known after apply)
+ associate_public_ip_address = (known after apply)
+ availability_zone = (known after apply

本文介绍如何使用Terraform在AWS上部署EC2实例,包括安装配置Terraform及AWS CLI、编写main.tf文件定义资源、执行创建与销毁操作。
最低0.47元/天 解锁文章
2038

被折叠的 条评论
为什么被折叠?



