Implementing Pulumi dynamic provider for local file
Providing a complete Python Pulumi program defining a dynamic provider with create, read, update, and delete methods managing a local text file as a resource.
Here's a minimal Pulumi program that defines a dynamic provider to manage a local text file. The provider implements the full CRUD surface (create, read, update, and delete), and a small LocalFile resource class that uses it:
# __main__.py
import os
import pulumi
from pulumi.dynamic import Resource, ResourceProvider, CreateResult, UpdateResult, ReadResult
class LocalFileProvider(ResourceProvider):
"""
A simple dynamic provider that manages a local text file.
"""
def create(self, props):
path = props["path"]
content = props.get("content", "")
# Ensure the directory exists
os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
# Write the file
with open(path, "w") as f:
f.write(content)
# Use the file path as the resource ID
return CreateResult(id_=path, outs={"path": path, "content": content})
def read(self, id_, props):
"""
Refresh the state by reading the file from disk.
"""
if not os.path.exists(id_):
# File has been removed outside of Pulumi, signal that it is gone.
return ReadResult(id_=id_, outs=None)
with open(id_, "r") as f:
content = f.read()
outs = dict(props)
outs["content"] = content
outs["path"] = id_
return ReadResult(id_=id_, outs=outs)
def update(self, id_, old_props, new_props):
"""
Update the file contents (and optionally rename the file).
"""
new_path = new_props.get("path", id_)
new_content = new_props.get("content", "")
# Handle rename
if new_path != id_:
os.makedirs(os.path.dirname(new_path) or ".", exist_ok=True)
os.rename(id_, new_path)
# Write new content
with open(new_path, "w") as f:
f.write(new_content)
# Return new outputs
return UpdateResult(outs={"path": new_path, "content": new_content})
def delete(self, id_, props):
"""
Delete the file from disk.
"""
if os.path.exists(id_):
os.remove(id_)
class LocalFile(Resource):
def __init__(self, name, path, content, opts=None):
super().__init__(
LocalFileProvider(),
name,
{"path": path, "content": content},
opts,
)
# Example usage in your Pulumi stack
file = LocalFile("exampleFile", path="out/example.txt", content="Hello, Pulumi!")
pulumi.export("filePath", file.path)
pulumi.export("fileContent", file.content)
When you run pulumi up, Pulumi will call create to write the file. On subsequent updates it will call read to refresh state and update if the inputs change. pulumi destroy will invoke delete to remove the file.