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

Nik*_*kar 7 yaml jinja2 ansible 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
Run Code Online (Sandbox Code Playgroud)

虽然,我希望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
Run Code Online (Sandbox Code Playgroud)

在上面,我从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'>
Run Code Online (Sandbox Code Playgroud)

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

Sha*_*Lee 1

它似乎在 Ansible 版本 2.1.1.0 中工作。如果您无法让它工作,一个可能的解决方案是将变量定义在字典的顶层,而不是使用int过滤器\xe2\x80\xa6

\n\n
vars:\n  APP_ENV: test\n  simple_app_container_cpu: 2560\n  simple_app_container_ram: 1920\n\ntasks:\n  - name: Create task definition\n    ecs_taskdefinition:\n      containers:\n        - name: simple-app\n          cpu: "{{simple_app_container_cpu}}"\n          memory: "{{simple_app_container_ram}}"\n
Run Code Online (Sandbox Code Playgroud)\n\n

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

\n