如何使用PHP在AWS上启动任务ECS



我尝试用PHP SDK在ECS (Ec2容器服务)上启动我的"TaskDefinition"。

    我创建了TaskDefinition。我创建了群集。我创建了服务。

我认为下一步将是"registerContainerInstance",但当我调用这个方法,我有一个错误:

Aws Ecs 例外 [EcsException]
执行"RegisterContainerInstance"时出错"https://ecs.eu -西方- 1. amazonaws.com";AWS HTTP错误:客户端错误400 ClientException (client):提供了身份证件,但是不是有效的。—{" __type":"ClientException","message":"标识文件已提供,但无效。"}

这是因为我不发送"instanceIdentityDocument"one_answers"instanceIdentityDocumentSignature"。但是,我不知道如何得到这两个参数。

我应该之前手动启动EC2吗?

还有我不知道的方法吗?

<?php
namespace AppHttpControllers;
use AwsEcsEcsClient;
use IlluminateHttpRequest;
use AppHttpRequests;
use AppHttpControllersController;
use IlluminateSupportFacadesApp;
use IlluminateSupportFacadesConfig;
class ECSController extends Controller
{
    protected $ecsClient;
    function __construct() {
        $config = Config::get('aws');
        $this->ecsClient = new EcsClient([
            'version'     => 'latest',
            'region'      => $config['region'],
            'credentials' => [
                'key'    => $config['credentials']['key'],
                'secret' => $config['credentials']['secret'],
            ],
        ]);
    }
    /**
     * Display a listing of the resource.
     *
     * @return Response
     */
    public function index()
    {
/*  $response = [
              'photos'  => []
            ];    
        return Response::json($response, $statusCode); */
    echo "indexn";
    }
    /**
     * Show the form for creating a new resource.
     *
     * @return Response
     */
    public function create()
    {
        $file = file_get_contents('config/configEC2basic.json');
        $data = json_decode($file, true /* associative arrays */);
        $result = $this->ecsClient->registerTaskDefinition($data);
        if ($result['taskDefinition']['status'] == "ACTIVE")
        {
            $taskName = $result['taskDefinition']['containerDefinitions'][0]['name'];
            if ($result['taskDefinition']['revision'] == 1)
                echo "Task : '".$taskName."' has been createdn";
            else
                echo  "Task : '".$taskName."' has been updatedn";
        }
        else
            echo "Error : The task is not active.n";
        $clusterName = $this->ecsClient->createCluster([
            'clusterName' => 'kaemo',
        ]);
        $result = $this->ecsClient->createService([
            'desiredCount' => 1,
            'serviceName' => 'kaedevAWS1',
            'taskDefinition' => 'testkaeDEV4',
            'cluster' => 'kaemo'
        ]);
     }
    public function start()
    {
        $result = $this->ecsClient->registerContainerInstance([
            'cluster' => 'kae',
            'totalResources' => [
                [
                    'integerValue' => 1,
                    "longValue" => 0,
                    'name' => "CPU",
                    'type' => "INTEGER",
                    "doubleValue" => 0.0,
                ],
                [
                    'integerValue' => 996,
                    "longValue" => 0,
                    'name' => "MEMORY",
                    'type' => "INTEGER",
                    "doubleValue" => 0.0,
                ],
                [
                    'integerValue' => 0,
                    "longValue" => 0,
                    'name' => "PORTS",
                    'type' => "STRINGSET",
                    "doubleValue" => 0.0,
                    "stringSetValue" => [
                        "80",
                        "22"
                    ]
                ]
            ]
        ]);
             echo ">".print_r($result, true);
       /* $result = $this->ecsClient->runTask([
            'taskDefinition' => 'testkaemoDEV4',
            'cluster' => 'kaemo'
        ]);
        echo ">".print_r($result, true); */
    }
    /**
     * Store a newly created resource in storage.
     *
     * @param  Request  $request
     * @return Response
     */
    public function store(Request $request)
    {
        //
    }
    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return Response
     */
    public function show($id)
    {
        //
    }
    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return Response
     */
    public function edit($id)
    {
        //
    }
    /**
     * Update the specified resource in storage.
     *
     * @param  Request  $request
     * @param  int  $id
     * @return Response
     */
    public function update(Request $request, $id)
    {
        //
    }
    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return Response
     */
    public function destroy($id)
    {
        //
    }
}

我终于找到解决问题的办法了:

首先,你需要用"registerTaskDefinition"创建任务:

$file = file_get_contents('config/configEC2basic.json');
        $data = json_decode($file, true /* associative arrays */);
        $result = $this->ecsClient->registerTaskDefinition($data);
        if ($result['taskDefinition']['status'] == "ACTIVE")
        {
            $taskName = $result['taskDefinition']['containerDefinitions'][0]['name'];
            if ($result['taskDefinition']['revision'] == 1)
                echo "Task : '".$taskName."' has been createdn";
            else
                echo  "Task : '".$taskName."' has been updatedn";
        }
        else
            echo "Error : The task is not active.n";

文件config/configEC2basic。json:

{
    "containerDefinitions": [{
        "command": [],
        "cpu": 1,
        "entryPoint": ["/usr/sbin/apache2ctl -D FOREGROUND"],
        "environment": [],
        "essential": true,
        "image": "usernamedockerhub/dockercontainer",
        "links": [],
        "memory": 500,
        "mountPoints": [],
        "name": "nameTask",
        "portMappings": [{
            "containerPort": 80,
            "hostPort": 80,
            "protocol": "tcp"
        }],
        "volumesFrom": []
    }],
    "family": "familyTask",
    "volumes": []
}

然后,需要创建集群:

$clusterName = $this->ecsClient->createCluster([
            'clusterName' => 'test',
        ]);

然后,服务:

$result = $this->ecsClient->createService([
            'desiredCount' => 1,
            'serviceName' => 'serviceName',
            'taskDefinition' => 'taskName',
            'cluster' => 'test'
        ]);

之后,您必须启动EC2实例:

$result = $this->ec2Client->runInstances([
            'ImageId'        => 'ami-2aaef35d',
            'MinCount'       => 1,
            'MaxCount'       => 1,
            'InstanceType'   => 't2.micro',
            'UserData'       => base64_encode("#!/bin/bash rn echo ECS_CLUSTER=test >> /etc/ecs/ecs.config"),
            'IamInstanceProfile' => [
                'Arn' => 'ARNEC2'
            ],
        ]);

当你的EC2准备好了,你可以开始你的任务:

$result = $this->ecsClient->runTask([
            'taskDefinition' => 'taskName',
            'cluster' => 'test'
        ]);

最新更新