Conditions in vars with Ansible task



  • - roles
      - consul
        - vars/main.yml
    

    main.yml Use:

    consul_is_server: {{ true if consul_server is defined else false }}
    

    playbook:

    - hosts: consul-server
    roles:
    - consul
    vars:
    consul_server: true

    Mistake:

    consul_is_server: {{ "true" if consul_server is defined else "false" }}
    ^
    We could be wrong, but this one looks like it might be an issue with
    missing quotes. Always quote template expression brackets when they
    start a value. For instance:

    with_items:
      - {{ foo }}
    

    Should be written as:

    with_items:
      - "{{ foo }}"
    

    I did this:

    consul_is_server:  >
    {{ true if consul_server is defined and consul_server==true else false }}

    But then consul_is_server "False" or "True."
    And then there's a stitch in the templates. bool:

    "server": {{ "true" if consul_is_server |bool else "false" }}

    We could do something. vars I want you to write a test of the conditions so you don't have to castle in the hat?



  • Use it. ternary

    Documentation: http://docs.ansible.com/playbooks_filters.html

    Example:

    ---
    # https://ru.stackoverflow.com/questions/470202/
    
    • name: https://ru.stackoverflow.com/questions/470202/
      hosts: test
      vars:
      str1: "asdf1"
      str2: "asdf2"
      cond1: True
      cond2: False
      result1: "{{ cond1 | ternary(str1, str2) }}"
      result2: "{{ cond2 | ternary(str1, str2) }}"
      tasks:
      • name: debug result1
        debug: msg="{{ result1 }}"
        connection: local
      • name: debug result2
        debug: msg="{{ result2 }}"
        connection: local

    Conclusion:

    $ ansible-playbook -i hosts_debug sample_ru_470202.yml
    
    
    
    

    PLAY [collect info] ************************************************************

    TASK [setup] *******************************************************************
    ok: [myserver1]

    TASK [debug result1] ***********************************************************
    ok: [myserver1] => {
    "msg": "asdf1"
    }

    TASK [debug result2] ***********************************************************
    ok: [myserver1] => {
    "msg": "asdf2"
    }

    PLAY RECAP *********************************************************************
    myserver1 : ok=3 changed=0 unreachable=0 failed=0

    PS was asking for a more complex example here today: https://ru.stackoverflow.com/questions/608873/


Log in to reply
 


Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2