如何在 Ansible 块中执行角色

How to Execute Role Inside the Ansible Blocks

我写了一个在远程机器上部署的 ansible 剧本

-   name: Deployment part of the script
    vars:
       hostName: 
       build_num: 
    hosts: "{{hostName}}"
    become: true
    serial: 1
    tasks: this does deployment

在此之后,我想执行本剧本将要执行的本地主机上的实用程序。

现在我已经编写了一个角色,如果我将它们作为剧本单独执行,它会为我做这件事


  - name: Roles Demo
    hosts: 127.0.0.1
    connection: local
    vars: 
       var1: "sometextvalue"
       var2: "sometextvalue"
       var3: "someurl" 
    roles: 
    - demorole #role which I created

现在我想将这个角色整合到顶部提到的我的主要剧本中,但我得到了

ERROR! no action detected in task. This often indicates a misspelled module name, or incorrect module path.

虽然它是相同的片段,但在 运行 单独

时工作正常

我还想使用 "Ansible blocks" 执行此操作,例如当满足特定条件时执行特定角色,但为此我也遇到了上述相同的错误,只是为了总结我想使用这些块实现的目标如下

-   name: Deployment part of the script
    vars:
       hostName: 
       build_num: 
    hosts: "{{hostName}}"
    become: true
    serial: 1
    tasks: this does deployment complete
- name: Task for Doing some check
  hosts: 127.0.0.1
  connection: local
  vars:
      var1: "dakdkadadakdhkahdkahkdh
      var2: "jdjaldjlaj"
      var3: "djasjdlajdlajdljadljaldjlaj"
  block: 
  - name: Doing Check for some1
    roles: 
    - role1
  when: x == "somevalue1"
- block: 
  - name: Doing check for some2
    roles: 
    - role2
  when: x == "somevalue2"
.
.
.
assuming the vars value are same

所以我不确定这是否可以实现

在任务部分之外使用块是无效的。

然而,您可以从任务部分执行角色,这将允许您使用块和 when 条件,但是您选择。

示例:

- name: Task for Doing some check
  hosts: 127.0.0.1
  connection: local
  vars:
      var1: "dakdkadadakdhkahdkahkdh
      var2: "jdjaldjlaj"
      var3: "djasjdlajdlajdljadljaldjlaj"
  tasks:
    - name: Doing Check for some1
      import_role:
        name: role1
      when: x == "somevalue1"

您需要决定是使用 import_role 还是 include_role。查看 https://docs.ansible.com/ansible/latest/user_guide/playbooks_reuse.html#dynamic-vs-static 了解差异的解释。