[PYTHON] It is surprisingly troublesome to get a list of the last login date and time of Workspaces

Introduction I run Workspaces, but here are some tips I found during the run.

What is Workspaces This article is intended for those who are actually operating Workspaces, so what is VDI? What is Workspaces? Is omitted. See official for details. [Amazon WorkSpaces](https://aws.amazon.com/jp/workspaces/)

Why do you need the last login date and time When operating AWS Workspaces, I want to know if there are people who have created instances but are not actually using them. Your last login date is X months ago, but don't you use it anymore? I want to do an inventory.

How can I get the last login date and time? There is no last login date and time in the instance list display of the management console. If you look at the details one by one, it will come out. .. .. Investigation starts from here. First of all, if you check the API specification, it is true that [DescribeWorkspaces](https://docs.aws.amazon.com/workspaces/latest/api/API_DescribeWorkspaces.html) that gets the instance list does not have the last login date. .. ..

If you take a closer look at the API documentation, you will find the last login date and time LastKnownUserConnectionTimestamp in DescribeWorkspacesConnectionStatus!


//Response Syntax
   "NextToken": "string",
   "WorkspacesConnectionStatus": [ 
         "ConnectionState": "string",
         "ConnectionStateCheckTimestamp": number,
         "LastKnownUserConnectionTimestamp": number, //<-this!
         "WorkspaceId": "string"

However, it seems that you can only request up to 25 instances after putting WorkspaceId in this API and request. It seems that if there are 25 or more units, it is not possible to acquire all of them at once.

WorkspaceIds The identifiers of the WorkSpaces. You can specify up to 25 WorkSpaces.

Use Python to get the list Now that I know the API specifications, I created a program in Python. Assuming that the required authority is in the environment variable, I made a program that spits out the instance list + last login date and time in CSV format. A little ingenuity is that even if the Direcotry ID is displayed in CSV, it sounds without knowing what it was, so I adjusted it to display the Direcotry Name. If you put the operating DirectoryID in `DirecotryIds` as an array, it should work. Python 2.7.10.


import boto3
import csv

# Initialize SDK client for AWS Workspaces
client = boto3.client('workspaces')
paginator_describe = client.get_paginator('describe_workspaces')
paginator_connection = client.get_paginator('describe_workspaces_connection_status')

# Initialize output CSV header
data = [["UserName", "WorkspaceId", "Directory", "State", "ComputerType", "LastLogin"]]

# Initialize Directory ID list
DirectoryIds = [

# Initialize mapping between Directory ID and Name
def addDirectoryMapping(direcotry):
    directoryMapping[direcotry["DirectoryId"]] = direcotry["Alias"]

directoryMapping = {}
paginator = client.get_paginator('describe_workspace_directories')
page_iterator = paginator.paginate()
for page in page_iterator:
    map(addDirectoryMapping, page["Directories"])
print("Direcotry mapping is DONE")

# Find Directory Name from ID
# @param  workspace ID
# @return Name of directory
def findDirectoryName(direcotyrId):
    if direcotyrId in directoryMapping:
        return directoryMapping[direcotyrId]
        return "Other"

# Find last login time by SingleId
# @param  workspace ID
# @return LastLogin Time
def findLatestLoginTimeById(workspaceId):
    response = client.describe_workspaces_connection_status(
    if not len(response["WorkspacesConnectionStatus"])==0:
        connectionStatus = response["WorkspacesConnectionStatus"][0]
        if "LastKnownUserConnectionTimestamp" in connectionStatus:
            return connectionStatus["LastKnownUserConnectionTimestamp"]
            return "unknown"
        return "Error"

# Get necessary information from Workspace Instance
# @param workspaces
# @return list
def parse_list(workspaces):
    return list

# Get necessary information from Workspace Connection Status
# @param WorkspacesConnectionStatus
# @return list
def parse_list_connection(WorkspacesConnectionStatus):
    if "LastKnownUserConnectionTimestamp" in WorkspacesConnectionStatus:
    return list

# Export CSV file
def exportCSV(data):
    with open("VDI_LIST.csv", "w") as f:
        writer = csv.writer(f, lineterminator="\n")
        print("Create File is DONE")

# main function
def describeWorkspacesByDirectoryId (Id):  
        workspacesDescribeInDirectory = []
        print(Id + " is started")
        # describe workspaces
        page_iterator_describe = paginator_describe.paginate(DirectoryId=Id,PaginationConfig={'PageSize': 10})
        for page in page_iterator_describe:
            workspacesDescribeInDirectory = map(parse_list, page["Workspaces"])
        print(Id + " describe_workspaces is DONE")
    except Exception as e:
        print(e.message + " :: impacted Directory ID is " + Id)

map(describeWorkspacesByDirectoryId, DirectoryIds)

More advanced usage analysis By the way, [Workspaces Cost Optimizer](Workspaces Cost Optimizer), a service that analyzes usage properly. https://docs.aws.amazon.com/solutions/latest/workspaces-cost-optimizer/welcome.html)がAWSでは用意されているみたいなので、本格的な運用ではコレを利用するのが良いみたい。

Conclusion It would be better to execute the batch once a month, but since I had an application for manual operation (laughs), there were some users who had never logged in even though I created an instance, so it was a surprisingly useful program. did.

Recommended Posts

It is surprisingly troublesome to get a list of the last login date and time of Workspaces
How to get the last (last) value in a list in Python
Recursively get the Excel list in a specific folder with python and write it to Excel.
[Introduction to Python] What is the difference between a list and a tuple?
[Linux] Command to get a list of commands executed in the past
Get the list in the S3 bucket with Python and search with a specific Key. Output the Key name, last update date, and count number to a file.
[Python] Get the last updated date of the website
[Python] Create a list of date and time (datetime type) for a certain period
A record of the time it took to deploy mysql on Cloud9 + Rails
Python script to get a list of input examples for the AtCoder contest
How to get a list of files in the same directory with python
The story of Airflow's webserver and DAG, which takes a long time to load
How to check in Python if one of the elements of a list is in another list
I managed to do it because the custom of attaching a zip with a password to an email and saying "I will send you the password separately" is troublesome.
I just wanted to extract the data of the desired date and time with Django
Script to get the expiration date of the SSL certificate
Creating a list when the nomenclature is a fixed time
Spit out a list of file name, last modified date and character code in python3
Get the value of a specific key up to the specified index in the dictionary list in Python
Give the history command a date and time and collect the history files of all users with a script
An easy way to view the time taken in Python and a smarter way to improve it
Try to get the function list of Python> os package
[Command] Command to get a list of files containing double-byte characters
[Python] Create a date and time list for a specified period
Get the number of specific elements in a python list
Get a global IP and export it to Google Spreadsheets
How to get a list of built-in exceptions in python
Get the current date and time in Python, considering the time difference
How to get a list of links from a page from wikipedia
Is there a secret to the frequency of pi numbers?
How to connect the contents of a list into a string
Scraping the list of Go To EAT member stores in Fukuoka prefecture and converting it to CSV
Find the white Christmas rate by prefecture with Python and map it to a map of Japan
[Python] The role of the asterisk in front of the variable. Divide the input value and assign it to a variable
Scraping the list of Go To EAT member stores in Niigata prefecture and converting it to CSV
python memo: enumerate () -get index and element of list at the same time and turn for statement
I want to record the execution time and keep a log.
Set the last modified date of the child file to the modified date of the parent directory
Note: Get the first and last items of Python OrderedDict non-destructively
I tried to get the index of the list using the enumerate function
How easy is it to synthesize a drug on the market?
On Linux, the time stamp of a file is a little past.
Delete a particular character in Python if it is the last
I tried to get a list of AMI Names using Boto3
[Python3] Define a decorator to measure the execution time of a function
How to get the vertex coordinates of a feature in ArcPy
What is a dog? Volume of GET request and query parameters
How to get a list excluding elements whose index is i ...?
Convert the result of python optparse to dict and utilize it
Dig the directory and create a list of directory paths + file names
Create a function to get the contents of the database in Go
Get the title and delivery date of Yahoo! News in Python
[Python] A program that rotates the contents of the list to the left
[Python / Jupyter] Translate the comment of the program copied to the clipboard and insert it in a new cell
Is it possible to enter a venture before listing and make a lot of money with stock options?
Get a list of camera parameters that can be set with cv2.VideoCapture and make it a dictionary type
How to input a character string in Python and output it as it is or in the opposite direction.
Upload data to s3 of aws with a command and update it, and delete the used data (on the way)
For Windows: Get a list of directories and files under a specific directory.
Until you get a snapshot of Amazon Elasticsearch service and restore it
[Introduction to Python] How to sort the contents of a list efficiently with list sort