Monday 11 December 2017

Ansible - multiple if else statement or case alternative

Ansible prefer to use when: statement and not have classic implementation of if else or case statement

To use many if statement you can use simple trick.
Example check many variables and depend of this value (if variable is different than empty string '') counting latest occurrence of "not null" value


- name: count number of nic
  vars:
    count_nic: "{{ 5 if NETWORK_5 != '' else '4' if NETWORK_4 != '' else '3' if NETWORK_3 != '' else '2' if NETWORK_2 != '' else '1'}}"
#import playbook based on variable
  include: tasks/nic_{{ count_nic }}.yml
  register: count_nic

Ansible - Restart server and wait until available

Since ansible 2.3 you can use wait_for_connection function to check when host will be available

Example:

- name: Reboot server
  shell: ( sleep 2 && shutdown -r now & )
  async: 1
  poll: 0
  ignore_errors: true

- name: Waiting for host {{ ansible_default_ipv4.address }} after reboot
  wait_for_connection:
    timeout: 300
    delay: 30


This example solve your problem :-)

Ansible "The destination directory (/etc) is not writable"

I've used ansible playbook:

- name: copy resolv.conf
  become: root
  become_method: sudo
  copy:
    src: "resolv.conf"
    dest: "/etc/resolv.conf"
    owner: root
    group: root
    mode: 0644
    force: yes


Error "The destination directory (/etc) is not writable" occur

The problem is with function become - this function require true or false as parameter

Working configuration is  (SOLVED)

- name: copy resolv.conf
  become: yes
  become_method: sudo
  copy:
    src: "resolv.conf"
    dest: "/etc/resolv.conf"
    owner: root
    group: root
    mode: 0644
    force: yes
roles/os_conf_dn