회사 테스트 환경을 관리하면서 VM 의 소유자(생성자)를 관리하면 좋겠다는 생각을 했습니다.
사실 실제 엔터프라이즈 서비스 환경에서는 크게 필요없는 기능 같습니다.
하지만 테스트환경이나 개발환경에서는 리소스를 크게 차지하는 VM의 소유자를 찾아 메시지를 보낸다거나 할 수 있겠죠.
파이썬을 이용했고 VMware 에서 제공하는 SDK를 사용했습니다.
While managing our company's test environment, I thought it would be useful to track the owners (creators) of the virtual machines (VMs).
In reality, this feature might not be particularly necessary in an actual enterprise service environment.
However, in a test or development environment, it could be helpful to identify the owner of a VM that consumes a lot of resources, allowing us to send a message or take necessary actions.
I used Python along with the SDK provided by VMware.
pip install pyvim
pip install pyVmomi
pip install ssl
from pyvim.connect import SmartConnect, Disconnect
from pyVmomi import vim
import ssl
vc_host='your vSphere environment url or ip'
vc_user='user ID'
vc_pwd='user Password'
context = ssl._create_unverified_context()
si = SmartConnect(host=vc_host,
user=vc_user,
pwd=vc_pwd,
sslContext=context)
content = si.RetrieveContent()
def get_all_vmnames(content):
container_view = content.viewManager.CreateContainerView(
content.rootFolder, [vim.VirtualMachine], True
)
vms = container_view.view
container_view.Destroy()
return vms
def check_vm_created_event(vm_name, content):
event_manager = content.eventManager
event_filter = vim.event.EventFilterSpec()
event_filter.entity = vim.event.EventFilterSpec.ByEntity(
entity=vm_name, recursion=vim.event.EventFilterSpec.RecursionOption.self
)
event_filter.type = [vim.event.VmCreatedEvent] # VmCreatedEvent만 필터링
events = event_manager.QueryEvents(event_filter)
for event in events:
if isinstance(event, vim.event.VmCreatedEvent):
print(f"{vm_name.name}-{event.userName}")
vm_name_list = get_all_vmnames(content)
# vm_names = [vm.name for vm in vm_name_list]
# print(vm_names)
for vm in vm_name_list:
check_vm_created_event(vm, content)
Disconnect(si)
출력값은 현재 존재하는 vm과 해당 vm의 created events 의 생성자 ID 입니다.
해당 값을 참조하여 VM Owner를 알 수 있습니다.
개선해야 할 점
- 해당 정보를 따로 저장하지는 않음 (엑셀, DB 등..)
- 이벤트 로그 저장 기한 이전의 내용은 알 수 없다
문의 사항은 댓글로 남겨주세요
*해당 코드내용은 작성자가 작성하고 실행시 문제가 없었으며, 코드 실행의 결과 대한 책임은 지지 않으므로 참고 바랍니다.
The output includes a list of currently existing VMs and the creator IDs from the "created" events associated with each VM.
By referencing these values, we can identify the owner of each VM.
Areas For Inprovement
- This information is not stored separately (e.g., in Excel, a database, etc.).
- It is not possible to retrieve details beyond the event log retention period.
Please leave any questions in the comments.
Note: This code was written and tested by the author without issues; however, please be aware that the author is not responsible for any outcomes resulting from executing the code. Use at your own discretion.
'실습' 카테고리의 다른 글
Azure와 Openvpn를 이용한 S2S vpn 연결 (0) | 2024.02.06 |
---|