【问题标题】:In Ansible, is there a way to force variable values to integer?在 Ansible 中,有没有办法将变量值强制为整数?
【发布时间】:2016-02-20 01:20:58
【问题描述】:

我正在尝试将 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

虽然,我希望 memory 和 cpu 是可模板化的。这样我就可以在不同的环境中使用相同的容器定义。

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 模块以实际尝试将这些值转换为整数的情况下修复?

【问题讨论】:

  • 因为我还没有从剧本中找到解决这个问题的任何方法;向这个特定模块建议这个特性。 github.com/ansible/ansible-modules-extras/pull/1715
  • 我在 ansible 2.0.2 中测试了 variable|int 并且工作正常。我认为错误是引号 " " 请在 {{vars.get(APP_ENV).containers.simple_app.cpu | int}} 然后再试一次。
  • @RaulHugo 根据Ansible doc,我认为没有引号它会起作用。它说,Further, Ansible uses "{{ var }}" for variables. If a value after a colon starts with a "{", YAML will think it is a dictionary, so you must quote it, like so: foo: "{{ variable }}"

标签: yaml ansible jinja2 botocore


【解决方案1】:

它似乎在 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 因为我喜欢它的排列方式:)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-03-25
    • 1970-01-01
    • 2020-09-04
    • 2020-09-02
    • 1970-01-01
    • 1970-01-01
    • 2022-01-26
    • 2018-10-23
    相关资源
    最近更新 更多