回答 |如何在角色中调用我的变量

ansible | how to call my vars inside a role

下面是我的流程图--

my-code
      plays
           play1
           play2
      roles
           role1
               vars1
               files1
               tasks1
               templates1
           role2
               vars2
               files2
               tasks2
               templates2
           role3
               vars3
               files3
               tasks3
               templates3

我想为我的所有变量创建一个单独的 'vars/defaults' 文件夹,以供不同角色访问。当我创建文件夹 'defaults/main.yml' 时,出现以下错误。

错误:-

The task includes an option with an undefined variable

我的要求应该是这样的-

my-code
          plays
               play1
               play2
          roles
               vars
                   main.yml
               role1
                   files1
                   tasks1
                   templates1
               role2
                   files2
                   tasks2
                   templates2
               role3
                   files3
                   tasks3
                   templates3

tasks/code.yml

- name: CODE | Downloading Presto and Kinesis Jars from S3
  shell: "aws s3 cp s3://services-{{ aws_accountid_test }}-cicd-storage/jars/ utilities/ --recursive"
  ignore_errors: yes
  args:
      chdir: /home/hadoop/code/
      executable: /bin/bash
  become: yes
  become_method: sudo
  become_user: hadoop

如果我很了解你的需要,你可以定义你的变量,例如./vars.yml

---

- hosts: all
  remote_user: root
  vars_files:
    - ./vars.yml
  roles:
    - role1
    - role2

注意variable precedence.

另一种不需要您显式包含 vars 文件的方法是修改您的目录结构

my-code
      play1
      play2
      group_vars
          all.yml
      roles
           role1
               files1
               tasks1
               templates1
           role2
               files2
               tasks2
               templates2
           role3
               files3
               tasks3
               templates3

您希望所有主机都可以使用的所有通用变量都放在 'all.yml' 中并自动包含在内。然后,您可以通过将“_group_name_.yml”添加到 'group_vars' 目录来进一步定位变量,以设置仅向这些特定组中的主机公开的变量。

有关 directory/file 布局最佳实践的更多信息,请查看 this section of the docs.