有什么方法可以将 Terraform 与 fastapi 集成?

Is there any way we can integrate terraform with fastapi?

有没有办法在服务端点(fastapi、flask)中调用 terraform 部署实用程序

总结服务端点与 Terraform 的集成?

在探索了一下之后,发现没有这样的直接模块可以使用,所以我想出了一种以路由方式使用它的方法。 以下是可以使用的步骤:

1> 使用模板在 aws 部署基础设施

2> 调用 ansible 剧本

---
- 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> 只有在 ansible playbook 中我们才能使用 terraform 模块

4> 在 ansible 剧本中编写一个方法,在部署后将 json 输出转储到某个文件

5> 现在编写服务端点代码,比如 endpoint.py 使用 fastapi

片段:

@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

这可能是 Terraform、ansible 和服务端点 (fastapi) 的集成。

谢谢!