calsaint
calsaint

Reputation: 93

ansbile: conditionally split a string

Trying to extract first part of dot separated string which may or may not have the second part after dot. Dot would exist only if the second part exits in the strning.

This is what I tried. if bugid variable has two parts with dot separation, this works fine. I am trying to make this work even when I don't have the second part ie., abcd1234. Thought default would work but it did not do the trick.

---
- hosts: localhost
  vars:
    bugid: 12345678.abcd1234
    #bugid: 12345678

  tasks:
    - name: "Extract first part."
      set_fact:
        bug_name: "{{ bugid.split('.')[0]| default('default_value') }}"
    - name: "Return bug id."
      debug:
        var: bug_name

When I run this with bugid: 1235678.abcd1234 it gives the following:

TASK [Extract first part.] ***********************************************************************************************************************************************************
ok: [localhost]

TASK [Return bug id.] ****************************************************************************************************************************************************************
ok: [localhost] => {
    "bug_name": "12345678"
}

When I run bugid: 12345678, I get the following:


TASK [Extract first part.] ***********************************************************************************************************************************************************
fatal: [localhost]: FAILED! => {}

MSG:

The task includes an option with an undefined variable. The error was: 'int object' has no attribute 'split'

The error appears to be in '/oracle/ansible/epd1/s1.yml': line 8, column 7, but may
be elsewhere in the file depending on the exact syntax problem.

The offending line appears to be:

  tasks:
    - name: "Extract first part."
      ^ here

Upvotes: 0

Views: 633

Answers (1)

Uttam
Uttam

Reputation: 596

First, it is complaining the error is 'int object' has no attribute 'split'. To handle that you convert the bugid to string object by passing it to string().

Secondly, you basically don't need to set a default. The split returns the whole string if the delimiter is not present.

For example,

"testid".split('.')[0] returns "testid"

"testid.afterdot".split('.')[0] returns "testid"


- hosts: localhost
  vars:
    bugid: 12345678.abcd1234
    #bugid: 12345678

  tasks:
    - name: "Extract first part."
      set_fact:
        bug_name: "{{ (bugid|string()).split('.')[0] }}"
    - name: "Return bug id."
      debug:
        var: bug_name

Upvotes: 0

Related Questions