我在 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/