All topics

Terraform interview questions

51 questions, 49 with answers. 1,454 open jobs in India ask for Terraform.

  1. What is IaC? What is Terraform?

    Infrastructure as Code, or IaC, is the practice of automating the provisioning of your cloud resources through code, rather than manually on the console. It facilitates for better tracking of resources, and allows for infrastructure configurations to be replicated over various projects.

    Terraform is one of many tools that fall under IaC. It'a used by engineers across the board as it's reusable, cloud agnostic and idempotent.

    From Tech Vault (Apache 2.0)

  2. Difference between Terraform, AWS CloudFormation and Azure ARM?
    • Terraform is cloud-agnostic (it can be used with multiple cloud providers)
    • CloudFormation is AWS-propietary
    • Azure ARM is Azure-propietary

    From Tech Vault (Apache 2.0)

  3. What is the difference between Terraform and Ansible?

    Terraform allows you to define what infrastructure you want. Ansible allows you to configure your infrastructure.

    An example would be, using Terraform to create a VM, and using Ansible to install and run services within it.

    From Tech Vault (Apache 2.0)

  4. What is Terraform state?

    In general terms, the Terraform state is a real-time description of all cloud infrastructure that has been created by terraform. The Terraform state however, branches into two:

    • Current state: Description of all infrastructure created by Terrafrom in the present. Usually stored in .tfstate files.
    • Desired state: Description of what you want to be created in the cloud. Stored in .tf files

    Terraform will always match the current state to the desired state.

    From Tech Vault (Apache 2.0)

  5. What is a local/remote state and when should I use them?

    A local state is a state that is stored in your machine, whereas a remote state is a state that is stored somewhere in the cloud, like S3 Buckets on AWS or Azure Blob Storage on Azure.

    • Use a local state when you're working independently on infrastructure.
    • Use a remote state when collaborating as part of a team.

    From Tech Vault (Apache 2.0)

  6. What are most common Terraform commands?
    • terraform init: Initialises Terraform in our directory, installs provider plugins and configures our backend. This allows us to start working with Terraform.
    • terraform plan: Compares our current & desired states and shows us what changes need to be made to match them
    • terraform apply: Makes the changes to our current state to meet our desired state

    From Tech Vault (Apache 2.0)

  7. What is Terraform backend?

    The Terraform backend is effectively where our Terraform statefile (.tfstate is stored). The backend can either be local (on your local machine), or remote (S3, Azure blob .etc).

    From Tech Vault (Apache 2.0)

  8. What are modules in Terraform?

    Terraform modules are resuable blocks of Terraform resources that are usually grouped by the services that they fall under. For example, when working with AWS, all of your networking-related resources may be created within a module named 'vpc' and all of your storage-related resources may be placed in an 's3' module.

    From Tech Vault (Apache 2.0)

  9. What are providers in Terraform?

    Terraform providers are plugins that enable Terraform to make API calls to other services, such as AWS, Azure, GCP and CloudFlare.

    From Tech Vault (Apache 2.0)

  10. How can you import existing resources under Terraform management?
    • Create an import block with the resource id (for later versions of terraform, you can use the 'identity' attribute)
    • Run terraform import <resource> (you can just run terraform apply for later versions of terraform)

    From Tech Vault (Apache 2.0)

  11. What is Terragrunt?

    Terragrunt is a tool that falls under the umbrella of Terraform. It's purpose is to keep our Terraform code DRY, and is best-used when reusing Terraform configurations across multiple environments, such as desired states and backends.

    From Tech Vault (Apache 2.0)

  12. I have 3 people in my team who want to work on the same AWS Infrastructure on Terraform as well as same state. What can I do to ensure there are no clashes?

    Configure a remote backend with state-locking enabled.

    From Tech Vault (Apache 2.0)

  13. In a pipeline, where would you store the Terraform state?

    You need to store your state remotely. Pipelines are ephemeral, so with a local state, each runner would have their own state, causing collisions and corruption due to re-creation attempts.

    From Tech Vault (Apache 2.0)

  14. How does state file locking work?

    When a terraform plan or a terraform apply is run, terraform first acquires a state lock before reading and comparing state, which stops other engineers from making changes to the state. As soon as the plan/apply is done, the state lock is released and the state is free to be changed again.

    From Tech Vault (Apache 2.0)

  15. What is Checkov?

    Chekov is a security scanning tool that scans your desired state and checks for compliance with security best-practices.

    From Tech Vault (Apache 2.0)

  16. How can one export data from one module to another?

    Create output variables in the module you want to export data from, and define them in other modules.

    From Tech Vault (Apache 2.0)

  17. Which command can be used to reconcile the Terraform state with the actual real-world infrastructure?

    Import our resources by either:

    • Creating an import block with the resource id (for later versions, you can use the 'identity' attribute)
    • Running terraform import <resource> (you can just run terraform apply for later versions of terraform)

    From Tech Vault (Apache 2.0)

  18. How do you handle secrets and sensitive data in Terraform?

    Store all sensitive data in .tfvars files, and place them in .gitignore.

    From Tech Vault (Apache 2.0)

  19. What are some best practices when writing Terraform code?
    • Keep code DRY (Don't Repeat Yourself)
    • Break up your Terraform configuration into reusable modules
    • Keep statefiles hidden (.tfstate)

    From Tech Vault (Apache 2.0)

  20. Should .terraform.lock.hcl be included in the .gitignore file?

    Per the Terraform documentation on the Dependency Lock File:

    Terraform automatically creates or updates the dependency lock file each time you run the terraform init command. You should include this file in your version control repository so that you can discuss potential changes to your external dependencies via code review, just as you would discuss potential changes to your configuration itself.

    The key to understanding why you should commit that file is found in the following section on Dependency Installation Behavior:

    When terraform init is working on installing all of the providers needed for a configuration, Terraform considers both the version constraints in the configuration and the version selections recorded in the lock file.

    If a particular provider has no existing recorded selection, Terraform will select the newest available version that matches the given version constraint, and then update the lock file to include that selection.

    If a particular provider already has a selection recorded in the lock file, Terraform will always re-select that version for installation, even if a newer version has become available. You can override that behavior by adding the -upgrade option when you run terraform init, in which case Terraform will disregard the existing selections and once again select the newest available version matching the version constraint.

    Essentially this is intended to have Terraform continue to use the version of the provider selected when you added it. If you do not checkin the lock file, you will always be automatically upgraded to the latest version that obeys the constraint in code, which could lead to unintended consequences.

    Note: You can force Terraform to upgrade when doing the init call by passing the -upgrade flag.

    terraform init -upgrade
    

    Update for Cross-Platform Development

    From the Terraform documentation on the providers lock command:

    Specifying Target Platforms In your environment you may, for example, have both developers who work with your Terraform configuration on their Windows or macOS workstations and automated systems that apply the configuration while running on Linux.

    In that situation, you could choose to verify that all of your providers support all of those platforms, and to pre-populate the lock file with the necessary checksums, by running terraform providers lock and specifying those three platforms:

    terraform providers lock \
        -platform=windows_amd64 \
        -platform=darwin_amd64 \
        -platform=linux_amd64 \
        -platform=darwin_arm64 \
        -platform=linux_arm64
    

    The above example uses Unix-style shell wrapping syntax for readability. If you are running the command on Windows then you will need to replace the backslashes with carets (for cmd) or backticks (for PowerShell).

    So you should still check the lock file into version control, but you should ensure the lock file contains the checksums for providers on all platforms.

    From Stack Overflow: asked by engineer-x, answered by DarrellNorton (CC BY-SA 4.0)

  21. Should I commit .tfstate files to Git?

    TL;DR:

    Important! Storing in source control could expose potentially sensitive data and risks running Terraform against an old version of state. Don't do it.

    Terraform no longer recommends storing state in source control. Your 'good' options are remote or local.

    Remote state grants significant benefits vs both local and storing in source control. Details of these are below.

    Original answer:

    Yevgeniy's answer is a good one. The issue is somewhat less controversial now as Terraform have updated their docs to state:

    Terraform also puts some state into the terraform.tfstate file by default. This state file is extremely important; it maps various resource metadata to actual resource IDs so that Terraform knows what it is managing. This file must be saved and distributed to anyone who might run Terraform. It is generally recommended to setup remote state when working with Terraform. This will mean that any potential secrets stored in the state file, will not be checked into version control

    So there is no longer a disagreement between established best practice and official recommendations.

    Update 2019-05-17

    In the most recent version of the docs this has been changed to say:

    ... This state is stored by default in a local file named "terraform.tfstate", but it can also be stored remotely, which works better in a team environment. ...

    I don't expect the advice will ever revert to source control being the preferred method of storing state.

    Despite the docs quote above remote state is still beneficial as a solo developer

    Remote state allows the solo developer to:

    • Work on/run their Terraform code from several devices
    • Easily backup and protect against losing the state file, depending on backend chosen
    • Segregate sections of their architecture via outputs
    • Automatically encrypt state file at rest, depending on backend chosen

    From Stack Overflow: asked by Golo Roden, answered by Tom Manterfield (CC BY-SA 4.0)

  22. Best practices when using Terraform? Is there any official guide to it?

    I am also in a state of migrating existing AWS infrastructure to Terraform so shall aim to update the answer as I develop.

    I have been relying heavily on the official Terraform examples and multiple trial and error to flesh out areas that I have been uncertain in.

    .tfstate files

    Terraform config can be used to provision many boxes on different infrastructure, each of which could have a different state. As it can also be run by multiple people this state should be in a centralised location (like S3) but not git.

    This can be confirmed looking at the Terraform .gitignore.

    Developer control

    Our aim is to provide more control of the infrastructure to developers whilst maintaining a full audit (git log) and the ability to sanity check changes (pull requests). With that in mind the new infrastructure workflow I am aiming towards is:

    1. Base foundation of common AMI's that include reusable modules e.g. puppet.
    2. Core infrastructure provisioned by DevOps using Terraform.
    3. Developers change Terraform configuration in Git as needed (number of instances; new VPC; addition of region/availability zone etc).
    4. Git configuration pushed and a pull request submitted to be sanity checked by a member of DevOps squad.
    5. If approved, calls webhook to CI to build and deploy (unsure how to partition multiple environments at this time)

    Edit 1 - Update on current state

    Since starting this answer I have written a lot of TF code and feel more comfortable in our state of affairs. We have hit bugs and restrictions along the way but I accept this is a characteristic of using new, rapidly changing software.

    Layout

    We have a complicated AWS infrastructure with multiple VPC's each with multiple subnets. Key to easily managing this was to define a flexible taxonomy that encompasses region, environment, service and owner which we can use to organise our infrastructure code (both terraform and puppet).

    Modules

    Next step was to create a single git repository to store our terraform modules. Our top level dir structure for the modules looks like this:

    tree -L 1 .
    

    Result:

    ├── README.md
    ├── aws-asg
    ├── aws-ec2
    ├── aws-elb
    ├── aws-rds
    ├── aws-sg
    ├── aws-vpc
    └── templates
    

    Each one sets some sane defaults but exposes them as variables that can be overwritten by our "glue".

    Glue

    We have a second repository with our glue that makes use of the modules mentioned above. It is laid out in line with our taxonomy document:

    .
    ├── README.md
    ├── clientA
    │   ├── eu-west-1
    │   │   └── dev
    │   └── us-east-1
    │       └── dev
    ├── clientB
    │   ├── eu-west-1
    │   │   ├── dev
    │   │   ├── ec2-keys.tf
    │   │   ├── prod
    │   │   └── terraform.tfstate
    │   ├── iam.tf
    │   ├── terraform.tfstate
    │   └── terraform.tfstate.backup
    └── clientC
        ├── eu-west-1
        │   ├── aws.tf
        │   ├── dev
        │   ├── iam-roles.tf
        │   ├── ec2-keys.tf
        │   ├── prod
        │   ├── stg
        │   └── terraform.tfstate
        └── iam.tf
    

    Inside the client level we have AWS account specific .tf files that provision global resources (like IAM roles); next is region level with EC2 SSH public keys; Finally in our environment (dev, stg, prod etc) are our VPC setups, instance creation and peering connections etc. are stored.

    Side Note: As you can see I'm going against my own advice above keeping terraform.tfstate in git. This is a temporary measure until I move to S3 but suits me as I'm currently the only developer.

    Next Steps

    Read the rest at the sourceFrom Stack Overflow: asked by Marc Young, answered by Ewan (CC BY-SA 4.0)

  23. What is the difference between AWS ASG Launch Templates and Launch Configurations?

    Launch templates (LTs) are newer than launch configurations (LCs) and provide more options to work with. Thus, the AWS documentation recommends use of launch templates (LTs) over launch configuration (LCs):

    We recommend that you create Auto Scaling groups from launch templates to ensure that you're getting the latest features from Amazon EC2.

    One of the practical key differences between LT and LC is the fact that LC is immutable. Once you define it, you can't edit it. Only a replacement is an option. However, a single LT can have multiple versions:

    defining a launch template instead of a launch configuration allows you to have multiple versions of a template. With versioning, you can create a subset of the full set of parameters and then reuse it to create other templates or template versions.

    Also LTs provide more EC2 options for you to configure, for example, dedicated hosting can be set only using a LT. Similarly, ability to use T2 unlimited burst credit option is only available in a LT.

    Thus if you can, its better to follow AWS recommendation and use LT.

    From Stack Overflow: asked by Dat Ho, answered by Marcin (CC BY-SA 4.0)

  24. What's the most efficient way to determine the minimum AWS permissions necessary for a Terraform configuration?

    Here is another approach, similar to what was said above, but without getting into CloudTrail -

    1. Give full permissions to your IAM user.
    2. Run TF_LOG=trace terraform apply --auto-approve &> log.log
    3. Run cat log.log | grep "DEBUG: Request"

    You will get a list of all AWS Actions used.

    From Stack Overflow: asked by Colin Dean, answered by AvnerSo (CC BY-SA 4.0)

  25. Is there a way to nuke all AWS resources in an AWS account?

    There is no way to delete all resources in an account owned by a particular user but there is a way to delete all resources in an account.

    You can use aws-nuke which was created somewhat out of the same use case you described.

    1. At first, you need to set an account alias for your account.
    2. You must create a config file.
    3. Then you can list down all resources that will be deleted using the following command:

      aws-nuke -c config/nuke-config.yml --profile aws-nuke-example

    4. Add --no-dry-run option to permanently delete all resources in the same command.

    5. There are also multiple filter options available such as target, resource type, exclude, etc. that you can leverage to suit your needs.

    From Stack Overflow: asked by Phelodas, answered by Shwetabh Shekhar (CC BY-SA 4.0)

  26. Can Terraform be used to provision on-premises servers?

    Terraform operates by calling into the APIs of various service providers and systems. Thus in principle Terraform can manage anything that has an API, and in practice it has existing support for a few different on-premises-capable systems, including:

    If the compute resources in your existing datacenter infrastructure are already managed with one of these systems, or if you are willing to install them, then Terraform can be used to manage at least parts of these systems. (For full details, see the documentation for each provider linked above.)

    Terraform's plugin architecture allows support for other systems to be developed, so other API-driven datacenter management systems such as The Foreman could be supported by Terraform, and indeed third parties have developed integrations with others that are distributed outside of the "official set" that HashiCorp hosts.

    From Stack Overflow: asked by qubsup, answered by Martin Atkins (CC BY-SA 4.0)

  27. Is there an AND/OR conditional operator?

    This is more appropriate in the actual version (0.12.X)

    The supported operators are:

    Equality: == and !=
    Numerical comparison: >, <, >=, <=
    Boolean logic: &&, ||, unary !

    https://www.terraform.io/docs/configuration/interpolation.html#conditionals

    condition_one and condition two:

    count = var.condition_one && var.condition_two ? 1 : 0
    

    condition_one and NOT condition_two:

    count = var.condition_one && !var.condition_two ? 1 : 0
    

    condition_one OR condition_two:

    count = var.condition_one || var.condition_two ? 1 : 0
    

    From Stack Overflow: asked by user2062360, answered by NicoKowe (CC BY-SA 4.0)

  28. What does terraform refresh really do?

    terraform refresh attempts to find any resources held in the state file and update with any drift that has happened in the provider outside of Terraform since it was last ran.

    For example, lets say your state file contains 3 EC2 instances with instance ids of i-abc123, i-abc124, i-abc125 and then you delete i-abc124 outside of Terraform. After running terraform refresh, a plan would show that it needs to create the second instance while a destroy plan would show that it only needs to destroy the first and third instances (and not fail to destroy the missing second instance).

    Terraform makes a very specific decision to not interfere with things that aren't being managed by Terraform. That means if the resource doesn't exist in its state file then it absolutely will not touch it in any way. This enables you to run Terraform alongside other tools as well as making manual changes in the AWS console. It also means that you can run Terraform in different contexts simply by providing a different state file to use, allowing you to split your infrastructure up into multiple state files and save yourself from catastrophic state file corruption.

    To get yourself out of your current hole I suggest you use terraform import liberally to get things back into your state file or, if possible, manually destroy everything outside of Terraform and start from scratch.

    In future I would suggest both splitting out state files to apply for more granular contexts and also to store your remote state in an S3 bucket with versioning enabled. You could also look towards tools like Terragrunt to lock your state file to help avoid corruption or wait for the native state file locking in the upcoming 0.9 release of Terraform.

    From Stack Overflow: asked by Bruno9779, answered by ydaetskcoR (CC BY-SA 3.0)

  29. Can a resource be passed as a variable into a module?

    This is possible with terraform > 0.12. You can use the object type, but you have to explicitly list fields that you use within your module.

    # module's variables.tf
    variable "parent_vnet" {
      # List each field in `azurerm_route_table` that your module will access
      type = object({
        name = string
        location = string
        resource_group_name = string
      })
    } 
    # caller
    resource "azurerm_route_table" "my_parent_vnet" {
      # ...
    }
    module "my-module" {
      parent_vnet = azurerm_route_table.my_parent_vnet
    }
    

    From Stack Overflow: asked by user2926169, answered by Cory ODaniel (CC BY-SA 4.0)

  30. Conditional creation of a resource based on a variable in .tfvars

    Add a count parameter with a ternary conditional using the variable declared in .tfvars like this:

    resource "cloudflare_record" "record" {
      count = var.cloudflare ? 1 : 0
      zone_id = "${data.cloudflare_zones.domain.zones[0].id}"
      name    = "${var.subdomain}"
      value   = "${var.origin_server}"
      type    = "CNAME"
      ttl     = 1
      proxied = true
    }
    

    In this example var.cloudflare is a boolean declared in the .tfvars file. If it is true a count of 1 record will be created. If it is false a count of 0 record will be created.

    After the count apply the resource becomes a group, so later in the reference use 0-index of the group:

    cloudflare_record.record[0].some_field
    

    From Stack Overflow: asked by Joel Guerra, answered by Joel Guerra (CC BY-SA 4.0)

After the last page: 2 questions more, without answers. Go to the last page

Related topics

Where these questions come from

Open-source collections on GitHub, official documentation, a government careers service and the Stack Exchange sites, each used under its own licence. The answers are the authors' own words: we only tidy the layout, leave out pictures, and cut a long answer with a link to the rest. Stack Exchange answers stay under CC BY-SA and name who asked and who answered.