Use Datasources, here to keep the AWS AMI (windows) updated.
main.tf
provider "aws" {
region = var.aws_region
access_key = var.access_key
secret_key = var.secret_key
}
resource "aws_security_group" "my_security_group" {
name = var.security_group
description = "SG for EC2 instance"
vpc_id = var.vpc_id
ingress {
from_port = 8080
to_port = 8080
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
ingress {
from_port = 22
to_port = 22
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
egress {
from_port = 0
to_port = 65535
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
tags= {
Name = var.security_group
}
}
resource "aws_instance" "my_instance" {
ami = data.aws_ami.AMIWindows.id
key_name = var.key_name
instance_type = var.instance_type
subnet_id = var.subnet_id
vpc_security_group_ids= [aws_security_group.my_security_group.id]
tags= {
Name = var.tag_name
}
}
resource "aws_eip" "my_eip" {
vpc = true
instance = aws_instance.my_instance.id
tags= {
Name = "myEIP"
}
variables.tf
variable "aws_region" {
description = "AWS region"
default = "us-east-1"
}
variable "access_key" {
type = string
}
variable "secret_key" {
type = string
}
variable "vpc_id" {
type = string
}
variable "subnet_id" {
type = string
}
variable "key_name" {
description = "Key Pair"
default = "KP-win2022-Jenkins-MASTER-us-east-1"
}
variable "instance_type" {
description = "EC2 instance type"
default = "t3.small"
}
variable "security_group" {
description = "Security Group"
default = "SG"
}
variable "tag_name" {
description = "EC2 Tag for Name"
default = "my-ec2-instance"
}
variable "ami_id" {
description = "AMI"
default = "ami-0b9064170e32bde34"
}
datasources.tf
data "aws_ami" "AMIWindows" {
most_recent = true
owners = ["801119661308"]
filter {
name = "name"
values = ["Windows_Server-2022-English-Full-Base-*"]
}
}