sdk.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630
  1. /*
  2. Copyright 2020 Docker, Inc.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package ecs
  14. import (
  15. "context"
  16. "fmt"
  17. "strings"
  18. "time"
  19. "github.com/aws/aws-sdk-go/aws/client"
  20. "github.com/docker/compose-cli/compose"
  21. "github.com/docker/compose-cli/secrets"
  22. "github.com/aws/aws-sdk-go/aws"
  23. "github.com/aws/aws-sdk-go/service/cloudformation"
  24. "github.com/aws/aws-sdk-go/service/cloudformation/cloudformationiface"
  25. "github.com/aws/aws-sdk-go/service/cloudwatchlogs"
  26. "github.com/aws/aws-sdk-go/service/cloudwatchlogs/cloudwatchlogsiface"
  27. "github.com/aws/aws-sdk-go/service/ec2"
  28. "github.com/aws/aws-sdk-go/service/ec2/ec2iface"
  29. "github.com/aws/aws-sdk-go/service/ecs"
  30. "github.com/aws/aws-sdk-go/service/ecs/ecsiface"
  31. "github.com/aws/aws-sdk-go/service/elbv2"
  32. "github.com/aws/aws-sdk-go/service/elbv2/elbv2iface"
  33. "github.com/aws/aws-sdk-go/service/iam"
  34. "github.com/aws/aws-sdk-go/service/iam/iamiface"
  35. "github.com/aws/aws-sdk-go/service/secretsmanager"
  36. "github.com/aws/aws-sdk-go/service/secretsmanager/secretsmanageriface"
  37. cf "github.com/awslabs/goformation/v4/cloudformation"
  38. "github.com/sirupsen/logrus"
  39. )
  40. type sdk struct {
  41. ECS ecsiface.ECSAPI
  42. EC2 ec2iface.EC2API
  43. ELB elbv2iface.ELBV2API
  44. CW cloudwatchlogsiface.CloudWatchLogsAPI
  45. IAM iamiface.IAMAPI
  46. CF cloudformationiface.CloudFormationAPI
  47. SM secretsmanageriface.SecretsManagerAPI
  48. }
  49. func newSDK(sess client.ConfigProvider) sdk {
  50. return sdk{
  51. ECS: ecs.New(sess),
  52. EC2: ec2.New(sess),
  53. ELB: elbv2.New(sess),
  54. CW: cloudwatchlogs.New(sess),
  55. IAM: iam.New(sess),
  56. CF: cloudformation.New(sess),
  57. SM: secretsmanager.New(sess),
  58. }
  59. }
  60. func (s sdk) CheckRequirements(ctx context.Context, region string) error {
  61. settings, err := s.ECS.ListAccountSettingsWithContext(ctx, &ecs.ListAccountSettingsInput{
  62. EffectiveSettings: aws.Bool(true),
  63. Name: aws.String("serviceLongArnFormat"),
  64. })
  65. if err != nil {
  66. return err
  67. }
  68. serviceLongArnFormat := settings.Settings[0].Value
  69. if *serviceLongArnFormat != "enabled" {
  70. return fmt.Errorf("this tool requires the \"new ARN resource ID format\".\n"+
  71. "Check https://%s.console.aws.amazon.com/ecs/home#/settings\n"+
  72. "Learn more: https://aws.amazon.com/blogs/compute/migrating-your-amazon-ecs-deployment-to-the-new-arn-and-resource-id-format-2", region)
  73. }
  74. return nil
  75. }
  76. func (s sdk) ClusterExists(ctx context.Context, name string) (bool, error) {
  77. logrus.Debug("CheckRequirements if cluster was already created: ", name)
  78. clusters, err := s.ECS.DescribeClustersWithContext(ctx, &ecs.DescribeClustersInput{
  79. Clusters: []*string{aws.String(name)},
  80. })
  81. if err != nil {
  82. return false, err
  83. }
  84. return len(clusters.Clusters) > 0, nil
  85. }
  86. func (s sdk) CreateCluster(ctx context.Context, name string) (string, error) {
  87. logrus.Debug("Create cluster ", name)
  88. response, err := s.ECS.CreateClusterWithContext(ctx, &ecs.CreateClusterInput{ClusterName: aws.String(name)})
  89. if err != nil {
  90. return "", err
  91. }
  92. return *response.Cluster.Status, nil
  93. }
  94. func (s sdk) CheckVPC(ctx context.Context, vpcID string) error {
  95. logrus.Debug("CheckRequirements on VPC : ", vpcID)
  96. output, err := s.EC2.DescribeVpcAttributeWithContext(ctx, &ec2.DescribeVpcAttributeInput{
  97. VpcId: aws.String(vpcID),
  98. Attribute: aws.String("enableDnsSupport"),
  99. })
  100. if err != nil {
  101. return err
  102. }
  103. if !*output.EnableDnsSupport.Value {
  104. return fmt.Errorf("VPC %q doesn't have DNS resolution enabled", vpcID)
  105. }
  106. return err
  107. }
  108. func (s sdk) GetDefaultVPC(ctx context.Context) (string, error) {
  109. logrus.Debug("Retrieve default VPC")
  110. vpcs, err := s.EC2.DescribeVpcsWithContext(ctx, &ec2.DescribeVpcsInput{
  111. Filters: []*ec2.Filter{
  112. {
  113. Name: aws.String("isDefault"),
  114. Values: []*string{aws.String("true")},
  115. },
  116. },
  117. })
  118. if err != nil {
  119. return "", err
  120. }
  121. if len(vpcs.Vpcs) == 0 {
  122. return "", fmt.Errorf("account has not default VPC")
  123. }
  124. return *vpcs.Vpcs[0].VpcId, nil
  125. }
  126. func (s sdk) GetSubNets(ctx context.Context, vpcID string) ([]string, error) {
  127. logrus.Debug("Retrieve SubNets")
  128. subnets, err := s.EC2.DescribeSubnetsWithContext(ctx, &ec2.DescribeSubnetsInput{
  129. DryRun: nil,
  130. Filters: []*ec2.Filter{
  131. {
  132. Name: aws.String("vpc-id"),
  133. Values: []*string{aws.String(vpcID)},
  134. },
  135. },
  136. })
  137. if err != nil {
  138. return nil, err
  139. }
  140. ids := []string{}
  141. for _, subnet := range subnets.Subnets {
  142. ids = append(ids, *subnet.SubnetId)
  143. }
  144. return ids, nil
  145. }
  146. func (s sdk) GetRoleArn(ctx context.Context, name string) (string, error) {
  147. role, err := s.IAM.GetRoleWithContext(ctx, &iam.GetRoleInput{
  148. RoleName: aws.String(name),
  149. })
  150. if err != nil {
  151. return "", err
  152. }
  153. return *role.Role.Arn, nil
  154. }
  155. func (s sdk) StackExists(ctx context.Context, name string) (bool, error) {
  156. stacks, err := s.CF.DescribeStacksWithContext(ctx, &cloudformation.DescribeStacksInput{
  157. StackName: aws.String(name),
  158. })
  159. if err != nil {
  160. if strings.HasPrefix(err.Error(), fmt.Sprintf("ValidationError: Stack with id %s does not exist", name)) {
  161. return false, nil
  162. }
  163. return false, nil
  164. }
  165. return len(stacks.Stacks) > 0, nil
  166. }
  167. func (s sdk) CreateStack(ctx context.Context, name string, template *cf.Template, parameters map[string]string) error {
  168. logrus.Debug("Create CloudFormation stack")
  169. json, err := marshall(template)
  170. if err != nil {
  171. return err
  172. }
  173. param := []*cloudformation.Parameter{}
  174. for name, value := range parameters {
  175. param = append(param, &cloudformation.Parameter{
  176. ParameterKey: aws.String(name),
  177. ParameterValue: aws.String(value),
  178. })
  179. }
  180. _, err = s.CF.CreateStackWithContext(ctx, &cloudformation.CreateStackInput{
  181. OnFailure: aws.String("DELETE"),
  182. StackName: aws.String(name),
  183. TemplateBody: aws.String(string(json)),
  184. Parameters: param,
  185. TimeoutInMinutes: nil,
  186. Capabilities: []*string{
  187. aws.String(cloudformation.CapabilityCapabilityIam),
  188. },
  189. })
  190. return err
  191. }
  192. func (s sdk) CreateChangeSet(ctx context.Context, name string, template *cf.Template, parameters map[string]string) (string, error) {
  193. logrus.Debug("Create CloudFormation Changeset")
  194. json, err := marshall(template)
  195. if err != nil {
  196. return "", err
  197. }
  198. param := []*cloudformation.Parameter{}
  199. for name := range parameters {
  200. param = append(param, &cloudformation.Parameter{
  201. ParameterKey: aws.String(name),
  202. UsePreviousValue: aws.Bool(true),
  203. })
  204. }
  205. update := fmt.Sprintf("Update%s", time.Now().Format("2006-01-02-15-04-05"))
  206. changeset, err := s.CF.CreateChangeSetWithContext(ctx, &cloudformation.CreateChangeSetInput{
  207. ChangeSetName: aws.String(update),
  208. ChangeSetType: aws.String(cloudformation.ChangeSetTypeUpdate),
  209. StackName: aws.String(name),
  210. TemplateBody: aws.String(string(json)),
  211. Parameters: param,
  212. Capabilities: []*string{
  213. aws.String(cloudformation.CapabilityCapabilityIam),
  214. },
  215. })
  216. if err != nil {
  217. return "", err
  218. }
  219. err = s.CF.WaitUntilChangeSetCreateCompleteWithContext(ctx, &cloudformation.DescribeChangeSetInput{
  220. ChangeSetName: changeset.Id,
  221. })
  222. return *changeset.Id, err
  223. }
  224. func (s sdk) UpdateStack(ctx context.Context, changeset string) error {
  225. desc, err := s.CF.DescribeChangeSetWithContext(ctx, &cloudformation.DescribeChangeSetInput{
  226. ChangeSetName: aws.String(changeset),
  227. })
  228. if err != nil {
  229. return err
  230. }
  231. if strings.HasPrefix(aws.StringValue(desc.StatusReason), "The submitted information didn't contain changes.") {
  232. return nil
  233. }
  234. _, err = s.CF.ExecuteChangeSet(&cloudformation.ExecuteChangeSetInput{
  235. ChangeSetName: aws.String(changeset),
  236. })
  237. return err
  238. }
  239. const (
  240. stackCreate = iota
  241. stackUpdate
  242. stackDelete
  243. )
  244. func (s sdk) WaitStackComplete(ctx context.Context, name string, operation int) error {
  245. input := &cloudformation.DescribeStacksInput{
  246. StackName: aws.String(name),
  247. }
  248. switch operation {
  249. case stackCreate:
  250. return s.CF.WaitUntilStackCreateCompleteWithContext(ctx, input)
  251. case stackDelete:
  252. return s.CF.WaitUntilStackDeleteCompleteWithContext(ctx, input)
  253. default:
  254. return fmt.Errorf("internal error: unexpected stack operation %d", operation)
  255. }
  256. }
  257. func (s sdk) GetStackID(ctx context.Context, name string) (string, error) {
  258. stacks, err := s.CF.DescribeStacksWithContext(ctx, &cloudformation.DescribeStacksInput{
  259. StackName: aws.String(name),
  260. })
  261. if err != nil {
  262. return "", err
  263. }
  264. return *stacks.Stacks[0].StackId, nil
  265. }
  266. func (s sdk) DescribeStackEvents(ctx context.Context, stackID string) ([]*cloudformation.StackEvent, error) {
  267. // Fixme implement Paginator on Events and return as a chan(events)
  268. events := []*cloudformation.StackEvent{}
  269. var nextToken *string
  270. for {
  271. resp, err := s.CF.DescribeStackEventsWithContext(ctx, &cloudformation.DescribeStackEventsInput{
  272. StackName: aws.String(stackID),
  273. NextToken: nextToken,
  274. })
  275. if err != nil {
  276. return nil, err
  277. }
  278. events = append(events, resp.StackEvents...)
  279. if resp.NextToken == nil {
  280. return events, nil
  281. }
  282. nextToken = resp.NextToken
  283. }
  284. }
  285. func (s sdk) ListStackParameters(ctx context.Context, name string) (map[string]string, error) {
  286. st, err := s.CF.DescribeStacksWithContext(ctx, &cloudformation.DescribeStacksInput{
  287. NextToken: nil,
  288. StackName: aws.String(name),
  289. })
  290. if err != nil {
  291. return nil, err
  292. }
  293. parameters := map[string]string{}
  294. for _, parameter := range st.Stacks[0].Parameters {
  295. parameters[aws.StringValue(parameter.ParameterKey)] = aws.StringValue(parameter.ParameterValue)
  296. }
  297. return parameters, nil
  298. }
  299. type stackResource struct {
  300. LogicalID string
  301. Type string
  302. ARN string
  303. Status string
  304. }
  305. func (s sdk) ListStackResources(ctx context.Context, name string) ([]stackResource, error) {
  306. // FIXME handle pagination
  307. res, err := s.CF.ListStackResourcesWithContext(ctx, &cloudformation.ListStackResourcesInput{
  308. StackName: aws.String(name),
  309. })
  310. if err != nil {
  311. return nil, err
  312. }
  313. resources := []stackResource{}
  314. for _, r := range res.StackResourceSummaries {
  315. resources = append(resources, stackResource{
  316. LogicalID: aws.StringValue(r.LogicalResourceId),
  317. Type: aws.StringValue(r.ResourceType),
  318. ARN: aws.StringValue(r.PhysicalResourceId),
  319. Status: aws.StringValue(r.ResourceStatus),
  320. })
  321. }
  322. return resources, nil
  323. }
  324. func (s sdk) DeleteStack(ctx context.Context, name string) error {
  325. logrus.Debug("Delete CloudFormation stack")
  326. _, err := s.CF.DeleteStackWithContext(ctx, &cloudformation.DeleteStackInput{
  327. StackName: aws.String(name),
  328. })
  329. return err
  330. }
  331. func (s sdk) CreateSecret(ctx context.Context, secret secrets.Secret) (string, error) {
  332. logrus.Debug("Create secret " + secret.Name)
  333. secretStr, err := secret.GetCredString()
  334. if err != nil {
  335. return "", err
  336. }
  337. response, err := s.SM.CreateSecret(&secretsmanager.CreateSecretInput{
  338. Name: &secret.Name,
  339. SecretString: &secretStr,
  340. Description: &secret.Description,
  341. })
  342. if err != nil {
  343. return "", err
  344. }
  345. return aws.StringValue(response.ARN), nil
  346. }
  347. func (s sdk) InspectSecret(ctx context.Context, id string) (secrets.Secret, error) {
  348. logrus.Debug("Inspect secret " + id)
  349. response, err := s.SM.DescribeSecret(&secretsmanager.DescribeSecretInput{SecretId: &id})
  350. if err != nil {
  351. return secrets.Secret{}, err
  352. }
  353. labels := map[string]string{}
  354. for _, tag := range response.Tags {
  355. labels[aws.StringValue(tag.Key)] = aws.StringValue(tag.Value)
  356. }
  357. secret := secrets.Secret{
  358. ID: aws.StringValue(response.ARN),
  359. Name: aws.StringValue(response.Name),
  360. Labels: labels,
  361. }
  362. if response.Description != nil {
  363. secret.Description = *response.Description
  364. }
  365. return secret, nil
  366. }
  367. func (s sdk) ListSecrets(ctx context.Context) ([]secrets.Secret, error) {
  368. logrus.Debug("List secrets ...")
  369. response, err := s.SM.ListSecrets(&secretsmanager.ListSecretsInput{})
  370. if err != nil {
  371. return nil, err
  372. }
  373. var ls []secrets.Secret
  374. for _, sec := range response.SecretList {
  375. labels := map[string]string{}
  376. for _, tag := range sec.Tags {
  377. labels[*tag.Key] = *tag.Value
  378. }
  379. description := ""
  380. if sec.Description != nil {
  381. description = *sec.Description
  382. }
  383. ls = append(ls, secrets.Secret{
  384. ID: *sec.ARN,
  385. Name: *sec.Name,
  386. Labels: labels,
  387. Description: description,
  388. })
  389. }
  390. return ls, nil
  391. }
  392. func (s sdk) DeleteSecret(ctx context.Context, id string, recover bool) error {
  393. logrus.Debug("List secrets ...")
  394. force := !recover
  395. _, err := s.SM.DeleteSecret(&secretsmanager.DeleteSecretInput{SecretId: &id, ForceDeleteWithoutRecovery: &force})
  396. return err
  397. }
  398. func (s sdk) GetLogs(ctx context.Context, name string, consumer func(service, container, message string)) error {
  399. logGroup := fmt.Sprintf("/docker-compose/%s", name)
  400. var startTime int64
  401. for {
  402. select {
  403. case <-ctx.Done():
  404. return nil
  405. default:
  406. var hasMore = true
  407. var token *string
  408. for hasMore {
  409. events, err := s.CW.FilterLogEvents(&cloudwatchlogs.FilterLogEventsInput{
  410. LogGroupName: aws.String(logGroup),
  411. NextToken: token,
  412. StartTime: aws.Int64(startTime),
  413. })
  414. if err != nil {
  415. return err
  416. }
  417. if events.NextToken == nil {
  418. hasMore = false
  419. } else {
  420. token = events.NextToken
  421. }
  422. for _, event := range events.Events {
  423. p := strings.Split(aws.StringValue(event.LogStreamName), "/")
  424. consumer(p[1], p[2], aws.StringValue(event.Message))
  425. startTime = *event.IngestionTime
  426. }
  427. }
  428. }
  429. time.Sleep(500 * time.Millisecond)
  430. }
  431. }
  432. func (s sdk) DescribeServices(ctx context.Context, cluster string, arns []string) ([]compose.ServiceStatus, error) {
  433. services, err := s.ECS.DescribeServicesWithContext(ctx, &ecs.DescribeServicesInput{
  434. Cluster: aws.String(cluster),
  435. Services: aws.StringSlice(arns),
  436. Include: aws.StringSlice([]string{"TAGS"}),
  437. })
  438. if err != nil {
  439. return nil, err
  440. }
  441. status := []compose.ServiceStatus{}
  442. for _, service := range services.Services {
  443. var name string
  444. for _, t := range service.Tags {
  445. if *t.Key == compose.ServiceTag {
  446. name = aws.StringValue(t.Value)
  447. }
  448. }
  449. if name == "" {
  450. return nil, fmt.Errorf("service %s doesn't have a %s tag", *service.ServiceArn, compose.ServiceTag)
  451. }
  452. targetGroupArns := []string{}
  453. for _, lb := range service.LoadBalancers {
  454. targetGroupArns = append(targetGroupArns, *lb.TargetGroupArn)
  455. }
  456. // getURLwithPortMapping makes 2 queries
  457. // one to get the target groups and another for load balancers
  458. loadBalancers, err := s.getURLWithPortMapping(ctx, targetGroupArns)
  459. if err != nil {
  460. return nil, err
  461. }
  462. status = append(status, compose.ServiceStatus{
  463. ID: aws.StringValue(service.ServiceName),
  464. Name: name,
  465. Replicas: int(aws.Int64Value(service.RunningCount)),
  466. Desired: int(aws.Int64Value(service.DesiredCount)),
  467. Publishers: loadBalancers,
  468. })
  469. }
  470. return status, nil
  471. }
  472. func (s sdk) getURLWithPortMapping(ctx context.Context, targetGroupArns []string) ([]compose.PortPublisher, error) {
  473. if len(targetGroupArns) == 0 {
  474. return nil, nil
  475. }
  476. groups, err := s.ELB.DescribeTargetGroups(&elbv2.DescribeTargetGroupsInput{
  477. TargetGroupArns: aws.StringSlice(targetGroupArns),
  478. })
  479. if err != nil {
  480. return nil, err
  481. }
  482. lbarns := []*string{}
  483. for _, tg := range groups.TargetGroups {
  484. lbarns = append(lbarns, tg.LoadBalancerArns...)
  485. }
  486. lbs, err := s.ELB.DescribeLoadBalancersWithContext(ctx, &elbv2.DescribeLoadBalancersInput{
  487. LoadBalancerArns: lbarns,
  488. })
  489. if err != nil {
  490. return nil, err
  491. }
  492. filterLB := func(arn *string, lbs []*elbv2.LoadBalancer) *elbv2.LoadBalancer {
  493. if aws.StringValue(arn) == "" {
  494. // load balancer arn is nil/""
  495. return nil
  496. }
  497. for _, lb := range lbs {
  498. if aws.StringValue(lb.LoadBalancerArn) == aws.StringValue(arn) {
  499. return lb
  500. }
  501. }
  502. return nil
  503. }
  504. loadBalancers := []compose.PortPublisher{}
  505. for _, tg := range groups.TargetGroups {
  506. for _, lbarn := range tg.LoadBalancerArns {
  507. lb := filterLB(lbarn, lbs.LoadBalancers)
  508. if lb == nil {
  509. continue
  510. }
  511. loadBalancers = append(loadBalancers, compose.PortPublisher{
  512. URL: aws.StringValue(lb.DNSName),
  513. TargetPort: int(aws.Int64Value(tg.Port)),
  514. PublishedPort: int(aws.Int64Value(tg.Port)),
  515. Protocol: aws.StringValue(tg.Protocol),
  516. })
  517. }
  518. }
  519. return loadBalancers, nil
  520. }
  521. func (s sdk) ListTasks(ctx context.Context, cluster string, family string) ([]string, error) {
  522. tasks, err := s.ECS.ListTasksWithContext(ctx, &ecs.ListTasksInput{
  523. Cluster: aws.String(cluster),
  524. Family: aws.String(family),
  525. })
  526. if err != nil {
  527. return nil, err
  528. }
  529. arns := []string{}
  530. for _, arn := range tasks.TaskArns {
  531. arns = append(arns, *arn)
  532. }
  533. return arns, nil
  534. }
  535. func (s sdk) GetPublicIPs(ctx context.Context, interfaces ...string) (map[string]string, error) {
  536. desc, err := s.EC2.DescribeNetworkInterfaces(&ec2.DescribeNetworkInterfacesInput{
  537. NetworkInterfaceIds: aws.StringSlice(interfaces),
  538. })
  539. if err != nil {
  540. return nil, err
  541. }
  542. publicIPs := map[string]string{}
  543. for _, interf := range desc.NetworkInterfaces {
  544. if interf.Association != nil {
  545. publicIPs[aws.StringValue(interf.NetworkInterfaceId)] = aws.StringValue(interf.Association.PublicIp)
  546. }
  547. }
  548. return publicIPs, nil
  549. }
  550. func (s sdk) LoadBalancerExists(ctx context.Context, arn string) (bool, error) {
  551. logrus.Debug("CheckRequirements if PortPublisher exists: ", arn)
  552. lbs, err := s.ELB.DescribeLoadBalancersWithContext(ctx, &elbv2.DescribeLoadBalancersInput{
  553. LoadBalancerArns: []*string{aws.String(arn)},
  554. })
  555. if err != nil {
  556. return false, err
  557. }
  558. return len(lbs.LoadBalancers) > 0, nil
  559. }
  560. func (s sdk) GetLoadBalancerURL(ctx context.Context, arn string) (string, error) {
  561. logrus.Debug("Retrieve load balancer URL: ", arn)
  562. lbs, err := s.ELB.DescribeLoadBalancersWithContext(ctx, &elbv2.DescribeLoadBalancersInput{
  563. LoadBalancerArns: []*string{aws.String(arn)},
  564. })
  565. if err != nil {
  566. return "", err
  567. }
  568. dnsName := aws.StringValue(lbs.LoadBalancers[0].DNSName)
  569. if dnsName == "" {
  570. return "", fmt.Errorf("Load balancer %s doesn't have a dns name", aws.StringValue(lbs.LoadBalancers[0].LoadBalancerArn))
  571. }
  572. return dnsName, nil
  573. }