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

时间:2015-11-22 16:25:38

标签: 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'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的多个条件。

由于

4 个答案:

答案 0 :(得分:33)

你可以这样使用。

0xDEADBEEF

官方文档的链接:The When Statement

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

答案 1 :(得分:4)

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

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

您可read more about stat module and how to use it

答案 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'