Terraform is an orchestration tool that can provision infrastructure with code. Instead of opening the AWS Management Console to create our resources, we can do that directly in our editor with HCL (HashiCorp's Configuration Langauge).🎉
In this example, we are creating an AWS resource of type aws_intstance with a unique name ec2_example. This resource spins up an ec2 server by launching a copy of the AMI(Amazon Machine Image).
The AMI is a dynamic value and needs to be updated when creating instances. You can find these on the AWS console or search for ubuntu images here (For t2.micro select hvm:ebs-ssd).
An s3 bucket is used for storage. To create a bucket a unique name is required. If you do not add one AWS will create one for you. To grant access to a bucket acl can be used. By default it is set to private. force_destory=true is set for testing purposes. This will allow us to delete the bucket with terraform destroy even if it is not empty.
versioning keeps different variants of an object in the bucket and outputs.tf will output the results of the file to the console after an apply.
In this example, remote state is being stored with a terraform.tfstate file. This is common practice when using Terraform with more than one person so state does not get locked and only one person can make changes at a time on the latest copy. Since the bucket we created is using versioning there will be a history of changes stored as well.
To add an object to a bucket the unique bucket name is required along with the key which defines the path of the file that's created in AWS.
Groups are collections of IAM users that share specific privileges or policies.
Two resources are created here, one for the IAM group and another to attach a policy to that group. The attribute policy_arn is set to attach the Administrator Access policy to the IAM group.
After an IAM group is created we can add new users to it. This is down with the resource type aws_iam_group_membership. Users are passed to this resource along with the name of the group.
To run these examples locally, clone the repo and navigate to the root directory. In your terminal cd into one of the above directories and follow these steps:
Initialize Terraform: terraform init
Check the plan to make sure the configuration will do what we expect: terraform plan
Apply the execution plan and build the stack: terraform apply
Check the resource is up: terraform state list or terraform state show 'type.name'ex. aws_instance.ec2_example
Tear down all provisions: terraform destroy
If you found this article useful give the repo a ⭐️ and check back later for more examples of automating AWS with Terraform. 🙂✌🏾