使用ssh获取gitlab-runner 10.0.2克隆repo

时间:2017-10-13 18:14:44

标签: ssh gitlab gitlab-ci-runner

我有一个gitlab安装,我正在尝试使用docker executor设置一个gitlab-runner。一切正常,直到测试开始运行,然后由于我的项目是私有的,并且没有启用http访问,它们在克隆时失败:

struct Category {
    let id: Int
    let name: String
}

class ViewController: UIViewController {
    @IBOutlet weak var pickerView: UIPickerView!

    var categories = [Category]()

    override func viewDidLoad() {
        super.viewDidLoad()

        startRequestAndParse() { categories, error in
            guard let categories = categories, error == nil else {
                print(error?.localizedDescription ?? "Unknown error")
                return
            }

            // if you got here, everything is OK, so update model and UI on main thread

            DispatchQueue.main.async {
                self.categories = categories
                print(self.categories)

                // trigger whatever UI update you want here, too;

                self.pickerView.reloadAllComponents()
            }
        }
    }

    /// Initiate request from server and parse results
    ///
    /// - Parameters:
    ///     - completion: This is called when the request/parsing is done. This may be called
    ///                         on background thread. If parsing failed, the array of categories
    ///                         will be `nil` and we should have `error`.
    ///     - categories: First parameter of the `completion` closure is the array of `Category` objects, or `nil` on error.
    ///     - error:      Second parameter of the `completion` closure is the resulting `Error`, if any.

    private func startRequestAndParse(completion: @escaping (_ categories: [Category]?, _ error: Error?) -> Void) {
        let url = URL(string: "http://thecatapi.com/api/categories/list")!
        let task = URLSession.shared.dataTask(with: url) { data, _, error in
            guard let data = data, error == nil else {
                completion(nil, error)
                return
            }

            // ok, now parse

            let parser = XMLParser(data: data)
            let delegate = ParserDelegate()
            parser.delegate = delegate
            parser.parse()

            completion(delegate.categories, parser.parserError)
        }
        task.resume()
    }
}

// this assumes you set the picker's `delegate` to be the view controller (either in IB or programmatically in `viewDidLoad`

extension ViewController: UIPickerViewDelegate {
    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        return categories[row].name
    }
}

// this assumes you set the picker's `dataSource` to be the view controller (either in IB or programmatically in `viewDidLoad`

extension ViewController: UIPickerViewDataSource {
    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }

    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return categories.count
    }
}

/// Parser delegate for categories

class ParserDelegate: NSObject, XMLParserDelegate {
    private var id: Int?
    private var name: String?
    private var value: String?

    var categories: [Category]?

    // initialize `categories`

    func parserDidStartDocument(_ parser: XMLParser) {
        categories = []
    }

    // if `id` or `name`, initialize `value` so we'll capture the appropriate value

    func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]) {
        if elementName == "id" || elementName == "name" {
            value = ""
        }
    }

    // if `value` is not `nil`, go ahead and concatenate the additional characters

    func parser(_ parser: XMLParser, foundCharacters string: String) {
        value? += string
    }

    // if `id` or `name`, update the appropriate property
    // if `category`, build a `Category` object and add it to our array
    // regardless, reset `value` to `nil`

    func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {
        switch elementName {
        case "id":
            if let value = value {
                id = Int(value)
            }
        case "name":
            name = value
        case "category":
            if let id = self.id, let name = self.name {
                categories!.append(Category(id: id, name: name))
            }
            id = nil
            name = nil
        default:
            ()
        }
        value = nil
    }

    // if any error, reset `categories` so caller knows there was an issue

    func parser(_ parser: XMLParser, parseErrorOccurred parseError: Error) {
        categories = nil
    }

}

我调查了https://docs.gitlab.com/ee/ci/ssh_keys/README.html 并决定尝试一下,以便Running with gitlab-runner 10.0.2 (a9a76a50) on Jupiter-docker (5f4ed288) Using Docker executor with image fedora:26 ... Using docker image sha256:1f082f05a7fc20f99a4ccffc0484f45e6227984940f2c57d8617187b44fd5c46 for predefined container... Pulling docker image fedora:26 ... Using docker image fedora:26 ID=sha256:b0b140824a486ccc0f7968f3c6ceb6982b4b77e82ef8b4faaf2806049fc266df for build container... Running on runner-5f4ed288-project-5-concurrent-0 via 2705e39bc3d7... Cloning repository... Cloning into '/builds/pmatos/tob'... remote: Git access over HTTP is not allowed fatal: unable to access 'https://gitlab.linki.tools/pmatos/tob.git': The requested URL returned error: 403 ERROR: Job failed: exit code 1 开头:

.gitlab-ci.yml

我正确设置了SSH_PRIVATE_KEY,但问题是项目的克隆发生在image: fedora:26 before_script: # Install ssh-agent if not already installed, it is required by Docker. # (change apt-get to yum if you use a CentOS-based image) - 'which ssh-agent || ( apt-get update -y && apt-get install openssh-client -y )' # Run ssh-agent (inside the build environment) - eval $(ssh-agent -s) # Add the SSH key stored in SSH_PRIVATE_KEY variable to the agent store - ssh-add <(echo "$SSH_PRIVATE_KEY") # For Docker builds disable host key checking. Be aware that by adding that # you are suspectible to man-in-the-middle attacks. # WARNING: Use this only with the Docker executor, if you use it with shell # you will overwrite your user's SSH config. - mkdir -p ~/.ssh - '[[ -f /.dockerenv ]] && echo -e "Host *\n\tStrictHostKeyChecking no\n\n" > ~/.ssh/config' ... JOBS... 之前。然后我尝试使用before_script启动容器,但克隆仍尝试使用-v /home/pmatos/gitlab-runner_ssh:/root/.ssh。如何通过ssh强制容器克隆?

2 个答案:

答案 0 :(得分:1)

由于gitlab CI的工作方式,CI需要https访问存储库。因此,如果启用CI,则还需要启用https repo访问权限。

然而,这不是隐私问题,因为容器https可访问并不会阻止gitlab检查您是否有权访问它。

答案 1 :(得分:0)

  

然后我尝试使用-v /home/pmatos/gitlab-runner_ssh:/root/.ssh启动容器,但仍然克隆尝试使用HTTP

尽可能在容器内尝试添加

git config --global url.ssh://git@.insteadOf https://

(假设ssh用户为git

这将使任何https URL的任何克隆都使用ssh。