我想用何时评估ansible中的多个条件,这是我的剧本:
- 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的多个条件。
由于
答案 0 :(得分:33)
答案 1 :(得分:4)
条件问题在于此部分sshkey_result.rc == 1
,因为sshkey_result
不包含rc
属性,整个条件失败。
如果要检查文件是否存在,请选中exists
属性。
答案 2 :(得分:4)
添加到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
答案 3 :(得分:1)
您还可以使用default()
过滤器。或只是快捷方式d()
- 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
- github_username | d('none') | lower == 'none'