我可以直接将 ansible 中的命令输出注册为布尔值吗?

我可以直接将 ansible 中的命令输出注册为布尔值吗?

我有一些代码用于检查某事物是否存在。如果有 2 行代码,则表示该帖子存在。我可以在第一个任务中立即将检查中的变量注册为布尔值,而不需要在第二项任务中进行强制转换吗?我当前的解决方案是:

- name: Check if home page has been created
  sudo_user: www-data
  shell: wp post list --post_type=page --post_title=Home --post_status=publish
    chdir={{wordpress_path}}
  register: is_homepage_created

- name: Booleanize homepage check
  set_fact:
    is_homepage_created={{is_homepage_created.stdout_lines|length >= 2}}

答案1

我不这么认为,因为您需要将set_fact其设置为除实际输出之外的任何东西,并且我认为不能shell直接返回布尔值。

我认为通常的做法是,在使用该事实的任何地方复制“布尔化”任务中的条件,这是可以理解的,您当然想避免这种情况。不幸的是,注册功能相当简单。

failed_when您可能可以使用和的组合ignore_errors: yes来实现这样的功能,但这样做会导致运行 shell 命令映射到一个布尔值或另一个布尔值失败,所以我不推荐这样做。

答案2

经过一番尝试wp,我无法让它真正过滤帖子标题的输出。它总是显示每个页面的列表。这可能与你无关,但也可能与你有关。

鉴于这个明显的错误,我将重写剧本如下:

首先,wp以 CSV 格式输出,这样更容易操作。然后检查所需的输出是否出现在其中。在 CSV 格式中,如果Home存在名为的页面,则该字符串,Home,将出现在输出中,并且不应与其他任何内容匹配,因此这就是我们要寻找的内容。

- name: Get list of WordPress pages
  sudo_user: www-data
  command: wp post list --post_type=page --post_title=Home --post_status=publish --format=csv
    chdir={{wordpress_path}}
  register: wordpress_pages

- name: Create the homepage if it doesn't exist
  sudo_user: www-data
  command: wp post create --post_type=page --post_title=Home --porcelain
    chdir={{wordpress_path}}
  when: "',Home,' not in wordpress_pages.stdout"

最后,最好使用command而不是 ,shell除非您确实需要通过 shell 传递命令。

答案3

您可以使用查找来实现这一点。

ansible-playbook -c local test_lines_lookup.yml

剧本:

---

- hosts: localhost
  gather_facts: false

  tasks:
    - set_fact:
        test: "{{ lookup('lines', 'echo "This is stdout"') }}"

    - debug:
        msg: "{{ test }}"

输出:

PLAY [localhost] ************************************************************************

TASK [set_fact] *************************************************************************
ok: [localhost]

TASK [debug] ****************************************************************************
ok: [localhost] => {
    "msg": "This is stdout"
}

PLAY RECAP ******************************************************************************    
localhost                  : ok=2    changed=0    unreachable=0    failed=0

相关内容