具有 to_nice_json 的 Ansible Vault 内联变量:发生意外的模板类型错误...不是 JSON 可序列化

Ansible Vault inline variable with to_nice_json: Unexpected templating type error occurred...not JSON serializable

我通常通过在 vars/main.yml 中设置配置变量来配置我的项目,并通过 to_nice_json.

将其中的一个子集渲染到 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 加密敏感位,例如,通过 encrypt_string 命令加密 sql_password

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 时出错了。但是,如果我将内联保险库变量用双引号引起来,则不会进行解密,并且生成的 JSON 包含整个保险库 blob。

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

作为此类问题的变通方法,将拱形值提取到单独的变量(而不是字典中的键值):

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"