Rubynetes: Using OpenAPI to validate Kubernetes configs

栏目: IT技术 · 发布时间: 6年前

内容简介:In theprevious post we saw how we can create a Kubernetes Manifest from a Ruby Hash. However, to check we don’t add incorrect values we have to write detailed tests. Can we automate that in any way? Yes, we can.Fortunately it is very easy to get the type a

Story So Far

In theprevious post we saw how we can create a Kubernetes Manifest from a Ruby Hash. However, to check we don’t add incorrect values we have to write detailed tests. Can we automate that in any way? Yes, we can.

Fortunately it is very easy to get the type and layout of the resources Kubernetes uses directly from the Kubernetes server.

Enter OpenAPI

$ kubectl get --raw /openapi/v2

This will obtain the OpenAPI definitions of all the resources installed on the Kubernetes Cluster. All we need to do is translate the OpenAPI definition into a Ruby library we can use.

We can do that with a Makefile

Remember Make?

vendor: kubernetes-client
	bundle install --clean --without development test --deployment

kubernetes-client: kubeapi.json
	docker run --rm -v $(CURDIR):/local \
		-u $(shell id -u $(USER)):$(shell id -g $(USER)) \
		openapitools/openapi-generator-cli generate \
		-g ruby \
		-p "moduleName=Kubernetes" \
		-i /local/$< \
		-o /local/$@

kubeapi.json:
	kubectl get --raw /openapi/v2 > $@

.PHONY: clean
clean:
	rm -rf kubernetes-client kubeapi.json vendor

then tie it all together via the Gemfile

gemspec path: File.expand_path('kubernetes-client', __dir__)

source 'https://rubygems.org'
gem 'activesupport', '~> 6.0'

Build the library with make and we have a typed Ruby library ready to use - precisely tailored to the resources on your Kubernetes cluster.

Use the Generated Library

Now let’s change the create_job_manifest method from last time to use the types from the generated OpenAPI library.

def create_job_manifest(release, config, version, name)
  Kubernetes::IoK8sApiBatchV1Job.new(
    api_version: 'batch/v1',
    kind: 'Job',
    metadata: Kubernetes::IoK8sApimachineryPkgApisMetaV1ObjectMeta.new(
      name: name,
      labels: { build: config[:prefix] }
    ),
    spec: Kubernetes::IoK8sApiBatchV1JobSpec.new(
      ttl_seconds_after_finished: config[:holdTime],
      template: Kubernetes::IoK8sApiCoreV1PodTemplateSpec.new(
        spec: Kubernetes::IoK8sApiCoreV1PodSpec.new(
          restart_policy: 'Never',
          containers: [
            Kubernetes::IoK8sApiCoreV1Container.new(
              name: name,
              image: config[:image],
              resources: Kubernetes::IoK8sApiCoreV1ResourceRequirements.new(
                requests: {
                  memory: config[:requestsMemory],
                  cpu: config[:requestsCpu]
                },
                limits: {
                  memory: config[:limitsMemory],
                  cpu: config[:limitsCpu]
                }
              ),
              args: [
                '--dockerfile=Dockerfile',
                "--context=#{config[:gitRepo]}#refs/heads/release-#{release}",
                "--destination=#{config[:dockerTarget]}:#{version}"
              ],
              volume_mounts: [
                Kubernetes::IoK8sApiCoreV1VolumeMount.new(
                  name: config[:secretName], fred: 'boo', mount_path: '/root'
                )
              ]
            )
          ],
          volumes: [
            Kubernetes::IoK8sApiCoreV1Volume.new(
              name: config[:secretName],
              secret: Kubernetes::IoK8sApiCoreV1SecretVolumeSource.new(
                secret_name: config[:secretName],
                items: [
                  Kubernetes::IoK8sApiCoreV1KeyToPath.new(
                    key: '.dockerconfigjson', path: '.docker/config.json'
                  )
                ]
              )
            )
          ]
        )
      )
    )
  )
end

update the spec to use ‘dot format’ access.

describe '#create_job_manifest' do
  let(:job) {
    load 'create_docker_jobs'
    create_job_manifest('1.16', config, '1.16.1', 'job-1.16')
  }

  it 'has a restart Policy of never' do
    expect(job.spec.template.spec.restart_policy).to eq 'Never'
  end
end

And Test

Run the spec with rspec

$ bundle install --with development
$ bundle exec rspec
F

Failures:

  1) #create_job_manifest has a restart Policy of never
     Failure/Error: load 'create_docker_jobs'
     
     ArgumentError:
       `fred` is not a valid attribute in
       `Kubernetes::IoK8sApiCoreV1VolumeMount`. Please check the name
       to make sure its valid. List of attributes: [:mount_path,
       :mount_propagation, :name, :read_only, :sub_path, :sub_path_expr]
...

Whoops. How did that get in there?

Can We Do More?

Now we have typed manifests that we can manipulate easily within Ruby, but we still have to remember the names of the types. If you can remember that metadata is IoK8sApimachineryPkgApisMetaV1ObjectMeta , you’re doing better than me. Remembering stuff like that is what we have computers for.

Reflect on that, and we’ll see what we can do about it in the next post. Stay tuned.

Postscript

Kubernetes knows about the resources it wants, therefore the best way to get the resources correct is to ask Kubernetes what it wants to see.

Fortunately, with the OpenAPI interface and the generators that can use that interface to create code libaries that match our cluster precisely, we can easily incorporate those resource specifications in our Ruby code with ease.

Interested in Managed Kubernetes?

Brightbox have been managing web deployments large and small for over a decade. If you’re interested in the benefits of Kubernetes but want us to handle managing and monitoring it for you,drop us a line.


以上所述就是小编给大家介绍的《Rubynetes: Using OpenAPI to validate Kubernetes configs》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

人工智能产品经理——AI时代PM修炼手册

人工智能产品经理——AI时代PM修炼手册

张竞宇 / 电子工业出版社 / 2018-6 / 59

随着人工智能热潮的兴起,企业对人工智能领域产品经理的人才需求也开始井喷,人工智能产品经理成为顺应时代潮流的重要人力资源。实际上,人工智能确实给现有的产品和服务带来了全方位的升级,这也给产品经理从业人员提出了更高的要求,是关注人工智能产品的产品经理们面临的一次关键转型考验。 《人工智能产品经理——AI时代PM修炼手册》从知识体系、能力模型、沟通技巧等方面帮助大家系统地梳理了人工智能产品经理所必......一起来看看 《人工智能产品经理——AI时代PM修炼手册》 这本书的介绍吧!

HTML 压缩/解压工具
HTML 压缩/解压工具

在线压缩/解压 HTML 代码

XML、JSON 在线转换
XML、JSON 在线转换

在线XML、JSON转换工具

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具