Search for previous posts

Blog History

2/27/21

AWS Terraform automation

This is a tutorials starter Terraform playbook broken up into three separate sections while referencing the outputs from other files, enabling you to selectively apply sections. There is the VPC portion, the logging portion, and finally launching the EC2 instances. I will post some more advanced Terraform tutorials at some point.

NOTE: When using this to continually manage resources, it's very important to keep state files safe and in a central place for team access. They can be uploaded to remote cloud destinations, such as Terraform Cloud or a S3 bucket. In my demo example, everything is just kept local.

I also included a picture below of my VSCode setup, as it might give you a helpful visual of how to efficiently work with this tool, as well as understand the moving pieces a little better.

I use Windows, so Chocolatey is utilized to install and update Terraform. 

You can find the files here at my GitHub:

https://github.com/centifanto/Terraform

For each region, you will need to copy whole file structure into a separate folder. Would look like this:

  • Terraform
    • East
      • 1VPC
      • 2Logging
      • 3EC2

As mentioned, each one of these can be applied separately. The steps are initialize, plan, and apply. You need to do this in each directory to apply the code:

  • terraform init
    • This initializes the directory that you are in, downloading modules and dependencies for that specific plan.
  • terraform plan -var-file="cidr_region.tfvars" -out test.tfplan
    • This will validate the plan to ensure syntax and variables are correct. It uses .tfvars files to input the unique variables for the CIDR and region. It then spits this into a ready to go plan.
    • When in directories != 1VPC, you will need to specify the path to this tfvars file like this:
      • "C:\Users\%userprofile%\OneDrive\VScode\Terraform\Terraform_demo\1VPC\cidr_region.tfvars"
  • terraform apply test.tfplan
    • Builds your plan
  • terraform destroy -var-file="cidr_region.tfvars"
    • Destroys all of the resources you just built
    • Conversely, you can also comment out items in your config and Terraform will see them as "removed". The next time you run "apply" it will ask you if you want to destroy those commented out resources.
Pay attention to the red boxes in the image below.
  • You will need a data.tf file in each directory that is not 1VPC. This data file points the directory back to find the information from the terraform.tfstate file.
  • The terraform.tfstate file contains all of the actual resource ID's. This state file also has hooks into the outputs.tf file that enable you to define any information you want extracted and usable by other config files.



No comments:

Post a Comment