How to have multiple tasks under one role in Ansible?

Dal*_*ods 2 ansible ansible-2.x

I am setting up Ansible as a newbie. I would like to group a few tasks under an Nginx role.

See my folder structure

在此输入图像描述

The only way I could get this to work is to use include statements in my playbooks... but that means I needed to start changing everything to relative paths since Ansible stopped being able to find things.

My playbook currently:

- name: 
    Install Nginx, Node, and Verdeccia
  hosts: 
    all
  remote_user: 
    root
  tasks:
    - include: ../roles/nginx/tasks/install.yml
    - include: ../roles/nginx/tasks/create_node_config.yml
  vars:
    hostname: daz.com
Run Code Online (Sandbox Code Playgroud)

How can I reference the sub task in the playbook to be something like

tasks:
  - nginx.install
Run Code Online (Sandbox Code Playgroud)

and still be within best practices.

pha*_*naz 6

到目前为止,您对角色的使用不符合 Ansible 的规范或理念。从纯粹的技术角度来看,您在 playbook 中包含的 yml 文件中很可能有多个任务包。

如果您想包含某个角色的特定任务文件,您最好通过带有参数的模块include_roletasks_from来完成此操作。

然而,角色的工作流程通常看起来不同。

  1. 文件夹中tasks应该始终是一个文件main.yml,如果只是包含角色,无论通过哪种方式,都会自动调用该文件。

  2. 然后,main.yml您可以添加进一步的控制逻辑以yml根据需要包含您的文件。

例如,在我看来,您总是需要安装,但根据用例您希望有不同的配置。

  1. 在您的角色中创建nginx一个文件defaults/main.yml

    ---
    config_flavor: none
    
    Run Code Online (Sandbox Code Playgroud)

    config_flavor用字符串初始化变量none

  2. 在您的角色中创建nginx一个文件tasks/main.yml

    ---
    - name: include installation process
      include_tasks: install.yml
    
    - name: configure node
      include_tasks: create_node_config.yml
      when: config_flavor == "node"
    
    - name: configure symfony
      include_tasks: create_symfony_config.yml
      when: config_flavor == "symfony"
    
    - name: configure wordpress
      include_tasks: create_wordpress_config.yml
      when: config_flavor == "wordpress"
    
    Run Code Online (Sandbox Code Playgroud)
    • main.yml应用角色时将默认包含。
    • 这是首先完成安装的地方,然后完成正确的配置。
    • 应该进行哪些配置由变量定义config_flavor。在列出的示例中,值为nodesymfonywordpress。在所有其他情况下,安装将完成,但不进行配置(因此在默认情况下为none)。
  3. 将您的角色包含在剧本中,如下所示

    ---
    - name: Install Nginx, Node, and Verdeccia
      hosts: all
      remote_user: root
    
      vars:
        hostname: daz.com
    
      roles:
        - role: nginx
          config_flavor: node
    
    Run Code Online (Sandbox Code Playgroud)

    此时可以设置 的值config_flavor。如果您进行了设置,则将使用 中的逻辑自动包含wordpress任务。create_wordpress_config.ymltasks/main.yml

您可以在 Ansible 文档中找到有关角色的更多信息。

还有更多的可能性和方式,你会在学习的过程中认识它们。基本上,我建议您阅读大量 Ansible 文档并将它们用作参考书。