Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,20 @@
# Unreleased

# Released
# v0.1.5

* `pytfe.__version__` added in src/pytfe/init.py via importlib.metadata.version("pytfe"). This will resolve to the version from pyproject.toml.
* Updated comments, sshkey, stateversion and cost-estimate models to have id as mandatory attribute by @isivaselvan [#137](https://github.com/hashicorp/python-tfe/pull/137)
* Updated workspace resource to include additional relationship models include AgentPool, Configuration-version, Run, Variables and State-version by @isivaselvan [#138](https://github.com/hashicorp/python-tfe/pull/138)

## Bug Fixes
* Run.read / Run.create fail with pydantic ValidationError when response has a `cost-estimate` and `comments` relationship.

# v0.1.4

## Enhancements
* Standardize Notification Configuration option models on Pydantic [#132](https://github.com/hashicorp/python-tfe/pull/132)

# v0.1.3

## Enhancements
Expand Down
6 changes: 1 addition & 5 deletions examples/notification_configuration.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,9 @@
"""

import os
import sys

# Add the src directory to the Python path so we can import the tfe module
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "src"))

from pytfe.client import TFEClient
from pytfe.models.notification_configuration import (
from pytfe.models import (
NotificationConfigurationCreateOptions,
NotificationConfigurationListOptions,
NotificationConfigurationSubscribableChoice,
Expand Down
212 changes: 212 additions & 0 deletions examples/organization_token.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,212 @@
#!/usr/bin/env python3
"""
Organization Token Operations Example

Demonstrates usage of all 6 organization token operations:
1. create() - Create a new organization token, replacing any existing token
2. create_with_options() - Create with options like expiration date and token type
3. read() - Read the organization token
4. read_with_options() - Read with options like token type
5. delete() - Delete the organization token
6. delete_with_options() - Delete with options like token type

Usage:
- Modify organization names as needed for your environment
- Ensure you have proper TFE credentials and organization access
- Organization tokens are used for organization-level API access

Prerequisites:
- Set TFE_TOKEN and TFE_ADDRESS environment variables
- You need an existing organization or admin permissions to create one
- Appropriate permissions to manage organization tokens
"""

from datetime import datetime, timedelta

# Add the src directory to the path
##sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "src"))
from pytfe import TFEClient, TFEConfig
from pytfe.models import (
OrganizationTokenCreateOptions,
OrganizationTokenDeleteOptions,
OrganizationTokenReadOptions,
TokenType,
)


def redact_token(token_value: str | None) -> str:
"""Redact token value for safe display."""
if not token_value:
return "None"
if len(token_value) <= 8:
return f"{'*' * len(token_value)}"
# Show first 3 and last 3 characters
return f"{token_value[:3]}...{token_value[-3:]}".replace(
token_value[3:-3], "*" * (len(token_value) - 6)
)


def redact_id(id_value: str | None) -> str:
"""Redact ID for safe display."""
if not id_value:
return "None"
if len(id_value) <= 6:
return f"{'*' * len(id_value)}"
# Show first 3 and last 3 characters
return f"{id_value[:3]}...{id_value[-3:]}"


def main():
"""Execute organization token operation examples."""

print("=" * 80)
print("ORGANIZATION TOKEN OPERATIONS")
print("=" * 80)

# Initialize the TFE client
client = TFEClient(TFEConfig.from_env())
organization_name = "prab-sandbox01"
# =====================================================
# 1. CREATE ORGANIZATION TOKEN (BASIC)
# =====================================================
print("\n1. create() - Create a new organization token:")
print("-" * 40)
try:
print(f"Creating token for organization: {organization_name}")
token = client.organization_tokens.create(organization_name)

print("Token created successfully!")
print(f" Token ID: {redact_id(token.id)}")
print(f" Created At: {token.created_at}")
print(f" Description: {token.description}")
print(f" Token Value: {redact_token(token.token)}")
if token.expired_at:
print(f" Expires At: {token.expired_at}")
print()

except Exception as e:
print(f" Error: {e}")
print()

# =====================================================
# 2. CREATE WITH OPTIONS (WITH EXPIRATION)
# =====================================================
print("2. create_with_options() - Create token with expiration date:")
print("-" * 40)
try:
# Create a token that expires in 30 days
expiry_date = datetime.utcnow() + timedelta(days=30)
options = OrganizationTokenCreateOptions(expired_at=expiry_date)

print(f"Creating organization token with expiration date: {expiry_date}")
token = client.organization_tokens.create_with_options(
organization_name, options
)

print("Token created with options successfully!")
print(f" Token ID: {redact_id(token.id)}")
print(f" Created At: {token.created_at}")
if token.expired_at:
print(f" Expires At: {token.expired_at}")
print()

except Exception as e:
print(f" Error: {e}")
print()

# =====================================================
print("3. create_with_options() - Create audit-trails token:")
print("-" * 40)
try:
options = OrganizationTokenCreateOptions(token_type=TokenType.AUDIT_TRAILS)

print(f"Creating audit-trails token for organization: {organization_name}")
token = client.organization_tokens.create_with_options(
organization_name, options
)

print(" Audit-trails token created successfully!")
print(f" Token ID: {redact_id(token.id)}")
print(f" Token Value: {redact_token(token.token)}")
print()

except Exception as e:
print(f"Error: {e}")
print()

# =====================================================
print("4. read() - Read the organization token:")
print("-" * 40)
try:
print(f"Reading organization token for organization: {organization_name}")
token = client.organization_tokens.read(organization_name)

print("Token read successfully!")
print(f" Token ID: {redact_id(token.id)}")
print(f" Created At: {token.created_at}")
print(f" Description: {token.description}")
if token.last_used_at:
print(f" Last Used At: {token.last_used_at}")
if token.expired_at:
print(f" Expires At: {token.expired_at}")
print()

except Exception as e:
print(f" Error: {e}")
print()

# =====================================================
print("5. read_with_options() - Read audit-trails token:")
print("-" * 40)
try:
options = OrganizationTokenReadOptions(token_type=TokenType.AUDIT_TRAILS)

print(f"Reading audit-trails token for organization: {organization_name}")
token = client.organization_tokens.read_with_options(organization_name, options)

print(" Audit-trails token read successfully!")
print(f" Token ID: {redact_id(token.id)}")
print(f" Token Value: {redact_token(token.token)}")
print()

except Exception as e:
print(f" Error: {e}")
print()

# =====================================================
print("6. delete() - Delete the organization token:")
print("-" * 40)
try:
print(f"Deleting organization token for organization: {organization_name}")
client.organization_tokens.delete(organization_name)

print(" Token deleted successfully!")
print()

except Exception as e:
print(f" Error: {e}")
print()

# =====================================================
print("7. delete_with_options() - Delete audit-trails token:")
print("-" * 40)
try:
options = OrganizationTokenDeleteOptions(token_type=TokenType.AUDIT_TRAILS)

print(f"Deleting audit-trails token for organization: {organization_name}")
client.organization_tokens.delete_with_options(organization_name, options)

print(" Audit-trails token deleted successfully!")
print()

except Exception as e:
print(f"Error: {e}")
print()

print("=" * 80)
print("ORGANIZATION TOKEN OPERATIONS COMPLETED")
print("=" * 80)


if __name__ == "__main__":
main()
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ build-backend = "hatchling.build"

[project]
name = "pytfe"
version = "0.1.3"
version = "0.1.5"
description = "Official Python SDK for HashiCorp Terraform Cloud / Terraform Enterprise (TFE) API v2"
readme = "README.md"
license = { text = "MPL-2.0" }
Expand Down
10 changes: 9 additions & 1 deletion src/pytfe/__init__.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,16 @@
# Copyright IBM Corp. 2025, 2026
# SPDX-License-Identifier: MPL-2.0

from importlib.metadata import PackageNotFoundError
from importlib.metadata import version as _pkg_version

from . import errors, models
from .client import TFEClient
from .config import TFEConfig

__all__ = ["TFEConfig", "TFEClient", "errors", "models"]
try:
__version__ = _pkg_version("pytfe")
except PackageNotFoundError: # running from a source checkout without install
__version__ = "0.0.0+unknown"

__all__ = ["TFEConfig", "TFEClient", "errors", "models", "__version__"]
3 changes: 2 additions & 1 deletion src/pytfe/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
from .resources.oauth_client import OAuthClients
from .resources.oauth_token import OAuthTokens
from .resources.organization_membership import OrganizationMemberships
from .resources.organization_token import OrganizationTokens
from .resources.organizations import Organizations
from .resources.plan import Plans
from .resources.policy import Policies
Expand Down Expand Up @@ -72,7 +73,7 @@ def __init__(self, config: TFEConfig | None = None):
self.plans = Plans(self._transport)
self.organizations = Organizations(self._transport)
self.organization_memberships = OrganizationMemberships(self._transport)

self.organization_tokens = OrganizationTokens(self._transport)
self.projects = Projects(self._transport)
self.variables = Variables(self._transport)
self.variable_sets = VariableSets(self._transport)
Expand Down
38 changes: 38 additions & 0 deletions src/pytfe/models/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,19 @@
DataRetentionPolicySetOptions,
)

# ── Notification Configurations ───────────────────────────────────────────────
from .notification_configuration import (
DeliveryResponse,
NotificationConfiguration,
NotificationConfigurationCreateOptions,
NotificationConfigurationList,
NotificationConfigurationListOptions,
NotificationConfigurationSubscribableChoice,
NotificationConfigurationUpdateOptions,
NotificationDestinationType,
NotificationTriggerType,
)

# ── OAuth ─────────────────────────────────────────────────────────────────────
from .oauth_client import (
OAuthClient,
Expand Down Expand Up @@ -96,6 +109,15 @@
OrganizationMembershipStatus,
OrgMembershipIncludeOpt,
)

# ── Organization Token ────────────────────────────────────────────────────────
from .organization_token import (
OrganizationToken,
OrganizationTokenCreateOptions,
OrganizationTokenDeleteOptions,
OrganizationTokenReadOptions,
TokenType,
)
from .policy import (
Policy,
PolicyCreateOptions,
Expand Down Expand Up @@ -376,6 +398,16 @@

# ── Public surface ────────────────────────────────────────────────────────────
__all__ = [
# Notification configurations
"DeliveryResponse",
"NotificationConfiguration",
"NotificationConfigurationCreateOptions",
"NotificationConfigurationList",
"NotificationConfigurationListOptions",
"NotificationConfigurationSubscribableChoice",
"NotificationConfigurationUpdateOptions",
"NotificationDestinationType",
"NotificationTriggerType",
# OAuth
"OAuthClient",
"OAuthClientAddProjectsOptions",
Expand Down Expand Up @@ -497,6 +529,12 @@
"OrganizationMembershipReadOptions",
"OrganizationMembershipStatus",
"OrgMembershipIncludeOpt",
# Organization tokens
"OrganizationToken",
"OrganizationTokenCreateOptions",
"OrganizationTokenDeleteOptions",
"OrganizationTokenReadOptions",
"TokenType",
"OrganizationAccess",
"Team",
"TeamPermissions",
Expand Down
2 changes: 1 addition & 1 deletion src/pytfe/models/comment.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,4 @@ class Comment(BaseModel):
model_config = ConfigDict(populate_by_name=True, validate_by_name=True)

id: str
body: str = Field(..., alias="body")
body: str = Field(default="", alias="body")
20 changes: 10 additions & 10 deletions src/pytfe/models/cost_estimate.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,17 +13,17 @@ class CostEstimate(BaseModel):
model_config = ConfigDict(populate_by_name=True, validate_by_name=True)

id: str
delta_monthly_cost: str = Field(..., alias="delta-monthly-cost")
error_message: str = Field(..., alias="error-message")
matched_resources_count: int = Field(..., alias="matched-resources-count")
prior_monthly_cost: str = Field(..., alias="prior-monthly-cost")
proposed_monthly_cost: str = Field(..., alias="proposed-monthly-cost")
resources_count: int = Field(..., alias="resources-count")
status: CostEstimateStatus = Field(..., alias="status")
status_timestamps: CostEstimateStatusTimestamps = Field(
..., alias="status-timestamps"
delta_monthly_cost: str = Field(default="", alias="delta-monthly-cost")
error_message: str = Field(default="", alias="error-message")
matched_resources_count: int = Field(default=0, alias="matched-resources-count")
prior_monthly_cost: str = Field(default="", alias="prior-monthly-cost")
proposed_monthly_cost: str = Field(default="", alias="proposed-monthly-cost")
resources_count: int = Field(default=0, alias="resources-count")
status: CostEstimateStatus | None = Field(default=None, alias="status")
status_timestamps: CostEstimateStatusTimestamps | None = Field(
default=None, alias="status-timestamps"
)
unmatched_resources_count: int = Field(..., alias="unmatched-resources-count")
unmatched_resources_count: int = Field(default=0, alias="unmatched-resources-count")


class CostEstimateStatus(str, Enum):
Expand Down
Loading
Loading