AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • Início
  • system&network
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • Início
  • system&network
    • Recentes
    • Highest score
    • tags
  • Ubuntu
    • Recentes
    • Highest score
    • tags
  • Unix
    • Recentes
    • tags
  • DBA
    • Recentes
    • tags
  • Computer
    • Recentes
    • tags
  • Coding
    • Recentes
    • tags
Início / server / Perguntas / 1130612
Accepted
alexus
alexus
Asked: 2023-05-08 10:13:22 +0800 CST2023-05-08 10:13:22 +0800 CST 2023-05-08 10:13:22 +0800 CST

Você deve definir o valor `loop_var` na opção `loop_control` para a tarefa para outra coisa para evitar variáveis

  • 772

Meu ambiente:

# cat /etc/debian_version
11.7
# ansible-playbook --version
ansible-playbook [core 2.13.1]
  config file = None
  configured module search path = ['/root/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
  ansible python module location = /usr/local/lib/python3.9/dist-packages/ansible
  ansible collection location = /root/.ansible/collections:/usr/share/ansible/collections
  executable location = /usr/local/bin/ansible-playbook
  python version = 3.9.2 (default, Feb 28 2021, 17:03:44) [GCC 10.2.1 20210110]
  jinja version = 3.1.2
  libyaml = True
#

A seguinte tarefa faz parte da minha função Ansible:

- name: _file - state:absent
  ansible.builtin.file:
    path: "{{ item.path }}"
    state: absent
  loop: "{{ find.files | flatten }}"
  register: file
  when: find.matched is defined and find.matched != 0

ainda assim, notei uma mensagem de aviso:

[WARNING]: TASK: XYZ : _file - state:absent: A variável de loop 'item' já está em uso. Você deve definir o loop_varvalor na loop_controlopção da tarefa para outra coisa para evitar colisões de variáveis ​​e comportamento inesperado.

depois de ler alguns:

  • Definindo nomes de variáveis ​​internas e externas com loop_var
  • Adicionando controles a loops

Eu modifiquei minha tarefa para algo assim:

- name: _file - state:absent
  ansible.builtin.file:
    path: "{{ item.path }}"
    state: absent
  loop: "{{ find.files | flatten }}"
  loop_control:
    label: "{{ item.path }}"
    loop_var: find
  register: file
  when: find.matched is defined and find.matched != 0

esta tarefa está sendo chamada duas vezes dentro da minha função, enquanto na primeira vez funciona bem, na segunda vez falha

TASK [XYZ : _file - state:absent] ******************************************************************************************************************************************************************************
[WARNING]: TASK: XYZ : _file - state:absent: The loop variable 'find' is already in use. You should set the `loop_var` value in the `loop_control` option for the task to something else to avoid variable
collisions and unexpected behavior.
failed: [127.0.0.1] (item=None) => {"ansible_loop_var": "find", "changed": false, "find": {"atime": 1683511713.8529496, "checksum": "ecd34202c34bf761e4c2c9800a39e18dffad5d9e", "ctime": 1683511714.972948, "dev": 2049, "gid": 0, "gr_name": "root", "inode": 150677, "isblk": false, "ischr": false, "isdir": false, "isfifo": false, "isgid": false, "islnk": false, "isreg": true, "issock": false, "isuid": false, "mode": "0644", "mtime": 1683511714.972948, "nlink": 1, "path": "tmp/FILE.CSV", "pw_name": "root", "rgrp": true, "roth": true, "rusr": true, "size": 642, "uid": 0, "wgrp": false, "woth": false, "wusr": true, "xgrp": false, "xoth": false, "xusr": false}, "msg": "Failed to template loop_control.label: 'item' is undefined", "skip_reason": "Conditional result was False"}

Por favor, avise.

ansible
  • 1 1 respostas
  • 36 Views

1 respostas

  • Voted
  1. Best Answer
    Vladimir Botka
    2023-05-08T12:01:47+08:002023-05-08T12:01:47+08:00

    Não está claro por que você precisa do loop externo (não documentado) que registra a variável item . Por exemplo, dada a árvore

    shell> tree /tmp/test
    /tmp/test
    ├── file1
    ├── file2
    └── file3
    

    a jogada abaixo

    shell> cat pb.yml
    - hosts: localhost
    
      tasks:
    
        - find:
            paths: /tmp/test
          register: find
    
        - file:
            path: "{{ item.path }}"
            state: absent
          loop: "{{ find.files }}"
          loop_control:
            label: "{{ item.path }}"
    

    dá a execução no modo --check --diff

    shell> ansible-playbook -CD pb.yml
    
    PLAY [localhost] ******************************************************************************
    
    TASK [find] ***********************************************************************************
    ok: [localhost]
    
    TASK [file] ***********************************************************************************
    --- before
    +++ after
    @@ -1,2 +1,2 @@
     path: /tmp/test/file3
    -state: file
    +state: absent
    
    changed: [localhost] => (item=/tmp/test/file3)
    --- before
    +++ after
    @@ -1,2 +1,2 @@
     path: /tmp/test/file2
    -state: file
    +state: absent
    
    changed: [localhost] => (item=/tmp/test/file2)
    --- before
    +++ after
    @@ -1,2 +1,2 @@
     path: /tmp/test/file1
    -state: file
    +state: absent
    
    changed: [localhost] => (item=/tmp/test/file1)
    
    PLAY RECAP ************************************************************************************
    localhost: ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
    

    Notas:

    • Se você definir loop_var, use-o. A tarefa abaixo fornece os mesmos resultados
    - file:
        path: "{{ my_loop_var.path }}"
        state: absent
      loop: "{{ find.files }}"
      loop_control:
        label: "{{ my_loop_var.path }}"
        loop_var: my_loop_var
    
    • A condição abaixo é redundante. Remova. Quando nada for encontrado ( find.matched: 0 ) a lista de arquivos estará vazia ( fined.files: [] ) e o loop será ignorado de qualquer maneira
      when: find.matched is defined and find.matched != 0
    
    • Não há nada para nivelar se find for a variável registrada do módulo find . O achatamento do filtro pode ser removido
      loop: "{{ find.files }}"
    
    • 0

relate perguntas

  • Ansible: Converter string em dicionário

Sidebar

Stats

  • Perguntas 205573
  • respostas 270741
  • best respostas 135370
  • utilizador 68524
  • Highest score
  • respostas
  • Marko Smith

    Você pode passar usuário/passar para autenticação básica HTTP em parâmetros de URL?

    • 5 respostas
  • Marko Smith

    Ping uma porta específica

    • 18 respostas
  • Marko Smith

    Verifique se a porta está aberta ou fechada em um servidor Linux?

    • 7 respostas
  • Marko Smith

    Como automatizar o login SSH com senha?

    • 10 respostas
  • Marko Smith

    Como posso dizer ao Git para Windows onde encontrar minha chave RSA privada?

    • 30 respostas
  • Marko Smith

    Qual é o nome de usuário/senha de superusuário padrão para postgres após uma nova instalação?

    • 5 respostas
  • Marko Smith

    Qual porta o SFTP usa?

    • 6 respostas
  • Marko Smith

    Linha de comando para listar usuários em um grupo do Windows Active Directory?

    • 9 respostas
  • Marko Smith

    O que é um arquivo Pem e como ele difere de outros formatos de arquivo de chave gerada pelo OpenSSL?

    • 3 respostas
  • Marko Smith

    Como determinar se uma variável bash está vazia?

    • 15 respostas
  • Martin Hope
    Davie Ping uma porta específica 2009-10-09 01:57:50 +0800 CST
  • Martin Hope
    kernel O scp pode copiar diretórios recursivamente? 2011-04-29 20:24:45 +0800 CST
  • Martin Hope
    Robert ssh retorna "Proprietário incorreto ou permissões em ~/.ssh/config" 2011-03-30 10:15:48 +0800 CST
  • Martin Hope
    Eonil Como automatizar o login SSH com senha? 2011-03-02 03:07:12 +0800 CST
  • Martin Hope
    gunwin Como lidar com um servidor comprometido? 2011-01-03 13:31:27 +0800 CST
  • Martin Hope
    Tom Feiner Como posso classificar a saída du -h por tamanho 2009-02-26 05:42:42 +0800 CST
  • Martin Hope
    Noah Goodrich O que é um arquivo Pem e como ele difere de outros formatos de arquivo de chave gerada pelo OpenSSL? 2009-05-19 18:24:42 +0800 CST
  • Martin Hope
    Brent Como determinar se uma variável bash está vazia? 2009-05-13 09:54:48 +0800 CST

Hot tag

linux nginx windows networking ubuntu domain-name-system amazon-web-services active-directory apache-2.4 ssh

Explore

  • Início
  • Perguntas
    • Recentes
    • Highest score
  • tag
  • help

Footer

AskOverflow.Dev

About Us

  • About Us
  • Contact Us

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve