首页 > 解决方案 > 带有for循环的ansible剧本没有按预期工作

问题描述

尝试创建一个剧本来检查 docker 容器日志,但它不会遍历 for 循环

- hosts: all
  become: yes
  gather_facts: no
  tasks:
      - name: Check container logs
        shell: |
          for i in "web_container_node{1..5}"; do
             echo ""
             echo "#### ${i} ####"
             echo ""
             docker logs --tail 10 ${i}
          done
        args:
          executable: /bin/bash

但是输出在没有迭代的情况下直接传递了剧本中的容器名称

No such container: "web_container_node{1..5}",

标签: bash

解决方案


您使用 bash 扩展的方式不起作用,即使在 bash 中,我建议您这样做。

  - name: Check container logs
    shell: |
      for i in {1..5}; do
         echo "webcontainer${i}"
         echo ""
         echo "#### ${i} ####"
         echo ""
         docker logs --tail 10 ${i}
      done
    args:
      executable: /bin/bash

推荐阅读