Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ansible join strings and variables in conditionals

Tags:

ansible

I can't figure out how to join strings and {{ item }} in a conditional. I'm not sure if this is even possible or supported

here's my task block:

- name: enable repos
  command: "subscription-manager repos --enable {{ item }}"
  when: enable_repo_{{ item }} == 'yes'
  with_items:
    - rhel-7-server-rpms
    - rhel-7-server-optional-rpms
    - rhel-7-server-extras-rpms
    - rhel-7-server-satellite-tools-6.2-rpms
    - rhel-7-server-thirdparty-oracle-java-rpms
    - jws-3-for-rhel-7-server-rpms

the error I am getting is:

TASK [satellite_client : enable repos] *****************************************
fatal: [10.187.15.31]: FAILED! => {"failed": true, "msg": "The conditional check 'enable_repo_item == 'yes'' failed. The error was: error while evaluating conditional (enable_repo_item == 'yes'): 'enable_repo_item' is undefined\n\nThe error appears to have been in '/home/marcp/git/satellite_client/tasks/main.yml': line 21, column 3, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n\n- name: enable repos\n  ^ here\n"}

PLAY RECAP *********************************************************************
10.187.15.31               : ok=1    changed=0    unreachable=0    failed=1

How can I concatenate the string with {{ item }} or should I be doing this differently?

like image 879
Eyestrain Avatar asked Oct 31 '25 11:10

Eyestrain


1 Answers

The condition in when is supposed to be a Jinja2 expression (so you can think it's implicitly enclosed in {{ ... }} and thus cannot open another Jinja2 expressing inside).

You can use vars dictionary and pass the name of the variable as a concatenated string:

when: vars['enable_repo_' + item] == 'yes'
like image 112
techraf Avatar answered Nov 03 '25 04:11

techraf