顯示具有 cli 標籤的文章。 顯示所有文章
顯示具有 cli 標籤的文章。 顯示所有文章

2025年2月17日 星期一

Docker 開發筆記 - 使用 aws cli 和 Docker Exec 進入 AWS ECS Container @ macOS

這個議題比我想像中麻煩了點,讓我回憶起 2009 年寫的 AWS 筆記,那時同事一開始還只在用 Firefox extension 管理 AWS EC2 呢 XD 我覺得這理論上要能都透過網頁搞定才對,先把目前研究的過程筆記一下。

總之,要能像 ssh 遠端(docker exec -it ContainerID bash)進去 AWS ECS container 的關鍵之處:
  • 使用 awscli 做事
  • AWS ECS 的 Task 定義,基礎設施需求 -> 任務角色,需要指定一下角色,例如 ecsTaskExecutionRole
  • AWS IAM -> ecsTaskExecutionRole -> 添加 AmazonSSMManagedInstanceCore 權限
  • AWS ECS -> Cluster -> Service ,需要用 awscli 啟動 enable-execute-command ,並且重新更新服務,使之生效
  • 使用 aws 指令登入
首先,先下載 awscli 並且版本要夠新:
安裝後檢查版本,版本太低會無法完成任務:

% aws --version
aws-cli/2.24.5 Python/3.12.6 Darwin/24.3.0 exe/x86_64

接著還要安裝 Session Manager plugin,此例紀錄 Mac with Apple silicon 版:
% curl "https://s3.amazonaws.com/session-manager-downloads/plugin/latest/mac_arm64/sessionmanager-bundle.zip" -o "sessionmanager-bundle.zip"
% unzip sessionmanager-bundle.zip
% sudo ./sessionmanager-bundle/install -i /usr/local/sessionmanagerplugin -b /usr/local/bin/session-manager-plugin

基本的環境已準備好了,下一刻是查看自己的 AWS ECS 的任務定義是否有把 任務角色 設定好,這部就維持用網頁吧:



若你的 AWS ECS 上定義的 Task 只有一個,也可以偷懶靠 awscli 操作(在此就不贅述 AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_DEFAULT_REGION 部分),會用到的指令:

aws ecs list-task-definition-families --status ACTIVE
aws ecs list-task-definitions --family-prefix webapp
aws ecs describe-task-definition --task-definition webapp:3

連續技,快速檢查 taskRoleArn 跟 executionRoleArn:

% NamespaceID=$(aws ecs list-task-definition-families --status ACTIVE | jq -r '.families[0]') ; echo "Namespace: $NamespaceID" ; TaskID=$(aws ecs list-task-definitions --family-prefix "$NamespaceID" | jq -r '.taskDefinitionArns[0]') ; echo "Task: $TaskID" ; aws ecs describe-task-definition --task-definition "$TaskID" | jq ".taskDefinition | { taskRoleArn: .taskRoleArn, executionRoleArn: .executionRoleArn}"
Namespace: myapp-task
Task: arn:aws:ecs:ap-northeast-1:####:task-definition/myapp-task:2
{
  "taskRoleArn": "arn:aws:iam::####:role/ecsTaskExecutionRole",
  "executionRoleArn": "arn:aws:iam::####:role/ecsTaskExecutionRole"
}

接下來,若 AWS ECS Cluster 還沒有建立任何 Service,用指令查:

% aws ecs list-tasks --cluster myapp-cluster  
{
    "taskArns": []
}

接著我們在 AWS ECS 網頁端起了一個 Service 名為 myapp-service ,在創建過程中沒看到啟用 enable-execute-command,這時在網頁上查看也是顯示 "ECS 執行: 關閉"



接下來用 aws cli 查詢:

% aws ecs list-tasks --cluster myapp-cluster   
{
    "taskArns": [
        "arn:aws:ecs:ap-northeast-1:####:task/myapp-cluster/#TASKID#"
    ]
}

% TaskID=$(aws ecs list-tasks --cluster myapp-cluster | jq -r '.taskArns[0]') ; echo "TaskID: $TaskID" ; aws ecs describe-tasks --cluster myapp-cluster --tasks $TaskID | jq '.tasks[0] | { "clusterArn": .clusterArn, "taskArn": .taskArn, "taskDefinitionArn": .taskDefinitionArn, "group": .group, "healthStatus": .healthStatus, "desiredStatus": .desiredStatus, "enableExecuteCommand": .enableExecuteCommand, "containers-name": [.containers |.[] | { "name":.name, "runtimeId": .runtimeId} ] }'
TaskID: arn:aws:ecs:ap-northeast-1:####:task/myapp-cluster/#TASKID#
{
  "clusterArn": "arn:aws:ecs:ap-northeast-1:####:cluster/myapp-cluster",
  "taskArn": "arn:aws:ecs:ap-northeast-1:####:task/myapp-cluster/#TASKID#",
  "taskDefinitionArn": "arn:aws:ecs:ap-northeast-1:####:task-definition/myapp-task:2",
  "group": "service:myapp-service",
  "healthStatus": "HEALTHY",
  "desiredStatus": "RUNNING",
  "enableExecuteCommand": false,
  "containers-name": [
    {
      "name": "php-fpm-docker",
      "runtimeId": "#TASKID#-#ContainerID#"
    },
    {
      "name": "web-docker",
      "runtimeId": "#TASKID#-#ContainerID#"
    }
  ]
}

可以看到 enableExecuteCommand 為 false

這時候,如果透過 aws cli 來設法登入到 Container:

% aws ecs execute-command --cluster myapp-cluster --task #TASKID# --container #containers#name# --command "/bin/bash" --interactive


The Session Manager plugin was installed successfully. Use the AWS CLI to start a session.


An error occurred (InvalidParameterException) when calling the ExecuteCommand operation: Unable to start session because the container doesn’t exist. Specify a valid container and try again.

接著,使用 aws cli 來啟動 enableExecuteCommand 吧:

% aws ecs update-service --cluster myapp-cluster --service arn:aws:ecs:ap-northeast-1:####:service/myapp-cluster/myapp-service --enable-execute-command 
{
    "service": {
        ... 
        "enableExecuteCommand": true,
        ...
    }
}

可以看到 enableExecuteCommand 被標記成 true 了,這時還需要重新發布服務,可以重網頁去觸發,或是靠指令觸發:

% aws ecs update-service --cluster myapp-cluster --service arn:aws:ecs:ap-northeast-1:####:service/myapp-cluster/myapp-service --force-new-deployment

當服務發布完畢後,在網頁上就可以看到改變,或是用指令在查一次:

% TaskID=$(aws ecs list-tasks --cluster myapp-cluster | jq -r '.taskArns[0]') ; echo "TaskID: $TaskID" ; aws ecs describe-tasks --cluster myapp-cluster --tasks $TaskID | jq '.tasks[0] | { "clusterArn": .clusterArn, "taskArn": .taskArn, "taskDefinitionArn": .taskDefinitionArn, "group": .group, "healthStatus": .healthStatus, "desiredStatus": .desiredStatus, "enableExecuteCommand": .enableExecuteCommand, "containers-name": [.containers |.[] | { "name":.name, "runtimeId": .runtimeId} ] }'
TaskID: arn:aws:ecs:ap-northeast-1:####:task/myapp-cluster/#TASKID#
{
  "clusterArn": "arn:aws:ecs:ap-northeast-1:####:cluster/myapp-cluster",
  "taskArn": "arn:aws:ecs:ap-northeast-1:####:task/myapp-cluster/#TASKID#",
  "taskDefinitionArn": "arn:aws:ecs:ap-northeast-1:####:task-definition/myapp-task:2",
  "group": "service:myapp-service",
  "healthStatus": "HEALTHY",
  "desiredStatus": "RUNNING",
  "enableExecuteCommand": true,
  "containers-name": [
    {
      "name": "php-fpm-docker",
      "runtimeId": "#TASKID#-#CONTAINERID#"
    },
    {
      "name": "web-docker",
      "runtimeId": "#TASKID#-#CONTAINERID#"
    }
  ]
}

如此,就可以正式遠端進去一下:

% aws ecs execute-command --cluster myapp-cluster --task #TASKID# --container web-docker --command "/bin/bash" --interactive

The Session Manager plugin was installed successfully. Use the AWS CLI to start a session.


Starting session with SessionId: ecs-execute-command-################
ip-123-45-6-123:/var/www/html# 

收工

參考資料:

2016年8月2日 星期二

Microsoft Azure 管理筆記 - 使用 Azure CLI 自訂映像檔的維護方式

大部分的潮流都是走 PaaS 架構,然而,有些歷史的包袱只能走 IaaS 的架構 XD 而建立 Image 更是最基本的方式,甚至搭配 rsync 完成發布。而對於 Resource manage 機器來說,每次透過 capture 建立 Image 後,等於報廢回收,所以寫了個簡單的步驟記憶一下:
  1. 登入機器清除基本設定檔: $ sudo waagent -deprovision+user
  2. 透過 azure cli 執行 Shutdown:$ azure vm deallocate -g MyResource -n MyCurrentServer --subscription MySubscription
  3. 透過 azure cli 執行 Generalized:$ azure vm generalize MyResource MyCurrentServer --subscription MySubscription
  4. 透過 azure cli 執行 Capture:$ azure vm capture MyResource MyCurrentServer MyImageName -t MyImageName-Date.json --subscription MySubscription
做完後,原機器就可以下去領便當,可以把它 Delete 囉。

若預設產生的 MyImageName-Date.json 不夠用時,會自行添加資料,因此維護上就會出現麻煩,每次產生新的 template 中,其實只有 storageProfile 的設定,可以用 jq 跟 vimdiff 方便更新一下:

$ jq '' < MyImageName-old.json > old-formated.json
$ jq '' < MyImageName-Date.json > date-formated.json
$ vimdiff old-formated.json date-formated.json


把 old-formated.json 裡的 storageProfile 更新完成即可。

$ mv old-formated.json MyImageName-Date-formated.json

未來要建置原先那台機器時,就可以用以下指令在重建出來:

$ azure group deployment create MyResource -f MyImageName-Date-formated.json --subscription MySubscription

其他提醒:
  1. template.json 有描述 VHD 的資訊,若用上述 azure group deployment create 時,會彈跳出已存在的錯誤訊息,這時除了更新 template.json 資訊外,也可以到 Azure Portal -> Browse -> Storage account -> Blobs -> 沿路去找資料,把舊的、沒在用的砍掉再重跑
  2. 每次建立映像檔時,在 Azure Portal -> Browse -> Storage account -> Blobs -> system -> Microsoft.Compute -> Images -> vhds  會有 Image.vhd 跟 template.json 檔案,想清掉舊的可以去刪掉
  3. 製作完 Image 後的 server ,可以直接把它刪掉,但他的 NIC應當還會在,下次建立時,就可以沿用舊的網卡,通常 private ip 可以沿用,若有 public ip 的,若是 dynamic 配置則會變動
  4. 想使用同一個 template 開機器時,若多道指令一直跑時,指使用同一個 template file 時,會出現 Unable to edit or replace deployment 'filename-template.json' 
    : previous deployment from 'DATETIME' is still active. Please see https://aka.ms/arm-deploy for usage details. 偷懶的解法就是複製出來用 Orz 不知是不是 azure 採用 local file lock 等機制
  5. 若要採用 Availability Set 時,必須一開機就設定了,解法製作兩份 template.json ,一份用來維護 Image ,另一份就是開機就擺進 Availability Set,只需在 resources 中,多添加 : { "availabilitySet": { "id" : "/subscriptions/MySubscription/resourceGroups/MyResource/providers/Microsoft.Compute/availabilitySets/MyAvailabilitySet" } }, 來處理即可

Microsoft Azure 管理筆記 - 使用 Azure CLI 建立自訂的映像檔與開新機器的方式 (create a custom image/launch a server)

由於 Azure Portal 對 Resource manager 機器尚為提供 Web UI 可以方便點擊處理,就還是下海摸一下 command line 啦。

參考文件:

對 server 建立 image 過程中,server 狀態改變後會無法重啟,得用建立好的 Resource template 重新建立,需分外留意!機器就這樣下去領便當了 囧 (Azure/azure-powershell: UN-generalize a VM)

首先,遠端登入機器,執行此道指令

$ sudo waagent -deprovision+user

此命令會嘗試清除系統,使之適合重新佈建。這項作業會執行下列工作:

移除 SSH 主機金鑰 (如果組態檔中的 Provisioning.RegenerateSshHostKeyPair 是 'y')
清除 /etc/resolv.conf 中的名稱伺服器設定
移除 /etc/shadow 中的 root 使用者密碼 (如果組態檔中的 Provisioning.DeleteRootPassword 是 'y')
移除快取的 DHCP 用戶端租用
將主機名稱重設為 localhost.localdomain
刪除最後佈建的使用者帳戶 (取自於 /var/lib/waagent) 和相關聯的資料。


接著,再回到自己的常用的機器,改用 azure cli 對該機器設置以下流程:

$ azure config mode arm
info:    Executing command config mode
info:    New mode is arm
info:    config mode command OK


// Shutdown a virtual machine in a resource group and release the compute resources
$ azure vm deallocate -g MyResource -n MyCurrentVM --subscription MySubscription
info:    Executing command vm deallocate
+ Looking up the VM "MyCurrentVM"                            
+ Deallocating the virtual machine "MyCurrentVM"            
info:    vm deallocate command OK


// Set the state of a VM in a resource group to Generalized.
$ azure vm generalize MyResource MyCurrentVM --subscription MySubscription
info:    Executing command vm generalize
+ Looking up the VM "MyCurrentVM"                            
+ Generalizing the virtual machine "MyCurrentVM"            
info:    vm generalize command OK


$ azure vm capture MyResource MyCurrentVM MyImageID -t MyImageID-base.json --subscription MySubscription
info:    Executing command vm capture
+ Looking up the VM "MyCurrentVM"                            
+ Capturing the virtual machine "MyCurrentVM"                
info:    Saved template to file "MyImageID-base.json"
info:    vm capture command OK


接著,可以建立新開機器!只是開機器前又得好好管理"Resouce"建立,由於我已經有常用的 Resource 跟 Location 了,在此只需建立 IP 跟 NIC 即可!

$ azure network public-ip create MyResource MyImageID-ip-1 -l westus --subscription MySubscription
info:    Executing command network public-ip create
warn:    Using default --idle-timeout 4
warn:    Using default --allocation-method Dynamic
warn:    Using default --ip-version IPv4
+ Looking up the public ip "MyImageID-ip-1"                              
+ Creating public ip address "MyImageID-ip-1"                            
data:    Id                              : /subscriptions/MySubscription/resourceGroups/MyResource/providers/Microsoft.Network/publicIPAddresses/MyImageID-ip-1
data:    Name                            : MyImageID-ip-1
data:    Type                            : Microsoft.Network/publicIPAddresses
data:    Location                        : westus
data:    Provisioning state              : Succeeded
data:    Allocation method               : Dynamic
data:    IP version                      : IPv4
data:    Idle timeout in minutes         : 4
info:    network public-ip create command OK


$ azure network nic create MyResource MyImageID-nic-1 -k default -m MyResource -p MyImageID-ip-1 -l westus --subscription MySubscription
info:    Executing command network nic create
+ Looking up the network interface "MyImageID-nic-1"                    
+ Looking up the subnet "default"                                            
+ Looking up the public ip "MyImageID-ip-1"                              
+ Creating network interface "MyImageID-nic-1"                          
data:    Id                              : /subscriptions/MySubscription/resourceGroups/MyResource/providers/Microsoft.Network/networkInterfaces/MyImageID-nic-1
data:    Name                            : MyImageID-nic-1
data:    Type                            : Microsoft.Network/networkInterfaces
data:    Location                        : westus
data:    Provisioning state              : Succeeded
data:    Internal domain name suffix     : #############.dx.internal.cloudapp.net
data:    Enable IP forwarding            : false
data:    IP configurations:
data:      Name                          : default-ip-config
data:      Provisioning state            : Succeeded
data:      Private IP address            : 10.0.0.6
data:      Private IP version            : IPv4
data:      Private IP allocation method  : Dynamic
data:      Public IP address             : /subscriptions/MySubscription/resourceGroups/MyResource/providers/Microsoft.Network/publicIPAddresses/MyImageID-ip-1
data:      Subnet                        : /subscriptions/MySubscription/resourceGroups/MyResource/providers/Microsoft.Network/virtualNetworks/MyResource/subnets/default
data:  
info:    network nic create command OK


建立機器吧!

$ azure --version
0.10.2 (node: 4.2.4)


$ azure group deployment create MyResource -f MyImageID-base.json --subscription MySubscription
$ azure group deployment create MyResource -f MyImageID-base.json --subscription MySubscription -p '{"vmName":{"value":"MyVM"},"adminUserName":{"value":"ubuntu"},"adminPassword":{"value":"MyPassword"},"networkInterfaceId":{"value":"/subscriptions/MySubscription/resourceGroups/MyResource/providers/Microsoft.Network/networkInterfaces/MyImageID-nic-base"}}'


然而,因為預設產出的 template 定義了以下資訊,以至於開機器必須填寫以下資訊:

$ cat template.json | jq '.parameters'
{
  "vmName": {
    "type": "string"
  },
  "vmSize": {
    "type": "string",
    "defaultValue": "Standard_A1"
  },
  "adminUserName": {
    "type": "string"
  },
  "adminPassword": {
    "type": "securestring"
  },
  "networkInterfaceId": {
    "type": "string"
  }
}


用在這邊:

$ cat template.json | jq '.resources[0].properties.osProfile'
{
  "computerName": "[parameters('vmName')]",
  "adminUsername": "[parameters('adminUsername')]",
  "adminPassword": "[parameters('adminPassword')]"
}


接著,稍微修改來支援 ssh keypair 登入方式,將 template.json 中的 parameters 多增加個 adminPublicKey/adminPublicKeyPath:

$ cat template.json | jq '.parameters'
{
  "vmName": {
    "type": "string"
  },
  "vmSize": {
    "type": "string",
    "defaultValue": "Standard_A1"
  },
  "adminUserName": {
    "type": "string"
  },
  "adminPassword": {
    "type": "securestring",
    "defaultValue": null
  },
  "networkInterfaceId": {
    "type": "string"
  },
  "adminPublicKey": {
    "type": "array"
  },
  "adminPublicKeyPath": {
    "type": "string"
  }
}


並修改 properties.osProfile 區:

$ cat template.json | jq '.resources[0].properties.osProfile'
{
  "computerName": "[parameters('vmName')]",
  "adminUsername": "[parameters('adminUsername')]",
  "adminPassword": "[parameters('adminPassword')]",
  "linuxConfiguration": {
    "disablePasswordAuthentication": true,
    "ssh": {
      "publicKeys": [
         {
           "path": "[parameters('adminPublicKeyPath')]",
           "keyData": "[parameters('adminPublicKey')]"
         }
      ]
    }
  }
}


如此一來,就開機能用 keypair 登入機器:

$ azure group deployment create MyResource -f MyImageID-base.json --subscription MySubscription -p '{"adminPassword":{"value":""},"vmName":{"value":"MyVM"},"adminUserName":{"value":"ubuntu"},"adminPublicKey":{"value":"ssh-rsa ########"},"adminPublicKeyPath":{"value":"/home/ubuntu/.ssh/authorized_keys"},"networkInterfaceId":{"value":"/subscriptions/MySubscription/resourceGroups/MyResource/providers/Microsoft.Network/networkInterfaces/MyImageID-nic-base"}}'

2014年6月25日 星期三

AWS 筆記 - 透過 AWS CLI 取得指定 ELB 下的所有機器的 Public IP @ Ubuntu 14.04

基於 deploying 需求,希望能夠得知指定 ELB 下的機器列表,再搭配 ssh keyfile 進行動作,以此降低人工部分,所以就需要用用 aws cli 啦,不然完全從 web ui 大多都能滿足一些操作手法。

關鍵兩個 aws cli 用法:
  • $ aws elb describe-load-balancers --load-balancer-name YourELBName
  • $ aws ec2 describe-instances --instance-ids YourEC2InstanceID
相關 AIM 權限:
  • elasticloadbalancing:DescribeLoadBalancers
  • ec2:DescribeInstances
使用 PHP 連續動作:

<?php
define("AWS_ELB_NAME", "YourELBName");

$elb_servers_public_ip = array();
$elb_info = @json_decode(@shell_exec("aws elb describe-load-balancers --load-balancer-name ".AWS_ELB_NAME), true);
if(isset($elb_info['LoadBalancerDescriptions'][0]['Instances']))
{
foreach( $elb_info['LoadBalancerDescriptions'][0]['Instances'] as $ec2_instance )
{
foreach( $ec2_instance as $ec2_id )
{
$ec2_info = @json_decode(@shell_exec("aws ec2 describe-instances --instance-ids $ec2_id 2>/dev/null"), true);
if(isset($ec2_info['Reservations'][0]['Instances'][0]['PublicIpAddress']))
array_push($elb_servers_public_ip, $ec2_info['Reservations'][0]['Instances'][0]['PublicIpAddress']);
}
}
}
print_r($elb_servers_public_ip);


其他心得:

雖然 aws ec2 describe-instances 可以一次查詢多筆,但是不知為何 aws elb describe-load-balancers 回傳的 instances 卻也有可能出現不存在的機器,這時透過 aws ec2 describe-instances 查詢多筆資料時,就會回傳機器不存在的訊息,得不到想要的資料,只好改成迴圈一筆一筆地問。