gitansibleansible-2.x

Add `git remote add usptream` to repositories but using Ansible


I have an Ansible 2.9.27 and I am trying to add upstream remote for git repositories which I previously cloned with Ansible. Let's assume that already cloned repositories are located in /home/user/Documents/github/ directory and I want to add upstream remote for them (git remote add upstream for each repo).

The task looks like this:

- 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 }}"

The issue is that ansible-lint doesn't like using command instead of git module:

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

What I need to do to add remote upstream for these repositories with git module?


Solution

  • Since what you want to achieve is not (yet...) taken in charge by the git module, this is a very legitimate use of command.

    In such cases, it is possible to silence the specific rule in ansible lint for that specific task.

    To go a bit further, your changed_when: false clause looks a bit like a quick and dirty fix to silence the no-changed-when rule and can be enhanced in conjunction with a failed_when clause to detect cases where the remote already exists.

    Here is how I would write that task to be idempotent, documented and passing all needed lint rules:

    - 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
      ansible.builtin.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 }}"