日本熟妇hd丰满老熟妇,中文字幕一区二区三区在线不卡 ,亚洲成片在线观看,免费女同在线一区二区

使用ROS CDK部署云端2048小游戲

本文主要介紹如何基于ROS CDK新建一臺ECS,在其上部署一個2048小游戲,并在本地瀏覽器游玩。本教程支持多種編程語言,包括TypeScript、JavaScript、Java、Python、C#和Go。

費用說明

ROS CDK本身不收費,但本方案需要部署ECS實例,會產生相關的資源費用。具體費用信息,請參見按量付費。

準備工作

請確保您已經完成以下操作:

  • 安裝和配置阿里云CLI、安裝ROS CDK。具體操作,請參見安裝ROS CDK。請確保您安裝的ros-cdk-cli 版本在 1.2.0 以上,可以通過運行 npm list -g 確認。

  • 獲取AccessKey信息,用于后續授權。如果沒有,請參見創建AccessKey。

    重要

    為保證賬號安全,建議您創建專用于API訪問的RAM用戶并創建對應的AccessKey。具體操作,請參見創建RAM用戶,為RAM用戶授權。

  • 開發語言環境要求 。

    • TypeScript:Node.js 8.0或更高版本。

    • JavaScript:JSON解析工具包(工具包名稱為jq)。

    • Java:JDK 1.8或以上版本、Maven 2.5或以上版本。

    • Python:Python 3.4以上版本。

    • C#:.NET Core 2.0以上版本、Visual Studio 2010 及以上版本。

    • Go:1.16或以上版本。

步驟一:初始化工程

在命令行窗口依次輸入以下命令,在當前目錄創建初始化工程。

TypeScript

mkdir demo
cd demo
ros-cdk init --language=typescript --generate-only=true

JavaScript

mkdir demo
cd demo
ros-cdk init --language=javascript --generate-only=true

Java

mkdir demo
cd demo
ros-cdk init --language=java --generate-only=true

Python

mkdir demo
cd demo
ros-cdk init --language=python --generate-only=true

執行以下命令,創建一個屬于當前工程的虛擬環境。

Python工程的運行依賴于虛擬環境(virtualenv),所以在初始化Python工程之后需要創建一個屬于當前工程的虛擬環境。

python3 -m venv .venv

執行以下命令,進入虛擬環境。

source .venv/bin/activate

C#

mkdir demo
cd demo
ros-cdk init --language=csharp --generate-only=true

Go

mkdir demo
cd demo
ros-cdk init --language=go --generate-only=true

步驟二:配置阿里云憑證信息

  1. 在命令行窗口執行以下命令,配置阿里云憑證信息。

    ros-cdk config
  2. 根據界面提示依次輸入配置信息。

    endpoint(optional, default:https://ros.aliyuncs.com):
    defaultRegionId(optional, default:cn-hangzhou):cn-beijing
    
    [1] AK
    [2] StsToken
    [3] RamRoleArn
    [4] EcsRamRole
    [0] CANCEL
    
    Authenticate mode [1...4 / 0]: 1
    accessKeyId:************************
    accessKeySecret:******************************
    
      Your cdk configuration has been saved successfully!

    配置內容說明如下:

    參數

    說明

    defaultRegionId

    ROS資源棧部署的地域。默認值為cn-hangzhou。您可以調用DescribeRegionsAPI,獲取RegionId參數選擇地域。

    image

    endpoint

    ROS服務地址。默認值為https://ros.aliyuncs.com。您可以調用DescribeRegionsAPI,獲取地域對應的公網接入地址或VPC接入地址,選擇ROS服務地址,并添加 https://

    image

    Authenticate mode

    鑒權方式。本示例的鑒權方式為[1] AK,您需要輸入準備工作中獲取的AccessKey IDAccessKey Secret。更多鑒權方式,請參見配置憑證

步驟三:安裝依賴

在工程中修改配置文件,并安裝依賴。

TypeScript

  1. package.json文件內容,全部更改為下面代碼。

    {
      "name": "demo",
      "version": "0.1.0",
      "bin": {
        "demo": "bin/demo.js"
      },
      "scripts": {
        "build": "tsc",
        "test": "jest"
      },
      "devDependencies": {
        "@types/jest": "^25.2.1",
        "@types/node": "10.17.5",
        "typescript": "^3.9.7",
        "jest": "^25.5.0",
        "ts-jest": "^25.3.1",
        "ts-node": "^8.1.0",
        "babel-jest": "^26.6.3",
        "@babel/core": "^7.12.9",
        "@babel/preset-env": "7.12.7",
        "@babel/preset-typescript": "^7.12.7",
        "@alicloud/ros-cdk-assert": "^1.4.0"
      },
      "dependencies": {
        "@alicloud/ros-cdk-core": "^1.4.0",
        "@alicloud/ros-cdk-ecs": "^1.4.0"
      }
    }
  2. 在命令行窗口執行以下命令,安裝依賴。

    npm install

JavaScript

  1. package.json文件內容,全部更改為下面代碼。

    {
      "name": "demo",
      "version": "0.1.0",
      "bin": {
        "demo": "bin/demo.js"
      },
      "scripts": {
        "build": "echo \"The build step is not required when using JavaScript!\" && exit 0",
        "cdk": "cdk",
        "test": "jest"
      },
      "devDependencies": {
        "@types/jest": "^25.2.1",
        "@types/node": "10.17.5",
        "typescript": "^3.9.7",
        "jest": "^25.5.0",
        "ts-jest": "^25.3.1",
        "ts-node": "^8.1.0",
        "babel-jest": "^26.6.3",
        "@babel/core": "^7.12.9",
        "@babel/preset-env": "7.12.7",
        "@babel/preset-typescript": "^7.12.7",
        "@alicloud/ros-cdk-assert": "^1.1.0"
      },
      "dependencies": {
        "@alicloud/ros-cdk-core": "^1.1.0",
        "@alicloud/ros-cdk-ecs": "^1.1.0",
        "@alicloud/ros-cdk-assert": "^1.1.0"
      }
    }
  2. 在命令行窗口執行以下命令,安裝依賴。

    npm install

Java

  1. pom.xml文件內容,全部更改為下面代碼。

    <?xml version="1.0" encoding="UTF-8"?>
    <project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
             xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
        <modelVersion>4.0.0</modelVersion>
    
        <groupId>com.myorg</groupId>
        <artifactId>demo</artifactId>
        <version>0.1</version>
    
        <properties>
            <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
            <cdk.version>1.1.0</cdk.version>
        </properties>
    
        <build>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>3.8.1</version>
                    <configuration>
                        <source>1.8</source>
                        <target>1.8</target>
                    </configuration>
                </plugin>
    
                <plugin>
                    <groupId>org.codehaus.mojo</groupId>
                    <artifactId>exec-maven-plugin</artifactId>
                    <version>1.6.0</version>
                    <configuration>
                        <mainClass>com.myorg.DemoApp</mainClass>
                    </configuration>
                </plugin>
            </plugins>
        </build>
    
        <dependencies>
            <!-- AliCloud ROS Cloud Development Kit (ROS CDK) -->
            <dependency>
                <groupId>com.aliyun</groupId>
                <artifactId>ros-cdk-core</artifactId>
                <version>1.1.0</version>
            </dependency>
            <dependency>
                <groupId>com.aliyun</groupId>
                <artifactId>ros-cdk-ecs</artifactId>
                <version>1.1.0</version>
            </dependency>
    
            <!-- https://mvnrepository.com/artifact/junit/junit -->
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>4.12</version>
                <scope>test</scope>
            </dependency>
        </dependencies>
    </project>
    
  2. 執行以下命令,安裝依賴:

    mvn compile

Python

  1. requirements.txt文件內容,全部更改為下面代碼。

    ros-cdk-core==1.1.0
    ros-cdk-ecs==1.1.0
  2. 在命令行窗口執行以下命令,安裝依賴。

    pip install -r requirements.txt

C#

src/Demo/Demo.csproj文件內容,全部更改為下面代碼(請根據您本地dotnet核心包版本修改)。

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp3.1</TargetFramework>
    <!-- Roll forward to future major versions of the netcoreapp as needed -->
    <RollForward>Major</RollForward>
  </PropertyGroup>

  <ItemGroup>
    <!-- CDK Construct Library dependencies -->
    <PackageReference Include="AlibabaCloud.SDK.ROS.CDK.Core" Version="1.1.0" />
    <PackageReference Include="AlibabaCloud.SDK.ROS.CDK.Ecs" Version="1.1.0" />

    <!-- jsii Roslyn analyzers (un-comment to obtain compile-time checks for missing required props
    <PackageReference Include="Amazon.Jsii.Analyzers" Version="*" PrivateAssets="all" />
    -->

  </ItemGroup>

</Project>

Go

  1. go.mod文件內容,全部修改為下面代碼(請根據您的Go語言版本修改)。

    module demo
    
    go 1.18
    
    require (
        github.com/alibabacloud-go/ros-cdk/alicloudroscdkcore v1.2.0
        github.com/alibabacloud-go/ros-cdk/alicloudroscdkecs v1.2.0
        github.com/stretchr/testify v1.8.4
    )
    
  2. 在命令行窗口執行以下命令,安裝依賴。

    go get

步驟四:添加資源

為項目添加資源,本示例涉及到的資源有:

TypeScript

lib/demo-stack.ts文件內容,全部改為下面代碼。

import * as ros from '@alicloud/ros-cdk-core';
import * as ecs from '@alicloud/ros-cdk-ecs';

export class DemoStack extends ros.Stack {
  constructor(scope: ros.Construct, id: string, props?: ros.StackProps) {
    super(scope, id, props);
    new ros.RosInfo(this, ros.RosInfo.description, "Deploy 2048 game through ROS CDK.");

    const zoneId = new ros.RosParameter(this, 'ZoneId', {
      type: ros.RosParameterType.STRING
    });

    const vpc = new ecs.Vpc(this, 'Vpc', {
      cidrBlock: '192.168.0.0/16'
    });

    const sg = new ecs.SecurityGroup(this, 'SecurityGroup', {
      vpcId: vpc.ref
    });

    const vsw = new ecs.VSwitch(this, 'VSwitch', {
      cidrBlock: '192.168.0.0/24',
      zoneId: zoneId,
      vpcId: vpc.ref
    })

    const instance = new ecs.Instance(this, 'Instance', {
      vpcId: vpc.ref,
      vSwitchId: vsw.ref,
      securityGroupId: sg.ref,
      zoneId: zoneId,
      instanceType: 'ecs.c6e.large',
      imageId: 'centos_7_8',
      systemDiskCategory: 'cloud_essd',
      ioOptimized: 'optimized'
    });

    const sgIngress = new ecs.SecurityGroupIngress(this, 'SecurityGroupIngress', {
      ipProtocol: 'tcp',
      portRange: '80/80',
      sourceCidrIp: '0.0.0.0/0',
      securityGroupId: sg.ref,
      nicType: 'intranet'
    });

    const runCommand = new ecs.RunCommand(this, 'RunCommand', {
      instanceIds: [instance.ref],
      type: 'RunShellScript',
      sync: true,
      timeout: 3600,
      commandContent: `yum install -y httpd wget\nsystemctl start httpd\nwget 'https://computenest-artifacts-cn-hangzhou.oss-cn-hangzhou-internal.aliyuncs.com/1853370294850618/cn-beijing/1697533575326/2048.tgz' -O 2048.tgz\ntar xvf 2048.tgz\nmv 2048/* /var/www/html && rm -rf 2048`
    });
    runCommand.addDependency(sgIngress);

    new ros.RosOutput(this, 'Url', {
      value: `http://${instance.attrPublicIp}:80`
    });
  }
}

JavaScript

lib/demo-stack.js文件內容,全部改為下面代碼。

const ros = require('@alicloud/ros-cdk-core');
const ecs = require('@alicloud/ros-cdk-ecs');

class DemoStack extends ros.Stack {
  /**
   *
   * @param {ros.Construct} scope
   * @param {string} id
   * @param {ros.StackProps} props
   */
  constructor(scope, id, props) {
    super(scope, id, props);
    new ros.RosInfo(this, ros.RosInfo.description, "Deploy 2048 game through ROS CDK.");
    // The code that defines your stack goes here
    const zoneId = new ros.RosParameter(this, 'ZoneId', {
      type: ros.RosParameterType.STRING
    });

    const vpc = new ecs.Vpc(this, 'Vpc', {
      cidrBlock: '192.168.0.0/16'
    });

    const sg = new ecs.SecurityGroup(this, 'SecurityGroup', {
      vpcId: vpc.ref
    });

    const vsw = new ecs.VSwitch(this, 'VSwitch', {
      cidrBlock: '192.168.0.0/24',
      zoneId: zoneId,
      vpcId: vpc.ref
    })

    const instance = new ecs.Instance(this, 'Instance', {
      vpcId: vpc.ref,
      vSwitchId: vsw.ref,
      securityGroupId: sg.ref,
      zoneId: zoneId,
      instanceType: 'ecs.c6e.large',
      imageId: 'centos_7_8',
      systemDiskCategory: 'cloud_essd',
      ioOptimized: 'optimized'
    });

    const sgIngress = new ecs.SecurityGroupIngress(this, 'SecurityGroupIngress', {
      ipProtocol: 'tcp',
      portRange: '80/80',
      sourceCidrIp: '0.0.0.0/0',
      securityGroupId: sg.ref,
      nicType: 'intranet'
    });

    const runCommand = new ecs.RunCommand(this, 'RunCommand', {
      instanceIds: [instance.ref],
      type: 'RunShellScript',
      sync: true,
      timeout: 3600,
      commandContent: `yum install -y httpd wget\nsystemctl start httpd\nwget 'https://computenest-artifacts-cn-hangzhou.oss-cn-hangzhou-internal.aliyuncs.com/1853370294850618/cn-beijing/1697533575326/2048.tgz' -O 2048.tgz\ntar xvf 2048.tgz\nmv 2048/* /var/www/html && rm -rf 2048`
    });
    runCommand.addDependency(sgIngress);

    new ros.RosOutput(this, 'Url', {
      value: `http://${instance.attrPublicIp}:80`
    });
  }
}

module.exports = { DemoStack }
重要

請將folderPath變量設置為你的本地文件夾路徑,同時,將ossBucketName變量指定為你計劃創建的OSS Bucket名稱,Bucket 名稱必須全局唯一!

Java

  1. src/main/java/com/myorg/DemoStack.java文件內容,全部改為下面代碼。

    package com.myorg;
    
    import com.aliyun.ros.cdk.core.*;
    import com.aliyun.ros.cdk.ecs.*;
    
    import java.util.ArrayList;
    import java.util.Arrays;
    
    public class DemoStack extends Stack {
        public DemoStack(final Construct scope, final String id) {
            this(scope, id, null);
        }
    
        public DemoStack(final Construct scope, final String id, final StackProps props) {
            super(scope, id, props);
    
            // The code that defines your stack goes here
            RosInfo.setDescription("Deploy 2048 game through ROS CDK.");
            RosParameter zoneId = RosParameter.Builder.create(this, "ZoneId")
                    .type(RosParameterType.STRING)
                    .build();
    
            Vpc vpc = Vpc.Builder.create(this, "Vpc")
                    .cidrBlock("192.168.0.0/16")
                    .build();
    
            SecurityGroup securityGroup = SecurityGroup.Builder.create(this, "SecurityGroup")
                    .vpcId(vpc.getRef())
                    .build();
    
            VSwitch vSwitch = VSwitch.Builder.create(this, "VSwitch")
                    .cidrBlock("192.168.0.0/24")
                    .zoneId(zoneId.getValue())
                    .vpcId(vpc.getRef())
                    .build();
    
            Instance instance = Instance.Builder.create(this, "Instance")
                    .vpcId(vpc.getRef())
                    .vSwitchId(vSwitch.getRef())
                    .securityGroupId(securityGroup.getRef())
                    .zoneId(zoneId.getValue())
                    .instanceType("ecs.c6e.large")
                    .imageId("centos_7_8")
                    .systemDiskCategory("cloud_essd")
                    .ioOptimized("optimized")
                    .build();
    
            SecurityGroupIngress securityGroupIngress = SecurityGroupIngress.Builder.create(this, "SecurityGroupIngress")
                    .ipProtocol("tcp")
                    .portRange("80/80")
                    .sourceCidrIp("0.0.0.0/0")
                    .securityGroupId(securityGroup.getRef())
                    .nicType("intranet")
                    .build();
    
            RunCommand runCommand = RunCommand.Builder.create(this, "RunCommand")
                    .instanceIds(new ArrayList<>(Arrays.asList(instance.getRef())))
                    .type("RunShellScript")
                    .sync(true)
                    .timeout(3600)
                    .commandContent("yum install -y httpd wget\nsystemctl start httpd\nwget 'https://computenest-artifacts-cn-hangzhou.oss-cn-hangzhou-internal.aliyuncs.com/1853370294850618/cn-beijing/1697533575326/2048.tgz' -O 2048.tgz\ntar xvf 2048.tgz\nmv 2048/* /var/www/html && rm -rf 2048")
                    .build();
            runCommand.addDependency(securityGroupIngress);
    
            RosOutput.Builder.create(this, "Url")
                    .value("http://" + instance.getAttrPublicIp().toString() +":80")
                    .build();
        }
    }
  2. 運行mvn compile以編譯CDK項目。

Python

demo/demo_stack.py文件內容,全部改為下面代碼。

import ros_cdk_core as core
import ros_cdk_ecs as ecs


class DemoStack(core.Stack):

    def __init__(self, scope: core.Construct, construct_id: str, **kwargs) -> None:
        super().__init__(scope, construct_id, **kwargs)

        # The code that defines your stack goes here
        core.RosInfo(self, core.RosInfo.description, "Deploy 2048 game through ROS CDK.")

        zone_id = core.RosParameter(self, "ZoneId", type=core.RosParameterType.STRING)

        vpc = ecs.Vpc(self, "Vpc", ecs.VPCProps(cidr_block="192.168.0.0/16"))

        sg = ecs.SecurityGroup(self, "SecurityGroup", ecs.SecurityGroupProps(vpc_id=vpc.ref))

        vsw = ecs.VSwitch(self, "VSwitch", ecs.VSwitchProps(
            cidr_block='192.168.0.0/24',
            vpc_id=vpc.ref,
            zone_id=zone_id,
        ))

        instance = ecs.Instance(self, "Instance", ecs.InstanceProps(
            vpc_id=vpc.ref,
            instance_type="ecs.c6e.large",
            image_id="centos_7_8",
            security_group_id=sg.ref,
            v_switch_id=vsw.ref,
            zone_id=zone_id,
            system_disk_category="cloud_essd",
            io_optimized="optimized"
        ))

        sg_ingress = ecs.SecurityGroupIngress(self, "SecurityGroupIngress", ecs.SecurityGroupIngressProps(
            security_group_id=sg.ref,
            port_range="80/80",
            ip_protocol="tcp",
            source_cidr_ip="0.0.0.0/0",
            nic_type="intranet"
        ))

        run_command = ecs.RunCommand(self, "RunCommand", ecs.RunCommandProps(
            instance_ids=[instance.ref],
            command_content= "yum install -y httpd wget\nsystemctl start httpd\nwget 'https://computenest-artifacts-cn-hangzhou.oss-cn-hangzhou-internal.aliyuncs.com/1853370294850618/cn-beijing/1697533575326/2048.tgz' -O 2048.tgz\ntar xvf 2048.tgz\nmv 2048/* /var/www/html && rm -rf 2048",
            type="RunShellScript",
            timeout=3600,
            sync=True
        ))
        run_command.add_dependency(sg_ingress)

        core.RosOutput(self, "Url", value="http://{}:80".format(instance.attr_public_ip.to_string()))

C#

src/Demo/DemoStack.cs文件內容,全部改為下面代碼。

using System.Collections.Generic;
using AlibabaCloud.SDK.ROS.CDK.Core;
using AlibabaCloud.SDK.ROS.CDK.Ecs;

namespace Demo
{
    public class DemoStack : Stack
    {
        public DemoStack(Construct scope, string id, IStackProps props = null) : base(scope, id, props)
        {
            // The code that defines your stack goes here
            new RosInfo(this, RosInfo.Description, "Deploy 2048 game through ROS CDK.");

            var zoneId = new RosParameter(this, "ZoneId", new RosParameterProps{
                Type = RosParameterType.STRING
            });

            var vpc = new Vpc(this, "Vpc", new VPCProps{
                CidrBlock = "192.168.0.0/16"
            });

            var sg = new SecurityGroup(this, "SecurityGroup", new SecurityGroupProps{
                VpcId = vpc.Ref
            });

            var vsw = new VSwitch(this, "VSwitch", new VSwitchProps{
                CidrBlock = "192.168.0.0/24",
                ZoneId = zoneId.Value,
                VpcId = vpc.Ref
            });

            var instance = new Instance(this, "Instance", new InstanceProps{
                VpcId = vpc.Ref,
                VSwitchId = vsw.Ref,
                SecurityGroupId = sg.Ref,
                ZoneId = zoneId.Value,
                InstanceType = "ecs.c6e.large",
                ImageId = "centos_7_8",
                SystemDiskCategory = "cloud_essd",
                IoOptimized = "optimized"
            });

            var sgIngress = new SecurityGroupIngress(this, "SecurityGroupIngress", new SecurityGroupIngressProps{
                IpProtocol = "tcp",
                PortRange = "80/80",
                SourceCidrIp = "0.0.0.0/0",
                SecurityGroupId = sg.Ref,
                NicType = "intranet"
            });

            var runCommand = new RunCommand(this, "RunCommand", new RunCommandProps{
                InstanceIds = new IResolvable[] { instance.AttrInstanceId },
                CommandContent = "yum install -y httpd wget\nsystemctl start httpd\nwget 'https://computenest-artifacts-cn-hangzhou.oss-cn-hangzhou-internal.aliyuncs.com/1853370294850618/cn-beijing/1697533575326/2048.tgz' -O 2048.tgz\ntar xvf 2048.tgz\nmv 2048/* /var/www/html && rm -rf 2048",
                Type = "RunShellScript",
                Timeout = 3600,
                Sync = true
            });
            runCommand.AddDependency(sgIngress);

            new RosOutput(this, "Url", new RosOutputProps{
                Value = "http://" + instance.AttrPublicIp.ToString() + ":80"
            });
        }
    }
}

Go

demo.go文件內容,全部改為下面代碼。

package main

import (
	"github.com/alibabacloud-go/ros-cdk/alicloudroscdkcore"
	"github.com/alibabacloud-go/ros-cdk/alicloudroscdkecs"
)

type demoStackProps struct {
	alicloudroscdkcore.StackProps
}

func NewdemoStack(scope alicloudroscdkcore.Construct, id string, props *demoStackProps) alicloudroscdkcore.Stack {
	var sprops alicloudroscdkcore.StackProps
	if props != nil {
		sprops = props.StackProps
	}
	stack := alicloudroscdkcore.NewStack(scope, &id, &sprops)

	// The code that defines your stack goes here
	description := "Deploy 2048 game through ROS CDK."
	alicloudroscdkcore.RosInfo_SetDescription(&description)

	zoneIdKey := "ZoneId"
	zoneIdProps := alicloudroscdkcore.RosParameterProps{Type: alicloudroscdkcore.RosParameterType_STRING}
	zoneId := alicloudroscdkcore.NewRosParameter(stack, &zoneIdKey, &zoneIdProps)

	vpcKey := "Vpc"
	vpcProps := alicloudroscdkecs.VPCProps{CidrBlock: "192.168.0.0/16"}
	vpc := alicloudroscdkecs.NewVpc(stack, &vpcKey, &vpcProps, nil)

	sgKey := "SecurityGroup"
	sgProps := alicloudroscdkecs.SecurityGroupProps{VpcId: vpc.Ref()}
	sg := alicloudroscdkecs.NewSecurityGroup(stack, &sgKey, &sgProps, nil)

	vswKey := "VSwitch"
	vswProps := alicloudroscdkecs.VSwitchProps{
		CidrBlock: "192.168.0.0/24",
		ZoneId:    zoneId.Value(),
		VpcId:     vpc.Ref(),
	}
	vsw := alicloudroscdkecs.NewVSwitch(stack, &vswKey, &vswProps, nil)

	instanceKey := "Instance"
	instanceProps := alicloudroscdkecs.InstanceProps{
		VpcId:              vpc.Ref(),
		VSwitchId:          vsw.Ref(),
		SecurityGroupId:    sg.Ref(),
		ZoneId:             zoneId.Value(),
		InstanceType:       "ecs.c6e.large",
		ImageId:            "centos_7_8",
		SystemDiskCategory: "cloud_essd",
		IoOptimized:        "optimized",
	}
	instance := alicloudroscdkecs.NewInstance(stack, &instanceKey, &instanceProps, nil)

	sgIngressKey := "SecurityGroupIngress"
	sgIngressProps := alicloudroscdkecs.SecurityGroupIngressProps{
		IpProtocol:      "tcp",
		PortRange:       "80/80",
		SourceCidrIp:    "0.0.0.0/0",
		SecurityGroupId: sg.Ref(),
		NicType:         "intranet",
	}
	sgIngress := alicloudroscdkecs.NewSecurityGroupIngress(stack, &sgIngressKey, &sgIngressProps, nil)

	var instanceIds []*string
	runCommandKey := "RunCommand"
	runCommandProps := alicloudroscdkecs.RunCommandProps{
		InstanceIds:    append(instanceIds, instance.Ref()),
		Type:           "RunShellScript",
		Sync:           true,
		Timeout:        3600,
		CommandContent: "yum install -y httpd wget\nsystemctl start httpd\nwget 'https://computenest-artifacts-cn-hangzhou.oss-cn-hangzhou-internal.aliyuncs.com/1853370294850618/cn-beijing/1697533575326/2048.tgz' -O 2048.tgz\ntar xvf 2048.tgz\nmv 2048/* /var/www/html && rm -rf 2048",
	}
	runCommand := alicloudroscdkecs.NewRunCommand(stack, &runCommandKey, &runCommandProps, nil)
	runCommand.AddDependency(sgIngress)

	urlKey := "Url"
	urlProps := alicloudroscdkcore.RosOutputProps{Value: "http://" + *instance.AttrPublicIp().ToString() + ":80"}
	alicloudroscdkcore.NewRosOutput(stack, &urlKey, &urlProps)

	return stack
}

func main() {
	app := alicloudroscdkcore.NewApp(nil)
	props := &demoStackProps{}

	NewdemoStack(app, "demoStack", props)

	app.Synth(nil)
}

步驟五:創建資源棧

  1. 在命令行窗口運行如下命令,創建資源棧。

    ros-cdk deploy --parameters ZoneId=cn-hangzhou-i --sync=true

    請選擇合適的可用區進行部署。命令行終端返回The deployment(sync create stack) has completed!表示創建成功,全部信息如下。

    Create bucket(cdk-tcbgaxxxx-assets-cn-hangzhou) successfully!
    Upload file(./cdk.out/DemoStack.template.json) to bucket(cdk-tcbgaxxxx-assets-cn-hangzhou) successfully!
    DemoStack: deploying...
    |DemoStack               |2024-09-09T08:56:47 | CREATE_COMPLETE      | ALIYUN::ECS::SecurityGroup | sg-bp121z2wd687mdxxxxxx | SecurityGroup
    
    |DemoStack               |2024-09-09T08:56:47 | CREATE_COMPLETE      | ALIYUN::ECS::SecurityGroupIngress | sg-bp121z2wd687mdxxxxxx | SecurityGroupIngress
    
    |DemoStack               |2024-09-09T08:56:47 | CREATE_COMPLETE      | ALIYUN::ECS::Instance   | i-bp16t9mt9b0uscixxxxx | Instance
    
    |DemoStack               |2024-09-09T08:56:47 | CREATE_COMPLETE      | ALIYUN::ECS::VPC        | vpc-bp10y18ke2x6v0bjxxxxx | Vpc
    
    |DemoStack               |2024-09-09T08:56:47 | CREATE_COMPLETE      | ALIYUN::ECS::VSwitch    | vsw-bp1qfb9u90cuyu69xxxxx | VSwitch
    
    |DemoStack               |2024-09-09T08:56:47 | CREATE_COMPLETE      | ALIYUN::ECS::RunCommand | t-hz04w6ckiuxxxxx | RunCommand
    
    
    Outputs:
    
     Key: Url  Value: http://121.40.xxx.xx:80 Description: No description given
    
     ? The deployment(sync create stack) has completed!
    Status: CREATE_COMPLETE
    StatusReason: Stack CREATE completed successfully
    StackId: 40c92773-33fb-4249-bd46-3ab6xxxxxxxx
    
  2. 部署完成后,復制Outputs中的鏈接并在瀏覽器中打開,即可暢玩2048。

步驟六:刪除資源棧

  1. 命令行窗口執行以下命令以刪除資源棧。

    ros-cdk destroy --sync=true 

    CDK會二次確認即將刪除的資源棧。

    The following stack(s) will be destroyed(Only deployed stacks will be displayed).
    
    DemoStack
    
    Please confirm.(Y/N)
  2. 輸入y并回車,刪除成功會顯示如下信息。

    The task(sync destroy stack) has finished!
    status: DELETE_COMPLETE
    StatusReason: Stack DELETE completed successfully
    StackId: 40c92773-33fb-4249-bd46-3ab6xxxxxxxx
    

更多參考

API參考頁面

CDK構造庫提供了一系列API,用于構建您的CDK應用程序。想要了解如何使用這些API及其特性,請參閱ROS CDK API參考

命令簡介

想要了解如何使用CDK命令行及其使用示例,請參閱ROS CDK命令簡介

功能簡介

想要了解如何使用CDK輸出、偽參數等功能及其使用示例,請參閱ROS CDK功能簡介

GitHub倉庫

有關ROS CDK的官方GitHub存儲庫,請參閱Resource-Orchestration-Service-Cloud-Development-Kit。在這里,您可以提交問題,查看我們的許可證、發布記錄等。