yaml - 在 Ansible 中,有没有办法将变量值强制为整数?

标签 yaml ansible jinja2 botocore

我正在尝试将 ecs_taskdefinition 模块用于 Ansible (v2.0),但我认为我陷入了基本的 Ansible YAML 陷阱。

根据模块的示例,如果我为 cpu 提供整数值和 memory ,这按预期工作:

- name: "Create task definition"
  ecs_taskdefinition:
    containers:
    - name: simple-app
      cpu: 10
      memory: 300
      essential: true
      image: "httpd:2.4"
      portMappings:
      - containerPort: 80
        hostPort: 80

虽然,我想要 memorycpu可模板化。这样我就可以对不同的环境使用相同的容器定义。
APP_ENV: "test"
test:
  containers:
    simple_app:
      memory: 1920
      cpu: 2560

- name: "Create task definition"
  ecs_taskdefinition:
    containers:
    - name: simple-app
      cpu: "{{vars.get(APP_ENV).containers.simple_app.cpu | int}}"
      memory: "{{vars.get(APP_ENV).containers.simple_app.memory | int}}"
      essential: true
      image: "httpd:2.4"
      portMappings:
      - containerPort: 80
        hostPort: 80

有了上面,我从 botocore API 得到错误:
botocore.exceptions.ParamValidationError: Parameter validation failed:
Invalid type for parameter containerDefinitions[0].memory, value: 1920, type: <type 'str'>, valid types: <type 'int'>, <type 'long'>
Invalid type for parameter containerDefinitions[0].cpu, value: 2560, type: <type 'str'>, valid types: <type 'int'>, <type 'long'>

这是否可以修复而无需更新 Ansible 模块以实际尝试将这些值转换为整数?

最佳答案

它似乎在 Ansible 版本 2.1.1.0 中工作。如果你不能让它工作,一个可能的解决方案是在字典的顶层定义变量而不使用 int筛选…

vars:
  APP_ENV: test
  simple_app_container_cpu: 2560
  simple_app_container_ram: 1920

tasks:
  - name: Create task definition
    ecs_taskdefinition:
      containers:
        - name: simple-app
          cpu: "{{simple_app_container_cpu}}"
          memory: "{{simple_app_container_ram}}"

注意:我使用了 ram而不是 memory因为我喜欢它的排列方式:)

关于yaml - 在 Ansible 中,有没有办法将变量值强制为整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35517979/

相关文章:

python - 使用 Flask 上传图片和标签

php - YAML国际化

ansible - 如何使用 Ansible "slurp"多个文件

amazon-web-services - 删除后 Kubernetes 集群仍在运行

postgresql - 服务器是否在本地运行并接受 Unix 域套接字 "/var/run/postgresql/.s.PGSQL.5432"上的连接

python - 如何在 Jinja2 模板中包含 HTML 文件?

go - 加载具有不同结构项列表的YAML文件

python - 如何使用yaml文件和dockerfile来激活conda环境

Python yaml safe_load : How to keep the original order

python - 在 Jinja2 中,如何结合 block 标签使用宏?