コード例 #1
0
ファイル: utils.py プロジェクト: johnsca/metallb-bundle
def create_pod_security_policy_with_api(namespace):
    """Create pod security policy."""
    # Using the API because of LP:1886694
    logging.info('Creating pod security policy with K8s API')
    _load_kube_config()

    metadata = client.V1ObjectMeta(
        namespace=namespace,
        name='controller',
        labels={'app': 'metallb'}
    )
    policy_spec = client.PolicyV1beta1PodSecurityPolicySpec(
        allow_privilege_escalation=False,
        default_allow_privilege_escalation=False,
        fs_group=client.PolicyV1beta1FSGroupStrategyOptions(
            ranges=[client.PolicyV1beta1IDRange(max=65535, min=1)],
            rule='MustRunAs'
        ),
        host_ipc=False,
        host_network=False,
        host_pid=False,
        privileged=False,
        read_only_root_filesystem=True,
        required_drop_capabilities=['ALL'],
        run_as_user=client.PolicyV1beta1RunAsUserStrategyOptions(
            ranges=[client.PolicyV1beta1IDRange(max=65535, min=1)],
            rule='MustRunAs'
        ),
        se_linux=client.PolicyV1beta1SELinuxStrategyOptions(
            rule='RunAsAny',
        ),
        supplemental_groups=client.PolicyV1beta1SupplementalGroupsStrategyOptions(
            ranges=[client.PolicyV1beta1IDRange(max=65535, min=1)],
            rule='MustRunAs'
        ),
        volumes=['configMap', 'secret', 'emptyDir'],
    )

    body = client.PolicyV1beta1PodSecurityPolicy(metadata=metadata, spec=policy_spec)

    with client.ApiClient() as api_client:
        api_instance = client.PolicyV1beta1Api(api_client)
        try:
            api_instance.create_pod_security_policy(body, pretty=True)
            return True
        except ApiException as err:
            logging.exception("Exception when calling PolicyV1beta1Api"
                              "->create_pod_security_policy.")
            if err.status != 409:
                # ignoring 409 (AlreadyExists) errors
                return False
            else:
                return True
コード例 #2
0
    def generate_psp(self, user):
        policy = client.PolicyV1beta1PodSecurityPolicy(
            api_version="policy/v1beta1",
            kind="PodSecurityPolicy",
            metadata=client.V1ObjectMeta(
                name="tool-{}-psp".format(user.name),
                annotations={
                    "seccomp.security.alpha.kubernetes.io/allowedProfileNames":
                    "runtime/default",  # noqa: E501
                    "seccomp.security.alpha.kubernetes.io/defaultProfileName":
                    "runtime/default",  # noqa: E501
                },
            ),
            spec=client.PolicyV1beta1PodSecurityPolicySpec(
                allow_privilege_escalation=False,
                fs_group=client.PolicyV1beta1FSGroupStrategyOptions(
                    rule="MustRunAs",
                    ranges=[
                        client.PolicyV1beta1IDRange(max=int(user.id),
                                                    min=int(user.id))
                    ],
                ),
                host_ipc=False,
                host_network=False,
                host_pid=False,
                privileged=False,
                required_drop_capabilities=["ALL"],
                read_only_root_filesystem=False,
                run_as_user=client.PolicyV1beta1RunAsUserStrategyOptions(
                    rule="MustRunAs",
                    ranges=[
                        client.PolicyV1beta1IDRange(max=int(user.id),
                                                    min=int(user.id))
                    ],
                ),
                se_linux=client.PolicyV1beta1SELinuxStrategyOptions(
                    rule="RunAsAny"),
                run_as_group=client.PolicyV1beta1RunAsGroupStrategyOptions(
                    rule="MustRunAs",
                    ranges=[
                        client.PolicyV1beta1IDRange(max=int(user.id),
                                                    min=int(user.id))
                    ],
                ),
                supplemental_groups=client.
                PolicyV1beta1SupplementalGroupsStrategyOptions(  # noqa: E501
                    rule="MustRunAs",
                    ranges=[client.PolicyV1beta1IDRange(min=1, max=65535)],
                ),
                volumes=[
                    "configMap",
                    "downwardAPI",
                    "emptyDir",
                    "projected",
                    "secret",
                    "hostPath",
                    "persistentVolumeClaim",
                ],
                allowed_host_paths=[
                    client.PolicyV1beta1AllowedHostPath(
                        path_prefix="/var/lib/sss/pipes", read_only=False),
                    client.PolicyV1beta1AllowedHostPath(
                        path_prefix="/data/project", read_only=False),
                    client.PolicyV1beta1AllowedHostPath(
                        path_prefix="/data/scratch", read_only=False),
                    client.PolicyV1beta1AllowedHostPath(
                        path_prefix="/public/dumps", read_only=True),
                    client.PolicyV1beta1AllowedHostPath(path_prefix="/mnt/nfs",
                                                        read_only=True),
                    client.PolicyV1beta1AllowedHostPath(
                        path_prefix="/etc/wmcs-project", read_only=True),
                    client.PolicyV1beta1AllowedHostPath(
                        path_prefix="/etc/ldap.yaml", read_only=True),
                    client.PolicyV1beta1AllowedHostPath(
                        path_prefix="/etc/novaobserver.yaml", read_only=True),
                    client.PolicyV1beta1AllowedHostPath(
                        path_prefix="/etc/ldap.conf", read_only=True),
                ],
            ),
        )
        try:
            _ = self.policy.create_pod_security_policy(policy)
        except ApiException as api_ex:
            if api_ex.status == 409 and "AlreadyExists" in api_ex.body:
                logging.info("PodSecurityPolicy tool-%s-psp already exists",
                             user.name)
                return

            logging.error("Could not create podsecuritypolicy for %s", user)
            raise