Default value on mappings AWS CloudFormation

Viewed 11424

What would be a good strategy to have a default value on mappings?

I.E.

I have a parameter called country

Based on that country I reference a DNS using mappings

"Mappings" : {
   "DNS":{
     "us" : {"dns" : "mypage.us.com", "ttl" : "600"},
     "mx" : {"dns" : "mypage.default.com", "ttl" : "300"},
     "ar" : {"dns" : "mypage.default.com", "ttl" : "300"},
     "br" : {"dns" : "mypage.default.com", "ttl" : "300"}
   }
}

If us it's been mapped:

{ "Fn::FindInMap" : [ "DNS", { "Ref" : "country" }, "dns" ]}

I get "mypage.us.com" for the other countries I've created a huge list of countries with a default value mypage.default.com, in the future, this values will be changing and we will be adding more countries, is there a better approach to this?

4 Answers

To elaborate on Steve Smith's answer.

Cloudformation always expects a valid mapping, even behind a missed logic gate.

You can combine !Sub and !If for a fair amount of flexibility though.

For example, we do this for dynamic staging ECS Env vars:

Parameters:

  Env:
    Type: String

  Branch:
    Type: String

  DevelopUrl:
    Type: String
    Default: "develop.example.com"

  MasterUrl:
    Type: String
    Default: "master.example.com"

  ...(ECS Resource)
          Environment:
            
            - !If
              - IsStaging
              - Name: SOME_CALLBACK_URL
                Value: !Sub
                  - "https://${Url}/some-callback-endpoint"
                  - Url: !If [ IsDevelop, !Ref DevelopUrl, !If [ IsMaster, !Ref MasterUrl, !GetAtt MyLoadBalancer.DNSName ] ]
              - !Ref "AWS::NoValue"

In your mapping, add a default entry:

"Mappings" : {
   "DNS":{
     "us" : {"dns" : "mypage.us.com", "ttl" : "600"},
     "mx" : {"dns" : "mypage.mx.com", "ttl" : "300"},
     "default" : {"dns" : "mypage.default.com", "ttl" : "300"}
   }
}

Then create a condition (YAML):

Conditions:
  HasSpecialDNS: !Or:
    - !Equals [!Ref country, "us"]
    - !Equals [!Ref country, "mx"]

Then change the 2nd parameter of FindInMap to:

{ "Fn::FindInMap" : [ "DNS", { "Fn::If": ["HasSpecialDNS", {"Ref" : "country"}, "default" ]}, "dns" ]}

Or YAML:

Fn::FindInMap:
  - DNS
  - !If ["HasSpecialDNS", !Ref country, "default" ]
  - "dns"
Related