Computed attributes are values that are calculated or generated by the provider rather than provided by the user. They represent outputs from resource operations.
🤖 AI-Generated Content
This documentation was generated with AI assistance and is still being audited. Some, or potentially a lot, of this information may be inaccurate. Learn more.
Computed attributes:
- Are set by the provider (not by Terraform users)
- Represent outputs (IDs, timestamps, derived values)
- Cannot be configured by users in Terraform
- May be unknown during planning and only determined during apply
frompyvider.schemaimports_resource,a_str,a_num,PvsSchema@classmethoddefget_schema(cls)->PvsSchema:returns_resource({# User inputs (required or with defaults)"name":a_str(required=True,description="Server name"),# Provider outputs (computed=True)"id":a_str(computed=True,description="Unique server ID"),"ip_address":a_str(computed=True,description="Assigned IP address"),"created_at":a_str(computed=True,description="Creation timestamp"),"status":a_str(computed=True,description="Current status"),})
frompyvider.resourcesimportregister_resource,BaseResourcefrompyvider.resources.contextimportResourceContextfrompyvider.schemaimports_resource,a_str,a_num,PvsSchemaimportattrsfromdatetimeimportdatetimeimportuuid@attrs.defineclassServerConfig:name:strinstance_type:str="t2.micro"@attrs.defineclassServerState:id:strname:strinstance_type:strip_address:strcreated_at:strstatus:str@register_resource("server")classServer(BaseResource):config_class=ServerConfigstate_class=ServerState@classmethoddefget_schema(cls)->PvsSchema:returns_resource({# Inputs"name":a_str(required=True,description="Server name"),"instance_type":a_str(default="t2.micro",description="Instance type"),# Computed outputs"id":a_str(computed=True,description="Server ID"),"ip_address":a_str(computed=True,description="IP address"),"created_at":a_str(computed=True,description="Creation time"),"status":a_str(computed=True,description="Server status"),})asyncdef_create_apply(self,ctx:ResourceContext)->tuple[ServerState|None,None]:"""Create server and set computed values."""ifnotctx.config:returnNone,None# Generate computed valuesserver_id=str(uuid.uuid4())ip_address=self._allocate_ip()created_at=datetime.utcnow().isoformat()# Call API to create serverawaitself.api.create_server(id=server_id,name=ctx.config.name,instance_type=ctx.config.instance_type,)# Return state with computed valuesreturnServerState(id=server_id,name=ctx.config.name,instance_type=ctx.config.instance_type,ip_address=ip_address,created_at=created_at,status="running",),Noneasyncdefread(self,ctx:ResourceContext)->ServerState|None:"""Refresh computed values from API."""ifnotctx.state:returnNone# Fetch current state from APIserver=awaitself.api.get_server(ctx.state.id)ifnotserver:returnNone# Server deleted# Update computed values from APIreturnServerState(id=ctx.state.id,name=server.name,instance_type=server.instance_type,ip_address=server.ip_address,created_at=ctx.state.created_at,status=server.status,# May have changed)
@classmethoddefget_schema(cls)->PvsSchema:returns_resource({"name":a_str(required=True),# Computed IDs"id":a_str(computed=True,description="Unique resource ID"),"arn":a_str(computed=True,description="Amazon Resource Name"),"resource_id":a_str(computed=True,description="External system ID"),})asyncdef_create_apply(self,ctx:ResourceContext):# Generate or receive ID from APIresource_id=awaitself.api.create(ctx.config.name)returnState(id=resource_id,arn=f"arn:aws:service:region:account:{resource_id}",resource_id=resource_id,name=ctx.config.name,),None
@classmethoddefget_schema(cls)->PvsSchema:returns_resource({"name":a_str(required=True),# Network information"ip_address":a_str(computed=True,description="Assigned IP"),"public_dns":a_str(computed=True,description="Public DNS name"),"private_dns":a_str(computed=True,description="Private DNS name"),"mac_address":a_str(computed=True,description="MAC address"),})asyncdef_create_apply(self,ctx:ResourceContext):# Get network info from APInetwork_info=awaitself.api.allocate_network(ctx.config.name)returnState(id=network_info.id,name=ctx.config.name,ip_address=network_info.ip,public_dns=network_info.public_dns,private_dns=network_info.private_dns,mac_address=network_info.mac,),None
@classmethoddefget_schema(cls)->PvsSchema:returns_resource({"size_gb":a_num(required=True,description="Size in GB"),# Derived computed values"size_bytes":a_num(computed=True,description="Size in bytes"),"size_mb":a_num(computed=True,description="Size in MB"),})asyncdef_create_apply(self,ctx:ResourceContext):size_gb=ctx.config.size_gbreturnState(id=generate_id(),size_gb=size_gb,size_bytes=size_gb*1024*1024*1024,size_mb=size_gb*1024,),None
@classmethoddefget_schema(cls)->PvsSchema:returns_resource({"name":a_str(required=True),# Status fields"status":a_str(computed=True,description="Resource status"),"ready":a_bool(computed=True,description="Whether resource is ready"),"health":a_str(computed=True,description="Health check status"),})asyncdefread(self,ctx:ResourceContext):# Check current statushealth_check=awaitself.api.health_check(ctx.state.id)returnState(id=ctx.state.id,name=ctx.state.name,status=health_check.status,ready=health_check.status=="healthy",health=health_check.message,)
@classmethoddefget_schema(cls)->PvsSchema:returns_resource({"name":a_str(required=True),# Optional + Computed: User can provide, or provider will generate"tags":a_map(a_str(),optional=True,computed=True,description="Resource tags"),})asyncdef_create_apply(self,ctx:ResourceContext):# Use user-provided tags, or generate defaultstags=ctx.config.tagsifctx.config.tagselse{"managed_by":"terraform","created_at":datetime.utcnow().isoformat(),}returnState(id=generate_id(),name=ctx.config.name,tags=tags,),None
resource"mycloud_server""web"{name="web-server"instance_type="t2.micro"}# Use computed outputsoutput"server_id"{value=mycloud_server.web.id}output"server_ip"{value=mycloud_server.web.ip_address}# Use computed values in other resourcesresource"mycloud_dns_record""web"{name="web.example.com"value=mycloud_server.web.ip_address # Computed from servertype="A"}# Conditional logic based on computed valuesresource"mycloud_alert""server_health"{server_id=mycloud_server.web.idenabled=mycloud_server.web.status=="running"}
asyncdef_create(self,ctx:ResourceContext,base_plan:dict):"""Planning phase: Values may be unknown."""# Mark fields that will be known after applybase_plan["id"]=None# Will be generatedbase_plan["ip_address"]=None# Will be allocatedreturnbase_plan,None
# ✅ Good: Stable, deterministic"endpoint":a_str(computed=True)asyncdef_create_apply(self,ctx):# Endpoint is deterministic based on inputsendpoint=f"https://{ctx.config.name}.api.example.com"returnState(endpoint=endpoint),None# ❌ Bad: Changes on every applyasyncdef_create_apply(self,ctx):# Random value changes every timeendpoint=f"https://{uuid.uuid4()}.api.example.com"returnState(endpoint=endpoint),None