Python binding for Terraform.

Overview

Python libterraform

libterraform libterraform libterraform Test libterraform

Python binding for Terraform.

Installation

$ pip install libterraform

NOTE

  • Please install version 0.3.1 or above, which solves the memory leak problem.
  • This library does not support multithreading.

Usage

Terraform CLI

TerraformCommand is used to invoke various Terraform commands.

Now, support all commands (plan, apply, destroy etc.), and return a CommandResult object. The CommandResult object has the following properties:

  • retcode indicates the command return code. A value of 0 or 2 is normal, otherwise is abnormal.
  • value represents command output. If json=True is specified when executing the command, the output will be loaded as json.
  • json indicates whether to load the output as json.
  • error indicates command error output.

To get Terraform verison:

>>> from libterraform import TerraformCommand
>>> TerraformCommand().version()
<CommandResult retcode=0 json=True>
>>> _.value
{'terraform_version': '1.1.7', 'platform': 'darwin_arm64', 'provider_selections': {}, 'terraform_outdated': False}
>>> TerraformCommand().version(json=False)
<CommandResult retcode=0 json=False>
>>> _.value
'Terraform v1.1.7\non darwin_arm64\n'

To init and apply according to Terraform configuration files in the specified directory:

>>> from libterraform import TerraformCommand
>>> cli = TerraformCommand('your_terraform_configuration_directory')
>>> cli.init()
<CommandResult retcode=0 json=False>
>>> cli.apply()
<CommandResult retcode=0 json=True>

Additionally, run() can execute arbitrary commands, returning a tuple (retcode, stdout, stderr).

>>> TerraformCommand.run('version')
(0, 'Terraform v1.1.7\non darwin_arm64\n', '')
>>> TerraformCommand.run('invalid')
(1, '', 'Terraform has no command named "invalid".\n\nTo see all of Terraform\'s top-level commands, run:\n  terraform -help\n\n')

Terraform Config Parser

TerraformConfig is used to parse Terraform config files.

For now, only supply TerraformConfig.load_config_dir method which reads the .tf and .tf.json files in the given directory as config files and then combines these files into a single Module. This method returns (mod, diags) which are both dict, corresponding to the *Module and hcl.Diagnostic structures in Terraform respectively.

>>> from libterraform import TerraformConfig
>>> mod, _ = TerraformConfig.load_config_dir('your_terraform_configuration_directory')
>>> mod['ManagedResources'].keys()
dict_keys(['time_sleep.wait1', 'time_sleep.wait2'])

Building & Testing

If you want to develop this library, should first prepare the following environments:

  • GoLang (Version 1.17.x or 1.16.x)
  • Python (Version 3.6~3.10)
  • GCC

Then, initialize git submodule:

$ git submodule init
$ git submodule update

pip install necessary tools:

$ pip install poetry pytest

Now, we can build and test:

$ poetry build -f wheel
$ pytest

Why use this library?

Terraform is a great tool for deploying resources. If you need to call the Terraform command in the Python program for deployment, a new process needs to be created to execute the Terraform command on the system. A typical example of this is the python-terraform library. Doing so has the following problems:

  • Requires Terraform commands on the system.
  • The overhead of starting a new process is relatively high.

This library compiles Terraform as a dynamic link library in advance, and then loads it for calling. So there is no need to install Terraform, nor to start a new process.

In addition, since the Terraform dynamic link library is loaded, this library can further call Terraform's internal capabilities, such as parsing Terraform config files.

You might also like...
PRAW, an acronym for "Python Reddit API Wrapper", is a python package that allows for simple access to Reddit's API.

PRAW: The Python Reddit API Wrapper PRAW, an acronym for "Python Reddit API Wrapper", is a Python package that allows for simple access to Reddit's AP

PRAW, an acronym for "Python Reddit API Wrapper", is a python package that allows for simple access to Reddit's API.

PRAW: The Python Reddit API Wrapper PRAW, an acronym for "Python Reddit API Wrapper", is a Python package that allows for simple access to Reddit's AP

alpaca-trade-api-python is a python library for the Alpaca Commission Free Trading API.

alpaca-trade-api-python is a python library for the Alpaca Commission Free Trading API. It allows rapid trading algo development easily, with support for both REST and streaming data interfaces

🖥️ Python - P1 Monitor API Asynchronous Python Client

🖥️ Asynchronous Python client for the P1 Monitor

Volt is yet another discord api wrapper for Python. It supports python 3.8 +

Volt Volt is yet another discord api wrapper for Python. It supports python 3.8 + How to install [Currently Not Supported.] pip install volt.py Speed

Bagas Mirror&Leech Bot is a multipurpose Telegram Bot written in Python for mirroring files on the Internet to our beloved Google Drive. Based on python-aria-mirror-bot
Bagas Mirror&Leech Bot is a multipurpose Telegram Bot written in Python for mirroring files on the Internet to our beloved Google Drive. Based on python-aria-mirror-bot

- [ MAYBE UPDATE & ADD MORE MODULE ] Bagas Mirror&Leech Bot Bagas Mirror&Leech Bot is a multipurpose Telegram Bot written in Python for mirroring file

A python Discord wrapper made in well, python.

discord.why A python Discord wrapper made in well, python. Made to be used by devs who want something a bit more, general. Basic Examples Sending a me

A wrapper for aqquiring Choice Coin directly through a Python Terminal. Leverages the TinyMan Python-SDK.

CHOICE_TinyMan_Wrapper A wrapper that allows users to acquire Choice Coin directly through their Terminal using ALGO and various Algorand Standard Ass

Python On WhatsApp - Run your python codes on whatsapp along with talking to a chatbot
Python On WhatsApp - Run your python codes on whatsapp along with talking to a chatbot

Python On WhatsApp Run your python codes on whatsapp along with talking to a chatbot This is a small python project to run python on whatsapp. and i c

Comments
  • Could not find a version that satisfies the requirement libterraform

    Could not find a version that satisfies the requirement libterraform

    $ pip install libterraform ERROR: Could not find a version that satisfies the requirement libterraform (from versions: none) ERROR: No matching distribution found for libterraform $

    opened by judab5ericom 0
  • ERROR: Could not build wheels for libterraform which use PEP 517 and cannot be installed directly

    ERROR: Could not build wheels for libterraform which use PEP 517 and cannot be installed directly

    getting the following error when trying to compile local Installing build dependencies ... done Getting requirements to build wheel ... done Preparing wheel metadata ... done /home/judab/.local/lib/python3.8/site-packages/pkg_resources/init.py:123: PkgResourcesDeprecationWarning: 0.23ubuntu1 is an invalid version and will not be supported in a future release warnings.warn( /home/judab/.local/lib/python3.8/site-packages/pkg_resources/init.py:123: PkgResourcesDeprecationWarning: 0.1.36ubuntu1 is an invalid version and will not be supported in a future release warnings.warn( Building wheels for collected packages: libterraform Building wheel for libterraform (PEP 517) ... error ERROR: Command errored out with exit status 1: command: /usr/bin/python3 /tmp/tmpjxsbgvg0 build_wheel /tmp/tmpmuv6vjmq cwd: /tmp/pip-req-build-4kwbn1bw Complete output (33 lines):

    sigs.k8s.io/json/internal/golang/encoding/json

    /home/judab/go/pkg/mod/sigs.k8s.io/[email protected]/internal/golang/encoding/json/encode.go:1249:12: sf.IsExported undefined (type reflect.StructField has no field or method IsExported) /home/judab/go/pkg/mod/sigs.k8s.io/[email protected]/internal/golang/encoding/json/encode.go:1255:18: sf.IsExported undefined (type reflect.StructField has no field or method IsExported) - Patching go-plugin package - Building libterraform Traceback (most recent call last): File "build.py", line 72, in build({}) File "build.py", line 54, in build subprocess.check_call( File "/usr/lib/python3.8/subprocess.py", line 364, in check_call raise CalledProcessError(retcode, cmd) subprocess.CalledProcessError: Command '['go', 'build', '-buildmode=c-shared', '-o=libterraform.so', 'github.com/hashicorp/terraform']' returned non-zero exit status 2. Traceback (most recent call last): File "/tmp/tmpjxsbgvg0", line 280, in main() File "/tmp/tmpjxsbgvg0", line 263, in main json_out['return_val'] = hook(**hook_input['kwargs']) File "/tmp/tmpjxsbgvg0", line 204, in build_wheel return _build_backend().build_wheel(wheel_directory, config_settings, File "/tmp/pip-build-env-e48g7589/overlay/lib/python3.8/site-packages/poetry/core/masonry/api.py", line 68, in build_wheel return unicode(WheelBuilder.make_in(poetry, Path(wheel_directory))) File "/tmp/pip-build-env-e48g7589/overlay/lib/python3.8/site-packages/poetry/core/masonry/builders/wheel.py", line 78, in make_in wb.build() File "/tmp/pip-build-env-e48g7589/overlay/lib/python3.8/site-packages/poetry/core/masonry/builders/wheel.py", line 106, in build self._build(zip_file) File "/tmp/pip-build-env-e48g7589/overlay/lib/python3.8/site-packages/poetry/core/masonry/builders/wheel.py", line 152, in _build self._run_build_script(self._package.build_script) File "/tmp/pip-build-env-e48g7589/overlay/lib/python3.8/site-packages/poetry/core/masonry/builders/wheel.py", line 202, in _run_build_script subprocess.check_call([self.executable.as_posix(), build_script]) File "/usr/lib/python3.8/subprocess.py", line 364, in check_call raise CalledProcessError(retcode, cmd) subprocess.CalledProcessError: Command '['/usr/bin/python3', 'build.py']' returned non-zero exit status 1.

    ERROR: Failed building wheel for libterraform Failed to build libterraform ERROR: Could not build wheels for libterraform which use PEP 517 and cannot be installed directly

    opened by judab5ericom 0
Releases(v0.4.0)
  • v0.3.1(Apr 19, 2022)

  • v0.3.0(Apr 6, 2022)

    TerraformCommand supports all Terraform commands. Compared with v0.2.1, the current version supports the following commands:

    • fmt
    • force unlock (The corresponding function is force_unlock)
    • graph
    • import (The corresponding function is import_resource)
    • refresh
    • state and all sub commands of state
    • taint
    • untaint
    • test
    • workspace and all sub commands of workspace

    The project adds Makefile so we can use make command, like make init, make test, make build etc.

    Source code(tar.gz)
    Source code(zip)
  • v0.2.1(Mar 31, 2022)

    Implement TerraformCommand which is used to invoke various Terraform commands.

    Currently, supports version and all main commands (init, validate, plan, show, apply and destroy), returning a CommandResult object. The CommandResult object has the following properties:

    • retcode indicates the command return code. A value of 0 or 2 is normal, otherwise is abnormal.
    • value represents command output. If json=True is specified when executing the command, the output will be loaded as json.
    • json indicates whether to load the output as json.
    • error indicates command error output.
    Source code(tar.gz)
    Source code(zip)
  • v0.1.0(Mar 11, 2022)

    Implement TerraformConfig which is used to parse Terraform config files.

    For now, only supply TerraformConfig.load_config_dir method which reads the .tf and .tf.json files in the given directory as config files and then combines these files into a single Module. This method returns (mod, diags) which are both dict, corresponding to the *Module and hcl.Diagnostic structures in Terraform respectively.

    Source code(tar.gz)
    Source code(zip)
Owner
Prodesire
Pythonista. Microsoft MVP.
Prodesire
A Telegram robot can clone medias from any chat to your own chat.

Clonebot A Telegram robot can clone medias from any chat to your own chat. Read the documentation to know how to use the bot Deploy Developer Document

Renjith Mangal 224 Dec 30, 2022
A curated list of awesome Amazon Web Services (AWS) libraries, open source repos, guides, blogs, and other resources.

A curated list of awesome Amazon Web Services (AWS) libraries, open source repos, guides, blogs, and other resources. Featuring the Fiery Meter of AWSome.

Donne Martin 11.1k Jan 04, 2023
A Python client for the Softcite software mention recognizer server

Softcite software mention recognizer client Python client for using the Softcite software mention recognition service. It can be applied to individual

4 Feb 02, 2022
Telegram Voice Chat Music Player UserBot Written with Pyrogram Smart Plugin and tgcalls

Telegram Voice Chat UserBot A Telegram UserBot to Play Audio in Voice Chats. This is also the source code of the userbot which is being used for playi

Dash Eclipse 7 May 21, 2022
Discord-Wrapper - Discord Websocket Wrapper in python

This does not currently work and is in development Discord Websocket Wrapper in

3 Oct 25, 2022
Telegram Bot to Connect Strangers

Telegram Bot to Connect Strangers How to Run Set your telegram bot token as environment variable TELEGRAM_BOT_TOKEN: export TELEGRAM_BOT_TOKEN=your_t

PyTopia 12 Dec 24, 2022
Python client and module for BGP Ranking

Python client and module for BGP Ranking THis project will make querying BGP Ranking easier. Installation pip install pybgpranking Usage Command line

D4 project 3 Dec 16, 2021
A frame to create discord bots (for myself) that uses cogs, JSON, activities, and more.

dpy-frame A frame to create discord bots (for myself) that uses cogs, JSON, activities, and more. NOTE: Documentation is incomplete, so please wait un

Apple Discord 1 Nov 06, 2021
A python library for building user interfaces in discord.

blurple.py A front-end framework for discord.py Blurple.py is a framework built on top of discord.py, giving you the tools you need to build discord b

4 Oct 25, 2021
Discord Custom Playing Status Redirecting

Discord-Custom-Playing-Status-Redirecting THINGS TO DO :- - Create an application from https://discord.com/developers/applications give it ur desired

WarLorD oP 1 Oct 30, 2021
Indian Space Research Organisation API With Python

ISRO Indian Space Research Organisation API Installation pip install ISRO Usage import isro isro.spacecrafts() # returns spacecrafts data isro.lau

Fayas Noushad 5 Aug 11, 2022
Практическая работа 6 - Документирование кода

Практическая работа №6 ПСП – правильная скобочная последовательность – последовательность из открывающих «(« и закрывающих «)» круглых скобок. Програм

0 Apr 14, 2022
Simulation artifacts, core components and configuration files to integrate AWS DeepRacer device with ROS Navigation stack.

AWS DeepRacer Overview The AWS DeepRacer Evo vehicle is a 1/18th scale Wi-Fi enabled 4-wheel ackermann steering platform that features two RGB cameras

AWS DeepRacer 31 Nov 21, 2022
Tracker to check the covid shot slot availability in India and send mobile alerts via Twilio Messaging Service.

Cowin-Slot-Tracker Tracker to check the covid vaccine slot availability in India and send mobile notifications through Twilio Messaging Service. Requi

invalid username 27 Nov 12, 2022
This is a simple collection of instructions and scripts to accompany the computerphile video about mininet and openflow.

How to get going. This project should work on Linux or MacOS. I used Ubuntu 20.04 and provide some notes here. Note, this is certainly not intended as

Richard G. Clegg 70 Jan 02, 2023
A simple Python TDLib wrapper

Telegram Forwarder App Description pywtdlib (Python Wrapper TDLib) is a simple synchronous Python wrapper that makes you easy to create new Python Tel

Álvaro Fernández 2 Jan 04, 2023
Python based Discord Bot with a simple music player

C32 Discord Bot Discord bot that plays music Table Of Contents About the Project Built With Acknowledgements About The Project Play music using the !p

Christopher Burwell 2 Oct 17, 2021
📷 Instagram Bot - Tool for automated Instagram interactions

InstaPy Tooling that automates your social media interactions to “farm” Likes, Comments, and Followers on Instagram Implemented in Python using the Se

Tim Großmann 13.5k Dec 01, 2021
A simple API wrapper for the Tenor API

Gifpy A simple API wrapper for the Tenor API Installation Python 3.9 or higher is recommended python3 -m pip install gifpy Clone repository: $ git cl

Juan Ignacio Battiston 4 Dec 22, 2021
A template that everyone can use for the start of their discord bot

Python Discord Bot Template This repository is a template that everyone can use for the start of their discord bot. When I first started creating my d

2 Nov 01, 2021