在ansible的单个任务中使用"when"检查多个条件

Arb*_*zar 33 ansible ansible-playbook

我想在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' )
Run Code Online (Sandbox Code Playgroud)

这是我的var文件供参考:

---
vpc_region: eu-west-1
key_name: my_github_key
ssh_key_location: .ssh/id_rsa.pub
Run Code Online (Sandbox Code Playgroud)

当我尝试执行此剧本时,我收到此错误:

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
Run Code Online (Sandbox Code Playgroud)

有人可以指出我们如何在单个任务中使用ansible的多个条件.

谢谢

Dha*_*gan 45

你可以像这样使用.

when: condition1 == "condition1" or condition2 == "condition2"
Run Code Online (Sandbox Code Playgroud)

链接到官方文档:何时声明.

另请参阅这个要点:https: //gist.github.com/marcusphi/6791404


use*_*480 16

添加到/sf/users/114717011/答案,这可能会解决您的错误。

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

when: 
  - sshkey_result.rc == 1
  - github_username is undefined or 
    github_username |lower == 'none'
Run Code Online (Sandbox Code Playgroud)

https://docs.ansible.com/ansible/latest/user_guide/playbooks_conditionals.html#the-when-statement


qui*_*ver 7

您可以使用逻辑运算符来组合条件。当您有多个条件都需要为真(即逻辑与)时,您可以将它们指定为列表:

tasks:
  - name: Shut down CentOS 6 systems
    ansible.builtin.command: /sbin/shutdown -t now
    when:
      - ansible_facts['distribution'] == "CentOS"
      - ansible_facts['distribution_major_version'] == "6"
Run Code Online (Sandbox Code Playgroud)

链接到文档:https://docs.ansible.com/ansible/latest/user_guide/playbooks_conditionals.html#the-when-statement


nva*_*mei 5

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

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

在这里您可以阅读有关 stat 模块及其使用方法的更多信息

  • 作为@nvartolomei 所说的后续内容,当你有一个像`sshkey_result` 这样的变量时,我发现在编写/调试剧本时立即显示它的值非常有用。添加一个 `-debug: var=sshkey_result` 任务会告诉你,正如他所说的,`rc` 在这个上下文中不存在,它还会告诉你该变量的哪些属性 *do* 存在。 (5认同)