checking group membership in Ansible templates

I use SolusVM as a virtualization solution, mainly because it’s pretty cheap and mostly effective. The new web-managed migration feature requires that the master node have SSH access into the slave nodes. As root. (Insert lots of swearing here.)

This isn’t a problem, except that I centrally manage my OpenSSH configuration with Ansible. I don’t want all of my hosts to permit the master SolusVM node to log in as root; I only want the Solus hosts to get that setting, and even then only from the master node’s IP address.

The good news is, I have an Ansible group defined for SolusVM hosts. I must modify my template so that it checks if the host is in this group. Ansible provides two variables for the host name, ansible_fqdn (fully qualified name) and ansible_hostname (short hostname). Use the one that reflects your inventory file.

{% if ansible_fqdn in groups['solus-hw'] %}
#solus needs root login from master node
Match Address 192.0.2.12
PermitRootLogin without-password
{% endif %}

As this is a Match statement, it goes at the end of your configuration. My complete sshd_config.j2 looks like this:

#{{ ansible_managed }}
Protocol 2
ListenAddress {{ ansible_ssh_host }}
X11Forwarding yes
PubkeyAuthentication yes
AuthorizedKeysFile /etc/ssh/authorized_keys/%u
PermitRootLogin no
PasswordAuthentication no
ChallengeResponseAuthentication no
{% if ansible_system == 'OpenBSD' %}
#no PAM on OpenBSD
{% else %}
UsePAM yes
{% endif %}
Subsystem sftp {{ program_sftp_server }}
{% if ansible_fqdn in groups['solus'] %}
#solus needs root login from master node
Match Address 192.0.2.12
PermitRootLogin without-password
{% endif %}

Do a push, and done. On to the next problem!

3 Replies to “checking group membership in Ansible templates”

  1. Hi Michael

    I have been googling a lot to do some task like you propose. I just want to centrally manage the crontab of servers then I am in a similar situation. My issue is I don’t know how to approach this tasks. For example, two servers, each of one needs diferents crontab or cron.d files. How do you writes the playbook? I think maybe the solution can be have some cron.d file as template but I am not sure.

    You, as expert in ansible what do you recommend to me?

    Thanks

  2. Rubén, I would use a file template just like I used for SSH. But there’s probably a better way to do it. Definitely ask the ansible mailing list, lots of smart people there.

  3. Ansible deals very well with this kind of variation. If-thens in your template is one way; another solution would be something like template: src={{ cron_variant }}.cron.d dest=/path/to/crons. Then use group_vars or host_vars to define the cron_variant prefix for each of your hosts.

Comments are closed.