Pulumi Preview Infrastructure State Analysis

The capacity to visualize infrastructure changes before they are committed to a live environment is a cornerstone of modern Infrastructure as Code (IaC) practices. The pulumi preview command serves as the primary mechanism for this validation, providing a dry-run execution that allows engineers to inspect the delta between the current deployed state and the desired state defined in the source code. By simulating the execution of a Pulumi program, the tool generates a comprehensive report of the intended operations—creation, update, replacement, or deletion—without actually modifying any real-world resources. This process is critical for preventing accidental downtime, avoiding the deletion of critical production databases, and ensuring that architectural changes align with organizational standards.

The underlying mechanism of pulumi preview involves a complex comparison process. First, the Pulumi engine executes the program written in the project's current directory to build a desired state object graph. This graph represents exactly what the infrastructure should look like based on the current code. Simultaneously, the engine references the existing state file of the targeted stack, which acts as the single source of truth for what is currently deployed in the cloud. By calculating the difference between these two representations, Pulumi identifies the precise set of resource operations required to bridge the gap. This ensures that the operator is not guessing the outcome of a deployment but is instead viewing a computed plan derived from the actual state of the cloud provider.

Core Functional Mechanics and Execution

The primary purpose of pulumi preview is to show a preview of updates to a stack's resources. When the command is invoked, it triggers a sequence of events designed to isolate the planning phase from the execution phase. Unlike pulumi up, which combines the preview and the actual deployment into a single workflow requiring confirmation, pulumi preview is explicitly dedicated to the inspection phase.

The execution flow begins with the loading of the project from the local directory. If the project is located elsewhere, the -C or --cwd flag allows the user to specify a different working directory, ensuring that the correct project files and configuration are loaded regardless of the current shell location. Once the program is executed, the engine extracts all resource allocations.

These allocations are then compared against the existing state. The output of this comparison is categorized into four primary operation types:

  • Create: A resource defined in the code that does not exist in the current state.
  • Update: A resource that exists but has property changes that can be applied in-place.
  • Replace: A resource change that requires the resource to be deleted and recreated because the cloud provider does not support an in-place update for that specific property.
  • Delete: A resource that exists in the state but is no longer present in the program code.

This detailed breakdown provides the user with the necessary intelligence to decide whether the deployment is safe to proceed. The impact of this is a drastic reduction in "deployment anxiety," as teams can verify that adding a new security group rule does not accidentally trigger the replacement of a primary load balancer.

Command Syntax and Flag Configurations

The pulumi preview command offers a wide array of flags that allow users to tailor the output to their specific needs, whether they are debugging a local environment or integrating the tool into a sophisticated CI/CD pipeline.

The basic syntax for the command is:

pulumi preview [url] [flags]

Below is a detailed breakdown of the available options and their specific impacts on the preview process.

Flag Alias Purpose Impact/Effect
--diff -d Rich Diff Display Shows a property-level view of changes rather than just the resource level.
--json -j Machine-Readable Output Emits the preview results in JSON format for use by other tools.
--stack -s Target Stack Selection Specifies which stack to run the preview against.
--refresh N/A Cloud State Sync Refreshes the state from the cloud provider before computing the diff.
--expect-no-changes N/A Drift Detection Returns a non-zero exit code if any changes are detected.
--target N/A Resource Filtering Limits the preview to a specific resource URN.
--target-dependents N/A Dependency Inclusion Includes resources that depend on the targeted URNs.
--exclude -x Resource Ignoring Specifies a resource URN to ignore during the preview.
--config -c Inline Configuration Applies specific configuration values during the preview.
--config-file N/A Custom Config File Uses a specific file for configuration instead of the default.
--config-path N/A Map/List Pathing Sets configuration keys that contain paths to properties.
--attach-debugger N/A Debugging Enablement Allows attaching a debugger to programs or plugins.
--debug -d Detailed Logging Prints detailed debugging output during resource operations.
--help -h Documentation Displays the help menu for the preview command.

Advanced Visualization and Data Output

While the standard output of pulumi preview is human-readable, certain scenarios require more granular data or machine-parsable formats.

The --diff flag is one of the most powerful tools for senior engineers. Instead of simply stating that a resource will be updated, the rich diff displays the exact property change. For example, if a VM instance type is changing from t2.micro to t3.small, the diff will explicitly highlight the specific line of configuration that is changing. This prevents the "hidden change" problem where a user might overlook a critical modification buried within a large resource object.

For automation and tool integration, the --json (or -j) flag transforms the output into a structured format. This is essential for custom internal dashboards or auditing tools that need to parse the planned changes to ensure they meet security or budgetary constraints before a human ever sees the pull request.

The --expect-no-changes flag is specifically engineered for CI pipelines. In a mature DevOps lifecycle, drift detection is vital. Drift occurs when a user manually changes a resource in the cloud console (ClickOps) without updating the Pulumi code. By running pulumi preview --expect-no-changes in a scheduled job, a team can be alerted via a non-zero exit status the moment the actual cloud state diverges from the defined code, ensuring the infrastructure remains immutable and reproducible.

Integration with CI/CD and GitHub Actions

Pulumi provides deep integration with GitHub Actions to automate the preview process. This ensures that every proposed change to the infrastructure is validated before it is merged into the main branch.

Within a GitHub Actions workflow, the pulumi/actions official action is used to execute the preview. This allows the team to collaborate on proposed deployments directly within the context of a Pull Request. The action handles the installation of the Pulumi CLI and the authentication process using a secret token.

An example configuration for a GitHub Actions workflow is as follows:

yaml name: Pulumi on: push: branches: - main jobs: up: name: Preview runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: pulumi/actions@v7 with: command: preview stack-name: org-name/stack-name env: PULUMI_ACCESS_TOKEN: ${{ secrets.PULUMI_ACCESS_TOKEN }}

In this configuration, the command: preview argument tells the action to perform a dry-run. The stack-name parameter ensures the preview is run against the correct environment (e.g., production or staging). The PULUMI_ACCESS_TOKEN provides the necessary authorization to access the Pulumi backend. This automation creates a safety gate: no code can be merged unless the pulumi preview has successfully run and been reviewed by a peer, effectively eliminating the risk of "blind" deployments.

Pulumi Neo and AI-Driven Previews

The evolution of infrastructure management has led to the integration of AI, specifically through Pulumi Neo. Neo extends the utility of the pulumi preview command by moving the execution from the local CLI to the Pulumi Cloud environment. This allows the AI to propose infrastructure changes and immediately validate them using the preview mechanism.

Neo utilizes previews for three primary objectives:

  1. Validation of Proposed Changes: Before Neo presents a solution to the user, it runs a preview to ensure the generated code is syntactically correct and will execute without errors.
  2. Impact Analysis: Neo uses the preview to generate a report of exactly what resources will be created, updated, or deleted, presenting this to the user for approval.
  3. Policy Compliance: By combining previews with organization-level policies, Neo can verify that the proposed changes do not violate security rules (e.g., ensuring no S3 buckets are made public) before the code is even committed.

The workflow with Neo is interactive. Once the AI arrives at a solution for a requested task, it will request permission to run a preview. The user then reviews the impact analysis and can either approve or decline the request, creating a human-in-the-loop system that leverages AI efficiency with human oversight.

Prerequisites and Configuration Management

For pulumi preview to function correctly, several environmental prerequisites must be met. Without these, the engine cannot authenticate with the cloud provider or retrieve the current state of the stack.

The core requirements include:

  • Cloud Provider Credentials: The environment must have valid credentials for the target provider, such as AWS, Azure, or GCP. Without these, Pulumi cannot refresh the state or verify if resources exist.
  • Stack Configuration: Configuration must be defined for the stack. This can be done via the Pulumi CLI, a stack config file, or through the Pulumi API.
  • State Access: The engine must have access to the state file, whether it is stored in Pulumi Cloud or a self-managed backend.

Configuration is managed using the pulumi config command, which is often a precursor to running a preview. For instance, setting a region or an API key:

pulumi config set [key] [value]

To retrieve a specific configuration value:

pulumi config get [key]

The most scalable approach for managing these configurations and secrets is through ESC (Environments, Secrets, and Configuration). ESC provides a centralized way to define stack configuration and integrates natively with OIDC (OpenID Connect) for all major cloud providers, removing the need to manage long-lived cloud credentials on local machines or CI runners.

Comparative Analysis of Preview and Related Commands

To fully understand the role of pulumi preview, it must be contrasted with other primary CLI commands used in the Pulumi lifecycle.

  • pulumi up: While both commands perform a preview, pulumi up is an execution command. It shows the preview and then asks for a confirmation to actually apply the changes. pulumi preview is a read-only operation that never modifies infrastructure.
  • pulumi refresh: This command updates the state file to match the actual current state of the cloud resources. It is common to run pulumi preview --refresh to ensure the preview is based on the most current real-world data, rather than a potentially stale state file.
  • pulumi destroy: This command is the inverse of deployment. It creates a plan to remove all resources associated with the stack. Like up, it provides a preview of what will be deleted before requiring confirmation.
  • pulumi state: This is a management command used to manipulate the state file directly (e.g., removing a resource from state without deleting it from the cloud). Unlike preview, it does not execute the Pulumi program.

Strategic Implementation of Targeted Previews

In massive infrastructure environments containing thousands of resources, running a full pulumi preview can be time-consuming and produce an overwhelming amount of output. To solve this, Pulumi provides targeting capabilities.

The --target flag allows an engineer to isolate a specific resource for inspection. By providing the Unique Resource Name (URN), the engine only computes changes for that specific entity.

Example usage:

pulumi preview --target urn:pulumi:aws:ec2:Instance::my-web-server

However, infrastructure is rarely isolated. Changing one resource often necessitates changes in others. The --target-dependents flag expands the scope of the preview to include any resources that depend on the targeted resource. This ensures that if a VPC ID changes, the associated subnets and security groups are also previewed, preventing a scenario where a targeted update breaks downstream dependencies.

Furthermore, the --exclude (or -x) flag allows the opposite approach: previewing everything except a specific set of resources. This is useful when a specific resource is known to be in a "noisy" state (constantly changing due to an external process) and its updates would otherwise clutter the preview output.

Conclusion: The Critical Role of the Preview Cycle

The pulumi preview command is not merely a convenience but a fundamental safety mechanism that transforms infrastructure deployment from a high-risk event into a predictable, auditable process. By decoupling the "plan" from the "apply," Pulumi enables a rigorous review cycle that is essential for maintaining the stability of production environments.

The power of the preview lies in its ability to provide absolute transparency. Through the use of rich diffs, JSON output, and targeted analysis, engineers can move from a state of uncertainty to a state of verification. When integrated into GitHub Actions, this transparency is extended to the entire team, fostering a culture of collaborative infrastructure management where every change is documented and validated via a pull request.

Moreover, the integration of AI via Pulumi Neo demonstrates that the preview mechanism is scalable. By allowing an AI to validate its own hypotheses through the preview engine, organizations can accelerate their development velocity without sacrificing security. Whether used as a simple CLI check or as the backbone of an automated CI/CD pipeline, pulumi preview serves as the final line of defense against infrastructure regression and configuration drift, ensuring that the deployed state of the cloud always mirrors the intended architectural design defined in code.

Sources

  1. Pulumi Preview - Show Infrastructure Updates | Online Free DevTools by Hexmos
  2. Common Pulumi Preview Examples
  3. Pulumi CLI Commands - pulumi preview
  4. Linux Command Library - pulumi-preview
  5. Running previews with Pulumi Neo
  6. Pulumi GitHub Actions
  7. Pulumi Basic Common CLI Commands Part 2

Related Posts