问题描述
我对Ansible非常陌生,在此方面面临一些困难 我必须基于ansible中的某些条件传递完整的shell命令 我试图设置事实,但是我无法执行shell并由于未定义变量而出错
msg“:”该任务包括带有未定义变量的选项。错误是:“ commands_to_run”未定义\ n \ n
- name: setting command for x
set_fact:
commands_to_run: ls -1d /filepath/* | grep app | grep -E "("{{ id }}".*){2}"
when: id == 'X'
- name:setting command for Y
set_fact:
commands_to_run: ls -1d /filepath/* | grep app| grep -e "{{ id }}"
when: id != 'X'
- name: list path
shell: "{{ commands_to_run }}"
register: path
需要根据条件执行的Shell命令完全不同。 请让我知道是否可以通过其他方式完成
ansible-playbook 2.4.2.0
预先感谢
解决方法
修复您的代码标识,以下示例有效:
文件 site.yml :
---
- hosts: localhost
connection: local
gather_facts: false
tasks:
- name: setting command for X
set_fact:
commands_to_run: "echo Case X"
when: id == 'X'
- name: setting command for Y
set_fact:
commands_to_run: "echo Case Y"
when: id != 'X'
- name: call command
shell: "{{ commands_to_run }}"
register: path
呼叫案例X:ansible-playbook site.yml -e id = X -v 通话案例Y:ansible-playbook site.yml -e id = Y -v
如果必须将案例Y称为默认案例,则可以设置默认值:
- hosts: localhost
connection: local
gather_facts: false
tasks:
- name: setting command for Y
set_fact:
commands_to_run: "echo Case Y"
- name: setting command for X
set_fact:
commands_to_run: "echo Case X"
when: id == 'X'
- name: call command
shell: "{{ commands_to_run }}"
register: path
如果无法定义id
,请使用默认值:
- hosts: localhost
connection: local
gather_facts: false
tasks:
- name: setting command for Y
set_fact:
commands_to_run: "echo Case Y"
- name: setting command for X
set_fact:
commands_to_run: "echo Case X"
when: id | default('Y') == 'X'
- name: call command
shell: "{{ commands_to_run }}"
register: path