我想運行一些Ansible命令,取決於基於存在的布爾值在我的任務中的條件檢查的結果,並且試圖將它綁定在結中工作。Ansible 2條件在循環中使用with_items
所需結果是如下,並且應該爲每個項目hosts
陣列在運行:
- 檢查是否
lynchburg
變量是true
或false
- 如果
lynchburg
變量是true
:- 設置文件夾結構如果它還不存在exis牛逼
- 創建一個從包含的模板文件
gulpfile.js
如果它不存在
- 如果
lynchburg
變量是false
:- 不要在安裝文件夾結構
- 唐't創建
gulpfile.js
- Regar的
lynchburg
是否是true
或false
dless,跳過隨後的reprovisions所有任務,作爲文件夾結構和gulpfile.js
要麼是有或沒有(儘管這應該由邏輯在條件語句被照顧)
從下面包括了代碼,我看到了以下結果:
- 當
lynchburg
是true
,提供貫穿預期 第一次就和任何後續reprovisions也作爲 預期。 - 當
lynchburg
是false
,所述inc
文件夾結構是創建,然而gulpfile.js
不。
主循環任務運行的經過是這樣的:
vhosts:
- site_name: sample
lynchburg: true
和任務如下:
# Create variable to check whether Lynchburg has already been installed
- name: Check if Lynchburg assets folders have been previously created
stat:
path: /var/www/{{ item.site_name }}/inc
with_items: "{{ vhosts }}"
when: item.lynchburg == true
register: lynchburg_assets
- name: Check if Lynchburg gulpfile.js has been previously created
stat:
path: /var/www/{{ item.site_name }}/gulpfile.js
with_items: "{{ vhosts }}"
when: item.lynchburg == true
register: lynchburg_gulpfile
- name: Create inc folder
with_items: "{{ lynchburg_assets.results }}"
file:
path: /var/www/{{ item.item.site_name }}/inc
state: directory
when: item.stat.isdir is undefined and item.item.lynchburg == true
- name: Create scss folder
with_items: "{{ lynchburg_assets.results }}"
file:
path: /var/www/{{ item.item.site_name }}/inc/scss
state: directory
when: item.stat.isdir is undefined and item.item.lynchburg == true
- name: Create js folder
with_items: "{{ lynchburg_assets.results }}"
file:
path: /var/www/{{ item.item.site_name }}/inc/js
state: directory
when: item.stat.isdir is undefined and item.item.lynchburg == true
- name: Create img folder
with_items: "{{ lynchburg_assets.results }}"
file:
path: /var/www/{{ item.item.site_name }}/inc/img
state: directory
when: item.stat.isdir is undefined and item.item.lynchburg == true
- name: Create fonts folder
with_items: "{{ lynchburg_assets.results }}"
file:
path: /var/www/{{ item.item.site_name }}/inc/fonts
state: directory
when: item.stat.isdir is undefined and item.item.lynchburg == true
- name: Create gulpfile.js
with_items: "{{ lynchburg_gulpfile.results }}"
template:
src: gulpfile.js
dest: /var/www/{{ item.item.site_name }}/gulpfile.js
when: item.stat.exists is defined and item.stat.exists == false and item.item.lynchburg == true
注:如果還有其他方法可以輕鬆創建完整的文件夾結構,而無需運行五個不同的任務 - 每個文件夾/子文件夾一個 - 並且有人可以建議這是什麼,那也將被讚賞!
謝謝!我似乎已經解決了我的原始問題(請參閱我的評論),但是我在Ansible設置的另一個區域使用了您的解決方案,但由於完全相同的原因而導致出現問題,並且工作完美。 –
這是因爲'defined/undefined'關鍵字有點髒處理(見[這裏](https://github.com/ansible/ansible/blob/ff20ab7d4439ad6e5ca099c428ac6d3f25a154e7/lib/ansible/playbook/conditional.py#L211 ))。所以'dummy.key'在未定義的情況下會破壞jinja2表達式,而且語句的第二部分未經過測試。在定義/未定義之後,你實際上可能會寫任何你想要的東西,比如:'when:dummy.key未定義,任何事情,你和想要的東西。爲了克服這個問題,可以使用定義/未定義的測試作爲最後一個測試,或者將其替換爲默認值。 –