Pandu_jh
(Pandu jh)
February 19, 2019, 2:41pm
1
Search keyword in “host_fqdn” variable. If the value has “lab.com ” keyword in it, it should directly store the value to “host_fqdn” again
or else it should add “lab.com ” keyword to the value and store it to “host_fqdn” variable. Please assist.
vars:
host_fqdn: server
host_fqdn: |
{% if ‘lab.com ’ in {{ host_fqdn }} %}
{% host_fqdn = “{{ host_fqdn }}” %}
{% else %}
{% host_fqdn = “{{ host_fqdn }}.lab.com” %}
{% endif %}
I'm pretty sure you can't use Jinja in vars like that, but you can have a set_fact task like this
- set_fact:
host_fqdn: "{{ host_fqdn if 'lab.com' in host_fqdn else host_fqdn ~ '.lab.com' }}"
Pandu_jh
(Pandu jh)
February 19, 2019, 3:49pm
3
Can you please confirm, if the below syntax is correct. I am getting error.
vars_prompt:
name: host_fqdn
prompt: Enter Hostname of a new VM
private: no
tasks:
set_fact:
host_fqdn: “{{ host_fqdn if ‘lab.com ’ in host_fqdn else host_fqdn ‘.lab.com’ }}”
debug: var=host_fqdn
What is the error then? We are not psychic.
Pandu_jh
(Pandu jh)
February 19, 2019, 3:57pm
5
This was the error.
TASK [set_fact] ****************************************************************************************************************************************
fatal: [rchtest01]: FAILED! => {“msg”: “template error while templating string: expected token ‘end of print statement’, got ‘string’. String: {{ host_fqdn if ‘lab.com ’ in host_fqdn else host_fqdn ‘.lab.com’ }}”}
You are missing the tilde ~ in you syntax, check my previous mail and you'll see the tilde.
Pandu_jh
(Pandu jh)
February 19, 2019, 4:06pm
7
Sorry my bad, it missed it. it’s working perfectly now, Thanks much !!
TASK [debug] *******************************************************************************************************************************************
ok: [rchtest01] => {
“host_fqdn”: “rchtest01.lab.com ”
}
Pandu_jh
(Pandu jh)
February 19, 2019, 4:07pm
8
If possible could you please explain the syntax, It will be very helpful for me to use it in other cases.
I could try, not sure if it's understandable
Just split it in multiple lines
[1] {{ host_fqdn
[2] if 'lab.com' in host_fqdn
[3] else
[4] host_fqdn ~ '.lab.com' }}
[2]
If the variable host_fqdn contains the string lab.com the choose [1].
[3]
If the variable host_fqdn dosen't contains the string lab.com the choose [4]
[4]
Tilde is used to concatenate two strings.
So this will concatenate the content of variable fqdn_host with the string .lab.com
You can also use the Ansible ternary filter
{{ ('lab.com' in host_fqdn) | ternary(host_fqdn, host_fqdn ~ '.lab.com') }}
Pandu_jh
(Pandu jh)
February 19, 2019, 4:51pm
10
Thank you so much for the explanation.