cloudformation.go 15 KB

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