Jump to content

Ansible case statement examples ?


bhaigan

Recommended Posts

https://docs.ansible.com/ansible/latest/user_guide/playbooks_conditionals.html

 

when ansible talks to a server, ansible gather information called ansible_facts of that server like OS type (Debian, Centos etc), version (7,8 etc), ip etc.

Based on this information you can use conditional statements.

tasks:
  - name: "shut down Debian flavored systems"
    command: /sbin/shutdown -t now
    when: ansible_facts['os_family'] == "Debian"
    # note that all variables can be used directly in conditionals without double curly braces

Variables defined in the playbooks or inventory can also be used, which means you define a variable in the playbook and use it in conditional statements

vars:
  epic: true
  monumental: "yes"

tasks:
    - shell: echo "This certainly isn't epic!"
      when: not epic

 

tasks:
    - command: echo {{ item }}
      loop: [ 0, 2, 4, 6, 8, 10 ]
      when: item > 5

it will print only 6, 8, 10

 

Link to comment
Share on other sites

1 hour ago, bhaigan said:

Anybody know

@Spartan throw some light regarding examples

same like if/when condition in general programming language...

u plan to run certain configuration rule, when the Condition defined in the case matches..

it may vary from OS type to, String matching etc....

paina Kumar uncle vesina example is one of them...

 

usecase:  you write one runbook for all Linux flavors, but want to omit or mandatorily run some configs on certain flavors, in that case u use these conditional stmts..

  • Upvote 1
Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...