{"id":1049,"date":"2021-06-01T12:51:44","date_gmt":"2021-06-01T12:51:44","guid":{"rendered":"https:\/\/blog.ngocha.biz\/?p=1049"},"modified":"2021-06-01T12:51:44","modified_gmt":"2021-06-01T12:51:44","slug":"create-kubernetes-role","status":"publish","type":"post","link":"https:\/\/blog.ngocha.biz\/?p=1049","title":{"rendered":"How to Create kubernetes Role for Service Account"},"content":{"rendered":"<p>In this blog, you will learn how to create Kubernetes role for a service account and use it with the pods, deployments, and cronjobs.<\/p>\n<blockquote><p><strong>Note: <\/strong>A <code>role<\/code> provides API access only to resources present in a namespace. For cluster-wide API access, you should use a <code>ClusterRole<\/code><\/p><\/blockquote>\n<h2 id=\"create-kubernetes-role-for-service-account\">Create Kubernetes Role for Service Account<\/h2>\n<p>Let&#8217;s consider the following scenario<\/p>\n<ol>\n<li>You have deployments\/pods in a namespace called <code>webapps<\/code><\/li>\n<li>The deployments\/pods need Kubernetes API access to manage resources in a namespace.<\/li>\n<\/ol>\n<p>The solution to the above scenarios is to have a service account with roles with specific API access.<\/p>\n<ol>\n<li>Create a service account bound to the namespace webapps namespace<\/li>\n<li>Create a role with the list of required API access to Kubernetes resoruces.<\/li>\n<li>Create a Rolebinding to bind the role to the service account.<\/li>\n<li>Use the service account in the pod\/deployment or <a href=\"https:\/\/devopscube.com\/create-kubernetes-jobs-cron-jobs\/\" rel=\"noreferrer noopener\">Kubernetes Cronjobs<\/a><\/li>\n<\/ol>\n<p>Lets implement it.<\/p>\n<h2 id=\"create-webapps-namespace\">Create webapps Namespace<\/h2>\n<p>For the purpose of demonstration, we will create a namespace called <code>webapps<\/code><\/p>\n<pre><code>kubectl create namespace webapps<\/code><\/pre>\n<h2 id=\"create-kubernetes-service-account\">Create Kubernetes Service Account<\/h2>\n<p>Let&#8217;s create a service account named <code>app-service-account<\/code> that bounds to <code>webapps<\/code> namespace<\/p>\n<p>Copy the following and execute directly on the terminal.<\/p>\n<pre><code>cat &lt;&lt;EOF | kubectl apply -f -\napiVersion: v1\nkind: ServiceAccount\nmetadata:\n  name: app-service-account\n  namespace: webapps\nEOF<\/code><\/pre>\n<h2 id=\"create-a-role-for-api-access\">Create a Role For API Access<\/h2>\n<p>In the kubernetes Role, we specify the list of API access required for Kubernetes resources.<\/p>\n<blockquote><p><strong>Note:<\/strong> The following role has access to most Kubernetes resources with all read, write, list, update, patch, and delete permissions. \u00a0When you implement it in real projects, you should add only the required resources and actions to the role.<\/p><\/blockquote>\n<p>Lets create a role named <code>app-role<\/code> specific to <code>webapps<\/code> namespace.<\/p>\n<p>Copy the following and execute directly on the terminal.<\/p>\n<pre><code>cat &lt;&lt;EOF | kubectl apply -f -\n---\napiVersion: rbac.authorization.k8s.io\/v1\nkind: Role\nmetadata:\n  name: app-role\n  namespace: webapps\nrules:\n  - apiGroups:\n        - \"\"\n        - apps\n        - autoscaling\n        - batch\n        - extensions\n        - policy\n        - rbac.authorization.k8s.io\n    resources:\n      - pods\n      - componentstatuses\n      - configmaps\n      - daemonsets\n      - deployments\n      - events\n      - endpoints\n      - horizontalpodautoscalers\n      - ingress\n      - jobs\n      - limitranges\n      - namespaces\n      - nodes\n      - pods\n      - persistentvolumes\n      - persistentvolumeclaims\n      - resourcequotas\n      - replicasets\n      - replicationcontrollers\n      - serviceaccounts\n      - services\n    verbs: [\"get\", \"list\", \"watch\", \"create\", \"update\", \"patch\", \"delete\"]\nEOF<\/code><\/pre>\n<p>Lets list the role.<\/p>\n<pre><code>kubectl get roles -n webapps<\/code><\/pre>\n<p>[powerkit_posts title=&#8221;Also Read&#8221; \u00a0ids=&#8221;1836&#8243; \u00a0image_size=&#8221;pk-thumbnail&#8221; template=&#8221;list&#8221;]<\/p>\n<h2 id=\"create-a-rolebinding-attaching-role-to-serviceaccount-\">Create a Rolebinding [ Attaching Role to ServiceAccount]<\/h2>\n<p>Now we have a service account and a role which has no relation.<\/p>\n<p>With Rolebinding we attach the role to the service account. So the pods which use the service account in <code>webapps<\/code> namespace will have all the access mentioned in the <code>app-role<\/code><\/p>\n<p>Copy the following and execute directly on the terminal.<\/p>\n<pre><code>cat &lt;&lt;EOF | kubectl apply -f -\n---\napiVersion: rbac.authorization.k8s.io\/v1\nkind: RoleBinding\nmetadata:\n  name: app-rolebinding\n  namespace: webapps \nroleRef:\n  apiGroup: rbac.authorization.k8s.io\n  kind: Role\n  name: app-role \nsubjects:\n- namespace: webapps \n  kind: ServiceAccount\n  name: app-service-account \nEOF<\/code><\/pre>\n<h2 id=\"validate-kubernetes-role-permissions\">Validate Kubernetes Role Permissions<\/h2>\n<p>We will use the <code>bibinwilson\/docker-kubectl <\/code>Docker image that I have created with the kubectl utility.<\/p>\n<p>Let&#8217;s deploy a pod named <code>debug<\/code> with bibinwilson\/docker-kubectl image and our service account <code>app-service-account<\/code>.<\/p>\n<pre><code>cat &lt;&lt;EOF | kubectl apply -f -\n---\napiVersion: v1\nkind: Pod\nmetadata:\n  name: debug\n  namespace: webapps\nspec:\n  containers:\n  - image: bibinwilson\/docker-kubectl:latest\n    name: kubectl\n  serviceAccountName: app-service-account\nEOF<\/code><\/pre>\n<p>Lets <code>exec<\/code> in to the <code>debug<\/code> pod and see if has the privileges we mentioned in the role.<\/p>\n<pre><code>kubectl exec -it debug \/bin\/bash -n webapps<\/code><\/pre>\n<p>Now, you should be able to list pods and other resources in <code>webapps<\/code> namespace. You cannot list the pods in other namespaces are this role is specific to <code>webapps<\/code> namespace.<\/p>\n<p>If you deploy a pod without the service account and list the pods, you will get the following error.<\/p>\n<pre><code>Error from server (Forbidden): pods is forbidden: User \"system:serviceaccount:webapps:default\" cannot list resource \"pods\" in API group \"\" in the namespace \"webapps\"<\/code><\/pre>\n<p>The default service account that gets attached to pods doesn&#8217;t have any API access to resources.<\/p>\n<h2 id=\"using-service-account-with-kubernetes-cronjob\">Using Service Account with Kubernetes Cronjob<\/h2>\n<p>Here is an example of Kubernetes Cronjob with a service account.<\/p>\n<pre><code>apiVersion: batch\/v1beta1\nkind: CronJob\nmetadata:\n    name: kubernetes-cron-job\nspec:\n  schedule: \"0,15,30,45 * * * *\"\n  jobTemplate:\n    spec:\n      template:\n        metadata:\n          labels:\n            app: cron-batch-job\n        spec:\n          restartPolicy: OnFailure\n          serviceAccountName: app-service-account\n          containers:\n          - name: kube-cron-job\n            image: devopscube\/kubernetes-job-demo:latest\n            args: [\"100\"]<\/code><\/pre>\n<h2 id=\"using-service-account-with-kubernetes-deployment\">Using Service Account With Kubernetes Deployment<\/h2>\n<p>Here is an example of a <a href=\"https:\/\/devopscube.com\/kubernetes-deployment-tutorial\/\" rel=\"noreferrer noopener\">Kubernetes deployment<\/a> with a service account.<\/p>\n<pre><code>apiVersion: apps\/v1\nkind: Deployment\nmetadata:\n  name: nginx-deployment\n  labels:\n    app: nginx\nspec:\n  replicas: 3\n  selector:\n    matchLabels:\n      app: nginx\n  template:\n    metadata:\n      labels:\n        app: nginx\n    spec:\n      serviceAccountName: app-service-account\n      containers:\n      - name: nginx\n        image: nginx:1.14.2\n        ports:\n        - containerPort: 80<\/code><\/pre>\n<h2 id=\"conclusion\">Conclusion<\/h2>\n<p>In this blog post, I have added all the steps required to create Kubernetes role and use it with the pod, deployment, and Cronjonbs.<\/p>\n<p>There are particularly not many use cases where you need the namespace specific roles.<\/p>\n<p>One main use would be for creating users with access limited to a namespace. Also, to create <a href=\"https:\/\/devopscube.com\/kubernetes-api-access-service-account\/\" rel=\"noreferrer noopener\">service accounts to have API access<\/a> to namespaces from external applications.<\/p>\n<p>Let me know if you face any issues or have any questions related to Kubernetes roles.<\/p>\n<hr>\n<p><strong>Ngu\u1ed3n:<\/strong> <a href=\"https:\/\/devopscube.com\/create-kubernetes-role\/\" target=\"_blank\" rel=\"noopener noreferrer\">How to Create kubernetes Role for Service Account \u2014 DevOpsCube<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Source: https:\/\/devopscube.com\/create-kubernetes-role\/<\/p>\n","protected":false},"author":0,"featured_media":1050,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1],"tags":[],"class_list":["post-1049","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-devops"],"_links":{"self":[{"href":"https:\/\/blog.ngocha.biz\/index.php?rest_route=\/wp\/v2\/posts\/1049","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/blog.ngocha.biz\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/blog.ngocha.biz\/index.php?rest_route=\/wp\/v2\/types\/post"}],"replies":[{"embeddable":true,"href":"https:\/\/blog.ngocha.biz\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=1049"}],"version-history":[{"count":0,"href":"https:\/\/blog.ngocha.biz\/index.php?rest_route=\/wp\/v2\/posts\/1049\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/blog.ngocha.biz\/index.php?rest_route=\/wp\/v2\/media\/1050"}],"wp:attachment":[{"href":"https:\/\/blog.ngocha.biz\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=1049"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/blog.ngocha.biz\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=1049"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/blog.ngocha.biz\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=1049"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}