将 `git remote add usptream` 添加到存储库,但使用 Ansible

nik*_*men 6 git ansible ansible-2.x

我有一个 Ansible 2.9.27,我正在尝试为我之前用 Ansible 克隆的 git 存储库添加上游远程。让我们假设已经克隆的存储库位于/home/user/Documents/github/目录中,并且我想为它们添加上游远程(git remote add upstream对于每个存储库)。

任务如下所示:

- name: Add remote upstream to github projects
  # TODO: how to add remote with git module?
  command: git remote add upstream git@github.com:{{ git_user }}/{{ item }}.git
  changed_when: false
  args:
    chdir: /home/user/Documents/github/{{ item }}
  loop: "{{ github_repos }}"
Run Code Online (Sandbox Code Playgroud)

问题是 ansible-lint 不喜欢使用command模块git

WARNING  Listing 1 violation(s) that are fatal
command-instead-of-module: git used in place of git module
tasks/github.yaml:15 Task/Handler: Add remote upstream to github projects
Run Code Online (Sandbox Code Playgroud)

我需要做什么才能使用git模块为这些存储库添加远程上游?

Zei*_*tor 5

由于您想要实现的目标尚未由模块负责git因此这是command.

在这种情况下,可以在 ansible lint 中针对该特定任务静默特定规则

更进一步,您的changed_when: false子句看起来有点像一个快速而肮脏的修复,以静默规则no-changed-when,并且可以与子句结合使用来增强failed_when以检测远程已存在的情况。

以下是我如何将该任务编写为幂等、记录并传递所有需要的 lint 规则:

- name: Add remote upstream to github projects
  # Git module does not know how to add remotes (yet...)
  # Using command and silencing corresponding ansible-lint rule 
  # noqa command-instead-of-module
  command:
    cmd: git remote add upstream git@github.com:{{ git_user }}/{{ item }}.git
    chdir: /home/user/Documents/github/{{ item }}
  register: add_result
  changed_when: add_result.rc == 0
  failed_when:
    - add_result.rc != 0
    - add_result.stderr | default('') is not search("remote .* already exists")
  loop: "{{ github_repos }}"
Run Code Online (Sandbox Code Playgroud)