4

我通常通过设置配置变量vars/main.yml并将其中的一部分通过to_nice_json.

考虑一个vars/main.yaml类似下面的例子:

  # Application Configuration Settings.
  config:

    dev:
      # General Settings.
      logger_level: DEBUG

      # PostgreSQL Server Configuration Settings.
      sql_host: "localhost"
      sql_port: 5432
      sql_username: "someuser"
      sql_password: "somepassword"
      sql_db: "somedb"

我通过 Jinja2 模板和template具有以下内容的模块呈现出来:

{{ config.dev | to_nice_json }}

最近我尝试使用 Ansible Vault 来加密敏感位,例如,sql_password通过encrypt_string命令如下:

ansible-vault encrypt_string --vault-id .ansible-vault-password "somepassword" --name 'sql_password'

并直接在 YAML 文件中内联加密版本,如下所示:

# Application Configuration Settings.
config:

    dev:
      # General Settings.
      logger_level: DEBUG

      # PostgreSQL Server Configuration Settings.
      sql_host: "localhost"
      sql_port: 5432
      sql_username: "someuser"
      sql_password: !vault |
      $ANSIBLE_VAULT;1.1;AES256
      35383832623937353934636538306539623336633336643430396662323161333838333463653764
      3839653635326166303636643664333466376236626137310a323839373862626237643162303535
      35333966383834356239376566356263656635323865323466306362323864356663383661333262
      3165643733633262650a663363653832373936383033306137633234626264353538356630336131
      3063
      sql_db: "somedb"

但是,当to_nice_json应用过滤器时,我收到以下错误:

fatal: [myrole]: FAILED! => {"changed": false, "msg": "AnsibleError: Unexpected templating type error occurred on ({{ config.dev | to_nice_json }}\n): somepassword' is not JSON serializable"}

可以看出,该变量是属性解密的,但在序列化为 JSON 时会出错。但是,如果我将内联 Vault 变量用双引号括起来,则不会发生解密,并且生成的 JSON 包含整个 Vault Blob。

我错过了什么吗?这是to_nice_json过滤器的问题还是内联方式错误?

4

1 回答 1

4

作为此类问题的解决方法,将存储的值提取到单独的变量中(与字典中键的值相反):

vars:
  my_sql_password: !vault | 
    $ANSIBLE_VAULT;1.1;AES256
    5383832623937353934636538306539623336633336643430396662323161333838333463653764
    3839653635326166303636643664333466376236626137310a323839373862626237643162303535
    35333966383834356239376566356263656635323865323466306362323864356663383661333262
    3165643733633262650a663363653832373936383033306137633234626264353538356630336131
    3063
  # Application Configuration Settings.
  config:
    dev:
      # General Settings.
      logger_level: DEBUG

      # PostgreSQL Server Configuration Settings.
      sql_host: "localhost"
      sql_port: 5432
      sql_username: "someuser"
      sql_password: "{{ my_sql_password }}"
      sql_db: "somedb"
于 2018-06-09T05:22:19.947 回答