Search code examples
variablesfilteransibleconditional-statements

How to switch a word to a variable in when condition


I'm using Ansible roles for create some VMs on vCenter.

My role works well, but I would like to make more dynamic playbooks.

In my sitation, I have vars/main.yml with this vars :

foldervm: /datacenter/vm/PROD/

vm1: thisismyfirstvm
vm2: thisismysecondvm
vm3: thisismythirdvm
vm4: thisismyfourthvm

array:
  - name: "{{ vm1 }}"
    cpu: 3
    memory: 84992
  - name: "{{ vm2 }}"
    cpu: 10
    memory: 20480
  - name: "{{ vm3 }}"
    cpu: 4
    memory: 8192
  - name: "{{ vm4 }}"
    cpu: 8
    memory: 65536

And a tasks/createlvmpart.yml like that :

- name: parted /dev/sdc
  vmware_vm_shell:

    hostname: "{{ ip_vcenter }}"
    username: "{{ username_vcenter }}"
    password: "{{ password_vcenter }}"
    datacenter: "{{ datacenter_name }}"
    validate_certs: no

    folder: "{{ foldervm }}"
    vm_id: "{{ item.name }}"
    vm_username: "{{ id }}"
    vm_password: "{{ pass }}"
    
    vm_shell: /usr/sbin/parted
    vm_shell_args: "-s /dev/sdc unit GB mkpart primary 50% 100% set 2 lvm on"

  with_items:
    - "{{ array }}"
  

  when: 
    - not item.name is search("thismysecond")
    - item.name != 'vm3'

My problem is in when condition. I would like to make like this line:

  when: not item.name is search("thismysecond")

but the word "thismysecond" is replace to his variable : "{{ vm2 }}".

I have tested this:

  when: not item.name is search("{{ vm2 }}")

and this:

  when: item.name != 'vm2'

But it doesn't work. My playbook don't apply the parted command on vm2, just for vm1, vm3 and vm4.

I have searched on the internet, but I think I formulated the question not well in my research because I didn't find the answer.

Do you have some suggestions?


Solution

  • Thank you @Mark Rotteveel for your correction (Sorry for my bad English :( )

    And thank you @β.εηοιτ.βε for your answer.

    It's just problem of syntax, it's not:

    when: item.name != 'vm2'

    But it's:

    when: item.name != vm2

    It's works like a charm now!