使用“检查多个条件”;什么时候;论ansible中的单任务

使用“检查多个条件”;什么时候;论ansible中的单任务,ansible,ansible-playbook,Ansible,Ansible Playbook,我想用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'

我想用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吗


谢谢

您的条件的问题在这部分
sshkey_result.rc==1
,因为
sshkey_result
不包含
rc
属性,整个条件失败

如果要检查文件是否存在,请检查
存在
属性

给你。

你可以这样使用

when: condition1 == "condition1" or condition2 == "condition2"
官方文件链接:

另请参阅本要点:

添加到答案,这可能会修复您的错误

严格地回答您的问题,我只想指出,
when:
语句可能是正确的,但在多行中看起来更容易阅读,并且仍然符合您的逻辑:

when: 
  - sshkey_result.rc == 1
  - github_username is undefined or 
    github_username |lower == 'none'

您还可以使用
default()
过滤器。或者只是一个快捷方式
d()


作为@nvartolomei所说的后续内容,当您有一个类似于
sshkey_result
的变量时,我发现在编写/调试剧本时,在其设置后立即显示其值非常有用。添加一个
-debug:var=sshkey_result
任务将向您显示,正如他所说,
rc
在此上下文中不存在,它还将向您显示该变量确实存在哪些属性。When语句链接已断开
- 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'