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 / 1091892
Accepted
dutsnekcirf
dutsnekcirf
Asked: 2022-02-01 15:57:41 +0800 CST2022-02-01 15:57:41 +0800 CST 2022-02-01 15:57:41 +0800 CST

Iterando por meio de lista/dicionário aninhado usando modelos Jinja2

  • 772

Estou tentando configurar dinamicamente vários servidores NFS no meu sistema gerando seus arquivos /etc/exports usando o Ansible. Espero poder fazer isso com um modelo jinja2. É o modelo jinja2 que não consigo descobrir com base na minha lista de exportações.

Eu tenho as seguintes variáveis ​​definidas na minha função nfs:

site_nfs_servers: ['ansibletarget1', 'ansibletarget2']

exports:
  - server: "ansibletarget1"
    shares:
      - path: "/my/first/share/path"
        client: "*"
        options: "rw,sync"
      - path: "/my/second/share/path"
        client: "*"
        options: "rw,sync,root_squash"
  - server: "ansibletarget2"
    shares:
      - path: "/another/shared/path/different/server"
        client: "*"
        options: "ro,sync"

Eu então tenho o seguinte ansible play para gerar o modelo:

- name: Generate the exports file.
  template:
    src: exports.j2
    dest: /etc/exports
    owner: root
    group: root
    mode: '0750'

Meu template atualmente está assim:

{% for export in exports %}
{% if ansible_hostname in export.server %}
{% for share in shares %}
{{ share.path }} {{ share.client }} {{ share.options }}
{% endfor %}
{% endif %}
{% endfor %}

Acho que não estou nem perto de ter a estrutura de modelo correta. Como diabos alguém itera nessa lista?

ansible ansible-playbook jinja2
  • 2 2 respostas
  • 3575 Views

2 respostas

  • Voted
  1. Gerald Schneider
    2022-02-01T22:15:24+08:002022-02-01T22:15:24+08:00

    Você está perdendo a referência ao exportem seu segundo loop.

    {% for export in exports %}
    {% if ansible_hostname in export.server %}
    {% for share in export.shares %}
    {{ share.path }} {{ share.client }} {{ share.options }}
    {% endfor %}
    {% endif %}
    {% endfor %}
    

    No entanto, seria melhor definir os compartilhamentos nas variáveis ​​do host, conforme mostrado na resposta de Vladimir.

    • 3
  2. Best Answer
    Vladimir Botka
    2022-02-01T21:09:02+08:002022-02-01T21:09:02+08:00

    Criar inventário

    shell> cat hosts
    [site_nfs_servers]
    ansibletarget1
    ansibletarget2
    

    e coloque os compartilhamentos no host_vars

    shell> cat host_vars/ansibletarget1.yml 
    shares:
      - path: "/my/first/share/path"
        client: "*"
        options: "rw,sync"
      - path: "/my/second/share/path"
        client: "*"
        options: "rw,sync,root_squash"
    
    shell> cat host_vars/ansibletarget2.yml 
    shares:
      - path: "/another/shared/path/different/server"
        client: "*"
        options: "ro,sync"
    

    Criar uma função simplificada para teste

    shell> tree roles/my_nfs_role/
    roles/my_nfs_role/
    ├── tasks
    │   └── main.yml
    └── templates
        └── exports.j2
    
    2 directories, 2 files
    
    shell> cat roles/my_nfs_role/tasks/main.yml 
    - template:
        src: exports.j2
        dest: /etc/exports.test
    
    shell> cat roles/my_nfs_role/templates/exports.j2 
    {% for share in shares %}
    {{ share.path }} {{ share.client }} {{ share.options }}
    {% endfor %}
    

    Em seguida, use o grupo de inventário e a função em um manual

    shell> cat playbook.yml
    - hosts: site_nfs_servers
      roles:
        - my_nfs_role
    

    Execute o manual e crie os arquivos

    shell> ansible-playbook -i hosts playbook.yml
    
    PLAY [site_nfs_servers] ************************************************
    
    TASK [my_nfs_role : template] ******************************************
    changed: [ansibletarget1]
    changed: [ansibletarget2]
     ...
    
    shell> ssh admin@ansibletarget1 cat /etc/exports.test
    /my/first/share/path * rw,sync
    /my/second/share/path * rw,sync,root_squash
    
    shell> ssh admin@ansibletarget2 cat /etc/exports.test
    /another/shared/path/different/server * ro,sync
    

    Consulte Exemplo de configuração do Ansible .


    Se você quiser manter os compartilhamentos em um objeto, coloque a lista em groups_vars . Para simplificar o código, converta a lista em um dicionário. Você pode usar community.general.groupby_as_dict por exemplo

    shell> cat group_vars/all.yml
    exports:
      - server: "ansibletarget1"
        shares:
          - path: "/my/first/share/path"
            client: "*"
            options: "rw,sync"
          - path: "/my/second/share/path"
            client: "*"
            options: "rw,sync,root_squash"
      - server: "ansibletarget2"
        shares:
          - path: "/another/shared/path/different/server"
            client: "*"
            options: "ro,sync"
    
    exports_dict: "{{ exports|community.general.groupby_as_dict('server') }}"
    

    dá

      exports_dict:
        ansibletarget1:
          server: ansibletarget1
          shares:
          - client: '*'
            options: rw,sync
            path: /my/first/share/path
          - client: '*'
            options: rw,sync,root_squash
            path: /my/second/share/path
        ansibletarget2:
          server: ansibletarget2
          shares:
          - client: '*'
            options: ro,sync
            path: /another/shared/path/different/server
    

    Em seguida, modifique o modelo. Isso deve criar os mesmos arquivos de antes.

    shell> cat roles/my_nfs_role/templates/exports.j2 
    {% for share in exports_dict[inventory_hostname]['shares'] %}
    {{ share.path }} {{ share.client }} {{ share.options }}
    {% endfor %}
    
    • 2

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