Exemplo n.º 1
0
        private void EnsureServiceAccount(User user)
        {
            var groupNamespaceName = user.Spec.GetGroupNamespace();
            var serviceAccountName = user.Metadata.Name;
            var serviceAccounts    = _client.ListNamespacedServiceAccount(groupNamespaceName,
                                                                          fieldSelector: $"metadata.name={serviceAccountName}");

            if (!serviceAccounts.Items.Any())
            {
                var serviceAccount = new V1ServiceAccount
                {
                    Metadata = new V1ObjectMeta
                    {
                        Name   = serviceAccountName,
                        Labels = new Dictionary <string, string>()
                        {
                            { "kiamol", "ch20" },
                        }
                    },
                    AutomountServiceAccountToken = false
                };
                _client.CreateNamespacedServiceAccount(serviceAccount, groupNamespaceName);
                Console.WriteLine($"** Created service account: {serviceAccountName}, in group namespace: {groupNamespaceName}");
            }
            else
            {
                Console.WriteLine($"** Service account exists: {serviceAccountName}, in group namespace: {groupNamespaceName}");
            }
        }
        public void ReturnsFalseIfFieldsAreDifferent()
        {
            var x = new V1ServiceAccount
            {
                Metadata = new V1ObjectMeta
                {
                    Annotations = new Dictionary <string, string>
                    {
                        [KubernetesConstants.K8sEdgeOriginalModuleId] = "Object1"
                    },
                    Labels = new Dictionary <string, string>
                    {
                        [KubernetesConstants.K8sEdgeDeviceLabel] = "device1",
                    },
                    Name = "object1"
                }
            };
            var y = new V1ServiceAccount
            {
                Metadata = new V1ObjectMeta
                {
                    Annotations = new Dictionary <string, string>
                    {
                        [KubernetesConstants.K8sEdgeOriginalModuleId] = "Object1"
                    },
                    Labels = new Dictionary <string, string>
                    {
                        [KubernetesConstants.K8sEdgeDeviceLabel] = "device1",
                    },
                    Name = "object1"
                }
            };

            Assert.True(Comparer.Equals(x, y));

            y.Metadata.Name = "object2";
            Assert.False(Comparer.Equals(x, y));

            y.Metadata.Name = "object1";
            Assert.True(Comparer.Equals(x, y));

            y.Metadata.Annotations = new Dictionary <string, string>
            {
                ["newkey"] = "Object1"
            };
            Assert.False(Comparer.Equals(x, y));

            y.Metadata.Annotations = new Dictionary <string, string>
            {
                [KubernetesConstants.K8sEdgeOriginalModuleId] = "Object1"
            };
            Assert.True(Comparer.Equals(x, y));

            y.Metadata.Labels = new Dictionary <string, string>
            {
                ["newkey2"] = "Object1"
            };
            Assert.False(Comparer.Equals(x, y));
        }
        public void ReferenceComparisonTest()
        {
            var pvc1 = new V1ServiceAccount();
            var pvc2 = pvc1;

            Assert.True(Comparer.Equals(pvc1, pvc2));
            Assert.False(Comparer.Equals(null, pvc2));
            Assert.False(Comparer.Equals(pvc1, null));
        }
        public static async Task AddModuleServiceAccountAsync(this KubernetesClient client, string name, IDictionary <string, string> labels, IDictionary <string, string> annotations)
        {
            var serviceAccount = new V1ServiceAccount
            {
                Metadata = new V1ObjectMeta
                {
                    Name        = name,
                    Annotations = annotations,
                    Labels      = labels
                }
            };

            await client.Kubernetes.CreateNamespacedServiceAccountAsync(serviceAccount, client.DeviceNamespace);
        }
Exemplo n.º 5
0
        public void IgnoreOtherMetadataTest()
        {
            var saWithOwnerRef = new V1ServiceAccount
            {
                Metadata = new V1ObjectMeta
                {
                    Annotations = new Dictionary <string, string>
                    {
                        [KubernetesConstants.K8sEdgeOriginalModuleId] = "Object1"
                    },
                    Labels = new Dictionary <string, string>
                    {
                        [KubernetesConstants.K8sEdgeDeviceLabel]  = "device1",
                        [KubernetesConstants.K8sEdgeHubNameLabel] = "hostname"
                    },
                    Name            = "object1",
                    OwnerReferences = new List <V1OwnerReference>
                    {
                        new V1OwnerReference("v1", name: "iotedged", kind: "Deployment", uid: "123")
                    }
                }
            };
            var saWithoutOwnerRef = new V1ServiceAccount
            {
                Metadata = new V1ObjectMeta
                {
                    Annotations = new Dictionary <string, string>
                    {
                        [KubernetesConstants.K8sEdgeOriginalModuleId] = "Object1"
                    },
                    Labels = new Dictionary <string, string>
                    {
                        [KubernetesConstants.K8sEdgeDeviceLabel]  = "device1",
                        [KubernetesConstants.K8sEdgeHubNameLabel] = "hostname"
                    },
                    Name = "object1"
                }
            };

            Assert.True(Comparer.Equals(saWithOwnerRef, saWithoutOwnerRef));
        }
 public void UpdateServiceAccount(V1ServiceAccount to, V1ServiceAccount from)
 {
     to.Metadata.ResourceVersion = from.Metadata.ResourceVersion;
 }
Exemplo n.º 7
0
 public static void UpdateServiceAccount(V1ServiceAccount serviceAccount)
 {
     Log.LogDebug((int)EventIds.UpdateServiceAccount, $"Update Service Account {serviceAccount.Metadata.Name}");
 }
Exemplo n.º 8
0
 internal static void CreateServiceAccount(V1ServiceAccount serviceAccount)
 {
     Log.LogDebug((int)EventIds.CreateServiceAccount, $"Create Service Account {serviceAccount.Metadata.Name}");
 }
        private async Task <string> DescribeObject(Kubernetes client, V1Namespace ns, V1ServiceAccount o, StringBuilder buffer)
        {
            var fetched = await client.ReadNamespacedServiceAccountAsync(o.Metadata.Name, ns.Metadata.Name).ConfigureAwait(false);

            buffer.AppendLine($"API Veresion: {fetched.ApiVersion}");
            buffer.AppendLine($"Kind: {fetched.Kind}");
            buffer.AppendLine(DescribeMetadata(fetched.Metadata));
            return($"Service Account - {fetched.Metadata.Name}");
        }
Exemplo n.º 10
0
    private async Task <T> WithKubernetesContext <T>(Component component, DeploymentScope deploymentScope, Func <IKubernetes, KubernetesData, V1ClusterRole, V1ServiceAccount, Task <T> > callback)
    {
        if (component is null)
        {
            throw new ArgumentNullException(nameof(component));
        }

        if (deploymentScope is null)
        {
            throw new ArgumentNullException(nameof(deploymentScope));
        }

        if (callback is null)
        {
            throw new ArgumentNullException(nameof(callback));
        }

        var identity = await azureResourceService
                       .GetResourceAsync <AzureIdentityResource>(component.IdentityId, throwIfNotExists : true)
                       .ConfigureAwait(false);

        var data   = GetKubernetesData(deploymentScope);
        var client = GetKubernetesClient(data);

        var roleDefinition = new V1ClusterRole()
        {
            Metadata = new V1ObjectMeta()
            {
                Name = "teamcloud-runner"
            },
            Rules = new List <V1PolicyRule>()
            {
                new V1PolicyRule()
                {
                    ApiGroups = new List <string>()
                    {
                        "", "extensions", "apps"
                    },
                    Resources = new List <string>()
                    {
                        "*"
                    },
                    Verbs = new List <string>()
                    {
                        "*"
                    }
                },
                new V1PolicyRule()
                {
                    ApiGroups = new List <string>()
                    {
                        "batch"
                    },
                    Resources = new List <string>()
                    {
                        "jobs", "cronjobs"
                    },
                    Verbs = new List <string>()
                    {
                        "*"
                    }
                }
            }
        };

        try
        {
            roleDefinition = await client
                             .CreateClusterRoleAsync(roleDefinition)
                             .ConfigureAwait(false);
        }
        catch (HttpOperationException exc) when(exc.Response.StatusCode == System.Net.HttpStatusCode.Conflict)
        {
            roleDefinition = await client
                             .ReadClusterRoleAsync(roleDefinition.Metadata.Name)
                             .ConfigureAwait(false);
        }

        var serviceAccount = new V1ServiceAccount()
        {
            Metadata = new V1ObjectMeta()
            {
                Name = $"{data.Namespace}-{identity.PrincipalId}"
            }
        };

        try
        {
            serviceAccount = await client
                             .CreateNamespacedServiceAccountAsync(serviceAccount, data.Namespace)
                             .ConfigureAwait(false);
        }
        catch (HttpOperationException exc) when(exc.Response.StatusCode == System.Net.HttpStatusCode.Conflict)
        {
            serviceAccount = await client
                             .ReadNamespacedServiceAccountAsync(serviceAccount.Metadata.Name, data.Namespace)
                             .ConfigureAwait(false);
        }

        return(await callback(client, data, roleDefinition, serviceAccount).ConfigureAwait(false));
    }
Exemplo n.º 11
0
    public static async Task <K8SConfiguration> CreateClusterConfigAsync(this IKubernetes kubernetes, V1ServiceAccount serviceAccount)
    {
        if (kubernetes is null)
        {
            throw new ArgumentNullException(nameof(kubernetes));
        }

        if (serviceAccount is null)
        {
            throw new ArgumentNullException(nameof(serviceAccount));
        }

        var serviceAccountSecret = await serviceAccount.Secrets
                                   .ToAsyncEnumerable()
                                   .SelectAwait(s => new ValueTask <V1Secret>(kubernetes.ReadNamespacedSecretAsync(s.Name, serviceAccount.Namespace())))
                                   .FirstAsync(s => s.Type.Equals("kubernetes.io/service-account-token"))
                                   .ConfigureAwait(false);

        var clusterName    = kubernetes.BaseUri.GetComponents(UriComponents.Host, UriFormat.Unescaped);
        var clusterUser    = serviceAccount.Name();
        var clusterContext = Guid.NewGuid().ToString();

        return(new K8SConfiguration()
        {
            ApiVersion = "v1",
            Kind = "Config",
            Clusters = new Cluster[]
            {
                new Cluster()
                {
                    Name = clusterName,
                    ClusterEndpoint = new ClusterEndpoint()
                    {
                        CertificateAuthorityData = Convert.ToBase64String(serviceAccountSecret.Data["ca.crt"]),
                        Server = kubernetes.BaseUri.ToString().TrimEnd('/')
                    }
                }
            },
            Users = new User[]
            {
                new User()
                {
                    Name = clusterUser,
                    UserCredentials = new UserCredentials()
                    {
                        ClientKeyData = Convert.ToBase64String(serviceAccountSecret.Data["ca.crt"]),
                        Token = Encoding.UTF8.GetString(serviceAccountSecret.Data["token"])
                    }
                }
            },
            Contexts = new Context[]
            {
                new Context()
                {
                    Name = clusterContext,
                    ContextDetails = new ContextDetails()
                    {
                        Cluster = clusterName,
                        Namespace = serviceAccount.Name(),
                        User = clusterUser
                    }
                }
            },
            CurrentContext = clusterContext
        });
    }
Exemplo n.º 12
0
    public static async Task <KubernetesClientConfiguration> CreateClientConfigAsync(this IKubernetes kubernetes, V1ServiceAccount serviceAccount)
    {
        if (kubernetes is null)
        {
            throw new ArgumentNullException(nameof(kubernetes));
        }

        if (serviceAccount is null)
        {
            throw new ArgumentNullException(nameof(serviceAccount));
        }

        var clusterConfig = await kubernetes
                            .CreateClusterConfigAsync(serviceAccount)
                            .ConfigureAwait(false);

        return(KubernetesClientConfiguration.BuildConfigFromConfigObject(clusterConfig));
    }