如何从 Gitlab-CI 运行 Ansible-Playbook?

And*_*kov 5 ansible gitlab-ci gitlab-ci-runner

我正在尝试在 Gitlab-ci 中创建一个管道来运行 ansible-playbook。这是我的 .gitlab-ci.yml 文件:

    image: "my_ansible_image"
    
    before_script:
        - eval $(ssh-agent -s)
        - echo "$SSH_PRIVATE_KEY" | tr -d '\r' | ssh-add -
        - mkdir -p ~/.ssh
        - chmod 700 ~/.ssh    
    
    build:
        script:
          - ansible-playbook -i inventory -u root --private-key "$SSH_PRIVATE_KEY" playbook.yml -vv
Run Code Online (Sandbox Code Playgroud)

该剧本尝试执行一个简单的 ping 模块:

---
   - name: Ping test ## name of the first task
     ping:  ##ping is a special case that do not requieres any attributs
Run Code Online (Sandbox Code Playgroud)

由于某种原因,ssh 连接总是失败,并出现以下错误:

$ ansible-playbook -i inventory -u root --private-key /builds/my_name/rhe7_set-up-rpm/private_key playbook.yml -vv
[WARNING]: Ansible is being run in a world writable directory
(/builds/aramniko/rhe7_set-up-rpm), ignoring it as an ansible.cfg source. For
more information see
https://docs.ansible.com/ansible/devel/reference_appendices/config.html#cfg-in-
world-writable-dir
ansible-playbook 2.9.11
  config file = None
  configured module search path = ['/root/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
  ansible python module location = /usr/local/lib/python3.8/site-packages/ansible
  executable location = /usr/local/bin/ansible-playbook
  python version = 3.8.3 (default, Jul 26 2020, 02:36:32) [GCC 9.2.0]
No config file found; using defaults
PLAYBOOK: playbook.yml *********************************************************
1 plays in playbook.yml
PLAY [Set-UP] ******************************************************************
TASK [Gathering Facts] *********************************************************
task path: /builds/my_name/rhe7_set-up-rpm/playbook.yml:2
fatal: [XXXXXXXXX]: UNREACHABLE! => {"changed": false, "msg": "Failed to connect to the host via ssh: Warning: Permanently added 'XXXXXXXX' (ECDSA) to the list of known hosts.\r\nno such identity: /builds/my_name/rhe7_set-up-rpm/private_key: No such file or directory\r\nroot@XXXXXXXXXX: Permission denied (publickey,gssapi-keyex,gssapi-with-mic,password).", "unreachable": true}
PLAY RECAP *********************************************************************
XXXXXXXXXXX               : ok=0    changed=0    unreachable=1    failed=0    skipped=0    rescued=0    ignored=0 
Run Code Online (Sandbox Code Playgroud)

我该如何解决这个问题?

编辑解决方案是将以下内容添加到before_script

---
   - name: Ping test ## name of the first task
     ping:  ##ping is a special case that do not requieres any attributs
Run Code Online (Sandbox Code Playgroud)

DV8*_*2XL 4

您应该通过ssh-keyscan在专用服务器上运行并将结果复制到名为 的 GitLab 变量来验证您的主机密钥SSH_KNOWN_HOSTS。在管道中,您需要将其复制到~/.ssh/known_hosts管道环境中的文件中。说明在这里: https: //docs.gitlab.com/ee/ci/ssh_keys/#verifying-the-ssh-host-keys

另外,您应该考虑创建一个安全目录来存储配置文件。请参阅: https: //docs.ansible.com/ansible/latest/reference_appendices/config.html