If you're using Ansible and want to set a setuid or setgid bit on a file or directory, you don't need any additional tricks like executing raw shell commands. A lesser known feature of the numeric chmod syntax (e.g. chmod 750 mydir) is that you can also pass in four digits instead of three, where the first digit controls the suid, sgid and sticky attributes.
From man chmod:
A numeric mode is from one to four octal digits (0-7), derived by adding up the bits with values 4, 2, and 1. Omitted digits are assumed to be leading zeros. The first digit selects the set user ID (4) and set group ID (2) and restricted deletion or sticky (1) attributes. The second digit selects permissions for the user who owns the file: read (4), write (2), and execute (1); the third selects permissions for other users in the file's group, with the same values; and the fourth for other users not in the file's group, with the same values.
So to set the setgid bit on a directory, simply use 2 as the first of the four digits in the mode parameter of the file module.
- name: Create the log directory with setgid bit.
file:
path: /var/log/mydir
owner: user
group: adm
state: directory
mode: 02750
(Update 2019-06-06: Fixed mode to ensure that it's parsed as an octal number)