Replace a network_name for a VM using var file?

Hi,

I need to change network_name for vm servers in vmware.

I have a file named vlan.yml contain:

vlan:
“name1” : “name2”
“name3” : “name4”

On my playbook I use the following code

  • name: Include vars of vlan.yaml into the ‘vlan’
    ansible.builtin.include_vars:
    file: vlan.yml
    name: vlan

  • name: Change Network Vlan
    community.vmware.vmware_guest_network:
    hostname: “----”
    username: “----”
    password: “----”
    datacenter: “----”
    folder: “/----/”
    validate_certs: no
    name: “-----”
    networks:
    - state: present
    label: “Network adapter 1”
    network_name: “{{ vlan.vlan.[network_info[0].name] }}”
    delegate_to: localhost

I would like: if the network_name is “name1” become “name2” - if it’s “name3” become “name4”.

Thank you for your help,

Ham

Hi
You should use conditionals for your task like a when:
to execute your task “when” the condition is true.

In your case, i’d use a when: on network name, and so, if network name is network 1 so my task will update it with value network2 as wanted.

2nd solution if you’re able to retrieve facts (i assume vmware collection does) so maybe you can use a when: on a specific facts (i.e : network name : XXX)

the idea was to have source and target in a file because I have more thant 60 vlan to migrate.

I’ll try the ‘when’ command…

Thanks

Ham

If you put your code in a “tripple-back-tick” block, it would be much easier to read.

- name: Include vars of vlan.yaml into the 'vlan'
  ansible.builtin.include_vars:
    file: vlan.yml
    name: vlan

- name: Change Network Vlan
  community.vmware.vmware_guest_network:
    hostname: "----"
    username: "----"
    password: "----"
    datacenter: "----"
    folder: "/----/"
    validate_certs: no
    name: "-----"
    networks:
      - state: present
        label: "Network adapter 1"
        network_name: "{{ vlan.vlan.[network_info[0].name] }}"
  delegate_to: localhost

So, presumably network_info[0].name is only one of about 60 you need to operate on. Do you have all these in some data structure you can loop over?

1 Like

For a VLAN migration, it’s maybe easier to do it through PowerCLI, especially if you have to correlate old_vlan => new vlan if you got a lot.

Or as @utoddl said, to loop over within your ansible task.

Both works.

2 Likes

I agree. Ansible works best if you use it as an infastructure-as-code tool (which it basically is). I also prefer PowerCLI for things that I want do do once, like migrating VMs to another portgroup or similar.

Besides, I think ansible isn’t well suited for any if-then-else logic. You can implement it somehow, but it usually feels wrong to me if I do.

2 Likes