我想在ansible中使用when评估多个条件,这里是我的剧本:
- name: Check that the SSH Key exists
local_action:
module: stat
path: "/home/{{ login_user.stdout }}/{{ ssh_key_location }}"
register: sshkey_result
- name: Generating a new SSH key for the current user it's not exists already
local_action:
module: user
name: "{{ login_user.stdout }}"
generate_ssh_key: yes
ssh_key_bits: 2048
when: sshkey_result.rc == 1 and ( github_username is undefined or github_username |lower == 'none' )
这是我的var文件供参考:
---
vpc_region: eu-west-1
key_name: my_github_key
ssh_key_location: .ssh/id_rsa.pub
当我尝试执行此剧本时,我收到此错误:
TASK: [test | Check that the SSH Key exists] **********************************
ok: [localhost -> 127.0.0.1]
TASK: [test | Generating a new SSH key for the current user it's not exists already] ***
fatal: [localhost] => error while evaluating conditional: sshkey_result.rc == 1 and ( github_username is undefined or github_username |lower == 'none' )
FATAL: all hosts have already failed -- aborting
有人可以指出我们如何在单个任务中使用ansible的多个条件。
谢谢
你可以像这样使用。
when: condition1 == "condition1" or condition2 == "condition2"
链接到官方文档:The When Statement。
你的条件问题在这部分sshkey_result.rc == 1
,因为sshkey_result
不包含rc
属性,整个条件失败。
如果要检查文件是否存在,请检查exists
属性。
添加到https://stackoverflow.com/users/1638814/nvartolomei答案,这可能会修复您的错误。
严格回答你的问题,我只想指出when:
语句可能是正确的,但在多行中看起来更容易阅读并仍然符合你的逻辑:
when:
- sshkey_result.rc == 1
- github_username is undefined or
github_username |lower == 'none'
https://docs.ansible.com/ansible/latest/user_guide/playbooks_conditionals.html#the-when-statement