Data Sources and EC2 Instances
We start by grabbing an AMI via a data
source, and building an instance from it.
Some resources:
- Terraform data source
aws_ami
- Getting the latest Ubuntu AMI using the
aws_ami
data source. - The AWS API on describing images, which directly correlates to the filter we'll use
Here's the configuration for finding an existing AMI based on some filters and other parameters:
1# File cloudcasts.tf 2# Find an official Ubuntu AMI 3 4data "aws_ami" "ubuntu" { 5 most_recent = true 6 7 filter { 8 name = "name" 9 values = ["ubuntu/images/hvm-ssd/ubuntu-focal-20.04-amd64-server-*"]10 }11 12 filter {13 name = "virtualization-type"14 values = ["hvm"]15 }16 17 filter {18 name = "architecture"19 values = ["x86_64"]20 }21 22 owners = ["099720109477"] # Canonical official23}
We can see what Terraform will do with this:
1# Make the file standard terraform format2terraform fmt3 4# See if we broke anything5terraform plan6# No changes. Infrastructure is up-to-date.
But let's use the AMI we created in our Packer video:
1# File cloudcasts.tf 2# Find the AMI we created 3 4data "aws_ami" "app" { 5 most_recent = true 6 7 filter { 8 name = "state" 9 values = ["available"]10 }11 12 filter {13 name = "tag:Component"14 values = ["app"]15 }16 17 filter {18 name = "tag:Project"19 values = ["cloudcasts"]20 }21 22 filter {23 name = "tag:Environment"24 values = ["staging"]25 }26 27 #filter {28 # name = "name"29 # values = ["cloudcast-staging-*-app"]30 #}31 32 owners = ["self"]33}
Then we can create an ec2 from that AMI with the aws_instance
resource.
We can update file cloudcasts.tf
to add that resource definition:
1# File cloudcasts.tf 2 3resource "aws_instance" "cloudcasts_web" { 4 ami = data.aws_ami.app.id 5 instance_type = "t3.small" 6 7 root_block_device { 8 volume_size = 8 # GB 9 volume_type = "gp3"10 }11}
And then run a plan/apply to see the changes.
1terraform plan2terraform apply # prompted to confirm