0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

[備忘(自分用)]AWS WorkspacesをCLIで量産する

Last updated at Posted at 2025-10-27

はじめに

色々あってAWS Workspacesを50個量産する必要があったので、CLIで量産しました。
(色々あった背景は近日別記事で投稿予定・・)
備忘として実行したソースと手順を残します。

実施方法

準備するもの

  1. Workspacesユーザの情報を記載したcsvファイル
  2. WorkspaceaのCREATE APIを呼び出すPythonファイル

1. Workspacesユーザの情報を記載したcsvファイル

以下のようにWorkspaces表示ユーザ名、姓、名、メールアドレスを一覧化したcsvを用意する。
※Workspacesのディレクトリにて既に用意されたユーザである必要があります。

Username,FirstName,LastName,Email
user1,英田部,流江洲,awsxxx@aws.com
user2,英田部,流江洲,awsxxx@aws.com
user3,英田部,流江洲,awsxxx@aws.com

2.WorkspaceaのCREATE APIを呼び出すPythonファイル

ソースをそのまま添付(ドヤ顔で生成AIの成果物を貼るスタンス)

 注意点は"RunningMode": "AUTO_STOP"の部分
 AUTO_STOP:起動時間指定モード → 時間課金制
 ALWAYS_ON:常時起動モード → 月額課金制
 一時的なテスト等で大量にWorkspacesを作成する場合は必ずAUTO_STOPで起動すること
 ※ALWAYS_ONで起動すると起動した瞬間に全台に対して月額固定金額が課金されるためお財布が即○する。。

import csv
import subprocess
import json # jsonモジュールを追加

# 設定値 (環境に合わせて変更してください)
# !!!ここを必ずご自身の環境に合わせて変更してください!!!
DIRECTORY_ID = 'd-xxxxxxxxxx'  # 例: 'd-9067253b2a'
BUNDLE_ID = 'wsb-xxxxxxxxxx'    # 例: 'wsb-bh8nkx13x' (Windows Standard)
USER_CSV_FILE = 'users.csv'

def create_workspaces_users():
    users_to_create_batch = []

    with open(USER_CSV_FILE, 'r', encoding='utf-8') as f:
        reader = csv.DictReader(f)
        
        for row in reader:
            username = row['Username']
            
            # WorkSpacesの設定を辞書形式で定義
            workspaces_config = {
                "DirectoryId": DIRECTORY_ID,
                "UserName": username,
                "BundleId": BUNDLE_ID,
                "RootVolumeEncryptionEnabled": False, # 必要であればTrueに設定
                "UserVolumeEncryptionEnabled": False, # 必要であればTrueに設定
                "WorkspaceProperties": {
                    "RunningMode": "AUTO_STOP",  # 常時稼働なら "ALWAYS_ON"
                    "RunningModeAutoStopTimeoutInMinutes": 60, # AUTO_STOPの場合のみ
                    "ComputeTypeName": "STANDARD", # バンドルによって自動設定される場合もありますが、明示的に指定可能
                    # "UserVolumeSizeGib": 50, # バンドルのデフォルト値を使用しない場合
                    # "RootVolumeSizeGib": 80  # バンドルのデフォルト値を使用しない場合
                }
            }
            users_to_create_batch.append(workspaces_config)
            
            # create-workspaces コマンドは最大25個のWorkSpacesを一度に作成できます。
            # バッチサイズに達したらコマンドを実行します。
            if len(users_to_create_batch) >= 25:
                print(f"{len(users_to_create_batch)} 個のWorkSpacesをバッチで作成します...")
                execute_create_workspaces_command(users_to_create_batch)
                users_to_create_batch = [] # 処理後クリア

        # 残りのユーザーを処理
        if users_to_create_batch:
            print(f"{len(users_to_create_batch)} 個のWorkSpacesをバッチで作成します...")
            execute_create_workspaces_command(users_to_create_batch)

def execute_create_workspaces_command(workspaces_list):
    # AWS CLI の --workspaces パラメータは JSON 形式の文字列を期待します。
    # Python のリストを JSON 文字列に変換します。
    workspaces_json_string = json.dumps(workspaces_list)
    
    command = [
        'aws', 'workspaces', 'create-workspaces',
        '--workspaces', workspaces_json_string
    ]
    
    try:
        # 実際に実行されるコマンドを出力 (デバッグ用)
        # print(f"Executing command: {' '.join(command)}")
        
        result = subprocess.run(command, capture_output=True, text=True, check=True)
        print(f"成功: {result.stdout}")
        
        # 成功したWorkSpacesと失敗したWorkSpacesの詳細を確認
        response_data = json.loads(result.stdout)
        if response_data.get('FailedRequests'):
            for failed in response_data['FailedRequests']:
                print(f"  -> WorkSpace の作成に失敗: ユーザー {failed['WorkspaceRequest']['UserName']}, エラー: {failed['ErrorCode']} - {failed['ErrorMessage']}")
        if response_data.get('PendingRequests'):
            for pending in response_data['PendingRequests']:
                print(f"  -> WorkSpace 作成リクエスト成功 (保留中): ユーザー {pending['UserName']}")

    except subprocess.CalledProcessError as e:
        print(f"エラー発生: {e.stderr}")
        print(f"コマンド: {' '.join(e.cmd)}")
    except json.JSONDecodeError as e:
        print(f"AWS CLI の出力解析エラー: {e}")
        print(f"CLI 出力:\n{result.stdout}")
    except Exception as e:
        print(f"予期せぬエラー: {e}")


if __name__ == '__main__':
    print("WorkSpacesユーザーの作成を開始します...")
    create_workspaces_users()
    print("WorkSpacesユーザーの作成処理が完了しました。")

実行方法

前提条件

PCに以下3点がインストールされていることが前提となります。
・Python
・aws CLI
(バージョンは割愛)

コマンドの実行

  1. 作成したPythonファイル実行する
    image.png

これだけ

結果

workspacesに大量の保留中workspaceが作成されているので利用可能になるまで〇〇して待機する。
(10分程)

image.png

以上

コンソールから作ったら1時間以上はかかりますがCLIなら1ポチ!
といいたいところですが、
Workspacesを使ったことがある方はここまで読んで、50台分のユーザは?と思ったかと思います、
そこは触れないでください。(教えてください)

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?