Don’t use a cable like the one shown above! These do not contain the required licensed Thunderbolt chips (inside the connectors) to support Thunderbolt protocol. While they will work for a connection to a DisplayPort only monitor input, they will not support a Thunderbolt Display or iMac in Target Display Mode.
You need a cable that looks like the one below that shows a Thunderbolt Logo on each connector indicating it’s compatibility. I recommend the 2m cable, the 0.5 is too short unless you are comfortable leaving your MacBook closed under your iMac.
If your MacBook Pro only has USB type C ports you’ll need to check which of those ports support Thunderbolt 3 and use Thunderbolt 3 to Thunderbolt 2 converter from Apple with a Thunderbolt 2 male-to-male cable to connect it to your iMac.
Here's an picture of the Thunderbolt 2 converter from Apple that'll do the trick.
Also check your MacBook's specs, and be sure to use the Thunderbolt ports, some are only USB C and it can be hard to tell.