【问题标题】:Loop over a list and copy a file if that file exists locally only如果该文件仅在本地存在,则循环遍历列表并复制文件
【发布时间】:2021-07-19 08:17:21
【问题描述】:

我的剧本使用 2 个外部文件:

  • 1 个包含用户名和其他变量的文件:
  - name: jimi
    status: present
    sudo: "yes"
  • files/jimi.pub 中的 1 个文件保存用户的公钥
-rw-rw-rw- 1 root root   0 Jul 19 10:45 jimi.pub

我的剧本将创建用户并复制密钥,但如果用户在files/username.pub 中没有密钥文件,则会出错。我的最终目标是在密钥文件存在时复制密钥,如果不存在,则继续复制到列表中的下一个用户。

我可以在本地统计文件,但由于它会遍历用户列表,它最终会找到没有密钥的用户并出错。

下面是密钥文件副本的样子:

  - name: Setting the authorized key for users
    authorized_key:
      user: "{{ item.name }}"
      key: "{{ lookup('file', 'files/'+ item.name + '.pub') }}"
      state: "{{ item.status }}"
    loop: "{{ users }}"  

如果密钥文件存在,我如何复制密钥,如果不存在,则继续到列表中的下一个用户,而不会出现剧本错误!?

【问题讨论】:

    标签: python ansible jinja2


    【解决方案1】:

    可以轻松测试本地文件。见Testing paths。例如,给定用户

        users: [alice, bob, jimi]
    

    和文件

    shell> ls -1 files/
    bob.pub
    jimi.pub
    

    任务

        - debug:
            msg: "Setting the authorized key for {{ item }}"
          loop: "{{ users }}"
          vars:
            _file: "files/{{ item }}.pub"
          when: _file is exists
    

    给予

    TASK [debug] **************************************************************
    skipping: [localhost] => (item=alice) 
    ok: [localhost] => (item=bob) => 
      msg: Setting the authorized key for bob
    ok: [localhost] => (item=jimi) => 
      msg: Setting the authorized key for jimi
    

    这些tests 始终提供有关控制器上路径的信息,例如它们独立于运行任务的主机。

    【讨论】:

    • 它更近了一步,但不知何故它没有为每个用户添加正确的密钥..- name: Setting the authorized key for usersauthorized_key:user: "{{ item.name }}"key: "{{ _file }}"state: "{{ item.status }}"loop: "{{ users }}"vars:@ 987654334@when: _file is exists
    猜你喜欢
    • 2012-02-17
    • 2017-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多