我有一些具有相同命名约定的 SQL 脚本文件。
pole15432-pole15435.sql
pole15435-pole15447.sql
pole15447-pole15453.sql
pole15453-pole15454.sql
我只想过滤掉大于: 的文件pole15435-pole15447.sql
。我可以通过以下方式直接在终端上执行此操作:
ls -1 pole* | awk '$1 > "pole15435-pole15447.sql"'
结果:
pole15447-pole15453.sql
pole15453-pole15454.sql
但是,从 ansible 执行相同的操作没有给我任何结果。
- name: Find upgrade scripts that need to be executed
shell: ls -1 pole* | awk '$1 > "pole15392-pole15402.sql\"'
#shell: "ls -1 | sed -n /pole15392-pole15402.sql/,//p"
args:
chdir: /data/releases/Upgrade Scripts
delegate_to: localhost
register: scripts
- debug:
msg: "{{scripts}}"
result:
changed: [10.101.96.176] => {"changed": true, "cmd": "ls -1 pole* | awk '$1 > \"pole15392-pole15402.sql\"'", "delta": "0:00:00.010166", "end": "2022-10-15 18:01:04.441383", "rc": 0, "start": "2022-10-15 18:01:04.431217", "stderr": "", "stderr_lines": [], "stdout": "", "stdout_lines": []}
有人可以帮忙吗?
答案1
问:“仅过滤掉大于:pole15435-pole15447.sql 的文件”
答:给定文件
file: pole15435-pole15447.sql
和文件列表
files:
- pole15453-pole15454.sql
- pole15432-pole15435.sql
- pole15435-pole15447.sql
- pole15447-pole15453.sql
对列表进行排序,获取文件的索引,并创建切片
files_sort: "{{ files|sort }}"
file_index: "{{ files_sort.index(file) }}"
files_select: "{{ files_sort[file_index|int + 1:] }}"
给出
files_select:
- pole15447-pole15453.sql
- pole15453-pole15454.sql
用于测试的完整剧本示例
- hosts: localhost
vars:
files:
- pole15432-pole15435.sql
- pole15435-pole15447.sql
- pole15447-pole15453.sql
- pole15453-pole15454.sql
files_sort: "{{ files|sort }}"
file: pole15435-pole15447.sql
file_index: "{{ files_sort.index(file) }}"
files_select: "{{ files_sort[file_index|int + 1:] }}"
tasks:
- debug:
var: files_sort
- debug:
var: file_index
- debug:
var: files_select
如果您想使用awk将文件名放入变量中。例如,给定树
shell> tree sql/
sql/
├── pole15432-pole15435.sql
├── pole15435-pole15447.sql
├── pole15447-pole15453.sql
└── pole15453-pole15454.sql
下面的剧本
- hosts: localhost
vars:
file: pole15435-pole15447.sql
tasks:
- shell:
cmd: ls -1 pole* | awk '$1 > "{{ file }}"'
chdir: "{{ playbook_dir }}/sql"
register: scripts
- debug:
var: scripts.stdout_lines
给出(删节)
scripts.stdout_lines:
- pole15447-pole15453.sql
- pole15453-pole15454.sql
答案2
我发现了 ls -1 polly* | 的问题awk '$1 > "{{ 文件 }}"'。 -1 参数提取的内容不只是文件名,而且 awk 无法通过 Ansible 处理该内容。使用 -1(一)修复它