Agent Skills by ALSEL
Anthropic Claudeデータ・分析⭐ リポ 0品質スコア 50/100

provider-resources

Terraform ProviderのリソースおよびデータソースをPlugin Frameworkを使用して実装します。ProviderリソースのCRUD操作、スキーマ設計、状態管理、受け入れテストを開発する際に使用してください。

description の原文を見る

Implement Terraform Provider resources and data sources using the Plugin Framework. Use when developing CRUD operations, schema design, state management, and acceptance testing for provider resources.

SKILL.md 本文

Terraform Provider リソース実装ガイド

概要

このガイドは、Terraform Plugin Framework を使用した Terraform Provider リソースおよびデータソースの開発をカバーしています。リソースは、Terraform が Create、Read、Update、Delete(CRUD)操作を通じて管理するインフラストラクチャオブジェクトを表します。

参考資料:

ファイル構造

リソースは標準的なサービスパッケージ構造に従います:

internal/service/<service>/
├── <resource_name>.go           # Resource implementation
├── <resource_name>_test.go      # Acceptance tests
├── <resource_name>_data_source.go    # Data source (if applicable)
├── find.go                      # Finder functions
├── exports_test.go              # Test exports
└── service_package_gen.go       # Auto-generated registration

ドキュメント構造:

website/docs/r/
└── <service>_<resource_name>.html.markdown  # Resource documentation

website/docs/d/
└── <service>_<resource_name>.html.markdown  # Data source documentation

リソース構造

SDKv2 リソースパターン

func ResourceExample() *schema.Resource {
    return &schema.Resource{
        CreateWithoutTimeout: resourceExampleCreate,
        ReadWithoutTimeout:   resourceExampleRead,
        UpdateWithoutTimeout: resourceExampleUpdate,
        DeleteWithoutTimeout: resourceExampleDelete,

        Importer: &schema.ResourceImporter{
            StateContext: schema.ImportStatePassthroughContext,
        },

        Schema: map[string]*schema.Schema{
            "name": {
                Type:         schema.TypeString,
                Required:     true,
                ForceNew:     true,
                ValidateFunc: validation.StringLenBetween(1, 255),
            },
            "arn": {
                Type:     schema.TypeString,
                Computed: true,
            },
            "tags":     tftags.TagsSchema(),
            "tags_all": tftags.TagsSchemaComputed(),
        },

        CustomizeDiff: verify.SetTagsDiff,
    }
}

Plugin Framework リソースパターン

type resourceExample struct {
    framework.ResourceWithConfigure
}

func (r *resourceExample) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
    resp.TypeName = req.ProviderTypeName + "_example"
}

func (r *resourceExample) Schema(ctx context.Context, req resource.SchemaRequest, resp *resource.SchemaResponse) {
    resp.Schema = schema.Schema{
        Attributes: map[string]schema.Attribute{
            "id": framework.IDAttribute(),
            "name": schema.StringAttribute{
                Required: true,
                PlanModifiers: []planmodifier.String{
                    stringplanmodifier.RequiresReplace(),
                },
                Validators: []validator.String{
                    stringvalidator.LengthBetween(1, 255),
                },
            },
            "arn": schema.StringAttribute{
                Computed: true,
                PlanModifiers: []planmodifier.String{
                    stringplanmodifier.UseStateForUnknown(),
                },
            },
        },
    }
}

CRUD 操作

Create 操作

func (r *resourceExample) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) {
    var data resourceExampleModel
    resp.Diagnostics.Append(req.Plan.Get(ctx, &data)...)
    if resp.Diagnostics.HasError() {
        return
    }

    conn := r.Meta().ExampleClient(ctx)

    input := &example.CreateExampleInput{
        Name: data.Name.ValueStringPointer(),
    }

    output, err := conn.CreateExample(ctx, input)
    if err != nil {
        resp.Diagnostics.AddError(
            "Error creating Example",
            fmt.Sprintf("Could not create example %s: %s", data.Name.ValueString(), err),
        )
        return
    }

    data.ID = types.StringPointerValue(output.Id)
    data.ARN = types.StringPointerValue(output.Arn)

    resp.Diagnostics.Append(resp.State.Set(ctx, &data)...)
}

Read 操作

func (r *resourceExample) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) {
    var data resourceExampleModel
    resp.Diagnostics.Append(req.State.Get(ctx, &data)...)
    if resp.Diagnostics.HasError() {
        return
    }

    conn := r.Meta().ExampleClient(ctx)

    output, err := findExampleByID(ctx, conn, data.ID.ValueString())
    if tfresource.NotFound(err) {
        resp.Diagnostics.AddWarning(
            "Resource not found",
            fmt.Sprintf("Example %s not found, removing from state", data.ID.ValueString()),
        )
        resp.State.RemoveResource(ctx)
        return
    }
    if err != nil {
        resp.Diagnostics.AddError(
            "Error reading Example",
            fmt.Sprintf("Could not read example %s: %s", data.ID.ValueString(), err),
        )
        return
    }

    data.Name = types.StringPointerValue(output.Name)
    data.ARN = types.StringPointerValue(output.Arn)

    resp.Diagnostics.Append(resp.State.Set(ctx, &data)...)
}

Update 操作

func (r *resourceExample) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) {
    var plan, state resourceExampleModel
    resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
    resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
    if resp.Diagnostics.HasError() {
        return
    }

    conn := r.Meta().ExampleClient(ctx)

    if !plan.Description.Equal(state.Description) {
        input := &example.UpdateExampleInput{
            Id:          plan.ID.ValueStringPointer(),
            Description: plan.Description.ValueStringPointer(),
        }

        _, err := conn.UpdateExample(ctx, input)
        if err != nil {
            resp.Diagnostics.AddError(
                "Error updating Example",
                fmt.Sprintf("Could not update example %s: %s", plan.ID.ValueString(), err),
            )
            return
        }
    }

    resp.Diagnostics.Append(resp.State.Set(ctx, &plan)...)
}

Delete 操作

func (r *resourceExample) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) {
    var data resourceExampleModel
    resp.Diagnostics.Append(req.State.Get(ctx, &data)...)
    if resp.Diagnostics.HasError() {
        return
    }

    conn := r.Meta().ExampleClient(ctx)

    _, err := conn.DeleteExample(ctx, &example.DeleteExampleInput{
        Id: data.ID.ValueStringPointer(),
    })

    if tfresource.NotFound(err) {
        return
    }

    if err != nil {
        resp.Diagnostics.AddError(
            "Error deleting Example",
            fmt.Sprintf("Could not delete example %s: %s", data.ID.ValueString(), err),
        )
        return
    }
}

スキーマ設計

属性タイプ

Terraform タイプFramework タイプユースケース
stringschema.StringAttribute名前、ARN、ID
numberschema.Int64Attribute, schema.Float64Attributeカウント、サイズ
boolschema.BoolAttribute機能フラグ
listschema.ListAttribute順序付きコレクション
setschema.SetAttribute順序なしの一意の項目
mapschema.MapAttributeキーと値のペア
objectschema.SingleNestedAttribute複雑なネストされた設定

Plan モディファイア

// 値の変更時に置換を強制
stringplanmodifier.RequiresReplace()

// 計画中に未知の値を保持
stringplanmodifier.UseStateForUnknown()

// カスタム plan モディファイア
stringplanmodifier.RequiresReplaceIf(
    func(ctx context.Context, req planmodifier.StringRequest, resp *stringplanmodifier.RequiresReplaceIfFuncResponse) {
        // Custom logic
    },
    "description",
    "markdown description",
)

バリデータ

// String バリデータ
stringvalidator.LengthBetween(1, 255)
stringvalidator.RegexMatches(regexp.MustCompile(`^[a-z0-9-]+$`), "must be lowercase alphanumeric with hyphens")
stringvalidator.OneOf("option1", "option2", "option3")

// Int64 バリデータ
int64validator.Between(1, 100)
int64validator.AtLeast(1)
int64validator.AtMost(1000)

// List バリデータ
listvalidator.SizeAtLeast(1)
listvalidator.SizeAtMost(10)

機密属性

"password": schema.StringAttribute{
    Required:  true,
    Sensitive: true,
    Validators: []validator.String{
        stringvalidator.LengthAtLeast(8),
    },
}

状態管理

リソースが見つからない場合の処理

func findExampleByID(ctx context.Context, conn *example.Client, id string) (*example.Example, error) {
    input := &example.GetExampleInput{
        Id: &id,
    }

    output, err := conn.GetExample(ctx, input)
    if err != nil {
        var notFound *types.ResourceNotFoundException
        if errors.As(err, &notFound) {
            return nil, &retry.NotFoundError{
                LastError:   err,
                LastRequest: input,
            }
        }
        return nil, err
    }

    if output == nil || output.Example == nil {
        return nil, tfresource.NewEmptyResultError(input)
    }

    return output.Example, nil
}

リソース状態の待機

func waitExampleCreated(ctx context.Context, conn *example.Client, id string, timeout time.Duration) (*example.Example, error) {
    stateConf := &retry.StateChangeConf{
        Pending: []string{"CREATING", "PENDING"},
        Target:  []string{"ACTIVE", "AVAILABLE"},
        Refresh: statusExample(ctx, conn, id),
        Timeout: timeout,
    }

    outputRaw, err := stateConf.WaitForStateContext(ctx)
    if output, ok := outputRaw.(*example.Example); ok {
        return output, err
    }

    return nil, err
}

func statusExample(ctx context.Context, conn *example.Client, id string) retry.StateRefreshFunc {
    return func() (interface{}, string, error) {
        output, err := findExampleByID(ctx, conn, id)
        if tfresource.NotFound(err) {
            return nil, "", nil
        }
        if err != nil {
            return nil, "", err
        }
        return output, string(output.Status), nil
    }
}

テスト

基本的な受け入れテスト

func TestAccExampleResource_basic(t *testing.T) {
    ctx := acctest.Context(t)
    rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix)
    resourceName := "provider_example.test"

    resource.ParallelTest(t, resource.TestCase{
        PreCheck:                 func() { acctest.PreCheck(ctx, t) },
        ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories,
        CheckDestroy:             testAccCheckExampleDestroy(ctx),
        Steps: []resource.TestStep{
            {
                Config: testAccExampleConfig_basic(rName),
                Check: resource.ComposeTestCheckFunc(
                    testAccCheckExampleExists(ctx, resourceName),
                    resource.TestCheckResourceAttr(resourceName, "name", rName),
                    resource.TestCheckResourceAttrSet(resourceName, "arn"),
                ),
            },
            {
                ResourceName:      resourceName,
                ImportState:       true,
                ImportStateVerify: true,
            },
        },
    })
}

Disappears テスト

func TestAccExampleResource_disappears(t *testing.T) {
    ctx := acctest.Context(t)
    rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix)
    resourceName := "provider_example.test"

    resource.ParallelTest(t, resource.TestCase{
        PreCheck:                 func() { acctest.PreCheck(ctx, t) },
        ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories,
        CheckDestroy:             testAccCheckExampleDestroy(ctx),
        Steps: []resource.TestStep{
            {
                Config: testAccExampleConfig_basic(rName),
                Check: resource.ComposeTestCheckFunc(
                    testAccCheckExampleExists(ctx, resourceName),
                    acctest.CheckResourceDisappears(ctx, acctest.Provider, ResourceExample(), resourceName),
                ),
                ExpectNonEmptyPlan: true,
            },
        },
    })
}

テストヘルパー関数

func testAccCheckExampleExists(ctx context.Context, name string) resource.TestCheckFunc {
    return func(s *terraform.State) error {
        rs, ok := s.RootModule().Resources[name]
        if !ok {
            return fmt.Errorf("Not found: %s", name)
        }

        conn := acctest.Provider.Meta().(*conns.Client).ExampleClient(ctx)
        _, err := findExampleByID(ctx, conn, rs.Primary.ID)

        return err
    }
}

func testAccCheckExampleDestroy(ctx context.Context) resource.TestCheckFunc {
    return func(s *terraform.State) error {
        conn := acctest.Provider.Meta().(*conns.Client).ExampleClient(ctx)

        for _, rs := range s.RootModule().Resources {
            if rs.Type != "provider_example" {
                continue
            }

            _, err := findExampleByID(ctx, conn, rs.Primary.ID)
            if tfresource.NotFound(err) {
                continue
            }
            if err != nil {
                return err
            }

            return fmt.Errorf("Example %s still exists", rs.Primary.ID)
        }

        return nil
    }
}

テストの実行

# Compile tests
go test -c -o /dev/null ./internal/service/<service>

# Run acceptance tests
TF_ACC=1 go test ./internal/service/<service> -run TestAccExample -v -timeout 60m

# Run with specific provider version
TF_ACC=1 go test ./internal/service/<service> -run TestAccExample -v

# Run sweeper to clean up
TF_ACC=1 go test ./internal/service/<service> -sweep=<region> -v

エラー処理

一般的なエラーパターン

// 特定の API エラーを処理
var notFound *types.ResourceNotFoundException
if errors.As(err, &notFound) {
    // Resource doesn't exist
}

var conflict *types.ConflictException
if errors.As(err, &conflict) {
    // Resource state conflict
}

var throttle *types.ThrottlingException
if errors.As(err, &throttle) {
    // Rate limited - SDK handles retry
}

診断

// エラーを追加
resp.Diagnostics.AddError(
    "Error creating resource",
    fmt.Sprintf("Could not create resource: %s", err),
)

// 警告を追加
resp.Diagnostics.AddWarning(
    "Resource modified outside Terraform",
    "Resource was modified outside of Terraform, state may be inconsistent",
)

// 属性エラーを追加
resp.Diagnostics.AddAttributeError(
    path.Root("name"),
    "Invalid name",
    "Name must be lowercase alphanumeric",
)

ドキュメント標準

リソースドキュメント

---
subcategory: "Service Name"
layout: "provider"
page_title: "Provider: provider_example"
description: |-
  Manages an Example resource.
---

# Resource: provider_example

Manages an Example resource.

## Example Usage

### Basic Usage

\```hcl
resource "provider_example" "example" {
  name = "my-example"
}
\```

## Argument Reference

* `name` - (Required) Name of the example.
* `description` - (Optional) Description of the example.

## Attribute Reference

* `id` - ID of the example.
* `arn` - ARN of the example.

## Import

Example can be imported using the ID:

\```
$ terraform import provider_example.example example-id-12345
\```

提出前のチェックリスト

  • コードはエラーなくコンパイルされる
  • すべてのテストがローカルで成功する
  • リソースにすべての CRUD 操作が実装されている
  • インポートが実装され、テストされている
  • Disappears テストが含まれている
  • ドキュメントが完全で、例が含まれている
  • エラーメッセージが明確で実用的である
  • 機密属性がマークされている
  • Plan モディファイアが適切である
  • バリデータがエッジケースに対応している

参考資料

ライセンス: MPL-2.0(寛容ライセンスのため全文を引用しています) · 原本リポジトリ

詳細情報

作者
hashicorp
リポジトリ
hashicorp/agent-skills
ライセンス
MPL-2.0
最終更新
不明

Source: https://github.com/hashicorp/agent-skills / ライセンス: MPL-2.0

関連スキル

OpenAIデータ・分析⭐ リポ 1,451

hugging-face-trackio

Trackioを使用してMLトレーニング実験を追跡・可視化できます。トレーニング中のメトリクスログ記録(Python API)、トレーニング診断のアラート発火、ログされたメトリクスの取得・分析(CLI)が必要な場合に活用してください。リアルタイムダッシュボード表示、Webhookを使用したアラート、HF Space同期、自動化向けのJSON出力に対応しています。

by gradio-app
汎用データ・分析⭐ リポ 855

btc-bottom-model

ビットコインのサイクルタイミングモデルで、加重スコアリングシステムを搭載しています。日次パルス(4指標、32ポイント)とウィークリー構造(9指標、68ポイント)の2カテゴリーにわたる13の指標を追跡し、0~100のマーケットヒートスコアを算出します。ETFフロー、ファンディングレート、ロング/ショート比率、恐怖・貪欲指数、LTH-MVRV、NUPL、SOPR(LTH+STH)、LTH供給率、移動平均倍率(365日MA、200週MA)、週次RSI、出来高トレンドに対応します。市場サイクル全体を通じて買いと売りの両方の推奨を提供します。ビットコインの底値拾い、BTCサイクルポジション、買い時・売り時、オンチェーン指標、MVRV、NUPL、SOPR、LTH動向、ETFの流出入、ファンディングレート、恐怖指数、ビットコインが過熱状態か、マイナーコスト、暗号資産市場のセンチメント、BTCのポジションサイジング、「今ビットコインを買うべきか」「BTCが天井をつけているか」「オンチェーン指標は何を示しているか」といった質問の際にこのスキルを活用します。

by star23
Anthropic Claudeデータ・分析⭐ リポ 380

protein_solubility_optimization

タンパク質の溶解性最適化 - タンパク質の溶解性を最適化します。タンパク質の特性を計算し、溶解性と親水性を予測し、有効な変異を提案します。タンパク質配列の特性計算、タンパク質機能の予測、親水性計算、ゼロショット配列予測を含むタンパク質エンジニアリング業務に使用できます。3つのSCPサーバーから4つのツールを統合しています。

by SpectrAI-Initiative
Anthropic Claudeデータ・分析⭐ リポ 1,743

research-lookup

Parallel Chat APIまたはPerplexity sonar-pro-searchを使用して、最新の研究情報を検索できます。学術論文の検索にも対応しています。クエリは自動的に最適なバックエンドにルーティングされるため、論文の検索、研究データの収集、科学情報の検証に活用できます。

by K-Dense-AI
Anthropic Claudeデータ・分析⭐ リポ 299

tree-formatting

ggtree(R)またはiTOL(ウェブ)を使用して、系統樹の可視化とフォーマットを行います。系統樹を図として描画する際、ツリーレイアウトの選択、分類学に基づく枝やラベルの色付け、クレードの折りたたみ、サポート値の表示、またはツリーへのオーバーレイ追加が必要な場合に使用してください。系統推定(protein-phylogenyスキルを使用)やドメイン注釈(今後の独立したスキル)には使用しないでください。

by majiayu000
汎用データ・分析⭐ リポ 145

querying-indonesian-gov-data

インドネシア政府の50以上のAPIとデータソースに接続できます。BPJPH(ハラール認証)、BOM(食品安全)、OJK(金融適正性)、BPS(統計)、BMKG(気象・地震)、インドネシア中央銀行(為替レート)、IDX(株式)、CKAN公開データポータル、pasal.id(第三者法MCP)に対応しています。インドネシア政府データを活用したアプリ開発、.go.idウェブサイトのスクレイピング、ハラール認証の確認、企業の法的適正性の検証、金融機関ステータスの照会、またはインドネシアMCPサーバーへの接続時に使用できます。CSRF処理、CKAN API使用方法、IP制限回避など、すぐに実行可能なPythonパターンを含んでいます。

by suryast
本サイトは GitHub 上で公開されているオープンソースの SKILL.md ファイルをクロール・インデックス化したものです。 各スキルの著作権は原作者に帰属します。掲載に問題がある場合は info@alsel.co.jp または /takedown フォームよりご連絡ください。
原作者: hashicorp · hashicorp/agent-skills · ライセンス: MPL-2.0