Skip to content

Terraform Workflow

← Back to all decks

47 cards — 🟢 8 easy | 🟡 21 medium | 🔴 8 hard

🟢 Easy (8)

1. What is one reason why manual processes can be helpful?

Show answer For learning a platform when first starting out

Remember: "init → plan → apply = the Terraform workflow." init downloads providers, plan previews, apply executes.

2. What is Terraform and what is infrastructure as code?

Show answer Terraform is an open-source Infrastructure as Code tool that lets you define cloud and on-prem infrastructure resources in declarative configuration files, then build and manage those resources safely and efficiently.

Remember: "CI/CD for Terraform: PR triggers plan, merge triggers apply." Atlantis and Terraform Cloud automate this.

3. How to identify which workspace are you using?

Show answer `terraform workspace show` displays the name of the currently active workspace. Workspaces let you manage multiple environments (dev, staging, prod) from the same configuration. Each workspace has its own state file. List all with `terraform workspace list`.
Gotcha: save plans with `terraform plan -out=plan.tfplan` — plans expire if state changes between plan and apply.

4. What are the advantages in using Terraform or IaC in general?

Show answer - Full automation: In the past, resource creation, modification and removal were handled manually or by using a set of tooling. With Terraform or other IaC technologies, you manage the full lifecycle in an automated fashion.
- Modular and Reusable: Code that you write for certain purposes can be used and assembled in different ways. You can write code to create resources on a public cloud and it can be shared with other teams who can also use it in their account on the same (or different) cloud>
- Improved testing: Concepts like CI can be easily applied on IaC based projects and code snippets. This allow you to test and verify operations beforehand
-

5. What are some use cases for using Terraform?

Show answer - Infra provisioning and management: You need to automated or code your infra so you are able to test it easily, apply it and make any changes necessary.
- Multi-cloud environment: You manage infrastructure on different clouds, but looking for a consistent way to do it across the clouds
- Consistent environments: You manage environments such as test, production, staging, ... and looking for a way to have them consistent so any modification in one of them, applies to other environments as well

6. How to create a new workspace?

Show answer `terraform workspace new ` creates a new workspace and switches to it immediately. Each workspace gets its own state file, allowing parallel environments from the same codebase.
Example: `terraform workspace new staging`. Use `terraform.workspace` in your config to vary resources per workspace (e.g., smaller instances in dev). List workspaces with `terraform workspace list`.

7. Every time there is a change in tags standards (for example your team decided to change one of the tags' name) you find yourself changing tags in multiple files and you find the process quite tedious. What can be done about it?

Show answer Use `default_tags` in the provider configuration to apply tags automatically to all resources. Example in AWS provider: `default_tags { tags = { Environment = var.env, Team = "platform" } }`. This eliminates repetitive tag blocks across resources and ensures consistency. Individual resource tags merge with and can override default_tags. Changes propagate automatically on the next apply.

8. An engineer in your team complains about having to copy-paste quite a lot of code between different folders and files of Terraform. What would you do?

Show answer Suggest using Terraform modules to encapsulate reusable infrastructure patterns. Modules group related resources into a single unit with defined inputs (variables) and outputs.
Example: a 'vpc' module that creates VPC, subnets, route tables, and NAT gateways — called once per environment with different parameters. This follows DRY (Don't Repeat Yourself) principles and reduces copy-paste errors.

🟡 Medium (21)

1. How do you handle secrets and sensitive information in Terraform configurations?

Show answer Managing secrets in Terraform involves avoiding hardcoding sensitive information directly in configuration files. Best practices include:
* Use Variables: Define variables for sensitive information and set them externally.
* Environment Variables: Utilize environment variables to pass sensitive data securely.
* Secret Management Tools: Integrate with secret management tools like HashiCorp Vault or AWS Secrets Manager.
* Avoid Hardcoding: Refrain from hardcoding passwords, API keys, or other sensitive data in plain text.
Proper handling of secrets is crucial for security and compliance.

2. How to manage multiple AWS accounts?

Show answer One way is to define multiple different provider blocks, each with its own "assume_role"

```\nprovider "aws" {\n region = "us-west-1"\n alias = "some-region"\n\n assume_role {\n role_arn = "arn:aws:iam:::role/"\n }\n}\n```

Gotcha: Atlantis auto-plans on every PR update. Merge = apply. Make sure PR reviewers understand the plan output.

3. Explain how to use Terraform with version control systems like Git.

Show answer Using Terraform with version control involves:
* Repository Setup: Create a Git repository to store Terraform configurations.
* Commit and Push: Regularly commit and push changes to the repository.
* Branching: Utilize branches for different environments or features.
* Pull Requests: Use pull requests for code review and collaboration.
* Tags: Tag releases for versioning and reproducibility.
* CI/CD Integration: Integrate with CI/CD pipelines for automated testing and deployment.

4. Why is it advisable to avoid using manual processes when creating infrastructure at scale?

Show answer - Declarative: Terraform uses the declarative approach (rather than the procedural one) in order to define end-status of the resources
- No agents: as opposed to other technologies (e.g. Puppet) where you use a model of agent and server, with Terraform you use the different APIs (of clouds, services, etc.) to perform the operations
- Community: Terraform has strong community who constantly publishes modules and fixes when needed. This ensures there is good modules maintenance and users can get support quite quickly at any point
-

5. What is Infrastructure as Code (IaC)?

Show answer Infrastructure as Code (IaC) is a key DevOps practice that involves managing and provisioning infrastructure using code rather than manual processes. In the context of Terraform, IaC means representing infrastructure configurations as code in declarative language syntax. This code defines the desired state of the infrastructure, allowing for version control, collaboration, and automation of the entire infrastructure lifecycle.

6. How to create multiple AWS instances but each with a different name?

Show answer ```\nresource "aws_instance" "server" {\n count = 6\n\n tags = {\n Name = "instance-${count.index}"\n }\n}\n```

The above configuration will create 6 instances, each with a different name.

Remember: "Pre-commit hooks catch issues before CI." terraform fmt, terraform validate, tflint in pre-commit.

7. How do you test and lint modules during development?

Show answer ```bash\nterraform -chdir=examples/vpc init\nterraform -chdir=examples/vpc validate\nterraform -chdir=examples/vpc plan\ntflint --module\n```

- `terraform validate` catches syntax errors and missing providers.
- Running `plan` against an example stack surfaces integration issues before promotion.
- `tflint --module` adds provider-specific linting; tools like Terratest can provision ephemeral infra for assertions.
- Include these commands in CI so every module change is exercised automatically.

8. What structure layout do you use for your projects?

Show answer There is no right or wrong answer, just what you personally adopted or your team, and being able to explain why.

One common approach is to have a separate directory for each environment.

```\nterraform_project/\n staging/\n production/\n```

Each environment has its own backend (as you don't want to use the same authentication and access controls for all environments)

Going further, under each environment you'll separate between components, applications and services

```\nterraform_project/\n staging/\n applications/\n some-app-service-1/\n some-app-service-2/\n databases/\n mongo/\n postgres/\n networking/\n```

9. One of the engineers in your team complains the inline shell scripts are quite big and maintaining them in Terraform files seems like a bad idea. What would you do?

Show answer A good solution for not including shell scripts inline (as in inside terraform configuration files) is to keep them in a separate file and then use the terraform `templatefile` function to render and get them as a string

10. When working with nested layout of many directories, it can make it cumbresome to run terraform commands in many different folders. How to deal with it?

Show answer There are multiple ways to deal with it:

1. Write scripts that perform some commands recursively with different conditions
2. Use tools like Terragrunt where you commands like "run-all" that can run in parallel on multiple different paths

Remember: "Blue-green deploys with Terraform: create new, switch traffic, destroy old." Terraform isn't ideal for this — it's declarative, not orchestrative.

11. How do you avoid accidentally applying changes in Terraform?

Show answer By running terraform plan first to review changes, and using version control for .tf files. Also, you can use a manual approval workflow or the -destroy and -refresh-only plan options to be explicit. Terraform Cloud/Enterprise can enforce manual confirms and policies (Sentinel).

Remember: "Terraform PR workflow: branch → plan → review → merge → apply." Never apply from a feature branch.

12. How can you manage secrets/credentials in CI/CD?

Show answer That very much depends on the CI/CD system/platform you are using.

- GitHub Actions: Use Open ID Connect (OIDC) to establish connection with your provider. You then can specify in your GitHub Actions workflow the following:

```\n- uses: aws-actions/configure-aws-credentials@v1\nwith:\n role-to-assume: arn:aws:iam::someIamRole\n aws-region: ...\n```

- Jenkins: If Jenkins runs on the provider, you can use the provider access entities (like roles, policies, ...) to grant the instance, on which Jenkins is running, access control
- CircleCI: you can use `CircleCI Context` and then specify it in your CircleCI config file

```\ncontext:\n- some-context\n```

13. What files do you have in your Terraform projects?

Show answer Again, no right or wrong answer. Just your personal experience.

main.tf
providers.tf
outputs.tf
variables.tf
dependencies.tf

Each one of these files can be divided to smaller parts if needed (no reason to maintain VERY long files)

Remember: "terraform apply -auto-approve skips confirmation." Only use in CI after a reviewed plan.

14. What's a typical Terraform workflow?

Show answer 1. Write Terraform definitions: `.tf` files written in HCL that described the desired infrastructure state (and run `terraform init` at the very beginning)
2. Review: With command such as `terraform plan` you can get a glance at what Terraform will perform with the written definitions
3. Apply definitions: With the command `terraform apply` Terraform will apply the given definitions, by adding, modifying or removing the resources

This is a manual process. Most of the time this is automated so user submits a PR/MR to propose terraform changes, there is a process to test these changes and once merged they are applied (`terraform apply`).

Remember: "Terraform Cloud runs: plan, cost estimation, sentinel policy check, apply." Each step is a gate.

15. How does Terraform manage secrets and sensitive information?

Show answer Terraform provides several mechanisms for managing secrets and sensitive information. One common approach is to use input variables with sensitive data types (string, object, etc.) and mark them as sensitive. Additionally, Terraform supports the use of environment variables, external vaults, or third-party tools for managing secrets. It's crucial to avoid storing sensitive information directly in Terraform configurations to ensure security and compliance. Best practices include leveraging secure storage solutions and not committing sensitive data to version control.

Remember: "terraform refresh is now terraform apply -refresh-only." Explicit refresh is better than auto-refresh during plan.

16. How does Terraform support the concept of "immutable infrastructure"?

Show answer Immutable infrastructure is the practice of not modifying running infrastructure components but instead replacing them with new instances. Terraform supports this concept by facilitating the creation and management of infrastructure as code. When changes are needed, Terraform generates a new plan and applies it, resulting in the recreation of resources with the updated configuration. This approach ensures consistency, reproducibility, and easier rollbacks. Immutable infrastructure is aligned with Terraform's declarative nature, where the desired state is defined, and Terraform determines the actions required to achieve that state.

17. How do you install Terraform?

Show answer To install Terraform, you can follow these general steps:
* Download the appropriate Terraform binary for your operating system from the official website (https://www.terraform.io/downloads.html).
* Extract the downloaded archive to a directory in your system's PATH.
* Verify the installation by running terraform --version in the terminal. If installed correctly, it will display the installed Terraform version.

18. Explain the benefits of using Terraform with infrastructure orchestration tools.

Show answer Using Terraform with infrastructure orchestration tools like Jenkins, GitLab CI, or AWS CodePipeline offers several benefits:
* Automation: Enables automated infrastructure provisioning and updates.
* Integration: Integrates seamlessly with CI/CD pipelines.
* Versioning: Facilitates version-controlled infrastructure as code.
* Scalability: Scales infrastructure provisioning across environments.
* Consistency: Ensures consistent deployments in various scenarios.
* Auditing: Provides audit trails for changes made to infrastructure.
* Collaboration: Supports collaborative development practices.

19. You noticed your Terraform code includes quite a lot of hardcoded values (like ports, subnets, ...) and they are duplicated in many locations. How'd you deal with it?

Show answer Using variables might not be a good solution because some things shouldn't be exposed and accidentally overridden. In such case you might want to use the concept of `locals`

20. How does Terraform manage secrets, and what are the alternatives to storing them securely?

Show answer Terraform typically manages secrets through variables. However, storing secrets directly in configuration files poses security risks. Alternatives include:
* Environment Variables: Load secrets from environment variables during runtime.
* Secret Management Tools: Utilize external tools like HashiCorp Vault or AWS Secrets Manager.
* Parameter Stores: Leverage cloud provider parameter stores for secure secret storage.
* Encryption: Encrypt sensitive data using encryption tools or services.

Remember: "State file backups: terraform.tfstate.backup is created on every apply." For real protection, use remote state with versioning.

21. You noticed a lot of your Terraform code/configuration is duplicated, between repositories and also within the same repository between different directories. What one way you may adopt that will help handling with that?

Show answer Using Terraform modules can help greatly with duplicated code and so different environments for example (staging and production) can reuse the same code by using the same modules.

Remember: "Terraform best practices: remote state, version pinning, small modules, CI/CD pipeline, code review for plans."

🔴 Hard (8)

1. Why workspaces might not be the best solution for managing states for different environments? like staging and production

Show answer One reason is that all the workspaces are stored in one location (as in one backend) and usually you don't want to use the same access control and authentication for both staging and production for obvious reasons. Also working in workspaces is quite prone to human errors as you might accidentally think you are in one workspace, while you are working a completely different one.

2. How do you handle sensitive information like API keys or passwords in Terraform configurations?

Show answer Handling sensitive information in Terraform involves:
* Variables: Use input variables and prompt for sensitive values during runtime.
* Environment Variables: Leverage environment variables to store sensitive data.
* Secret Management Tools: Integrate with tools like HashiCorp Vault or external secret management systems.
* Terraform Vault Provider: Utilize the Vault provider for direct integration with HashiCorp Vault.
* Secure File Storage: Store sensitive files separately and reference them securely.

3. What are the pros and cons of using environment variables for managing secrets in Terraform configurations?

Show answer Pros:

- You avoid using secrets directly in configurations in plain text
- free (no need to pay for secret management platforms/solutions)
- Straightforward to use

Cons:

- Configurations might not be usable without the environment variables which may make impact the user experience as the user has to know what environment variables he should pass for everything to work properly
- Mostly managed outside of Terraform mechanisms which makes it hard to enforce, track, ... anything that is related to secrets when it depends on the user to pass environment variables

4. How does Terraform handle secret rotation for resources like database passwords?

Show answer Terraform doesn't handle secret rotation directly but can integrate with external tools. Strategies include:
* External Tools: Use secret management tools like HashiCorp Vault or AWS Secrets Manager for rotation.
* Variable Updates: Manually update secret variables in Terraform configurations.
* CI/CD Pipelines: Integrate secret rotation into CI/CD pipelines for automated updates.
* Custom Scripts: Employ custom scripts or Terraform provisioners for rotation.
* Rolling Updates: Rotate secrets in a rolling fashion to minimize downtime.

5. What's the difference between Terraform and technologies such as Ansible, Puppet, Chef, etc.

Show answer Terraform is considered to be an IaC technology. It's used for provisioning resources, for managing infrastructure on different platforms.

Ansible, Puppet and Chef are Configuration Management technologies. They are used once there is an instance running and you would like to apply some configuration on it like installing an application, applying security policy, etc.

Remember: "Workspaces separate state, not code." Same config, different state files.

6. Explain the difference between Terraform and other configuration management tools.

Show answer While traditional configuration management tools like Ansible, Chef, and Puppet focus on automating the configuration of software on existing servers, Terraform is specifically designed for provisioning and managing infrastructure. Terraform is an Infrastructure as Code tool that allows you to define, deploy, and update infrastructure across various cloud providers and on-premises environments. Unlike configuration management tools, Terraform is not tied to a specific technology stack and is cloud-agnostic, providing a unified approach to managing diverse infrastructure resources.

7. Discuss the considerations for managing security groups and firewall rules in Terraform.

Show answer Managing security groups and firewall rules in Terraform involves:
* Variable Configuration: Using variables for flexible security group configurations.
* Security Group Rules: Defining rules based on protocols, ports, and sources.
* Dynamic Block Usage: Employing dynamic blocks for dynamic rule creation.
* Provider-Specific Rules: Adapting configurations to the specificities of each cloud provider.
* Network Policies: Implementing network policies for fine-grained control.

8. What is "Terraform Enterprise," and how does it cater to enterprise-scale infrastructure deployments?

Show answer Terraform Enterprise is a commercial offering by HashiCorp designed for enterprise-scale infrastructure management. Features include:
* Collaboration: Enables collaboration and access control for large teams.
* VCS Integration: Integrates with version control systems for automated workflows.
* Registry Integration: Connects with Terraform Registry for module sharing.
* Policy Enforcement: Enforces policies for compliance and security.
* Workspaces: Supports multiple workspaces for environment isolation.
* Remote Operations: Facilitates remote execution of Terraform runs.