NKR NKR - 3 months ago 11
Bash Question

Automation of networks using ansible on openstack

I've written an ansible script, to create a network based on a condition. So that, even if I run ansible script again it will not create duplicate entries in my openstack environment.

task:

name: "create network"

shell: neutron net-create (openstack details like project username,password, api) network_1

when: ("neutron net-list -c name| grep network_1| awk '{print$2}'" == "null")
the above condition didn't work so, I tried another condition

when: ("neutron net-list -c name| grep network_1| awk '{print$2}'" == neutron net-list -c name| grep network_2 | awk '{print$2}')


I don't have either of the twonetworks in my project. My intention was, both the statments display null output and firsttime condition becomes true and it should execute and create a network. If I run the script for second time it not satify condition and condition check becomes false and network will not be created.

But both the conditions skipped and returned false saying condition check failed.

Answer

Your when condition needs to be something that Ansible will recognise and not just a shell command that you haven't told it how to execute.

In this case you could do something like this:

- name: check for network_1    
  shell: "neutron net-list -c name| grep network_1| awk '{print$2}'"    
  register: network_1

- name: "create network"    
  shell: neutron net-create (openstack details like project username,password, api) network_1    
  when: network_1.stdout == "null"

That's presuming that when you run neutron net-list -c name| grep network_1| awk '{print$2}' when network_1 doesn't exist it returns null (I haven't used OpenStack much so not sure if this is in fact true).

In general though, with Ansible you should only be shelling out if you absolutely need to because then you need to do things like above where you need to check for existence of resources and manage idempotency which should be covered for you by any decent module. In this case you should be able to use os_network to create your network if it doesn't already exist:

- os_network:
    cloud: mycloud
    state: present
    name: network_1
    external: false

It will also happily pick up environment variables such as OS_USERNAME on the host running Ansible so you can avoid putting credentials in to your Ansible code.

Comments