DevOps-Automation with Python 5
TF advantages for Infrastructure provisioning
What is the difference? Which one to use?
首先列一下Terraform相關特性:
Terraform manages state of the infrastructure:
- TF knows the current state
- TF knows the difference of current state and your configured/desired state
- TF is idempotent(multiple execution of same config file will always result in same end result)
- 例如透過TF一樣建立一個VPC+兩個Subnet,寫好的TF不管執行幾次,AWS上面只會多一個VPC與兩個Subnet,不會再更多了
- TF is more high-level(後面會解釋)
但是Python透過Boto3寫的程式建立一個VPC與兩個Subnet
重複地執行就會越來越多個VPC與Subnet被建立出來
講師執行第二次看到:
講師執行第三次看到:
Python Boto3建立AWS資源特性:
- Python doesn’t have state
- Python is not idempotent
移除Resource部分
- 以前瞭解Terraform要移除像是AWS的資源就是把相關資源定義Code移除後執行
- 也就是TF Code定義了最終資源
- 或是有針對整份TF Code內容定義的資源移除的destroy指令
- 但是在Python則要專門寫移除的程式,並且執行了才能移除
- 但是不一定容易撰寫,甚至VPC內有其它資源在運行,還有可能移除不了
就目前Python建立的VPC與兩個Subnet來說
在AWS Web上手動刪除甚至還更快一點(同前一篇最後我就手動移除了)
否則要靠Coding方式大致上就是在VPC確認的for迴圈內去做移除
(但可想而知還要寫條件避開default VPC的移除,真的不容易)
就上面整理的比較資訊來說,就建立AWS的資源(像是範例VPC與Subnet)而言
Terraform是比較適合的工具!
前面整理TF有說道,TF is more high-level
即是相比Python還要特地寫一堆邏輯
TF Code的程式結構也比較容易瀏覽資源
相比下Python的Boto3 Library也是low-level,因為其沒有建立太多的抽象來對AWS API做溝通
Different Use Cases for Boto3
Terraform這麼好用,那我們這邊為何還有Boto3的存在?
- With Boto3 you can do more thing, because of its low-level API
- More complex logic possible
- Because Python is a full fledged programming language
- Because Boto3 is a full fledged AWS Library(can get more info/resource from AWS) compare to Terraform’s AWS provider
Python+Boto3 can do:
- Python+Boto3 => Monitoring
- Python+Boto3 => BackUps
- Python+Boto3 => Scheduled Tasks
- Python+Boto3 => Add Web interface
像是在Python專案中增加一個按鈕來透過Boto3的API查詢AWS資源或監控狀態等
也就是有更多的程式上的彈性
最後...
When to use which tool?
資深的工程師或DevOps工程師可能熟悉兩種工具,就該知道哪個適合用在什麼情景之下!