Chris
Chris

Reputation: 1019

ansible variable basing on hostname's suffix

I need to create a user on a system depending on it's function (test or production) Test systems are named with suffix -tXX while prod ones are with -pXX (where XX is two digits numbering).

in variable file I have set:

auser: "{{ 'usertest' if {{ ansible_hostname|lower }} | regex_search('t[0-9]{2}$') else 'userprod' }}"

the error I get is during playbook run is:

fatal: [192.168.1.10]: FAILED! => {"msg": "An unhandled exception occurred while templating '{{ 'usertest' if {{ ansible_hostname|lower }} | regex_search('t[0-9]{2}$') else 'userprod' }}'. Error was a <class 'ansible.errors.AnsibleError'>, original message: template error while templating string: expected token ':', got '}'. String: {{ 'usertest' if {{ ansible_hostname|lower }} | regex_search('t[0-9]{2}$') else 'userprod' }}"}

Complete playbook is:

---
- hosts: testgrp
  become: yes
  vars:
     - auser: "{{ 'usertest' if {{ ansible_hostname|lower }} | regex_search('t[0-9]{2}$') else 'userprod' }}"

  tasks:
  - name: Add groups
    group:
     name: "{{ item.name }}"
     gid: "{{ item.gid }}"
     state: present
    loop:
     - { name: 'group1', gid: '1101' }
     - { name: 'group2', gid: '1102' }
     - { name: 'group3', gid: '1103' }

  - name: Add users
    user:
     name: "{{ item.name }}"
     group: "{{ item.group }}"
     groups: "{{ item.groups }}"
     state: present
    loop:
     - { name: "{{ auser }}", group: 'group1', groups: 'group2,group3', uid: '1101' }

Upvotes: 1

Views: 360

Answers (1)

Vladimir Botka
Vladimir Botka

Reputation: 67959

For example

- hosts: srv-t01,srv-p01
  gather_facts: false
  vars:
    auser: "{{ inventory_hostname | lower is match('^.*-t[0-9]{2}$') |
               ternary('usertest', 'userprod') }}"
  tasks:
    - debug:
        var: auser

gives

ok: [srv-t01] => 
  auser: usertest
ok: [srv-p01] => 
  auser: userprod

A more robust solution is to select an index, e.g. the play below gives the same result

- hosts: srv-t01,srv-p01
  gather_facts: false
  vars:
    auser_dict:
      t: usertest
      p: userprod
    aindex: "{{ inventory_hostname | lower |
                regex_replace('^.*-(.+)[0-9]{2}$', '\\1') }}"
    auser: "{{ auser_dict[aindex] }}"
  tasks:
    - debug:
        var: auser

Upvotes: 1

Related Questions