我想使用find模块从外部vars文件中查找带有变量的文件模式,该外部vars文件在字典列表中具有动态变量。从剧本访问它们时,如何在vars文件中为这些动态变量分配值?
deletememes.yml:
---
name: generic name
hosts: all
vars_files: vars.yml
tasks:
- set_fact:
combinedlist: "{{ first_list + second_list }}"
- find:
paths: "{{ item.0.path }}" # pass a value(item.1.username?) here for the username in the vars file
patterns: "{{ item.0.extension }}"
register: someRegister
with_items:
- combinedlist
- usernameList # for the value in
vars.yml
---
first_list:
- { path : "/Users/{{ username }}/memes/" , extension : '{{ username }}_*.jpg'}
- { path : "/someOtherFolder/{{ username }}/catVideos/" , extension : '{{ item.username }}_*.mp4'}
second_list:
- { path : "/{{ memesrc }}/memes/" , extension : '{{ memesrc }}_*.gif'}
错误:
"msg": "The task includes an option with an undefined variable. The error was: 'username' is undefined\n\nThe error appears to have been in 'deletememes.yml'
答案 0 :(得分:0)
各种文件不是动态的。您将必须在set_fact
个任务中进行这些分配。现在,您必须从文本中分解变量,并使用字符串隐含运算符+
。我在这里只显示一个列表:
---
- hosts: localhost
connection: local
vars:
external_list_of_users:
- username: fred
- username: barney
- username: wilma
- username: betty
tasks:
- name: Create arrays
set_fact:
first_list: []
- name: Put items in arrays
set_fact:
first_list: "{{ first_list + [ { 'path' : '/Users/'+item.username+'/memes/' , 'extension' : item.username+'_*.jpg' } ] }}"
with_items: "{{ external_list_of_users }}"
- name: Show vars
debug:
var: first_list
最后一个任务的结果是:
TASK [Show vars] *******************************************************************************************
ok: [localhost] => {
"first_list": [
{
"extension": "fred_*.jpg",
"path": "/Users/fred/memes/"
},
{
"extension": "barney_*.jpg",
"path": "/Users/barney/memes/"
},
{
"extension": "wilma_*.jpg",
"path": "/Users/wilma/memes/"
},
{
"extension": "betty_*.jpg",
"path": "/Users/betty/memes/"
}
]
}