Search code examples
pythongitautomationpushgitpython

How to use GitPython to perform "git push" when using SSH Keys?


I am trying to write a Python Controller, which would help me automate Git -usage. I've gotten all other commands to work - but I am having difficulties with git push equivalent, when using GitPython Library.

This is where I am right now. This should be working without the SSH Key identification, but I have to squeeze that in.

""" Execute Git Push with GitPython Library.
Hardcoded values: 'branch' environment.
TODO: This is not working. """
def push(self, repo_path, branch, commit_message, user):
    repo = Repo(repo_path)
    repo.git.add('--all')
    repo.git.commit('-m', commit_message)
    origin = repo.remote(name=branch)
    origin.push()

This is what I have on my Initialization. (Cleared some values due to privacy.)

    load_dotenv()
    self.BRANCH = "TBD" # Hardcoded Value
    self.REPO_PATH = os.getenv('REPO_PATH')
    self.REPO = Repo(self.REPO_PATH)
    self.COMMIT_MESSAGE = '"Commit from Controller."'

    # TODO: These should be changed, when deployed.
    self.GIT_SSH_KEY = os.path.expanduser('/home/user/.ssh/id_rsa')
    self.GIT_SSH_CMD = "ssh -i %s" % self.GIT_SSH_KEY
    self.GIT_USER = "user" # This needs to be changed.

From my understanding from this (GitPython and SSH Keys?) the tactic here is to use GIT_SSH environment variable to provide executable, which will call the ssh - but since I am a beginner, I am having trouble understanding what exactly that environment variable should contain, and how to wrap that with the push function.

Thank you in advance!


Solution

  • First, setting values on self isn't going to accomplish anything by itself, unless there are parts of your code you're not showing us. If you need to set the GIT_SSH environment variable, then you would need to set os.environ['GIT_SSH'].


    In general, you shouldn't need to set GIT_SSH unless you require a non-default ssh commandline. That is, if I have:

    $ git remote -v
    origin  ssh://[email protected]/larsks/gnu-hello (fetch)
    origin  ssh://[email protected]/larsks/gnu-hello (push)
    

    Then I can write:

    >>> import git
    >>> repo = git.Repo('.')
    >>> origin = repo.remote('origin')
    >>> res = origin.push()
    >>> res[0].summary
    '[up to date]\n'
    

    I didn't have to set anything special here; the defaults were entirely appropriate. Under the hood, GitPython just calls the git command line, so anything that works with the cli should work fine without special configuration.