{Alibaba ECS} vm起動停止自動化

 

https://www.softbank.jp/biz/blog/cloud-technology/articles/201912/ac-functioncompute/

https://qiita.com/feel_good/items/7fa5f14564be7ab63b40

https://www.alibabacloud.com/help/en/cloud-config/latest/configure-manual-remediation


-- 1. TerraformでECSインスタンスを2個作成

cat <<-'EOF' > variables.tf

locals {
  availability_zone = "ap-northeast-1a"
}

 

EOF

 

cat <<-'EOF' > main.tf

terraform {
  required_version = ">= 1.0.0, < 2.0.0"
  required_providers {
    alicloud = {
      source  = "aliyun/alicloud"
      version = "= 1.217.0"
    }
  }
}

provider "alicloud" {
  region  = "ap-northeast-1"
}


resource "alicloud_vpc" "vpc01" {
  vpc_name          = "vpc01"
  description       = "vpc01"
  cidr_block        = "10.2.0.0/16"
}

 

resource "alicloud_vswitch" "sw01" {
  vswitch_name      = "sw01"
  description       = "sw01"
  vpc_id            = alicloud_vpc.vpc01.id
  cidr_block        = "10.2.1.0/24"
  zone_id           = local.availability_zone
}

resource "alicloud_security_group" "sg01" {
  name                = "sg01"
  description         = "sg01"
  vpc_id              = alicloud_vpc.vpc01.id
  security_group_type = "normal"
}


resource "alicloud_security_group_rule" "sg0101" {
  type              = "ingress"
  ip_protocol       = "tcp"
  port_range        = "22/22"
  security_group_id = alicloud_security_group.sg01.id
  nic_type          = "intranet"
  policy            = "accept"
  priority          = 10
  cidr_ip           = "0.0.0.0/0"
  description       = "sg0101"
}


resource "alicloud_vpc_ipv4_gateway" "gw01" {
  ipv4_gateway_name        = "gw01"
  ipv4_gateway_description = "gw01"
  vpc_id                   = alicloud_vpc.vpc01.id
  enabled                  = true
}

 

 

# ルートテーブルへvSwitchの関連付け
resource "alicloud_route_table_attachment" "sw01_rt01" {
  vswitch_id     = alicloud_vswitch.sw01.id
  route_table_id = alicloud_vpc.vpc01.route_table_id
}


# ルートテーブルへカスタムルート追加
resource "alicloud_route_entry" "rt0101" {
  name                  = "rt0101"
  route_table_id        = alicloud_vpc.vpc01.route_table_id
  destination_cidrblock = "0.0.0.0/0"
  nexthop_type          = "Ipv4Gateway"
  nexthop_id            = alicloud_vpc_ipv4_gateway.gw01.id
}


resource "alicloud_instance" "ecs01" {

  image_id                   = "aliyun_2_1903_x64_20G_alibase_20231221.vhd"
  instance_type              = "ecs.t5-lc2m1.nano"
  security_groups            = [alicloud_security_group.sg01.id]
  instance_name              = "ecs01"
  system_disk_category       = "cloud_ssd"
  system_disk_name           = "ecs01"
  system_disk_size           = 20
  description                = "ecs01"
  internet_charge_type       = "PayByBandwidth"
  internet_max_bandwidth_out = 0
  host_name                  = "ecs01"
  vswitch_id                 = alicloud_vswitch.sw01.id
  instance_charge_type       = "PostPaid"
  key_name                   = "alibabakey01"
  deletion_protection        = false
  credit_specification       = "Standard"
  tags ={
    Key    = "hoge"
    Value  = "123"
  }

}


resource "alicloud_eip_address" "eip01" {
  address_name              = "eip01"
  bandwidth                 = 1
  deletion_protection       = false
  description               = "eip01"
  internet_charge_type      = "PayByTraffic"
  isp                       = "BGP"
  payment_type              = "PayAsYouGo"
  netmode                   = "public"
}

# インスタンスとEIPの関連付け
resource "alicloud_eip_association" "ecs01_eip01" {
  instance_id              = alicloud_instance.ecs01.id
  allocation_id            = alicloud_eip_address.eip01.id
}

resource "alicloud_instance" "ecs02" {

  image_id                   = "aliyun_2_1903_x64_20G_alibase_20231221.vhd"
  instance_type              = "ecs.t5-lc2m1.nano"
  security_groups            = [alicloud_security_group.sg01.id]
  instance_name              = "ecs02"
  system_disk_category       = "cloud_ssd"
  system_disk_name           = "ecs02"
  system_disk_size           = 20
  description                = "ecs02"
  internet_charge_type       = "PayByBandwidth"
  internet_max_bandwidth_out = 0
  host_name                  = "ecs02"
  vswitch_id                 = alicloud_vswitch.sw01.id
  instance_charge_type       = "PostPaid"
  key_name                   = "alibabakey01"
  deletion_protection        = false
  credit_specification       = "Standard"
  tags = {
    Key    = "fuga"
    Value  = "123"
  }

}


resource "alicloud_eip_address" "eip02" {
  address_name              = "eip02"
  bandwidth                 = 1
  deletion_protection       = false
  description               = "eip02"
  internet_charge_type      = "PayByTraffic"
  isp                       = "BGP"
  payment_type              = "PayAsYouGo"
  netmode                   = "public"
}

# インスタンスとEIPの関連付け
resource "alicloud_eip_association" "ecs02_eip02" {
  instance_id              = alicloud_instance.ecs02.id
  allocation_id            = alicloud_eip_address.eip02.id
}

EOF

 

cat <<-'EOF' > outputs.tf


output "vpc01_id" {
  value = alicloud_vpc.vpc01.id
  description = "vpc01.id"
}


output "sw01_id" {
  value = alicloud_vswitch.sw01.id
  description = "sw01.id"
}

output "sg01_id" {
  value = alicloud_security_group.sg01.id
  description = "sg01.id"
}

 


EOF

 


terraform init
terraform fmt
terraform -version

 

terraform plan

terraform apply -auto-approve

 

 

 

 

 

-- 2. サービスの作成

aliyun fc-open GET /2021-04-06/services 


aliyun fc-open POST /2021-04-06/services \
--body "{\"serviceName\":\"service01\",\"description\":\"service01\"}"

 

-- 3. Create a bucket for code package upload

aliyun oss ls -s

aliyun oss mb oss://bucket123 \
--storage-class Standard \
--redundancy-type LRS \
--acl private 

 


cat <<-'EOF' > ecs_start.py
#!/usr/bin/env python
# -*- coding: utf8 -*-

from aliyunsdkcore.client import AcsClient
from aliyunsdkcore.acs_exception.exceptions import ClientException
from aliyunsdkcore.acs_exception.exceptions import ServerException
from aliyunsdkecs.request.v20140526.DescribeInstancesRequest import DescribeInstancesRequest
from aliyunsdkecs.request.v20140526.StartInstanceRequest import StartInstanceRequest
import json

# ACK情報、リージョン情報
ACCESSKEY_ID = "111111111111111111111111"
ACCESSKE_SECRET = "111111111111111111111111111111"
REGION_ID = "ap-northeast-1"
client = AcsClient(ACCESSKEY_ID, ACCESSKE_SECRET, REGION_ID)

# ハンドラー作成
def handler(event, context):
    describe_request = DescribeInstancesRequest()
    describe_request.set_InstanceIds(["i-11111111111111111111","i-11111111111111111111"])
    execute_describe = client.do_action_with_exception(describe_request)
    data = json.loads(execute_describe)
    items = data['Instances']


    for instance in items['Instance']: 
        instanceid = instance['InstanceId']
        start_instance = StartInstanceRequest()
        start_instance.set_InstanceId(instanceid)
        start_instance_response = client.do_action_with_exception(start_instance)
        print(start_instance_response)
EOF


cat ecs_start.py 

 

 

cat <<-'EOF' > ecs_stop.py
#!/usr/bin/env python
# -*- coding: utf8 -*-

from aliyunsdkcore.client import AcsClient
from aliyunsdkcore.acs_exception.exceptions import ClientException
from aliyunsdkcore.acs_exception.exceptions import ServerException
from aliyunsdkecs.request.v20140526.DescribeInstancesRequest import DescribeInstancesRequest
from aliyunsdkecs.request.v20140526.StopInstanceRequest import StopInstanceRequest
import json

# ACK情報、リージョン情報
ACCESSKEY_ID = "111111111111111111111111"
ACCESSKE_SECRET = "111111111111111111111111111111"
REGION_ID = "ap-northeast-1"
client = AcsClient(ACCESSKEY_ID, ACCESSKE_SECRET, REGION_ID)

# ハンドラー作成
def handler(event, context):
    describe_request = DescribeInstancesRequest()
    describe_request.set_InstanceIds(["i-11111111111111111111","i-11111111111111111111"])
    execute_describe = client.do_action_with_exception(describe_request)
    data = json.loads(execute_describe)
    items = data['Instances']

    for instance in items['Instance']: 
        instanceid = instance['InstanceId']
        stop_instance = StopInstanceRequest()
        stop_instance.set_InstanceId(instanceid)
        stop_instance.set_StoppedMode("StopCharging")
        stop_instance_response = client.do_action_with_exception(stop_instance)
        print(stop_instance_response)

EOF


cat ecs_stop.py 


mkdir package
pip install aliyun-python-sdk-core --target ./package
pip install aliyun-python-sdk-ecs --target ./package

rm -rf package/cryptography*


cd package
zip -r ../ecs_start.zip .
cd ..
zip -g ecs_start.zip ecs_start.py

cd package
zip -r ../ecs_stop.zip .
cd ..
zip -g ecs_stop.zip ecs_stop.py

 


aliyun oss cp ecs_start.zip oss://bucket123
aliyun oss cp ecs_stop.zip oss://bucket123

aliyun oss ls oss://bucket123 -s

 


-- 4. 関数の作成

aliyun fc-open GET /2021-04-06/services/service01/functions

aliyun fc-open POST /2021-04-06/services/service01/functions \
--body "{\"functionName\": \"ecs_start\",\"runtime\": \"python3\",\"handler\": \"ecs_start.handler\",\"code\": {\"ossBucketName\": \"bucket123\",\"ossObjectName\": \"ecs_start.zip\"}}"

aliyun fc-open POST /2021-04-06/services/service01/functions \
--body "{\"functionName\": \"ecs_stop\",\"runtime\": \"python3\",\"handler\": \"ecs_stop.handler\",\"code\": {\"ossBucketName\": \"bucket123\",\"ossObjectName\": \"ecs_stop.zip\"}}"

 

 

-- 5. 関数の手動実行

aliyun fc-open POST /2021-04-06/services/service01/functions/ecs_start/invocations

aliyun fc-open POST /2021-04-06/services/service01/functions/ecs_stop/invocations

 

 

-- 6. タイムトリガーの作成

★ Cron式に秒もある


aliyun fc-open POST /2021-04-06/services/service01/functions/ecs_start/triggers --body "{\"triggerConfig\": \"{\\\"cronExpression\\\":\\\"0 8 6 * * * \\\"}\", \"triggerName\": \"trigger_ecs_start\", \"triggerType\": \"timer\" }"

aliyun fc-open POST /2021-04-06/services/service01/functions/ecs_stop/triggers --body "{\"triggerConfig\": \"{\\\"cronExpression\\\":\\\"0 5 6 * * * \\\"}\", \"triggerName\": \"trigger_ecs_stop\", \"triggerType\": \"timer\" }"

 

aliyun fc-open GET /2021-04-06/services/service01/functions/ecs_start/triggers

aliyun fc-open GET /2021-04-06/services/service01/functions/ecs_stop/triggers

 

 

 

-- 7. クリーンアップ

aliyun fc-open DELETE /2021-04-06/services/service01/functions/ecs_start/triggers/trigger_ecs_start
aliyun fc-open DELETE /2021-04-06/services/service01/functions/ecs_stop/triggers/trigger_ecs_stop


aliyun fc-open GET /2021-04-06/services/service01/functions

aliyun fc-open DELETE /2021-04-06/services/service01/functions/ecs_start
aliyun fc-open DELETE /2021-04-06/services/service01/functions/ecs_stop


バケットの削除
※最初にバケットを空にする必要がある

aliyun oss rm oss://bucket123 --recursive --force 
aliyun oss ls oss://bucket123 -s

aliyun oss rm oss://bucket123 --bucket --force
aliyun oss ls -s


aliyun fc-open GET /2021-04-06/services 

aliyun fc-open DELETE /2021-04-06/services/service01 

 


terraform destroy -auto-approve