Different values based on provider.stage (for CustomDomain)

Following this blog post and a few other google searches, I have managed to get a domain set up for my API Gateway.

However I need a different domain depending on the Stage. In the development environment I want dev.example.com whereas in production, just example.com. There seems to be an Fn::if that might help, but I can’t work out how to create the conditional.

Has anyone done anything similar? It doesn’t have to just be with CustomDomain of course, any examples of changing a parameter depending on the stage would be great.

I have found an answer on StackOverflow. Repeating it here in case anyone else needs it (and yes, this should work for any config, not just CustomDomain)

custom:
  domain:
    dev: MY_DEV_DOMAIN
    prod: MY_PROD_DOMAIN
  customDomain:
    basePath: ''
    domainName:  ${self:custom.domain.${opt:stage}}
    stage: ${opt:stage}
    createRoute53Record: true