はじめに
<バージョン>
ansible: 2.9.7
fastapi: 0.65.2
Python: 3.6.8
uvicorn: 0.14.0
FastAPIとは、Python 3.6 以降でAPI を構築するためのWeb フレームワークです。
今回はFastAPIに対して、AnsibleのuriモジュールでPOSTしてみます。
1. 前準備
まずはFastAPIとuvicornをインストールしましょう。
pip install fastapi uvicorn
2. Pythonコード作成
実際に作成したコードが以下です。Ansibleからnumberという値をもらい、
その2倍の値を戻すコードを作成しました。
- ポイント
- @app.post("/calculate")のように、使用するメソッドとアクセス先を記載
- /calculateとすると、アクセスするURLはhttp://127.0.0.1:8000/calculateになる
- return {"calculate_result": return_value}のように、戻り値の変数を記載
- Ansibleでの戻り値は、
register変数.json.calculate_result
になる
- Ansibleでの戻り値は、
- @app.post("/calculate")のように、使用するメソッドとアクセス先を記載
test_calculate.py
from pydantic import BaseModel
from fastapi import FastAPI
app = FastAPI()
class main_dict(BaseModel):
number: int
# url is http://127.0.0.1:8000/calculate
@app.post("/calculate")
async def declare_nested_request_body(data: main_dict):
return_value = data.number * 2
return {"calculate_result": return_value}
3. Playbook作成
実際に作成したplaybookが以下です。FastAPIに変数number(=10)を渡します。
- ポイント
- uriモジュール
- FastAPIに渡す変数はbodyに記載
- 実行結果はregisterで変数resultに格納する
- debugモジュール
-
result.json.calculate_result
で実行結果が確認可能
-
- uriモジュール
post_fastapi.yml
---
- hosts: localhost
gather_facts: false
tasks:
- name: "post number"
uri:
url: "http://127.0.0.1:8000/calculate"
method: "POST"
body_format: "json"
body:
number: 10
register: result
- name: "debug calculate result"
debug:
var: result.json.calculate_result
4. サーバー起動
作成したコード(test_calculate.py)のあるディレクトリに移動して、
サーバを起動させましょう。以下のように、uvicornコマンドで実行するコードを指定しましょう。
uvicorn test_calculate:app --reload
5. 実行結果
想定通り、渡した変数number(=10)の2倍の値が戻ってきました。
出力
(venv) [centos@ip-<ip-addr> python]$ ansible-playbook post_fastapi.yml
[WARNING]: No inventory was parsed, only implicit localhost is available
[WARNING]: provided hosts list is empty, only localhost is available. Note that the implicit localhost does not match 'all'
PLAY [localhost] ******************************************************************************************************************
TASK [post number] ****************************************************************************************************************
ok: [localhost]
TASK [debug calculate result] *****************************************************************************************************
ok: [localhost] => {
"result.json.calculate_result": "20"
}
PLAY RECAP ************************************************************************************************************************
localhost : ok=2 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
参考記事
チュートリアル - FastAPI
[FastAPI] Python製のASGI Web フレームワーク FastAPIに入門する
Ansible Documentation - uri