marshall.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. /*
  2. Copyright 2020 Docker Compose CLI authors
  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. "encoding/json"
  16. "fmt"
  17. "strings"
  18. "github.com/awslabs/goformation/v4/cloudformation"
  19. "github.com/sanathkr/go-yaml"
  20. )
  21. func marshall(template *cloudformation.Template, format string) ([]byte, error) {
  22. var (
  23. source func() ([]byte, error)
  24. marshal func(in interface{}) ([]byte, error)
  25. unmarshal func(in []byte, out interface{}) error
  26. )
  27. switch format {
  28. case "yaml":
  29. source = template.YAML
  30. marshal = yaml.Marshal
  31. unmarshal = yaml.Unmarshal
  32. case "json":
  33. source = template.JSON
  34. marshal = func(in interface{}) ([]byte, error) {
  35. return json.MarshalIndent(in, "", " ")
  36. }
  37. unmarshal = json.Unmarshal
  38. default:
  39. return nil, fmt.Errorf("unsupported format %q", format)
  40. }
  41. raw, err := source()
  42. if err != nil {
  43. return nil, err
  44. }
  45. var unmarshalled interface{}
  46. if err := unmarshal(raw, &unmarshalled); err != nil {
  47. return nil, fmt.Errorf("invalid JSON: %s", err)
  48. }
  49. if input, ok := unmarshalled.(map[interface{}]interface{}); ok {
  50. if resources, ok := input["Resources"]; ok {
  51. for _, uresource := range resources.(map[interface{}]interface{}) {
  52. if resource, ok := uresource.(map[interface{}]interface{}); ok {
  53. if resource["Type"] == "AWS::ECS::TaskDefinition" {
  54. properties := resource["Properties"].(map[interface{}]interface{})
  55. for _, def := range properties["ContainerDefinitions"].([]interface{}) {
  56. containerDefinition := def.(map[interface{}]interface{})
  57. if strings.HasSuffix(containerDefinition["Name"].(string), "_InitContainer") {
  58. containerDefinition["Essential"] = false
  59. }
  60. }
  61. }
  62. }
  63. }
  64. }
  65. }
  66. return marshal(unmarshalled)
  67. }