10 Testing and Refactoring

 

This chapter covers:

  • Tainting and rotating AWS access keys provisioned by Terraform
  • Module expansion refactoring techniques
  • Migrating state with terraform mv and terraform state commands
  • Importing existing resources with terraform import
  • Testing Infrastructure as Code with terraform-exec

The ancient Greek philosopher Heraclitus is famous for positing that: “Life is flux”. In other words, change is inevitable, and to resist change is to resist the essence of our existence. Perhaps nowhere is change more pronounced than in the software industry. Either due to changing customer requirements, or shifting market conditions, software is guaranteed to change. If not actively maintained, software degrades over time. Refactoring and testing are steps that developers take to keep software current.

What is refactoring? Refactoring is the art of improving the design of code without changing existing behavior or adding new functionality. Benefits of refactoring include:

  • Maintainability – the ability to quickly fix bugs and address problems faced by customers.
  • Extensibility – how easy it is to add new features. If your software is extensible, then you are more agile and able to respond to marketplace changes.
  • Reusability – removing duplicated and highly coupled code. Reusable code is readable and easier to maintain.

10.1  Self Service Infrastructure Provisioning

10.1.1    Architecture

10.1.2    Code

10.1.3    Preliminary Deployment

10.1.4    Tainting and Rotating Access Keys

10.2  Refactoring Terraform Configuration

10.2.1    Modularizing Code

10.2.2    Module Expansions

10.2.3    Replacing Multi-Line Strings with Local Values

10.2.4    Looping Through Multiple Module Instances

10.2.5    New IAM Module

10.3  Migrating Terraform State

10.3.1    State File Structure

10.3.2    Moving Resources

10.3.3    Redeploy

10.3.4    Importing Resources

10.4  Testing Infrastructure as Code

10.4.1    Writing a Basic Terraform Test

10.4.2    Test Fixtures

10.4.3    Running Tests

10.5  Fireside Chat

10.6  Summary