provider-actions

0
0
Source

Implement Terraform Provider actions using the Plugin Framework. Use when developing imperative operations that execute at lifecycle events (before/after create, update, destroy).

Install

mkdir -p .claude/skills/provider-actions && curl -L -o skill.zip "https://mcp.directory/api/skills/download/9329" && unzip -o skill.zip -d .claude/skills/provider-actions && rm skill.zip

Installs to .claude/skills/provider-actions

About this skill

Terraform Provider Actions Implementation Guide

Overview

Terraform Actions enable imperative operations during the Terraform lifecycle. Actions are experimental features that allow performing provider operations at specific lifecycle events (before/after create, update, destroy).

References:

File Structure

Actions follow the standard service package structure:

internal/service/<service>/
├── <action_name>_action.go       # Action implementation
├── <action_name>_action_test.go  # Action tests
└── service_package_gen.go        # Auto-generated service registration

Documentation structure:

website/docs/actions/
└── <service>_<action_name>.html.markdown  # User-facing documentation

Changelog entry:

.changelog/
└── <pr_number_or_description>.txt  # Release note entry

Action Schema Definition

Actions use the Terraform Plugin Framework with a standard schema pattern:

func (a *actionType) Schema(ctx context.Context, req action.SchemaRequest, resp *action.SchemaResponse) {
    resp.Schema = schema.Schema{
        Attributes: map[string]schema.Attribute{
            // Required configuration parameters
            "resource_id": schema.StringAttribute{
                Required:    true,
                Description: "ID of the resource to operate on",
            },
            // Optional parameters with defaults
            "timeout": schema.Int64Attribute{
                Optional:    true,
                Description: "Operation timeout in seconds",
                Default:     int64default.StaticInt64(1800),
                Computed:    true,
            },
        },
    }
}

Common Schema Issues

Pay special attention to the schema definition - common issues after a first draft:

  1. Type Mismatches

    • Using types.String instead of fwtypes.String in model structs
    • Using types.StringType instead of fwtypes.StringType in schema
    • Mixing framework types with plugin-framework types
  2. List/Map Element Types

    // WRONG - missing ElementType
    "items": schema.ListAttribute{
        Optional: true,
    }
    
    // CORRECT
    "items": schema.ListAttribute{
        Optional:    true,
        ElementType: fwtypes.StringType,
    }
    
  3. Computed vs Optional

    • Attributes with defaults must be both Optional: true and Computed: true
    • Don't mark action inputs as Computed unless they have defaults
  4. Validator Imports

    // Ensure proper imports
    "github.com/hashicorp/terraform-plugin-framework-validators/int64validator"
    "github.com/hashicorp/terraform-plugin-framework-validators/stringvalidator"
    
  5. Region/Provider Attribute

    • Use framework-provided region handling when available
    • Don't manually define provider-specific config in schema if framework handles it
  6. Nested Attributes

    • Use appropriate nested object types for complex structures
    • Ensure nested types are properly defined

Schema Validation Checklist

Before submitting, verify:

  • All attributes have descriptions
  • List/Map attributes have ElementType defined
  • Validators are imported and applied correctly
  • Model struct uses correct framework types
  • Optional attributes with defaults are marked Computed
  • Code compiles without type errors
  • Run go build to catch type mismatches

Action Invoke Method

The Invoke method contains the action logic:

func (a *actionType) Invoke(ctx context.Context, req action.InvokeRequest, resp *action.InvokeResponse) {
    var data actionModel
    resp.Diagnostics.Append(req.Config.Get(ctx, &data)...)

    // Create provider client
    conn := a.Meta().Client(ctx)

    // Progress updates for long-running operations
    resp.Progress.Set(ctx, "Starting operation...")

    // Implement action logic with error handling
    // Use context for timeout management
    // Poll for completion if async operation

    resp.Progress.Set(ctx, "Operation completed")
}

Key Implementation Requirements

1. Progress Reporting

  • Use resp.SendProgress(action.InvokeProgressEvent{...}) for real-time updates
  • Provide meaningful progress messages during long operations
  • Update progress at key milestones
  • Include elapsed time for long operations

2. Timeout Management

  • Always include configurable timeout parameter (default: 1800s)
  • Use context.WithTimeout() for API calls
  • Handle timeout errors gracefully
  • Validate timeout ranges (typically 60-7200 seconds)

3. Error Handling

  • Add diagnostics with resp.Diagnostics.AddError()
  • Provide clear error messages with context
  • Include API error details when relevant
  • Map provider error types to user-friendly messages
  • Document all possible error cases

Example error handling:

// Handle specific errors
var notFound *types.ResourceNotFoundException
if errors.As(err, &notFound) {
    resp.Diagnostics.AddError(
        "Resource Not Found",
        fmt.Sprintf("Resource %s was not found", resourceID),
    )
    return
}

// Generic error handling
resp.Diagnostics.AddError(
    "Operation Failed",
    fmt.Sprintf("Could not complete operation for %s: %s", resourceID, err),
)

4. Provider SDK Integration

  • Use provider SDK clients from a.Meta().<Service>Client(ctx)
  • Handle pagination for list operations
  • Implement retry logic for transient failures
  • Use appropriate error types

5. Parameter Validation

  • Use framework validators for input validation
  • Validate resource existence before operations
  • Check for conflicting parameters
  • Validate against provider naming requirements

6. Polling and Waiting

For operations that require waiting for completion:

result, err := wait.WaitForStatus(ctx,
    func(ctx context.Context) (wait.FetchResult[*ResourceType], error) {
        // Fetch current status
        resource, err := findResource(ctx, conn, id)
        if err != nil {
            return wait.FetchResult[*ResourceType]{}, err
        }
        return wait.FetchResult[*ResourceType]{
            Status: wait.Status(resource.Status),
            Value:  resource,
        }, nil
    },
    wait.Options[*ResourceType]{
        Timeout:            timeout,
        Interval:           wait.FixedInterval(5 * time.Second),
        SuccessStates:      []wait.Status{"AVAILABLE", "COMPLETED"},
        TransitionalStates: []wait.Status{"CREATING", "PENDING"},
        ProgressInterval:   30 * time.Second,
        ProgressSink: func(fr wait.FetchResult[any], meta wait.ProgressMeta) {
            resp.SendProgress(action.InvokeProgressEvent{
                Message: fmt.Sprintf("Status: %s, Elapsed: %v", fr.Status, meta.Elapsed.Round(time.Second)),
            })
        },
    },
)

Common Action Patterns

Batch Operations

  • Process items in configurable batches
  • Report progress per batch
  • Handle partial failures gracefully
  • Support prefix/filter parameters

Command Execution

  • Submit command and get operation ID
  • Poll for completion status
  • Retrieve and report output
  • Handle timeout during polling
  • Validate resources exist before execution

Service Invocation

  • Invoke service with parameters
  • Wait for completion (if synchronous)
  • Return output/results
  • Handle service-specific errors

Resource State Changes

  • Validate current state
  • Apply state change
  • Poll for target state
  • Handle transitional states

Async Job Submission

  • Submit job with configuration
  • Get job ID
  • Optionally wait for completion
  • Report job status

Action Triggers

Actions are invoked via action_trigger lifecycle blocks in Terraform configurations:

action "provider_service_action" "name" {
  config {
    parameter = value
  }
}

resource "terraform_data" "trigger" {
  lifecycle {
    action_trigger {
      events  = [after_create]
      actions = [action.provider_service_action.name]
    }
  }
}

Available Trigger Events

Terraform 1.14.0 Supported Events:

  • before_create - Before resource creation
  • after_create - After resource creation
  • before_update - Before resource update
  • after_update - After resource update

Not Supported in Terraform 1.14.0:

  • before_destroy - Not available (will cause validation error)
  • after_destroy - Not available (will cause validation error)

Testing Actions

Acceptance Tests

  • Test action invocation with valid parameters
  • Test timeout scenarios
  • Test error conditions
  • Verify provider state changes
  • Test progress reporting
  • Test with custom parameters
  • Test trigger-based invocation

Test Pattern

func TestAccServiceAction_basic(t *testing.T) {
    ctx := acctest.Context(t)

    resource.ParallelTest(t, resource.TestCase{
        PreCheck:                 func() { acctest.PreCheck(ctx, t) },
        ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories,
        TerraformVersionChecks: []tfversion.TerraformVersionCheck{
            tfversion.SkipBelow(tfversion.Version1_14_0),
        },
        Steps: []resource.TestStep{
            {
                Config: testAccActionConfig_basic(),
                Check: resource.ComposeTestCheckFunc(
                    testAccCheckResourceExists(ctx, "provider_resource.test"),
                ),
            },
        },
    })
}

Test Cleanup with Sweep Functions

Add sweep functions to clean up test resources:

func sweepResources(region string) error {
    ctx := context.Background()
    client := /* get client for region */

    input := &service.ListInput{
        // Filter for test resources
    }

    var sweeperErrs *multierror.Error

    pages := service.NewListPaginator(client, input)
    for pages.HasMorePages() {
        page, err := pages.NextPage(ctx)
        if err != nil {
      

---

*Content truncated.*

You might also like

flutter-development

aj-geddes

Build beautiful cross-platform mobile apps with Flutter and Dart. Covers widgets, state management with Provider/BLoC, navigation, API integration, and material design.

1,4071,302

drawio-diagrams-enhanced

jgtolentino

Create professional draw.io (diagrams.net) diagrams in XML format (.drawio files) with integrated PMP/PMBOK methodologies, extensive visual asset libraries, and industry-standard professional templates. Use this skill when users ask to create flowcharts, swimlane diagrams, cross-functional flowcharts, org charts, network diagrams, UML diagrams, BPMN, project management diagrams (WBS, Gantt, PERT, RACI), risk matrices, stakeholder maps, or any other visual diagram in draw.io format. This skill includes access to custom shape libraries for icons, clipart, and professional symbols.

1,2201,024

ui-ux-pro-max

nextlevelbuilder

"UI/UX design intelligence. 50 styles, 21 palettes, 50 font pairings, 20 charts, 8 stacks (React, Next.js, Vue, Svelte, SwiftUI, React Native, Flutter, Tailwind). Actions: plan, build, create, design, implement, review, fix, improve, optimize, enhance, refactor, check UI/UX code. Projects: website, landing page, dashboard, admin panel, e-commerce, SaaS, portfolio, blog, mobile app, .html, .tsx, .vue, .svelte. Elements: button, modal, navbar, sidebar, card, table, form, chart. Styles: glassmorphism, claymorphism, minimalism, brutalism, neumorphism, bento grid, dark mode, responsive, skeuomorphism, flat design. Topics: color palette, accessibility, animation, layout, typography, font pairing, spacing, hover, shadow, gradient."

9001,013

godot

bfollington

This skill should be used when working on Godot Engine projects. It provides specialized knowledge of Godot's file formats (.gd, .tscn, .tres), architecture patterns (component-based, signal-driven, resource-based), common pitfalls, validation tools, code templates, and CLI workflows. The `godot` command is available for running the game, validating scripts, importing resources, and exporting builds. Use this skill for tasks involving Godot game development, debugging scene/resource files, implementing game systems, or creating new Godot components.

958658

nano-banana-pro

garg-aayush

Generate and edit images using Google's Nano Banana Pro (Gemini 3 Pro Image) API. Use when the user asks to generate, create, edit, modify, change, alter, or update images. Also use when user references an existing image file and asks to modify it in any way (e.g., "modify this image", "change the background", "replace X with Y"). Supports both text-to-image generation and image-to-image editing with configurable resolution (1K default, 2K, or 4K for high resolution). DO NOT read the image file first - use this skill directly with the --input-image parameter.

970608

pdf-to-markdown

aliceisjustplaying

Convert entire PDF documents to clean, structured Markdown for full context loading. Use this skill when the user wants to extract ALL text from a PDF into context (not grep/search), when discussing or analyzing PDF content in full, when the user mentions "load the whole PDF", "bring the PDF into context", "read the entire PDF", or when partial extraction/grepping would miss important context. This is the preferred method for PDF text extraction over page-by-page or grep approaches.

1,033496

Stay ahead of the MCP ecosystem

Get weekly updates on new skills and servers.