'Is there any way we can integrate terraform with fastapi?

Is there a way to call terraform deployment utility in service endpoint(fastapi, flask)

To summarize Integration of service endpoint with Terraform?



Solution 1:[1]

After exploring a bit on it, Observed that there is no such direct module which can be utilized so I have come to a way of using it in routed manner. Following are the steps that can be used :

1> Use template for deployment of infra at aws

2> Invoke ansible playbook

---
- hosts: localhost
  become: no
  gather_facts: False
  vars:
    ansible_python_interpreter: /usr/bin/python3
  tasks:
  - name: Deployment CFT via terraform for aws infra
    community.general.terraform:
      project_path: '/root/terraform-sample-ansible'
      state: present

3> In ansible playbook only we can use terraform module

4> Write a method in ansible playbook which after deployment dumps the json output to some file

5> Now write service endpoint code, say endpoint.py using fastapi

Snippet :

@app.get("/")
async def get_instances():
    """ REST endpoint to query instances """

    play_run = run_playbook(playbook='<path of ansible file>')
    with open("<file where output of ansible is dumped>", "r") as read_file:
        data = json.load(read_file)
        pretty_json = json.dumps(data, indent=4)
        print(pretty_json)
    return data

This can be a possible integration of terraform, ansible and service endpoint (fastapi).

Thanks!

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Himanshu Pandey