角色内环境变量的可用清单

时间:2020-02-17 13:39:06

标签: ansible ansible-inventory ansible-role

我有一个Ansible角色,我想与之一起执行psql脚本。该角色的名称是“ db_scripts”,我将在下面列出相应目录/文件的内容。

db_scripts / tasks / mail.yml

-
  name: "Run the SQLS"
  command: "psql -f \"{{ script }}\"/files/my_sql_script.sql"
  environment:
    PGDATABASE: "{{ db_name }}"
    PGUSER: "{{ db_user }}"
    PGHOST: "{{ db_host }}"
    PGPORT: "{{ db_port }}"
  delegate_to: localhost

db_scripts / files / my_sql_script.yml

insert into employees(name, contact) values (Jack, 5555555);

db_scripts / default / main.yml

script: "{{ role_path }}"

/ app / production / inventory

[dbservers]
db_host=192.168.1.100 db_name=mycompany db_user=abc db_port=3308

/app/playbooks/run_sqls.yml

- name: Run sql
  hosts: dbservers
  roles:
    - db_scripts

我按如下方式运行剧本“ run_sqls”。

ansible-playbook run_sqls.yml -i inventories/app/production/inventory

我想了解的是,我应该如何为以下环境变量指定值,以便它们可以是动态的,并可以由其他环境(例如,开发等)的主机使用。

PGDATABASE: "{{ db_name }}"
PGUSER: "{{ db_user }}"
PGHOST: "{{ db_host }}"
PGPORT: "{{ db_port }}"

在各自的清单文件中指定它们似乎不起作用,对于“未定义的变量”来说,剧本错误是有道理的。以下是我尝试过的方法。 / app /生产/库存

[dbservers]
192.168.1.100 db_name=mycompany db_user=abc db_port=3308

运行剧本时发生的错误

TASK [db_scripts : Run the SQLS] ******************************************************************************************************************************************************************
fatal: [localhost]: FAILED! => {"msg": "The field 'environment' has an invalid value, which includes an undefined variable. The error was: 'db_host' is undefined\n\nThe error appears to be in '/home/db_scripts/tasks/mail.yml': line 37, column 3, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n-\n  name: \"Run the SQLS\"\n  ^ here\n"}

请注意,在“ db_scripts / default / main.yml”下指定了上述环境变量的值时 ,playbook完美运行。真的很感谢一些投入。我刚开始使用ansible,所以请尽可能简单地举例说明。在此先感谢:)

1 个答案:

答案 0 :(得分:0)

[dbservers]
192.168.1.100 db_name=mycompany db_user=abc db_port=3308

Q:“在相应清单文件中指定它们(变量)似乎不起作用,对于“未定义变量”来说,剧本错误很有意义。

A:该清单中的变量应按预期工作。只需测试

- hosts: dbservers
  tasks:
    - debug:
        msg:
          - '{{ db_name }}'
          - '{{ db_user }}'
          - '{{ db_host }}'
          - '{{ db_port }}'

有2个问题

1)库存中缺少db_host

2)命令inventories/app/production/inventory中的路径与/app/production/inventory中描述的路径不同

ansible-playbook run_sqls.yml -i inventories/app/production/inventory