github.com/defang-io/defang/src@v0.0.0-20240505002154-bdf411911834/pkg/clouds/aws/ecs/info.go (about)

     1  package ecs
     2  
     3  import (
     4  	"context"
     5  	"errors"
     6  
     7  	"github.com/aws/aws-sdk-go-v2/service/ec2"
     8  	"github.com/aws/aws-sdk-go-v2/service/ecs"
     9  	"github.com/aws/smithy-go/ptr"
    10  	"github.com/defang-io/defang/src/pkg/types"
    11  )
    12  
    13  func (a AwsEcs) Info(ctx context.Context, id TaskArn) (*types.TaskInfo, error) {
    14  	cfg, err := a.LoadConfig(ctx)
    15  	if err != nil {
    16  		return nil, err
    17  	}
    18  
    19  	ti, err := ecs.NewFromConfig(cfg).DescribeTasks(ctx, &ecs.DescribeTasksInput{
    20  		Cluster: ptr.String(a.ClusterName),
    21  		Tasks:   []string{*id},
    22  		// Reason: ptr.String("defang stop"),
    23  	})
    24  	if err != nil {
    25  		return nil, err
    26  	}
    27  
    28  	// b, err := json.MarshalIndent(ti, "", "  ")
    29  	// println(string(b))
    30  
    31  	if len(ti.Tasks) == 0 || len(ti.Tasks[0].Attachments) == 0 {
    32  		return nil, errors.New("no attachments")
    33  	}
    34  
    35  	if *ti.Tasks[0].LastStatus == "PROVISIONING" {
    36  		return nil, errors.New("task is provisioning")
    37  	}
    38  
    39  	for _, detail := range ti.Tasks[0].Attachments[0].Details {
    40  		if *detail.Name != "networkInterfaceId" {
    41  			continue
    42  		}
    43  		ni, err := ec2.NewFromConfig(cfg).DescribeNetworkInterfaces(ctx, &ec2.DescribeNetworkInterfacesInput{
    44  			NetworkInterfaceIds: []string{*detail.Value},
    45  		})
    46  		if err != nil {
    47  			return nil, err
    48  		}
    49  		if len(ni.NetworkInterfaces) == 0 || ni.NetworkInterfaces[0].Association == nil {
    50  			return nil, errors.New("no network interface association")
    51  		}
    52  		ip := *ni.NetworkInterfaces[0].Association.PublicIp
    53  		if ip == "" {
    54  			return nil, nil
    55  		}
    56  		// TODO: add mapped ports / endpoints
    57  		return &types.TaskInfo{IP: ip}, nil
    58  	}
    59  	return nil, nil // no public IP?
    60  }