Package: pyterraformer
PyterraformerAbout The ProjectPyterraformer is a library for reading, modifying, and writinghuman readable terraform code. This is in contrast to
libraries such as the excellentpyhcl2, which don't support writing
back in the human format. It is similar toterraform-cdkin that it also enables
directly executing terraform from python as well, but is different in that it can produce human readable code to check
in. This opens up a range of options for creative developers.Pyterraformer can be used for any of the following:bulk generation of human readable terraform codelarge scale refactoringprocess automation, since as CIaccessing the power of Terraform directly from pythonintrospecting a terraform repo to collect informationand more!Parsing and ModifyingSpecifically, this library would enable reading this stringresource"aws_s3_bucket""b"{bucket="my-tf-test-bucket"tags={Name="My bucket"Environment="Dev"}}into python, directly modifying the tags, and writing it back.Let's take a look.frompyterraformerimportHumanSerializerhs=HumanSerializer(terraform='/path/to/my/terraform/binary')example_string:str='''resource "aws_s3_bucket" "b" {bucket = "my-tf-test-bucket"tags = {Name        = "My bucket"Environment = "Dev"}}'''# parse a string into a list of terraform objectsnamespace=hs.parse_string(example_string)# get the bucket from that listbucket=namespace[0]# modify the bucketbucket.tags["Environment"]="Prod"bucket.bucket='my-updated-bucket'# and write the modified namespace back# formatting requires a valid terraform binary to be providedupdated=hs.render_object(bucket,format=True)assertupdated=='''resource "aws_s3_bucket" "b" {bucket = "my-updated-bucket"tags = {Name        = "My bucket"Environment = "Prod"}}'''ApplyingIf you just want to directly create/modify resources from python, you can do that too.For example, creating or modifying GCS bucket with a local state store is as simple as the below.importosfrompyterraformerimportTerraform,TerraformWorkspace,HumanSerializer,LocalBackendfrompyterraformer.core.genericsimportBlockListfrompyterraformer.core.resourcesimportResourceObjectclassGoogleStorageBucket(ResourceObject):"""Let's define a google storge bucket resource.To get provider resources defined for you, check out the provider packages."""_type='google_storage_bucket'if__name__=="__main__":tf=Terraform(terraform_exec_path=r'/path/to/my/terraform/binary',backend=LocalBackend(path=os.getcwd()))workspace=TerraformWorkspace(terraform=tf,path=os.getcwd(),serializer=HumanSerializer(terraform=tf))namespace=workspace.get_file_safe('resource.tf')namespace.add_object(GoogleStorageBucket(id='my-new-bucket',name="my-new-bucket",location="US-EAST1",project="my-project",force_destroy=True,uniform_bucket_level_access=True,website=BlockList([{'not_found_page':"404.html"}]),cors=BlockList([{'origin':["https://readthedocs.org"],'method':["GET","HEAD","PUT","POST","DELETE"],'response_header':["*"],'max_age_seconds':3601}])))workspace.save()application_output=workspace.apply()Next StepsRead thedocumentationto discover more, including how to work with
directories, files, apply terraform directly, and get IDE auto-completion for your favorite providers.Project Maturitypyterraformeris under active development; we’re still working out key workflows and best practices. While it has
been used extensively in internal projects, the open-source version contains significant rewrites for improved flexibility.
We’re iterating fast and are likely to introduce breaking changes to existing APIs to improve the developer experience.
Feedback is appreciated.Installationpyterraformerishosted on PyPI, and is installable
withpip:pipinstallpyterraformerTyped classes for IDE autocomplete and validation [if available] can be installed under the package name
pytf-[provider-owner]-[provider-name]pipinstallpytf-hashicorp-awsAnd then imported in the following wayfrompyterraformer.providers.hashicorp.awsimportaws_s3_bucketDocumentationPrimary documentation is onRead the DocsRoadmapSee theopen issuesfor a list of proposed features (and known issues).ContributingContributions are what make the open source community such an amazing place to learn, inspire, and create. Any
contributions you make aregreatly appreciated. For detailed contributing guidelines, please
seeCONTRIBUTING.mdLicenseDistributed under theMIT LicenseLicense. SeeLICENSEfor more information.ContactProject Link:https://github.com/org_name/repo_nameAcknowledgementsThis template adapted fromhttps://github.com/othneildrew/Best-README-Template