Learn HCP Terraform (TA-004) with Interactive Flashcards
Master key concepts in HCP Terraform through our interactive flashcard system. Click on each card to reveal detailed explanations and enhance your understanding.
HCP Terraform overview
HCP Terraform (formerly known as Terraform Cloud) is HashiCorp's managed service platform designed to help teams collaborate on infrastructure as code using Terraform. It provides a centralized environment where organizations can manage their Terraform workflows efficiently and securely.
Key features of HCP Terraform include:
**Remote State Management**: HCP Terraform stores your Terraform state files securely in the cloud, enabling team collaboration while preventing state file conflicts. State is encrypted at rest and versioned for easy rollback capabilities.
**Workspaces**: These are isolated environments that contain their own state, variables, and configurations. Workspaces allow teams to manage multiple infrastructure deployments from a single codebase, such as development, staging, and production environments.
**Version Control Integration**: HCP Terraform connects with popular VCS providers like GitHub, GitLab, and Bitbucket. This enables automatic Terraform runs when code changes are pushed, supporting GitOps workflows.
**Policy as Code with Sentinel**: Organizations can enforce compliance and governance policies using Sentinel, HashiCorp's policy-as-code framework. This ensures infrastructure changes meet organizational standards before being applied.
**Private Module Registry**: Teams can publish and share reusable Terraform modules internally, promoting consistency and reducing code duplication across projects.
**Cost Estimation**: Before applying changes, HCP Terraform can estimate the cost impact of infrastructure modifications, helping teams make informed decisions.
**Run Triggers**: Workspaces can be connected so that changes in one workspace automatically trigger runs in dependent workspaces, maintaining infrastructure dependencies.
**Team Management and RBAC**: Organizations can define teams with granular permissions, controlling who can read, plan, or apply changes to specific workspaces.
HCP Terraform offers multiple tiers including a free tier for small teams and paid tiers for enterprises requiring advanced features like SSO, audit logging, and enhanced support. It eliminates the operational overhead of managing Terraform infrastructure while providing enterprise-grade security and collaboration capabilities.
Remote execution in HCP Terraform
Remote execution in HCP Terraform (formerly Terraform Cloud) is a core feature that enables teams to run Terraform operations on HCP Terraform's managed infrastructure rather than on local machines. This approach offers significant advantages for enterprise environments and collaborative workflows.
When you configure remote execution, HCP Terraform becomes responsible for running terraform plan and terraform apply operations. Your local Terraform CLI acts as a client that triggers these operations and streams the output back to your terminal. The actual computation, state management, and provider interactions occur within HCP Terraform's secure environment.
Key benefits of remote execution include:
1. **Consistent Environment**: All team members execute Terraform in the same environment, eliminating "works on my machine" issues and ensuring reproducible results.
2. **Centralized State Management**: State files are stored securely in HCP Terraform, preventing conflicts and ensuring team members always work with the latest infrastructure state.
3. **Access Control**: Sensitive credentials and variables are stored in HCP Terraform and never exposed to individual workstations, enhancing security.
4. **Audit Logging**: Every plan and apply operation is logged, providing complete visibility into infrastructure changes and who made them.
5. **Policy Enforcement**: Sentinel policies or OPA policies can be evaluated before applies, ensuring compliance with organizational standards.
To enable remote execution, you configure a backend block in your Terraform configuration pointing to your HCP Terraform organization and workspace. When you run terraform init, the CLI establishes the connection to HCP Terraform.
Workspaces can be configured for either remote execution or local execution mode. Remote execution is the default and recommended approach for most production environments. The execution occurs on HCP Terraform runners, which handle provider authentication, network access to target infrastructure, and operation queuing to prevent concurrent modifications to the same resources.
HCP Terraform runs and applies
HCP Terraform (formerly Terraform Cloud) provides a managed environment for executing Terraform operations, with runs and applies being core concepts for infrastructure management.
**Terraform Runs**
A run in HCP Terraform represents the complete lifecycle of executing Terraform code. Each run consists of multiple phases:
1. **Plan Phase**: Terraform analyzes your configuration files, compares them against the current state, and generates an execution plan showing proposed changes. This phase helps teams review what modifications will occur before any infrastructure changes happen.
2. **Cost Estimation**: HCP Terraform can estimate the cost impact of proposed changes for supported cloud providers.
3. **Policy Check**: If Sentinel or OPA policies are configured, they evaluate the planned changes against organizational rules.
4. **Apply Phase**: The actual execution of infrastructure changes based on the approved plan.
**Apply Operations**
The apply phase executes the changes outlined in the plan. HCP Terraform supports different apply methods:
- **Manual Apply**: Requires explicit confirmation from a user before proceeding. This is ideal for production environments where human review is essential.
- **Auto Apply**: Automatically proceeds with the apply phase after a successful plan, useful for development environments or automated pipelines.
**Run Triggers**
Runs can be initiated through various methods:
- VCS webhooks when code is pushed
- API calls for CI/CD integration
- Manual triggers from the UI
- Run triggers from dependent workspaces
**State Management**
During applies, HCP Terraform securely manages state files, providing locking mechanisms to prevent concurrent modifications and maintaining version history for rollback capabilities.
**Run Environment**
HCP Terraform executes runs in isolated, ephemeral environments, ensuring consistency and security. Teams can configure variables, credentials, and provider settings at the workspace level for streamlined operations across multiple environments.
Team collaboration features
Team collaboration features in HCP Terraform (formerly Terraform Cloud) provide essential capabilities for organizations to manage infrastructure as code effectively across multiple team members. These features enable secure, organized, and efficient workflow management for Terraform operations.
**Teams and Organizations**: HCP Terraform allows you to create organizations that serve as containers for workspaces, teams, and policies. Within organizations, you can define teams with specific members, making it easier to group users based on their roles or project assignments.
**Role-Based Access Control (RBAC)**: Teams can be assigned different permission levels to workspaces. Common permissions include read, plan, write, and admin access. This granular control ensures team members only have access appropriate to their responsibilities, maintaining security and preventing unauthorized changes.
**Workspace Management**: Workspaces act as isolated environments where teams can manage distinct infrastructure components or environments (development, staging, production). Teams can be granted varying access levels across different workspaces, enabling proper separation of concerns.
**Run Approvals and Notifications**: Collaborative workflows benefit from run approval processes where designated team members must review and approve Terraform plans before they are applied. Integration with communication tools like Slack enables real-time notifications about infrastructure changes.
**Version Control Integration**: Teams can connect workspaces to version control systems like GitHub, GitLab, or Bitbucket. This enables code review processes, pull request workflows, and maintains a complete audit trail of infrastructure changes.
**Sentinel Policies**: Policy as code through Sentinel allows organizations to enforce compliance and governance rules across all team activities, ensuring infrastructure changes meet organizational standards.
**Audit Logging**: Comprehensive audit logs track all actions performed within the organization, providing visibility into who made changes and when, which is crucial for compliance and troubleshooting.
These collaboration features make HCP Terraform an enterprise-ready solution for teams managing infrastructure at scale.
Run triggers and notifications
Run triggers and notifications are powerful collaboration features in HCP Terraform (formerly Terraform Cloud) that help automate and coordinate infrastructure workflows across multiple workspaces.
**Run Triggers**
Run triggers establish dependencies between workspaces, allowing one workspace to automatically initiate a run in another workspace when its apply completes successfully. This is particularly useful when you have infrastructure that depends on resources managed in separate workspaces.
For example, if Workspace A manages your VPC and Workspace B manages EC2 instances within that VPC, you can configure Workspace B to trigger a run whenever Workspace A successfully applies changes. This ensures downstream infrastructure stays synchronized with upstream dependencies.
Key characteristics of run triggers:
- They create a source-to-target relationship between workspaces
- Only successful applies in the source workspace trigger runs in the target workspace
- A workspace can have multiple source workspaces configured
- Run triggers help maintain consistency across related infrastructure components
**Notifications**
Notifications allow HCP Terraform to send alerts about workspace events to external systems. This keeps teams informed about infrastructure changes and enables integration with existing communication and monitoring tools.
Supported notification destinations include:
- Slack channels
- Microsoft Teams
- Email addresses
- Generic webhooks for custom integrations
You can configure notifications to trigger on various events:
- Run started, needs attention, completed, or errored
- Assessment results
- Drift detection findings
Notifications help teams:
- Stay informed about infrastructure changes in real-time
- Respond quickly to failed runs or issues requiring approval
- Maintain audit trails of infrastructure modifications
- Integrate Terraform workflows with incident management systems
Both features enhance team collaboration and operational efficiency by automating coordination between workspaces and keeping stakeholders informed about infrastructure state changes throughout the deployment lifecycle.
Policy as Code with Sentinel
Policy as Code with Sentinel is a powerful governance framework integrated into HCP Terraform that enables organizations to define, manage, and enforce compliance policies programmatically. Sentinel acts as a policy-as-code framework developed by HashiCorp, allowing teams to write fine-grained, logic-based policies that automatically evaluate Terraform runs before infrastructure changes are applied.
Sentinel policies are written in a declarative language designed specifically for policy enforcement. These policies can inspect the planned changes, existing state, and configuration details of Terraform runs. They operate at different enforcement levels: advisory (warnings only), soft-mandatory (can be overridden by authorized users), and hard-mandatory (cannot be bypassed).
Key benefits of Sentinel include standardizing security practices across teams, ensuring compliance with regulatory requirements, and preventing costly misconfigurations. For example, organizations can create policies that require all S3 buckets to have encryption enabled, restrict instance types to approved sizes, or mandate specific tagging conventions for cost allocation.
Sentinel policies integrate into the HCP Terraform workflow by evaluating during the plan phase. When a terraform plan is executed, Sentinel checks the proposed changes against defined policies. If violations occur, the run can be blocked or flagged depending on the enforcement level.
Policies are organized into policy sets, which can be applied to specific workspaces or across entire organizations. This allows granular control over which policies apply to different environments or projects. Policy sets can be version-controlled in VCS repositories, enabling collaborative policy development and change tracking.
The Sentinel framework provides imports specifically for Terraform, including tfplan, tfconfig, tfstate, and tfrun. These imports give policy authors access to comprehensive data about infrastructure changes, making it possible to write sophisticated policies that address complex compliance requirements while maintaining developer productivity.
Cost estimation features
Cost estimation is a powerful feature available in HCP Terraform (formerly Terraform Cloud) that helps organizations understand the financial impact of infrastructure changes before they are applied. This feature automatically calculates the estimated monthly costs for resources defined in your Terraform configurations.
When you create a plan in HCP Terraform, the cost estimation feature analyzes the resources being created, modified, or destroyed and provides a detailed breakdown of expected costs. This happens during the plan phase, allowing teams to review potential expenses before committing changes to production infrastructure.
Key aspects of cost estimation include:
1. **Supported Providers**: Cost estimation works with major cloud providers including AWS, Azure, and Google Cloud Platform. It covers commonly used resources like compute instances, storage, databases, and networking components.
2. **Cost Breakdown**: The feature displays costs at multiple levels - per resource, per workspace, and aggregated across the organization. This granularity helps identify which specific resources contribute most to infrastructure spending.
3. **Delta Calculations**: When modifying existing infrastructure, cost estimation shows the difference between current and proposed configurations, highlighting whether changes will increase or decrease monthly spending.
4. **Policy Integration**: Organizations can use Sentinel policies to enforce cost-related governance rules. For example, you can create policies that require approval for changes exceeding a certain cost threshold or block deployments that would exceed budget limits.
5. **Run Task Integration**: Cost estimation can be configured as part of the workflow, ensuring financial review occurs consistently across all infrastructure changes.
6. **Visibility**: Cost estimates appear in the HCP Terraform UI during plan review, making financial information accessible to all team members involved in the approval process.
This feature is particularly valuable for organizations practicing FinOps, as it shifts cost awareness earlier in the development lifecycle and promotes financial accountability among infrastructure teams.
HCP Terraform workspaces
HCP Terraform workspaces are isolated environments within HCP Terraform (formerly Terraform Cloud) that manage separate instances of infrastructure configurations. Each workspace maintains its own state file, variables, and run history, enabling teams to organize and manage infrastructure deployments effectively.
Key characteristics of HCP Terraform workspaces include:
**State Management**: Each workspace stores its own Terraform state file remotely and securely. This eliminates the need for local state files and provides state locking to prevent concurrent modifications that could corrupt infrastructure.
**Variable Configuration**: Workspaces allow you to define workspace-specific variables, including sensitive variables that are encrypted and stored securely. This enables the same Terraform configuration to be deployed across different environments (development, staging, production) with varying parameters.
**VCS Integration**: Workspaces can connect to version control systems like GitHub, GitLab, or Bitbucket. When changes are pushed to the repository, HCP Terraform can trigger automatic plans or applies based on configured settings.
**Run Management**: Every terraform plan and apply operation is tracked as a run within the workspace. This provides a complete audit trail of all infrastructure changes, who initiated them, and their outcomes.
**Access Control**: Organizations can implement fine-grained permissions on workspaces, controlling who can read, plan, or apply changes. This supports team collaboration while maintaining security boundaries.
**Workspace Types**: HCP Terraform offers CLI-driven, VCS-driven, and API-driven workflows, giving teams flexibility in how they trigger infrastructure operations.
**Organization**: Workspaces can be tagged and grouped for easier management across large-scale deployments. Teams commonly create separate workspaces per environment, application, or region.
Unlike open-source Terraform workspaces (which are simply named state files), HCP Terraform workspaces are comprehensive management units that provide collaboration features, remote execution, and enterprise-grade security for infrastructure as code workflows.
Workspace variables and settings
Workspace variables and settings in HCP Terraform (formerly Terraform Cloud) are essential components for managing infrastructure configurations effectively across different environments.
**Workspace Variables**
Workspace variables allow you to customize Terraform runs for each workspace. There are two primary types:
1. **Terraform Variables**: These correspond to input variables defined in your Terraform configuration files. They set values for variables declared with the 'variable' block and influence how your infrastructure is provisioned.
2. **Environment Variables**: These are shell environment variables available during Terraform execution. They commonly store provider credentials (like AWS_ACCESS_KEY_ID) or configure Terraform behavior (like TF_LOG for debugging).
Variables can be marked as **sensitive**, which masks their values in the UI and logs, providing security for credentials and secrets. Variables can also be configured as **HCL** type to pass complex data structures like lists or maps.
**Variable Precedence**
HCP Terraform follows a specific precedence order: workspace-specific variables override variable set values, which override default values in configuration files.
**Variable Sets**
Variable sets allow you to define reusable groups of variables that can be applied across multiple workspaces, reducing duplication and ensuring consistency for shared configurations like provider credentials.
**Workspace Settings**
Key workspace settings include:
- **Execution Mode**: Choose between remote execution (runs on HCP Terraform) or local execution (runs on your machine)
- **Auto Apply**: Automatically apply successful plans or require manual confirmation
- **Terraform Version**: Specify which Terraform version to use
- **Working Directory**: Define the subdirectory containing your Terraform configuration
- **VCS Integration**: Connect to version control repositories for automatic triggering of runs
- **Run Triggers**: Configure dependencies between workspaces
These features enable teams to manage multiple environments efficiently while maintaining security and consistency across infrastructure deployments.
Projects for workspace organization
Projects in HCP Terraform provide a hierarchical organizational structure for managing workspaces, offering teams a powerful way to group and categorize their infrastructure configurations logically.
Projects serve as containers that hold multiple workspaces, enabling administrators to organize infrastructure based on business units, applications, environments, or any other logical grouping that makes sense for their organization. This hierarchical approach simplifies management at scale.
Key benefits of using Projects include:
1. **Logical Organization**: Teams can group related workspaces together, such as all workspaces for a specific application or department, making navigation and management more intuitive.
2. **Access Control**: Projects allow administrators to apply permissions at the project level, which then cascade to all workspaces within that project. This reduces administrative overhead when managing team access.
3. **Variable Sets**: Organizations can attach variable sets to projects, ensuring consistent configuration across all workspaces within that project.
4. **Visibility and Governance**: Projects provide better visibility into infrastructure ownership and help enforce governance policies across related workspaces.
When creating a workspace in HCP Terraform, you can assign it to a specific project. The default project is created automatically for each organization, and all workspaces must belong to exactly one project.
Common organizational patterns include:
- Organizing by environment (development, staging, production)
- Organizing by application or service
- Organizing by team or department
- Organizing by cloud provider or region
Projects support nested permission models, where organization owners have full access, and project-level permissions can be granted to specific teams. This enables fine-grained access control while maintaining simplicity in administration.
For Terraform Associate certification, understanding that Projects enhance workspace organization, simplify access management, and provide logical grouping capabilities is essential for managing infrastructure at enterprise scale.
Workspace execution modes
Workspace execution modes in HCP Terraform determine how and where Terraform operations are performed. There are three primary execution modes available: Remote, Local, and Agent.
**Remote Execution Mode** is the default setting for HCP Terraform workspaces. In this mode, Terraform plans and applies are executed on HCP Terraform's managed infrastructure. This provides several benefits including consistent execution environments, secure variable storage, and centralized state management. Team members can trigger runs through the UI, API, or VCS integrations, and all operations happen in the cloud.
**Local Execution Mode** allows you to run Terraform operations on your local machine while still using HCP Terraform for state storage and management. This is useful when you need access to local resources, credentials, or when debugging configurations. The state file remains stored in HCP Terraform, but the actual plan and apply commands execute locally.
**Agent Execution Mode** enables Terraform operations to run on self-hosted agents within your own infrastructure. This is particularly valuable when you need to access private resources behind firewalls or in air-gapped environments. Terraform Cloud Agents establish outbound connections to HCP Terraform and execute runs in your controlled environment.
To configure execution modes, navigate to workspace settings in the HCP Terraform UI or use the API. You can set the execution mode per workspace based on your specific requirements.
Key considerations when choosing execution modes include network access requirements, security policies, available credentials, and compliance needs. Remote mode offers simplicity and managed infrastructure, local mode provides flexibility for development, and agent mode bridges the gap between cloud management and private infrastructure access.
Understanding these execution modes is essential for the Terraform Associate certification as they represent fundamental concepts for managing infrastructure workflows effectively in enterprise environments.
Configuring the cloud block
The cloud block in Terraform is used to configure integration with HCP Terraform (formerly Terraform Cloud) or Terraform Enterprise. This configuration enables remote state management, remote operations, and team collaboration features.
To configure the cloud block, you add it within the terraform block in your configuration files. Here is the basic structure:
terraform {
cloud {
organization = "your-organization-name"
workspaces {
name = "your-workspace-name"
}
}
}
Key components of the cloud block include:
1. **Organization**: This required argument specifies the HCP Terraform organization where your workspaces reside. Organizations serve as containers for workspaces and team management.
2. **Workspaces**: This nested block defines which workspace to use. You can specify workspaces using either the 'name' attribute for a single workspace or 'tags' attribute to match multiple workspaces based on tag criteria.
3. **Hostname**: An optional argument that defaults to app.terraform.io. For Terraform Enterprise installations, you would specify your custom hostname here.
4. **Token**: While you can specify authentication tokens here, it is recommended to use environment variables (TF_TOKEN_app_terraform_io) or the terraform login command for security purposes.
When using the cloud block, Terraform stores state remotely in HCP Terraform and can execute runs remotely rather than on your local machine. This provides benefits such as centralized state storage, state locking, run history, and policy enforcement.
Important considerations: The cloud block cannot be used simultaneously with backend blocks. You must choose one approach for state management. Additionally, some arguments within the cloud block can be configured through environment variables, providing flexibility for different deployment scenarios.
After adding the cloud block, run terraform init to initialize the connection to HCP Terraform and migrate any existing state if necessary.
CLI-driven runs with HCP Terraform
CLI-driven runs with HCP Terraform allow you to execute Terraform operations from your local command line while leveraging HCP Terraform's powerful backend features for state management, collaboration, and governance.
When using CLI-driven runs, you configure your Terraform project to use HCP Terraform as a remote backend. This is accomplished by adding a cloud block or backend configuration in your Terraform configuration files. Once configured, commands like 'terraform plan' and 'terraform apply' are executed through HCP Terraform's infrastructure rather than on your local machine.
The workflow begins when you run Terraform commands locally. Your CLI sends the configuration to HCP Terraform, which then performs the actual execution in a secure, isolated environment. The output streams back to your terminal in real-time, providing a familiar experience while benefiting from centralized execution.
Key benefits of CLI-driven runs include:
1. **Centralized State Management**: State files are stored securely in HCP Terraform, enabling team collaboration and preventing state file conflicts.
2. **Consistent Environment**: Operations run in HCP Terraform's controlled environment, ensuring consistency across team members regardless of their local setups.
3. **Policy Enforcement**: Sentinel policies and cost estimation can be applied to all runs, maintaining governance standards.
4. **Audit Trail**: All operations are logged in HCP Terraform, providing visibility into who made changes and when.
5. **Secure Variable Storage**: Sensitive variables are stored encrypted in HCP Terraform rather than locally.
To enable CLI-driven runs, set the execution mode to 'remote' or 'cloud' in your workspace settings. You must authenticate using 'terraform login' to establish credentials.
This approach combines the convenience of local development with enterprise-grade features, making it ideal for teams transitioning from local Terraform usage to a more collaborative, governed workflow while maintaining familiar command-line interactions.
VCS integration and workflows
VCS (Version Control System) integration in HCP Terraform enables seamless collaboration between your infrastructure code repository and Terraform Cloud workspaces. This integration supports popular platforms like GitHub, GitLab, Bitbucket, and Azure DevOps.
When you connect a VCS repository to an HCP Terraform workspace, you establish an automated workflow that triggers Terraform runs based on repository events. The primary workflow types include:
**VCS-driven Workflow**: This is the most common approach where commits or pull requests to specified branches automatically initiate Terraform plans. When a pull request is opened, HCP Terraform runs a speculative plan and posts the results as a comment, allowing team members to review infrastructure changes before merging.
**Branch-based Triggers**: You can configure workspaces to monitor specific branches. Changes pushed to the designated branch (typically main or master) trigger automatic plan and apply operations, ensuring your infrastructure stays synchronized with your code.
**Pull Request Integration**: HCP Terraform provides feedback on pull requests by running plans and displaying results in the VCS interface. This enables code review processes to include infrastructure validation before changes are merged.
**Key Benefits**:
- Automatic plan execution on code changes
- Infrastructure change visibility in pull request discussions
- Audit trail linking infrastructure changes to specific commits
- Collaboration through familiar VCS workflows
- Policy enforcement through Sentinel before applies
**Configuration Steps**:
1. Connect your VCS provider to HCP Terraform organization settings
2. Create or configure a workspace with VCS connection
3. Select the repository and branch to monitor
4. Optionally specify working directory and trigger patterns
The VCS integration ensures infrastructure changes follow the same review and approval processes as application code, promoting GitOps practices and maintaining consistency across your team's deployment workflows.
API tokens and authentication
API tokens are essential security credentials used to authenticate with HCP Terraform (formerly Terraform Cloud) and Terraform Enterprise. They serve as the primary mechanism for programmatic access to the platform's REST API and CLI operations.
There are three types of tokens in HCP Terraform:
1. **User Tokens**: These are personal tokens tied to individual user accounts. They inherit all permissions associated with that user across organizations and workspaces. Users can create multiple tokens and should treat them like passwords, keeping them secure and rotating them regularly.
2. **Team Tokens**: Each team can have one API token that represents the team's collective permissions. These tokens are useful for CI/CD pipelines where actions should be attributed to a team rather than an individual user.
3. **Organization Tokens**: These tokens have permissions across the entire organization and are typically used for organization-level automation tasks. They should be used sparingly due to their broad access scope.
To authenticate with the Terraform CLI, you can use the `terraform login` command, which initiates an OAuth flow and stores the resulting token in your credentials file (typically at `~/.terraform.d/credentials.tfrc.json`). Alternatively, you can set the `TF_TOKEN_app_terraform_io` environment variable.
For API requests, tokens are included in the Authorization header using the Bearer scheme: `Authorization: Bearer <token>`.
Best practices for token management include:
- Generating tokens with minimal required permissions
- Rotating tokens periodically
- Revoking tokens that are no longer needed
- Never committing tokens to version control
- Using environment variables or secure secret management systems to store tokens
HCP Terraform also supports SAML SSO and integrates with identity providers for enhanced authentication security in enterprise environments. Understanding token management is crucial for the Terraform Associate certification exam.