Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to launch a task ECS on AWS with PHP

I try to launch my "TaskDefinition" on ECS (Ec2 container service) with the PHP SDK.

  1. I created the TaskDefinition.
  2. I created the Cluster.
  3. I created the service.

I thought the next step would be "registerContainerInstance" but when i call this method, i have an error :

[Aws\Ecs\Exception\EcsException]
Error executing "RegisterContainerInstance" on "https://ecs.eu-west-1.amazonaws.com"; AWS HTTP error: Client error: 400 ClientException (client): An identity document was provided, but not valid. - {" __type":"ClientException","message":"An identity document was provided, but not valid."}

This is because i don't send "instanceIdentityDocument" and "instanceIdentityDocumentSignature". But, i don't know how to get this two parameters.

Should I launch an EC2 manually before?

Is there another way to do that I do not know?

<?php

namespace App\Http\Controllers;

use Aws\Ecs\EcsClient;
use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Config;

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 "index\n";
    }

    /**
     * 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 created\n";
            else
                echo  "Task : '".$taskName."' has been updated\n";
        }
        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)
    {
        //
    }
}
like image 914
Guillaume Avatar asked Feb 03 '26 19:02

Guillaume


1 Answers

I finally found the solution for my problem :

First, you need to create the task with "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 created\n";
            else
                echo  "Task : '".$taskName."' has been updated\n";
        }
        else
            echo "Error : The task is not active.\n";

The file 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": []
}

Then, you need to create the cluster :

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

Then, the service :

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

After that, you have to start your EC2 instance :

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

        ]);

When your EC2 is ready, you can start your task :

$result = $this->ecsClient->runTask([
            'taskDefinition' => 'taskName',
            'cluster' => 'test'
        ]);
like image 140
Guillaume Avatar answered Feb 06 '26 12:02

Guillaume