file - ansible 查找的替代方法,因为它总是在 localhost 上查找文件

标签 file ubuntu ansible terraform lookup

我在 terraform local-exec 中运行 ansible playbook具有远程实例 IP 的内联 list 的配置程序。

- name: Install git
  apt:
    name: git
    state: present
    update_cache: yes

- name: Clone the git repository
  become_user: "{{ SSH_USER }}"
  git:
    repo: "{{ REPO_URL }}"
    dest: "{{ SRC_DIR }}"

- name : Find files with .pub extension
  become_user: "{{ SSH_USER }}"
  find:
    paths: "{{ SRC_DIR }}"
    patterns: '*.pub'
  register: pub_files

- name: Append the content of all public key files to authorized_keys file.
  become_user: "{{ SSH_USER }}"
  lineinfile:
    path: "{{ DEST_FILE }}"
    line: "{{ lookup('file', '{{ item.path }}') }}"
    insertafter: EOF
    create: "yes"
    state: present
# loop: "{{ lookup('fileglob', "{{ SRC_DIR }}/*.pub", wantlist=True) }}"
# with_fileglob: "{{ SRC_DIR }}/*.pub"
  with_items: "{{ pub_files.files }}"      
    
- name: Display destinationFile contents
  become_user: "{{ SSH_USER }}"
  command: cat "{{ DEST_FILE }}"
  register: command_output

- name: Print to console
  become_user: "{{ SSH_USER }}"
  debug:
    msg: "{{command_output.stdout}}"  
ansible playbook 应该克隆一个 git repo 并将其文件的内容复制到另一个文件。
但是当使用 ansible lookups要读取文件的内容(在远程主机中克隆),它总是在 localhost 中查找文件。

Like all templating, lookups execute and are evaluated on the Ansible control machine.


因此,上面给出的剧本失败并出现错误:
No such file or directory found
使用 with_fileglob 时出现类似问题和 loop使用 fileglob 查找来遍历文件,因为它们也在内部进行查找。我将其替换为 find列出文件名的模块,register它在一个变量中,然后在下一步中使用 with_items 对其进行迭代.
有没有这样的替代方法来读取文件的内容?

最佳答案

首先将它们取回 ansible 控制节点。请注意,ansible 有一个 authorized_keys 模块,可以简化添加 key 的任务。

  tasks:
  - name: find all the .pub files
    find: 
      paths: "/path/remote"
      recurse: no
      patterns: "*.pub"
    register: files_to_fetch
  - debug:
      var: files_to_fetch.files

  - name: "fetch .pub files from remote host"
    fetch: 
      flat: yes
      src:  "{{ item.path }}"
      dest: ./local/
    with_items: "{{ files_to_fetch.files }}"

  - name: update SSH keys
    authorized_key:
     user: user1
     key: "{{ lookup('file', item) }}"
     state: present
     #exclusive: yes
    with_fileglob:
      - local/*.pub

关于file - ansible 查找的替代方法,因为它总是在 localhost 上查找文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65952847/

相关文章:

c - 从文件中逐行读取并保存在列表中 C

Java-在另一个进程更新文件时读取文件

linux - QEMU 错误且权限被拒绝

ansible - 无法识别组变量

ansible - 如何在 Ansible 中获取任意远程用户的主目录?

ansible - ansible回调是如何配置的

linux - 用于在文本文件中查找模式并返回整行的 bash 脚本

javascript - 不能将 forEach 与文件列表一起使用

python-2.7 - 如何在 Ubuntu 16.04 上为 Python 2.7 安装 openCV 2.4.13?

ruby-on-rails - 安装 capybara-webkit gem 时出现 qmake 问题?