EE port of: https://gitlab.com/gitlab-org/gitlab-ce/merge_requests/24806
Related issue https://gitlab.com/gitlab-org/gitlab-ce/issues/56851