cloudformation.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491
  1. package backend
  2. import (
  3. "fmt"
  4. "regexp"
  5. "strings"
  6. ecsapi "github.com/aws/aws-sdk-go/service/ecs"
  7. "github.com/aws/aws-sdk-go/service/elbv2"
  8. cloudmapapi "github.com/aws/aws-sdk-go/service/servicediscovery"
  9. "github.com/awslabs/goformation/v4/cloudformation"
  10. "github.com/awslabs/goformation/v4/cloudformation/ec2"
  11. "github.com/awslabs/goformation/v4/cloudformation/ecs"
  12. "github.com/awslabs/goformation/v4/cloudformation/elasticloadbalancingv2"
  13. "github.com/awslabs/goformation/v4/cloudformation/iam"
  14. "github.com/awslabs/goformation/v4/cloudformation/logs"
  15. cloudmap "github.com/awslabs/goformation/v4/cloudformation/servicediscovery"
  16. "github.com/awslabs/goformation/v4/cloudformation/tags"
  17. "github.com/compose-spec/compose-go/compatibility"
  18. "github.com/compose-spec/compose-go/errdefs"
  19. "github.com/compose-spec/compose-go/types"
  20. "github.com/docker/ecs-plugin/pkg/compose"
  21. "github.com/sirupsen/logrus"
  22. )
  23. const (
  24. ParameterClusterName = "ParameterClusterName"
  25. ParameterVPCId = "ParameterVPCId"
  26. ParameterSubnet1Id = "ParameterSubnet1Id"
  27. ParameterSubnet2Id = "ParameterSubnet2Id"
  28. ParameterLoadBalancerARN = "ParameterLoadBalancerARN"
  29. )
  30. // Convert a compose project into a CloudFormation template
  31. func (b Backend) Convert(project *types.Project) (*cloudformation.Template, error) {
  32. var checker compatibility.Checker = &FargateCompatibilityChecker{
  33. compatibility.AllowList{
  34. Supported: compatibleComposeAttributes,
  35. },
  36. }
  37. compatibility.Check(project, checker)
  38. for _, err := range checker.Errors() {
  39. if errdefs.IsIncompatibleError(err) {
  40. logrus.Error(err.Error())
  41. } else {
  42. logrus.Warn(err.Error())
  43. }
  44. }
  45. if !compatibility.IsCompatible(checker) {
  46. return nil, fmt.Errorf("compose file is incompatible with Amazon ECS")
  47. }
  48. template := cloudformation.NewTemplate()
  49. template.Parameters[ParameterClusterName] = cloudformation.Parameter{
  50. Type: "String",
  51. Description: "Name of the ECS cluster to deploy to (optional)",
  52. }
  53. template.Parameters[ParameterVPCId] = cloudformation.Parameter{
  54. Type: "AWS::EC2::VPC::Id",
  55. Description: "ID of the VPC",
  56. }
  57. /*
  58. FIXME can't set subnets: Ref("SubnetIds") see https://github.com/awslabs/goformation/issues/282
  59. template.Parameters["SubnetIds"] = cloudformation.Parameter{
  60. Type: "List<AWS::EC2::Subnet::Id>",
  61. Description: "The list of SubnetIds, for at least two Availability Zones in the region in your VPC",
  62. }
  63. */
  64. template.Parameters[ParameterSubnet1Id] = cloudformation.Parameter{
  65. Type: "AWS::EC2::Subnet::Id",
  66. Description: "SubnetId, for Availability Zone 1 in the region in your VPC",
  67. }
  68. template.Parameters[ParameterSubnet2Id] = cloudformation.Parameter{
  69. Type: "AWS::EC2::Subnet::Id",
  70. Description: "SubnetId, for Availability Zone 2 in the region in your VPC",
  71. }
  72. template.Parameters[ParameterLoadBalancerARN] = cloudformation.Parameter{
  73. Type: "String",
  74. Description: "Name of the LoadBalancer to connect to (optional)",
  75. }
  76. // Create Cluster is `ParameterClusterName` parameter is not set
  77. template.Conditions["CreateCluster"] = cloudformation.Equals("", cloudformation.Ref(ParameterClusterName))
  78. cluster := createCluster(project, template)
  79. networks := map[string]string{}
  80. for _, net := range project.Networks {
  81. networks[net.Name] = convertNetwork(project, net, cloudformation.Ref(ParameterVPCId), template)
  82. }
  83. logGroup := fmt.Sprintf("/docker-compose/%s", project.Name)
  84. template.Resources["LogGroup"] = &logs.LogGroup{
  85. LogGroupName: logGroup,
  86. }
  87. // Private DNS namespace will allow DNS name for the services to be <service>.<project>.local
  88. createCloudMap(project, template)
  89. loadBalancerARN := createLoadBalancer(project, template)
  90. for _, service := range project.Services {
  91. definition, err := Convert(project, service)
  92. if err != nil {
  93. return nil, err
  94. }
  95. taskExecutionRole, err := createTaskExecutionRole(service, err, definition, template)
  96. if err != nil {
  97. return template, err
  98. }
  99. definition.ExecutionRoleArn = cloudformation.Ref(taskExecutionRole)
  100. taskDefinition := fmt.Sprintf("%sTaskDefinition", normalizeResourceName(service.Name))
  101. template.Resources[taskDefinition] = definition
  102. var healthCheck *cloudmap.Service_HealthCheckConfig
  103. if service.HealthCheck != nil && !service.HealthCheck.Disable {
  104. // FIXME ECS only support HTTP(s) health checks, while Docker only support CMD
  105. }
  106. serviceRegistry := createServiceRegistry(service, template, healthCheck)
  107. serviceSecurityGroups := []string{}
  108. for net := range service.Networks {
  109. serviceSecurityGroups = append(serviceSecurityGroups, networks[net])
  110. }
  111. dependsOn := []string{}
  112. serviceLB := []ecs.Service_LoadBalancer{}
  113. if len(service.Ports) > 0 {
  114. for _, port := range service.Ports {
  115. protocol := strings.ToUpper(port.Protocol)
  116. if getLoadBalancerType(project) == elbv2.LoadBalancerTypeEnumApplication {
  117. protocol = elbv2.ProtocolEnumHttps
  118. if port.Published == 80 {
  119. protocol = elbv2.ProtocolEnumHttp
  120. }
  121. }
  122. if loadBalancerARN != "" {
  123. targetGroupName := createTargetGroup(project, service, port, template, protocol)
  124. listenerName := createListener(service, port, template, targetGroupName, loadBalancerARN, protocol)
  125. dependsOn = append(dependsOn, listenerName)
  126. serviceLB = append(serviceLB, ecs.Service_LoadBalancer{
  127. ContainerName: service.Name,
  128. ContainerPort: int(port.Target),
  129. TargetGroupArn: cloudformation.Ref(targetGroupName),
  130. })
  131. }
  132. }
  133. }
  134. desiredCount := 1
  135. if service.Deploy != nil && service.Deploy.Replicas != nil {
  136. desiredCount = int(*service.Deploy.Replicas)
  137. }
  138. for _, dependency := range service.DependsOn {
  139. dependsOn = append(dependsOn, serviceResourceName(dependency))
  140. }
  141. template.Resources[serviceResourceName(service.Name)] = &ecs.Service{
  142. AWSCloudFormationDependsOn: dependsOn,
  143. Cluster: cluster,
  144. DesiredCount: desiredCount,
  145. LaunchType: ecsapi.LaunchTypeFargate,
  146. LoadBalancers: serviceLB,
  147. NetworkConfiguration: &ecs.Service_NetworkConfiguration{
  148. AwsvpcConfiguration: &ecs.Service_AwsVpcConfiguration{
  149. AssignPublicIp: ecsapi.AssignPublicIpEnabled,
  150. SecurityGroups: serviceSecurityGroups,
  151. Subnets: []string{
  152. cloudformation.Ref(ParameterSubnet1Id),
  153. cloudformation.Ref(ParameterSubnet2Id),
  154. },
  155. },
  156. },
  157. SchedulingStrategy: ecsapi.SchedulingStrategyReplica,
  158. ServiceRegistries: []ecs.Service_ServiceRegistry{serviceRegistry},
  159. Tags: []tags.Tag{
  160. {
  161. Key: compose.ProjectTag,
  162. Value: project.Name,
  163. },
  164. {
  165. Key: compose.ServiceTag,
  166. Value: service.Name,
  167. },
  168. },
  169. TaskDefinition: cloudformation.Ref(normalizeResourceName(taskDefinition)),
  170. }
  171. }
  172. return template, nil
  173. }
  174. func getLoadBalancerType(project *types.Project) string {
  175. for _, service := range project.Services {
  176. for _, port := range service.Ports {
  177. if port.Published != 80 && port.Published != 443 {
  178. return elbv2.LoadBalancerTypeEnumNetwork
  179. }
  180. }
  181. }
  182. return elbv2.LoadBalancerTypeEnumApplication
  183. }
  184. func getLoadBalancerSecurityGroups(project *types.Project, template *cloudformation.Template) []string {
  185. securityGroups := []string{}
  186. for _, network := range project.Networks {
  187. if !network.Internal {
  188. net := convertNetwork(project, network, cloudformation.Ref(ParameterVPCId), template)
  189. securityGroups = append(securityGroups, net)
  190. }
  191. }
  192. return uniqueStrings(securityGroups)
  193. }
  194. func createLoadBalancer(project *types.Project, template *cloudformation.Template) string {
  195. ports := 0
  196. for _, service := range project.Services {
  197. ports += len(service.Ports)
  198. }
  199. if ports == 0 {
  200. // Project do not expose any port (batch jobs?)
  201. // So no need to create a LoadBalancer
  202. return ""
  203. }
  204. // load balancer names are limited to 32 characters total
  205. loadBalancerName := fmt.Sprintf("%.32s", fmt.Sprintf("%sLoadBalancer", strings.Title(project.Name)))
  206. // Create LoadBalancer if `ParameterLoadBalancerName` is not set
  207. template.Conditions["CreateLoadBalancer"] = cloudformation.Equals("", cloudformation.Ref(ParameterLoadBalancerARN))
  208. loadBalancerType := getLoadBalancerType(project)
  209. securityGroups := []string{}
  210. if loadBalancerType == elbv2.LoadBalancerTypeEnumApplication {
  211. securityGroups = getLoadBalancerSecurityGroups(project, template)
  212. }
  213. template.Resources[loadBalancerName] = &elasticloadbalancingv2.LoadBalancer{
  214. Name: loadBalancerName,
  215. Scheme: elbv2.LoadBalancerSchemeEnumInternetFacing,
  216. SecurityGroups: securityGroups,
  217. Subnets: []string{
  218. cloudformation.Ref(ParameterSubnet1Id),
  219. cloudformation.Ref(ParameterSubnet2Id),
  220. },
  221. Tags: []tags.Tag{
  222. {
  223. Key: compose.ProjectTag,
  224. Value: project.Name,
  225. },
  226. },
  227. Type: loadBalancerType,
  228. AWSCloudFormationCondition: "CreateLoadBalancer",
  229. }
  230. return cloudformation.If("CreateLoadBalancer", cloudformation.Ref(loadBalancerName), cloudformation.Ref(ParameterLoadBalancerARN))
  231. }
  232. func createListener(service types.ServiceConfig, port types.ServicePortConfig, template *cloudformation.Template, targetGroupName string, loadBalancerARN string, protocol string) string {
  233. listenerName := fmt.Sprintf(
  234. "%s%s%dListener",
  235. normalizeResourceName(service.Name),
  236. strings.ToUpper(port.Protocol),
  237. port.Target,
  238. )
  239. //add listener to dependsOn
  240. //https://stackoverflow.com/questions/53971873/the-target-group-does-not-have-an-associated-load-balancer
  241. template.Resources[listenerName] = &elasticloadbalancingv2.Listener{
  242. DefaultActions: []elasticloadbalancingv2.Listener_Action{
  243. {
  244. ForwardConfig: &elasticloadbalancingv2.Listener_ForwardConfig{
  245. TargetGroups: []elasticloadbalancingv2.Listener_TargetGroupTuple{
  246. {
  247. TargetGroupArn: cloudformation.Ref(targetGroupName),
  248. },
  249. },
  250. },
  251. Type: elbv2.ActionTypeEnumForward,
  252. },
  253. },
  254. LoadBalancerArn: loadBalancerARN,
  255. Protocol: protocol,
  256. Port: int(port.Target),
  257. }
  258. return listenerName
  259. }
  260. func createTargetGroup(project *types.Project, service types.ServiceConfig, port types.ServicePortConfig, template *cloudformation.Template, protocol string) string {
  261. targetGroupName := fmt.Sprintf(
  262. "%s%s%dTargetGroup",
  263. normalizeResourceName(service.Name),
  264. strings.ToUpper(port.Protocol),
  265. port.Published,
  266. )
  267. template.Resources[targetGroupName] = &elasticloadbalancingv2.TargetGroup{
  268. Name: targetGroupName,
  269. Port: int(port.Target),
  270. Protocol: protocol,
  271. Tags: []tags.Tag{
  272. {
  273. Key: compose.ProjectTag,
  274. Value: project.Name,
  275. },
  276. },
  277. VpcId: cloudformation.Ref(ParameterVPCId),
  278. TargetType: elbv2.TargetTypeEnumIp,
  279. }
  280. return targetGroupName
  281. }
  282. func createServiceRegistry(service types.ServiceConfig, template *cloudformation.Template, healthCheck *cloudmap.Service_HealthCheckConfig) ecs.Service_ServiceRegistry {
  283. serviceRegistration := fmt.Sprintf("%sServiceDiscoveryEntry", normalizeResourceName(service.Name))
  284. serviceRegistry := ecs.Service_ServiceRegistry{
  285. RegistryArn: cloudformation.GetAtt(serviceRegistration, "Arn"),
  286. }
  287. template.Resources[serviceRegistration] = &cloudmap.Service{
  288. Description: fmt.Sprintf("%q service discovery entry in Cloud Map", service.Name),
  289. HealthCheckConfig: healthCheck,
  290. HealthCheckCustomConfig: &cloudmap.Service_HealthCheckCustomConfig{
  291. FailureThreshold: 1,
  292. },
  293. Name: service.Name,
  294. NamespaceId: cloudformation.Ref("CloudMap"),
  295. DnsConfig: &cloudmap.Service_DnsConfig{
  296. DnsRecords: []cloudmap.Service_DnsRecord{
  297. {
  298. TTL: 60,
  299. Type: cloudmapapi.RecordTypeA,
  300. },
  301. },
  302. RoutingPolicy: cloudmapapi.RoutingPolicyMultivalue,
  303. },
  304. }
  305. return serviceRegistry
  306. }
  307. func createTaskExecutionRole(service types.ServiceConfig, err error, definition *ecs.TaskDefinition, template *cloudformation.Template) (string, error) {
  308. taskExecutionRole := fmt.Sprintf("%sTaskExecutionRole", normalizeResourceName(service.Name))
  309. policy, err := getPolicy(definition)
  310. if err != nil {
  311. return taskExecutionRole, err
  312. }
  313. rolePolicies := []iam.Role_Policy{}
  314. if policy != nil {
  315. rolePolicies = append(rolePolicies, iam.Role_Policy{
  316. PolicyDocument: policy,
  317. PolicyName: fmt.Sprintf("%sGrantAccessToSecrets", service.Name),
  318. })
  319. }
  320. template.Resources[taskExecutionRole] = &iam.Role{
  321. AssumeRolePolicyDocument: assumeRolePolicyDocument,
  322. Policies: rolePolicies,
  323. ManagedPolicyArns: []string{
  324. ECSTaskExecutionPolicy,
  325. ECRReadOnlyPolicy,
  326. },
  327. }
  328. return taskExecutionRole, nil
  329. }
  330. func createCluster(project *types.Project, template *cloudformation.Template) string {
  331. template.Resources["Cluster"] = &ecs.Cluster{
  332. ClusterName: project.Name,
  333. Tags: []tags.Tag{
  334. {
  335. Key: compose.ProjectTag,
  336. Value: project.Name,
  337. },
  338. },
  339. AWSCloudFormationCondition: "CreateCluster",
  340. }
  341. cluster := cloudformation.If("CreateCluster", cloudformation.Ref("Cluster"), cloudformation.Ref(ParameterClusterName))
  342. return cluster
  343. }
  344. func createCloudMap(project *types.Project, template *cloudformation.Template) {
  345. template.Resources["CloudMap"] = &cloudmap.PrivateDnsNamespace{
  346. Description: fmt.Sprintf("Service Map for Docker Compose project %s", project.Name),
  347. Name: fmt.Sprintf("%s.local", project.Name),
  348. Vpc: cloudformation.Ref(ParameterVPCId),
  349. }
  350. }
  351. func convertNetwork(project *types.Project, net types.NetworkConfig, vpc string, template *cloudformation.Template) string {
  352. if sg, ok := net.Extensions[compose.ExtensionSecurityGroup]; ok {
  353. logrus.Debugf("Security Group for network %q set by user to %q", net.Name, sg)
  354. return sg.(string)
  355. }
  356. var ingresses []ec2.SecurityGroup_Ingress
  357. if !net.Internal {
  358. for _, service := range project.Services {
  359. if _, ok := service.Networks[net.Name]; ok {
  360. for _, port := range service.Ports {
  361. ingresses = append(ingresses, ec2.SecurityGroup_Ingress{
  362. CidrIp: "0.0.0.0/0",
  363. Description: fmt.Sprintf("%s:%d/%s", service.Name, port.Target, port.Protocol),
  364. FromPort: int(port.Target),
  365. IpProtocol: strings.ToUpper(port.Protocol),
  366. ToPort: int(port.Target),
  367. })
  368. }
  369. }
  370. }
  371. }
  372. securityGroup := networkResourceName(project, net.Name)
  373. template.Resources[securityGroup] = &ec2.SecurityGroup{
  374. GroupDescription: fmt.Sprintf("%s %s Security Group", project.Name, net.Name),
  375. GroupName: securityGroup,
  376. SecurityGroupIngress: ingresses,
  377. VpcId: vpc,
  378. Tags: []tags.Tag{
  379. {
  380. Key: compose.ProjectTag,
  381. Value: project.Name,
  382. },
  383. {
  384. Key: compose.NetworkTag,
  385. Value: net.Name,
  386. },
  387. },
  388. }
  389. ingress := securityGroup + "Ingress"
  390. template.Resources[ingress] = &ec2.SecurityGroupIngress{
  391. Description: fmt.Sprintf("Allow communication within network %s", net.Name),
  392. IpProtocol: "-1", // all protocols
  393. GroupId: cloudformation.Ref(securityGroup),
  394. SourceSecurityGroupId: cloudformation.Ref(securityGroup),
  395. }
  396. return cloudformation.Ref(securityGroup)
  397. }
  398. func networkResourceName(project *types.Project, network string) string {
  399. return fmt.Sprintf("%s%sNetwork", normalizeResourceName(project.Name), normalizeResourceName(network))
  400. }
  401. func serviceResourceName(dependency string) string {
  402. return fmt.Sprintf("%sService", normalizeResourceName(dependency))
  403. }
  404. func normalizeResourceName(s string) string {
  405. return strings.Title(regexp.MustCompile("[^a-zA-Z0-9]+").ReplaceAllString(s, ""))
  406. }
  407. func getPolicy(taskDef *ecs.TaskDefinition) (*PolicyDocument, error) {
  408. arns := []string{}
  409. for _, container := range taskDef.ContainerDefinitions {
  410. if container.RepositoryCredentials != nil {
  411. arns = append(arns, container.RepositoryCredentials.CredentialsParameter)
  412. }
  413. if len(container.Secrets) > 0 {
  414. for _, s := range container.Secrets {
  415. arns = append(arns, s.ValueFrom)
  416. }
  417. }
  418. }
  419. if len(arns) > 0 {
  420. return &PolicyDocument{
  421. Statement: []PolicyStatement{
  422. {
  423. Effect: "Allow",
  424. Action: []string{ActionGetSecretValue, ActionGetParameters, ActionDecrypt},
  425. Resource: arns,
  426. }},
  427. }, nil
  428. }
  429. return nil, nil
  430. }
  431. func uniqueStrings(items []string) []string {
  432. keys := make(map[string]bool)
  433. unique := []string{}
  434. for _, item := range items {
  435. if _, val := keys[item]; !val {
  436. keys[item] = true
  437. unique = append(unique, item)
  438. }
  439. }
  440. return unique
  441. }