我正在寻找如何让Ansible在运行playbook执行之前分析必备和强制变量的剧本的方式,如:
- name: create remote app directory hierarchy
file:
path: "/opt/{{ app_name | required }}/"
state: directory
owner: "{{ app_user | required }}"
group: "{{ app_user_group | required }}"
...
并且如果变量未定义则会出现错误消息,例如:
please set "app_name" variable before run (file XXX/main.yml:99)
答案 0 :(得分:7)
您可以使用this:
{{ variable | mandatory }}
答案 1 :(得分:6)
如Arbab Nazar所述,您可以在Ansible任务中使用{{ variable | mandatory }}
(请参阅Forcing variables to be defined)。
但我认为将其添加为第一个任务看起来更好,它检查是否存在app_name
,app_user
和app_user_group
:
- name: 'Check mandatory variables are defined'
assert:
that:
- app_name is defined
- app_user is defined
- app_user_group is defined
答案 2 :(得分:6)
通常在角色内部,像示例一样执行输入变量检查:
- name: "Verify that required string variables are defined"
assert:
that: ahs_var is defined and ahs_var | length > 0 and ahs_var != None
fail_msg: "{{ ahs_var }} needs to be set for the role to work "
success_msg: "Required variable {{ ahs_var }} is defined"
loop_control:
loop_var: ahs_var
with_items:
- ahs_item1
- ahs_item2
- ahs_item3
顺便说一下,有一些技巧:
some_role_name__db_port: "{{ db_port | default(5432) }}"
。item
。答案 3 :(得分:3)
定义检查强制变量的一种方法是:
- fail:
msg: "Variable '{{ item }}' is not defined"
when: item not in vars
with_items:
- app_nam
- var2
答案 4 :(得分:1)
有两种方法:
指定|mandatory
过滤器
使用assert
模块