Terraform provides us a way to fetch the latest AMI in AWS while deploying our VMs. With terraform, we can make use of data sources to pull the latest AMI.
What is Amazon Machine Image(AMI)
An Amazon Machine Image (AMI) is used in creating virtual machines in AWS. It is possible to launch different types of instances from a single AMI. It is fast and easy to set up a VM with AMI as there is no need for manual setup and configuration.
To understand more about AMIs refer to this link.
What is Data sources in Terraform?
- With Data source, data can be fetched or computed for use from elsewhere in terraform configuration.
- Use of Data source allows a terraform configuration to make use of information defined outside of terraform.
- We can access a data source using a special kind of resource known as a data resource, declared using a data block.
let’s have a look at data source
Now let’s first understand how data source looks like:
This whole block is a data resource, “aws_ami” is a data source and amzLinux is just the local name of our data resource. This name can be used to refer to this data resource. The data resource calls the data source aws_ami.
Each data resource always calls a single data source which determines the kind of object it reads and what arguments are available.
Understanding the arguements of data source
most_recent, owners, and all filters defined inside the data block are the arguments for the data source aws_ami. Now let’s understand how these arguments work and help us in fetching the latest ami-id.
Let’s see how we choose an AMI from the web console of AWS.
We make use of several filters while searching for the desired AMI like virtualization, architecture, etc. Similarly, we are using these filters in our terraform configuration inside the definition of the data source.
Therefore, we can conclude that the data sources are making use of remote API calls to filter and fetch the latest AMI.
Calling data source in resources
Till now, we have defined the data source but we need to reference this data source inside a resource block to create a resource with the latest AMI.
Let’s see how to call the data source inside the resource block.
So, as we can see in the snapshot above we can reference the data source in the resource block as data <DatasourceName>.<LocalName>.id
In Conclusion, we learned how we can create data sources in terraform and reference the data source inside the resource block to fetch the latest AMI.