使用变量创建带有 ansible 的符号链接

Creating symlinks with ansible using variables

我正在编写一个剧本来创建 nodejs、npm 和 gulp 的符号链接,因为我需要使用特定版本并安装它我只是将文件夹解压缩到 /opt/ 所有这些会留下来。

我用于创建链接的项目任务是:

- name: Create NPM symlink
  file:
    src: '{{ item.src_dir }}/{{ item.src_name }}'
    dest: '{{ item.dest_dir }}/{{ item.dest_name }}'
    owner: "{{ ansible_ssh_user }}"
    group: "{{ ansible_ssh_user }}"
    state: link
  with_items:
    - { src_dir: "{{ npm_real_dir }}", src_name: "{{ npm_real_name }}" }
    - { dest_dir: "{{ nodenpm_link_dir }}", dest_name: "{{ npm_link_name }}" }

项目"zone"中使用的所有变量在主机文件中声明如下: npm_real_dir=/opt/nodejs/node-v6.11.2-linux-x64/lib/node_modules/npm/bin

npm_real_name=npm-cli.js

nodenpm_link_dir=/opt/nodejs/node-v6.11.2-linux-x64/bin

npm_link_name=npm

ansible_ssh_user=vagrant

我收到错误消息:

FAILED! => {"msg": "The task includes an option with an undefined variable. The error was: 'dict object' has no attribute 'dest_dir'

我不明白,因为任务中使用的所有变量都已声明且正确无误。我做了一个没有项目的类似任务:

- name: Create symbolic link for npm
  file:
    src: '{{ npm_real_dir }}/{{ npm_real_name }}'
    path: '{{ nodenpm_link_dir }}/{{ npm_link_name }}'
    owner: "{{ ansible_ssh_user }}"
    group: "{{ ansible_ssh_user }}"
    state: link

它的工作原理,但是结构和以前一样,只是没有项目。

此时我只想知道它是否是一个已知错误,使用项目创建链接是否有任何问题,或者我是否犯了一个愚蠢的错误并获得了相关知识

提前致谢

问题是您将两个不同的对象传递给 with_items 属性。第一个对象有两个属性(src_dirsrc_name),而第二个对象有两个不同的属性(dest_dirdest_name)。

您似乎想像这样将它们组合成一个对象:

- name: Create NPM symlink
  file:
    src: '{{ item.src_dir }}/{{ item.src_name }}'
    dest: '{{ item.dest_dir }}/{{ item.dest_name }}'
    owner: "{{ ansible_ssh_user }}"
    group: "{{ ansible_ssh_user }}"
    state: link
  with_items:
    - { src_dir: "{{ npm_real_dir }}", src_name: "{{ npm_real_name }}", dest_dir: "{{ nodenpm_link_dir }}", dest_name: "{{ npm_link_name }}" }

这应该会更好地工作并消除错误,但在这种情况下,您并不真正需要 with_items,因为它只是您正在处理的一项。您可以为其他工具添加更多对象,例如gulp 以同样的方式,例如像这样:

- name: Create symlinks
  file:
    src: '{{ item.src_dir }}/{{ item.src_name }}'
    dest: '{{ item.dest_dir }}/{{ item.dest_name }}'
    owner: "{{ ansible_ssh_user }}"
    group: "{{ ansible_ssh_user }}"
    state: link
  with_items:
    - { src_dir: "{{ npm_real_dir }}", src_name: "{{ npm_real_name }}", dest_dir: "{{ nodenpm_link_dir }}", dest_name: "{{ npm_link_name }}" }
    - { src_dir: "{{ gulp_real_dir }}", src_name: "{{ gulp_real_name }}", dest_dir: "{{ gulp_link_dir }}", dest_name: "{{ gulp_link_name }}" }