Skip to content

Instantly share code, notes, and snippets.

@debakarr
Created September 28, 2023 06:14
Show Gist options
  • Save debakarr/4edd7dddd5278ec7b97603f54a6771da to your computer and use it in GitHub Desktop.
Save debakarr/4edd7dddd5278ec7b97603f54a6771da to your computer and use it in GitHub Desktop.
Quiz from kodekloud.md

KodeKloud Quiz

test

1. What is the command to view the version of docker engine installed?

  • docker --version
  • docker version
  • docker engine info
  • docker info engine

Correct answer:

  • docker version

Documentation Link: https://docs.docker.com/engine/reference/commandline/docker/

2. testing question includes links and answers.

  • answer
  • false
  • true
  • right

Correct answer:

  • answer

Code: terraform state list

Explaination: The terraform state command is used for advanced state management. As your Terraform usage becomes more advanced, there are some cases where you may need to modify the Terraform state. Rather than modify the state directly, the terraform state commands can be used in many cases instead.

Documentation Link: https://www.terraform.io/cli/commands/state

3. Which operator you can use to perform string concatenation?

  • /
  • *
  • +
  • -

Correct answer:

  • +

Docker Architecture

1. Which component is a read-only template and used for creating a Docker container

  • Docker Network
  • Docker Images
  • Container
  • Docker Volume

Correct answer:

  • Docker Images

2. What is the command to view the version of docker engine installed?

  • docker --version
  • docker version
  • docker engine info
  • docker info engine

Correct answer:

  • docker version

Documentation Link: https://docs.docker.com/engine/reference/commandline/docker/


Mock Exam 1

1. If you have one manager in your swarm cluster, is it possible to demote it to a worker node?

  • Yes
  • No

Correct answer:

  • No

Explaination: You should have at least 1 manager in ur cluster. If you try, you will have an error " error: code = FailedPrecondition desc = attempting to demote the last manager of the Swarm"

2. We have a single manager 2 worker node swarm cluster. All three nodes are hosting workload. What is the sequence of activities to remove the manager node from the swarm cluster?

  • Drain the node, and run docker swarm leave
  • Demote to a worker node, drain the node and run docker swarm leave.
  • Promote a worker node to master, demote manager to worker, drain the node and run docker swarm leave
  • Add a new worker node, drain the manager node, and run docker swarm leave

Correct answer:

  • Promote a worker node to master, demote manager to worker, drain the node and run docker swarm leave

3. The webapp:v1 had some bugs and we fixed them in webapp:v2. We want to update the service to use the image webapp:v2. What is the right command?

  • docker service update --image=webapp:v1 webapp
  • docker service update --image=webapp:v2 webapp
  • docker service update webapp webapp:v1
  • docker service update webapp webapp:v2

Correct answer:

  • docker service update --image=webapp:v2 webapp

4. Create a swarm service named webapp and this service should be connected to my-overlay network and add a custom DNS 8.8.8.8 to it.

  • docker service create --name=webapp --dns=8.8.8.8 nginx
  • docker service create --name=webapp --dns=8.8.8.8 --network=my-overlay nginx
  • docker service create --name=webapp --network=my-overlay nginx

Correct answer:

  • docker service create --name=webapp --dns=8.8.8.8 --network=my-overlay nginx

5. Which statement best describes Quorum?

  • Quorum is the minimum number of nodes that must be available for the cluster to function properly.
  • In the case of 3 manager nodes, the quorum is 3
  • You should maintain an odd number of managers in the swarm to support manager node failures.

Correct answer:

  • Quorum is the minimum number of nodes that must be available for the cluster to function properly.

6. Which node is responsible for maintaining the desired state of the swarm cluster and taking necessary actions if a node was to fail or a new node was added to the cluster?

  • manager node
  • worker node
  • slave node
  • worker, slave nodes

Correct answer:

  • manager node

7. Which command can be used to create and start containers in the foreground using a docker compose file?

  • docker-compose up
  • docker-compose ps
  • docker-compose logs
  • docker-compose stop

Correct answer:

  • docker-compose up

8. To list the services created by a stack, run …

  • docker stack deploy
  • docker stack ls
  • docker stack services
  • docker stack ps

Correct answer:

  • docker stack services

9. Which of the following are correct commands to create config maps? Select all the answers that apply.

  • kubectl create configmap CONFIGMAP-NAME --from-literal=KEY1=VALUE1 --from-literal=KEY2=VALUE2
  • kubectl create configmap CONFIGMAP-NAME --from-file=/tmp/env
  • kubectl create configmap CONFIGMAP-NAME --file=/tmp/env
  • kubectl create configmap CONFIGMAP-NAME --literal=KEY1=VALUE1 KEY2=VALUE2

Correct answer:

  • kubectl create configmap CONFIGMAP-NAME --from-literal=KEY1=VALUE1 --from-literal=KEY2=VALUE2
  • kubectl create configmap CONFIGMAP-NAME --from-file=/tmp/env

10. Which command can be used to deploy exactly one instance of the application on all the nodes in the cluster?

  • docker service create --replicas=1 webapp
  • docker service create --mode=replicated --replicas=1 webapp
  • docker service create --mode=global --replicas=1 webapp
  • docker service create --mode=global webapp

Correct answer:

  • docker service create --mode=global webapp

11. Create a swarm service webapp with image httpd and expose port 8080 on host to port 80 in container.

  • docker container run --name=webapp -p 8080:80 httpd
  • docker service create --name=webapp -p 8080:80 httpd
  • docker service create --name=webapp -p 80:8080 httpd
  • docker service create --replicas=3 httpd

Correct answer:

  • docker service create --name=webapp -p 8080:80 httpd

12. Where do you configure the configMapKeyRef in a pod to use environment variables defined in a ConfigMap?

  • spec.containers.env
  • spec.env.valueFrom
  • spec.containers.valueFrom
  • spec.containers.env.valueFrom

Correct answer:

  • spec.containers.env.valueFrom

13. Which statements best describe kubernetes secrets?

  • Kubernetes secrets let you store and manage sensitive information, such as passwords, OAuth tokens, and ssh keys.
  • Storing confidential information in a Secret is safer.
  • Secrets may be created by Users or the System itself.
  • It is a best practice to check-in secrets into source code repositories.

Correct answer:

  • Kubernetes secrets let you store and manage sensitive information, such as passwords, OAuth tokens, and ssh keys.
  • Storing confidential information in a Secret is safer.
  • Secrets may be created by Users or the System itself.

14. What is the command to deploy a service named webapp on a node which has a type=cpu-optimized label?

  • docker service create --constraint=node.labels.type==cpu-optimized webapp
  • docker service create --labels type==cpu-optimized webapp
  • docker service create --container-label type==cpu-optimized webapp

Correct answer:

  • docker service create --constraint=node.labels.type==cpu-optimized webapp

15. How do you configure all key-value pairs in a Secret object as environment variables within a container?

  • env.secreRef
  • envFrom.secret
  • envFrom.secretRef
  • envFrom.secretRefKey

Correct answer:

  • envFrom.secretRef

Explaination: Use envFrom to define all of the Secret's data as container environment variables. The key from the Secret becomes the environment variable name in the Pod.

16. How many IP addresses are consumed by the pod when it’s created?

  • 1
  • 2
  • 3
  • 4

Correct answer:

  • 1

Code: apiVersion: v1 kind: Pod metadata: name: myapp-pod labels: app: myapp spec: containers:

  • name: nginx-container image: nginx
  • name: agent image: agent

17. An application you are developing requires an httpd server as frontend, a python application as the backend API server, a MongoDB database and a worker developed in Python. What is the recommended approach in building images for these containers?

  • Build httpd, python API server, MongoDB database and Python worker into a single image to allow ease of deployment
  • Build httpd into an image, MongoDB database to another and Python API and worker together into a single image
  • Build separate images for each component of the application

Correct answer:

  • Build separate images for each component of the application

18. Which of the following commands may be used to list all images matching the com.example.version label?

  • docker images --label=”com.example.version”
  • docker images --filter "com.example.version"
  • docker images --filter "label=com.example.version"
  • docker images --format "label=com.example.version"

Correct answer:

  • docker images --filter "label=com.example.version"

19. Choose the correct statement regarding the following compose file.

  • Compose will pull the latest version of the mysql image
  • Volumes must be under services section and not at the root-level
  • The app service will be able to successfully connect to the mysql service
  • The app service will not be able to connect to the mysql service as the host and password specified are incorrect

Correct answer:

  • The app service will not be able to connect to the mysql service as the host and password specified are incorrect

Code: version: "3.7" services: app: image: node:12-alpine working_dir: /app environment: MYSQL_HOST: localhost MYSQL_USER: root MYSQL_PASSWORD: secret MYSQL_DB: foo mysql: image: mysql:5.6 volumes: - foo-mysql-data: /var/lib/mysql environment: MYSQL_ROOT_PASSWORD: password MYSQL_DATABASE: foo volumes:

20. What is the command to change the tag of httpd:latest to httpd:v1

  • docker container image retag httpd:latest httpd:v1
  • docker container image tag httpd:latest httpd:v1
  • docker image retag httpd:latest httpd:v1
  • docker image tag httpd:latest httpd:v1

Correct answer:

  • docker image tag httpd:latest httpd:v1

21. When you log in to a registry using the docker login command, the credentials are stored locally at…

  • $HOME/.docker/config.json
  • /etc/docker/.docker/config.json
  • /var/lib/docker/.docker/config.json
  • /var/lib/docker/containers/.docker/config.json

Correct answer:

  • $HOME/.docker/config.json

22. Which of the following is the correct docker image address to be used to access an image named payapp hosted under the organization payroll at a private registry registry.company.io?

  • registry.company.io/payapp/payroll
  • payroll/registry.company.io/payapp
  • payapp/registry.company.io/payroll
  • registry.company.io/payroll/payapp

Correct answer:

  • registry.company.io/payroll/payapp

23. What is a recommended best practice for installing packages and libraries using the apt-get package manager while building an image?

  • Download packages on the host and use ADD instructions to add them to the image.
  • Use the ADD instruction to provide a URL to the package on the remote host.
  • Use the RUN instruction and have the apt-get update and apt-get install commands on the same instruction
  • Use the RUN instruction and have the apt-get update and apt-get install commands as separate instructions

Correct answer:

  • Use the RUN instruction and have the apt-get update and apt-get install commands on the same instruction

24. What is the command used to find images with a name containing postgres, with at least 12 stars?

  • docker find --filter=stars=12 postgres
  • docker search --filter=stars=12 postgres
  • docker find --limit=12 postgres
  • docker search --limit=12 postgres

Correct answer:

  • docker search --filter=stars=12 postgres

25. After building the below code with an image named webapp, What will happen when you run docker run webapp sleep 1000?

  • docker overrides the ENTRYPOINT instruction with sleep 1000
  • docker overrides the CMD instruction with sleep 1000
  • docker override ENTRYPOINT instruction with sleep and CMD instruction with 1000

Correct answer:

  • docker overrides the CMD instruction with sleep 1000

Code: FROM ubuntu:18.04 COPY . /app RUN make /app CMD python /app/app.py

26. Which of the below is a recommended best practice while taking backups of a swarm cluster?

  • Perform the backup operations from a swarm manager node that is a leader
  • Perform the backup operations from a swarm worker node
  • Perform the backup operations from a swarm manager node that is not a leader

Correct answer:

  • Perform the backup operations from a swarm manager node that is not a leader

Explaination: It is better to perform a backup operation on a swarm node that is not the leader to avoid leader re-election.

27. What are the recommended hardware requirements to install DTR in a production environment?

  • 16GB RAM, 2vCPUs and 100GB of free disk space.
  • 16GB RAM, 4vCPUs and 25-100GB of free disk space.
  • 8GB RAM, 4vCPUs and 25-100GB of free disk space.
  • 8GB RAM, 2vCPUs and 100GB of free disk space.

Correct answer:

  • 16GB RAM, 4vCPUs and 25-100GB of free disk space.

28. Which of the following steps are required to add a worker node in the UCP cluster?

  • Provision a node and Install Docker enterprise engine on it.
  • Run the docker swarm join command to join the new node to the cluster.
  • Deploy an instance of the ucp-agent on the new node.
  • ucp-agent then installs the necessary components on the worker node.

Correct answer:

  • Provision a node and Install Docker enterprise engine on it.
  • Run the docker swarm join command to join the new node to the cluster.
  • ucp-agent then installs the necessary components on the worker node.

29. Docker Content Trust (DCT) provides the ability to use digital signatures for data sent to and received from remote Docker registries.

  • True
  • False

Correct answer:

  • True

30. What will happen if the container consumes more memory than its limit?

  • the container will not be killed
  • the container will be killed with an Out of Memory exception
  • the container’s memory usage will be throttled

Correct answer:

  • the container will be killed with an Out of Memory exception

31. To take a backup of UCP, which docker image do you need to run along with the backup command?

  • docker/ucp-backup
  • docker/ucp
  • docker/backup
  • docker/backup-ucp

Correct answer:

  • docker/ucp

32. What will happen if the --memory-swap is set to 0?

  • the container does not have access to swap
  • the container is allowed to use unlimited swap
  • the setting is ignored, and the value is treated as unset

Correct answer:

  • the setting is ignored, and the value is treated as unset

33. What is the command to create an overlay network that can also be connected by standalone containers that were not created as part of a swarm service.

  • docker network create --driver overlay --attachable my-overlay-network
  • docker network create --driver overlay --subnet 10.15.0.0/16 my-overlay-network
  • docker network create --driver overlay --opt encrypted my-overlay-network
  • docker network create --driver overlay my-overlay-network

Correct answer:

  • docker network create --driver overlay --attachable my-overlay-network

34. Unless specified otherwise, docker publishes the exposed port on all network interfaces on the host.

  • True
  • False

Correct answer:

  • True

35. When you create a swarm service and do not specify a user-defined overlay network, it connects to the ... network by default

  • host
  • bridge
  • macvlan
  • ingress

Correct answer:

  • ingress

36. Which command is used to get the events of the container named webapp?

  • docker system events since 10m
  • docker system events --filter 'container=webapp'
  • docker system events --filter 'image=webapp'

Correct answer:

  • docker system events --filter 'container=webapp'

37. How does docker map a port on a container to a port on the host?

  • Using an internal load balancer
  • FirewallD Rules
  • Using an external load balancer
  • IPTables Rules

Correct answer:

  • IPTables Rules

38. An application deployed in a kubernetes cluster has 2 tiers - a web service that must be externally accessible by users on the nodes interfaces and a database service that must be accessible within the cluster only. What service types should be configured for each?

  • Web - NodePort, Database - LoadBalancer
  • Web - ClusterIP, Database - ClusterIP
  • Web - NodePort, Database - ClusterIP
  • Web - ClusterIP, Database - NodePort

Correct answer:

  • Web - NodePort, Database - ClusterIP

39. What is the type and the name of the network created for the DTR services to communicate with each other?

  • overlay/dtr
  • overlay/dtr-ol
  • bridge/dtr
  • bridge/dtr-ol

Correct answer:

  • overlay/dtr-ol

40. Which of the following solutions support network policies?

  • kube-router
  • Calico
  • Flannel
  • Weave-Net

Correct answer:

  • kube-router
  • Calico
  • Weave-Net

41. What is a Linux feature that prevents a process within the container from performing filesystem related operations such as altering attributes of certain files?

  • Control Groups (CGroups)
  • Namespaces
  • Kernel Capabilities
  • Network Namespaces

Correct answer:

  • Kernel Capabilities

42. What flags are used to configure encryption on docker daemon without any authentication?

  • tlsverify, tlscert, tlskey
  • key, cert, tls
  • tls, tlscert, tlskey
  • host, key, cert, tls

Correct answer:

  • tls, tlscert, tlskey

43. In which of the following will image scanning look for known vulnerabilities

  • OS packages
  • Libraries
  • Other dependencies that are defined in a container image

Correct answer:

  • OS packages
  • Libraries
  • Other dependencies that are defined in a container image

44. Which of the statements best describes "Subjects" in the Access Control Model?

  • A subject represents a user, team, organization
  • A subject does not represent a service account.
  • A subject can be granted a role that defines permitted operations against one or more resource sets.

Correct answer:

  • A subject represents a user, team, organization
  • A subject can be granted a role that defines permitted operations against one or more resource sets.

45. Which of the statements best describe "Grants" in the Access Control Model?

  • Grants define which users can access what resources in what way.
  • A grant is made up of a role and a resource set.
  • A grant is made up of a subject, a role, and a resource set.
  • Grants are effectively Access Control Lists (ACLs) which provide comprehensive access policies for an entire organization when grouped together.

Correct answer:

  • Grants are effectively Access Control Lists (ACLs) which provide comprehensive access policies for an entire organization when grouped together.
  • Grants define which users can access what resources in what way.
  • A grant is made up of a subject, a role, and a resource set.

46. Which of the following statements best describes users?

  • Users are shared across UCP and DTR.
  • When you create a new user in UCP, that user becomes available in DTR.
  • When you create a new user in DTR, that user does not become available in UCP.

Correct answer:

  • Users are shared across UCP and DTR.
  • When you create a new user in UCP, that user becomes available in DTR.

47. The … allows you to authorize a remote Docker engine to a specific user account managed in Docker EE, absorbing all associated RBAC controls in the process

  • DTR
  • UCP
  • RBAC
  • Client bundle

Correct answer:

  • Client bundle

48. Which component is responsible for performing all of these operations: Maintaining the layered architecture, creating a write-able layer, moving files across layers to enable Copy-OnWrite etc?

  • Namespaces
  • Storage drivers
  • Control groups
  • LibContainer

Correct answer:

  • Storage drivers

49. Which of the following modes is used to configure the device-mapper storage driver

  • loop-lvm
  • direct-lvm
  • CoW
  • ReadWriteMany

Correct answer:

  • loop-lvm
  • direct-lvm

50. You are developing an e-commerce application. The application must store cart details of users temporarily as long as the user’s session is active. What is the recommended approach to storing the cart details with the application deployed as a docker container?

  • Store the cart details in the /tmp directory of the container
  • Store the cart details in the memory of the container
  • Store the cart details in a volume backed by an in-memory cache service like redis

Correct answer:

  • Store the cart details in a volume backed by an in-memory cache service like redis

Explaination: as containers are ephemeral in nature, you will lose the data.

51. Which among the below is a correct command to start a webapp container with the volume vol2, mounted to the destination directory /app

  • docker run -d --name webapp -v vol2:/app httpd
  • docker run -d --name webapp --volume vol2:/app httpd
  • docker run -d --name webapp --storage vol2:/app httpd
  • docker run -d --name webapp --mount source=vol2,target=/app httpd

Correct answer:

  • docker run -d --name webapp -v vol2:/app httpd
  • docker run -d --name webapp --volume vol2:/app httpd
  • docker run -d --name webapp --mount source=vol2,target=/app httpd

52. Which statement best describes a kubernetes storage class?

  • A StorageClass provides a way for administrators to describe the "classes" of storage they offer
  • Each StorageClass contains the fields provisioner, parameters, and reclaimPolicy.
  • The StorageClass objects can use a provisioner that can dynamically provision storage on supported storage providers.
  • A StorageClass requires an equal number of Persistent Volumes pre-provisioned before being used by a Persistent Volume Claim.

Correct answer:

  • A StorageClass provides a way for administrators to describe the "classes" of storage they offer
  • Each StorageClass contains the fields provisioner, parameters, and reclaimPolicy.
  • The StorageClass objects can use a provisioner that can dynamically provision storage on supported storage providers.

53. What is the status of a persistent volume when it is associated with a claim?

  • Available
  • Bound
  • Released
  • Failed

Correct answer:

  • Bound

54. What are the different access modes configurable on a persistent volume?

  • ReadOnlyMany
  • ReadWrite
  • ReadWriteMany
  • ReadOnly
  • ReadWriteOnce

Correct answer:

  • ReadOnlyMany
  • ReadWriteMany
  • ReadWriteOnce

55. Which statements best describe a PersistentVolumeClaim?

  • A PersistentVolumeClaim (PVC) is a request for storage by a user.
  • A PVC will be automatically bound to a PV on creation when a PV is available
  • Claims can request specific size and access modes
  • Each PVC contains the fields provisioner, parameters, and reclaimPolicy.

Correct answer:

  • A PersistentVolumeClaim (PVC) is a request for storage by a user.
  • A PVC will be automatically bound to a PV on creation when a PV is available
  • Claims can request specific size and access modes

Mock Exam 2

1. Which command can be used to return the current autolock key used to lock a docker swarm cluster?

  • docker swarm lock-key
  • docker swarm lock --autolock=true
  • docker swarm unlock --autolock=true
  • docker swarm unlock-key

Correct answer:

  • docker swarm unlock-key

2. The ... assigns tasks to nodes in Docker Swarm.

  • scheduler
  • dispatcher
  • orchestrator
  • allocator

Correct answer:

  • dispatcher

3. How many manager nodes must be online in a cluster with 13 manager nodes for the swarm cluster to continue to operate?

  • 3
  • 1
  • 6
  • 7

Correct answer:

  • 7

4. ... is defined as the minimum number of managers required to be present for carrying out cluster management tasks.

  • Fault tolerance
  • Quorum
  • Consensus
  • RAFT

Correct answer:

  • Quorum

5. What is the command to change the role of a manager node named manager1 to a worker node in a Docker Swarm cluster?

  • docker swarm node demote manager1
  • docker demote node manager1
  • docker node demote manager1
  • docker node demote manager1 worker

Correct answer:

  • docker node demote manager1

6. We deployed a container called webapp. What is the command to inspect this container to get the property IPPrefixLen on the container

  • docker container inspect webapp | grep IPPrefixLen
  • docker container top webapp | grep IPPrefixLen
  • docker container run webapp | grep IPPrefixLen
  • docker container logs webapp | grep IPPrefixLen

Correct answer:

  • docker container inspect webapp | grep IPPrefixLen

7. Which command can be used to remove a stack named webapp?

  • docker stack deploy webapp
  • docker stack ls webapp
  • docker stack services webapp
  • docker stack rm webapp

Correct answer:

  • docker stack rm webapp

8. When you create a new container, you add a new read-only layer on top of the underlying layers.

  • True
  • False

Correct answer:

  • False

Explaination: you add a new writable layer on top of the underlying layers.

9. Which of the below are features/functionalities offered by Kubernetes?

  • Self-healing & Batch execution
  • Container Image Management
  • Automated rollouts and rollbacks
  • Auto scaling

Correct answer:

  • Self-healing & Batch execution
  • Automated rollouts and rollbacks
  • Auto scaling

Explaination: Other features are Automated Scheduling, Horizontal Scaling & Load balancing, Storage Orchestration etc.

10. Which option of the docker service command can be used to update 4 replicas at a time of a service named mywebapp?

  • --update-delay 4
  • --update-parallelism 4
  • --placement-pref-add 4
  • --replicas 4

Correct answer:

  • --update-parallelism 4

11. In Docker Swarm, with a global service, you can specify a minimum number of replicas of the service to be provisioned on each node.

  • True
  • False

Correct answer:

  • False

Explaination: With the replicated service

12. Where do you specify image names in a pod definition YAML file to be deployed on Kubernetes?

  • containers.image
  • spec.containers.image
  • template.containers.image
  • kind.containers.image

Correct answer:

  • spec.containers.image

13. What is the command to rebalance the docker swarm cluster workloads?

  • docker service update
  • docker service update --force
  • docker update service
  • docker update service --force

Correct answer:

  • docker service update --force

Explaination: If you really need to rebalance the cluster, then you could run the "docker service update" command with the force flag for each service.

14. Where do you specify labels to a pod in a pod definition YAML file to be deployed on Kubernetes?

  • labels
  • spec.labels
  • spec.containers.labels
  • metadata.labels

Correct answer:

  • metadata.labels

15. How do you inject configmap into a pod in Kubernetes?

  • Using envFrom and configMapRef
  • Using env and configMapRef
  • Using envFrom and configMap
  • Using env and configMap

Correct answer:

  • Using envFrom and configMapRef

Explaination: Use envFrom to define all of the ConfigMap's data as container environment variables. The key from the ConfigMap becomes the environment variable name in the Pod.

16. Refer to the below specification and identify which of the statements are true?

  • This is an invalid configuration because the selector matchLabel nginx does not match the label web set on the deployment
  • This is an invalid configuration because there are more than 1 containers configured in the template
  • This is an invalid configuration because the selector field must come under the template section and not directly under spec
  • This is an invalid configuration because the API version is not set correctly
  • This is a valid configuration

Correct answer:

  • This is a valid configuration

Code: apiVersion: apps/v1 kind: Deployment metadata: name: web-application labels: app: web spec: replicas: 3 selector: matchLabels: app: nginx template: metadata: labels: app: nginx spec: containers: - name: nginx image: nginx:1.14.2 ports: - containerPort: 80 - name: logger image: log-agent:1.2 - name: monitor image: monitor-agent:1.0

17. Choose the correct instruction to add the command instruction with the command echo "Hello World" in the Dockerfile

  • CMD [echo "Hello World"]
  • CMD ["echo", "Hello World"]
  • CMD ["Hello World"]
  • CMD Hello World

Correct answer:

  • CMD ["echo", "Hello World"]

18. Which is the correct statement referring to the following Compose file?

  • The depends_on configuration is not supported in Compose version 3
  • db and redis services will be started before web service
  • web service will be started before db and redis services

Correct answer:

  • db and redis services will be started before web service

Code:

version: "3.8" services: web: build: . depends_on: - db - redis volumes: - .:/code - logvolume01:/var/log ports: - "8080:80" redis: image: redis db: image: postgres volumes: logvolume01: {}

19. What is the right instruction to download a file from https://file.tar.xz and auto-extract it into /testdir in the image

Correct answer:

Explaination: COPY instruction only supports the basic copying of local files into the container.

20. Which command is used to delete the stopped containers?

  • docker container remove $(docker container ls -aq)
  • docker container prune
  • docker rm $(docker ps --filter status=exited -q)

Correct answer:

  • docker container prune
  • docker rm $(docker ps --filter status=exited -q)

21. Which of the below can help minimize the image size?

  • Only install necessary packages within the image
  • Avoid sending unwanted files to the build context using .dockerignore
  • Combine multiple dependent instructions into a single instruction and cleanup temporary files
  • Move the instructions that are likely to change most frequently to the bottom of the Dockerfile
  • Use multi-stage builds

Correct answer:

  • Only install necessary packages within the image
  • Combine multiple dependent instructions into a single instruction and cleanup temporary files
  • Use multi-stage builds
  • Avoid sending unwanted files to the build context using .dockerignore

22. What is the command to find images with a name containing busybox, at least 3 stars and are official builds

  • docker find --filter is-official=true --filter stars=3 busybox
  • docker search --filter is-official=true --filter stars=3 busybox
  • docker find --filter is-official=true --limit=3 busybox
  • docker search --filter is-official=true --limit=3 busybox

Correct answer:

  • docker search --filter is-official=true --filter stars=3 busybox

23. Which of the following statements best describe Docker Trusted Registry (DTR)?

  • Docker Trusted Registry (DTR) is Mirantis’s enterprise-grade image storage solution.
  • Installed behind the firewall only on-premises
  • DTR provides a secure environment from which users can store and manage Docker images.
  • Using DTR in Docker EE we can control who can access and make changes to your cluster and applications

Correct answer:

  • Docker Trusted Registry (DTR) is Mirantis’s enterprise-grade image storage solution.
  • DTR provides a secure environment from which users can store and manage Docker images.

24. A government facility runs a secure data center with no internet connectivity. A new application requires access to docker images hosted on docker hub. What is the best approach to solve this?

  • Get the Dockerfile of the image and build a local version from within the restricted environment.
  • Establish a secure link between the host in the restricted environment and docker hub
  • Pull docker images from a host with access to docker hub, convert to a tarball using docker image save command, and copy to the restricted environment and extract the tarball
  • Pull docker images from a host with access to docker hub, then push to a registry hosted within the restricted environment.

Correct answer:

  • Pull docker images from a host with access to docker hub, convert to a tarball using docker image save command, and copy to the restricted environment and extract the tarball

25. Which of the below commands may be used to change the default logging driver to splunk?

  • echo ‘{"splunk": "log-driver"}’ > /etc/docker/daemon.json
  • echo ‘{"log-driver": "splunk"}’ > /var/lib/docker/daemon.json
  • echo ‘{"splunk": "log-driver"}’ > /var/lib/docker/daemon.json
  • echo ‘{"log-driver": "splunk"}’ > /etc/docker/daemon.json

Correct answer:

  • echo ‘{"log-driver": "splunk"}’ > /etc/docker/daemon.json

26. Refer to the Dockerfile below and identify which value should be added to the --from= option in the second stage to copy the application build from the first stage.

  • 0
  • builder
  • golang:1.7.3
  • /app

Correct answer:

  • 0
  • builder

Code:

FROM golang:1.7.3 AS builder WORKDIR /go/src/github.com/alexellis/href-counter/ RUN go get -d -v golang.org/x/net/html
COPY app.go . RUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -o app .

FROM alpine RUN apk --no-cache add ca-certificates WORKDIR /root/ COPY --from=???? /go/src/github.com/alexellis/href-counter/app . CMD ["./app"]

27. Run a webapp container, and make sure that No logs are configured for this container

  • docker run -it --logging-driver none webapp
  • docker run -it webapp
  • docker run -it --log-driver none webapp
  • docker run -it --log none webapp

Correct answer:

  • docker run -it --log-driver none webapp

28. What are the steps to be followed to backup the Docker swarm database?

  • Create a tar backup of the swarm data at /var/lib/docker/db and restart the docker service.
  • Stop docker service, create a tar backup of the swarm data at /var/lib/docker/swarm, start the docker.
  • Stop docker service, run the docker backup command and start the docker
  • Create a tar backup of the swarm data at /var/lib/docker, stop docker service

Correct answer:

  • Stop docker service, create a tar backup of the swarm data at /var/lib/docker/swarm, start the docker.

29. The communication between UCP server on the manager node and its associated agent services running on worker nodes are encrypted and properly authenticated using certificate-based client-server authentication by default.

  • True
  • False

Correct answer:

  • True

30. Which command can be used to enable the debugging mode on the Docker Host?

  • echo '{"debug": true}' > /etc/docker/daemon.json
  • echo '{"debug"}' > /etc/docker/daemon.json
  • echo '{"debug": true}' > /var/lib/docker/daemon.json
  • echo '{"debug"}' > /var/lib/docker/daemon.json

Correct answer:

  • echo '{"debug": true}' > /etc/docker/daemon.json

31. Which command can be used to start the docker engine enterprise service on a systemctl configured system?

  • sudo systemctl start docker-ee
  • sudo systemctl start docker
  • sudo systemctl docker start
  • sudo systemctl docker-ee start

Correct answer:

  • sudo systemctl start docker

32. What is the high level command to restore the DTR from a backup tar named dtr-metadata-backup.tar ?

  • docker run -i --rm docker/dtr-restore < dtr-metadata-backup.tar
  • docker run -i --rm docker/dtr restore < dtr-metadata-backup.tar
  • docker run -i --rm docker/restore-dtr < dtr-metadata-backup.tar
  • docker run -i --rm docker/restore dtr < dtr-metadata-backup.tar

Correct answer:

  • docker run -i --rm docker/dtr restore < dtr-metadata-backup.tar

33. How can you mitigate the risk of system instability due to OOME?

  • Perform tests to understand the memory requirements of your application before placing it into production.
  • Ensure that your application runs only on hosts with adequate resources.
  • Limit the amount of memory your container can use.

Correct answer:

  • Perform tests to understand the memory requirements of your application before placing it into production.
  • Ensure that your application runs only on hosts with adequate resources.
  • Limit the amount of memory your container can use.

34. What IPTables chains does Docker modify to configure port mapping on a host?

  • INPUT
  • FORWARD
  • DOCKER
  • OUTPUT

Correct answer:

  • DOCKER

35. ETCD by default listens on port 2780.

  • True
  • False

Correct answer:

  • False

Explaination: When you start ETCD it will by default listens on port 2379

36. What types of networks will be created when you initialize a swarm or join a Docker host to an existing swarm?

  • host
  • bridge
  • macvlan
  • ingress

Correct answer:

  • bridge
  • ingress

37. Service Discovery allows containers and Services to locate and communicate with each other with their names.

  • True
  • False

Correct answer:

  • True

38. What is the command to create an overlay network driver called my-overlay with subnet 10.15.0.0/16 ?

  • docker network create my-overlay
  • docker network create --driver overlay --subnet 10.15.0.0/16 my-overlay
  • docker network create -d overlay -subnet 10.15.0.0/16
  • docker network create overlay my-overlay

Correct answer:

  • docker network create --driver overlay --subnet 10.15.0.0/16 my-overlay

39. Which command returns events since the past 30 minutes?

  • docker system events since 30m
  • docker system events --since 30m
  • docker container events --since 30m
  • docker container events since 30m

Correct answer:

  • docker system events --since 30m

40. Which of the following are valid service types in kubernetes?

  • NodePort
  • ClusterIP
  • LoadBalancer
  • ExternalName
  • ElasticLoadBalancer

Correct answer:

  • NodePort
  • ClusterIP
  • LoadBalancer
  • ExternalName

41. In DTR, when a user creates a repository, by default other users will also have permissions to make changes to the repository.

  • True
  • False

Correct answer:

  • False

Explaination: By default, anonymous users can only pull images from public repositories. They can’t create new repositories or push to existing ones. You can then grant permissions to enforce fine-grained access control to image repositories. When a user creates a repository, only that user has permissions to make changes to the repository.

42. The organization is a group of teams that share a specific set of permissions, defined by the roles of the organization

  • True
  • False

Correct answer:

  • True

43. To scan an image, DTR ________________.

  • Extracts a copy of the image layers from backend storage.
  • Extracts the files from the layer into a working directory inside the dtr-jobrunner container.
  • Executes the scanner against the files in this working directory, collecting a series of scanning data.
  • Once the scanning data is collected, the working directory for the layer will not be removed automatically.
  • Once the scanning data is collected, the working directory for the layer is removed.

Correct answer:

  • Extracts a copy of the image layers from backend storage.
  • Extracts the files from the layer into a working directory inside the dtr-jobrunner container.
  • Executes the scanner against the files in this working directory, collecting a series of scanning data.
  • Once the scanning data is collected, the working directory for the layer is removed.

44. What feature of the Docker Enterprise Edition provides the functionality to create users and group them into teams which are nothing but group of users and tie them up with organization.

  • UCP Bundles
  • Docker Content Trust
  • Image Scanning
  • RBAC

Correct answer:

  • RBAC

45. Universal Control Plane (UCP), lets you authorize users to view, edit, and use cluster resources by granting role-based permissions against resource sets.

  • True
  • False

Correct answer:

  • True

46. Which option is used to change the default storage driver to use devicemapper?

  • {"storage-driver": "devicemapper"}
  • {"driver": "devicemapper"}
  • {"dev-storage": "devicemapper"}

Correct answer:

  • {"storage-driver": "devicemapper"}

47. Which of the following are a valid storage driver supported by Docker?

  • AUFS
  • S3
  • overlay2
  • Device Mapper

Correct answer:

  • AUFS
  • overlay2
  • Device Mapper

48. By default all files created inside a container are stored on a writable container layer.

  • True
  • False

Correct answer:

  • True

Explaination: This means that: The data doesn’t persist when that container no longer exists, and it can be difficult to get the data out of the container if another process needs it.

49. What is the command to create a volume with the name my-vol

  • docker volume create my-vol
  • docker create volume my-vol
  • docker volume prune
  • docker volume rm all

Correct answer:

  • docker volume create my-vol

50. What is the command to list storage classes in Kubernetes?

  • kubectl list sc
  • kubectl get sc
  • kubectl get storageclass
  • kubectl list storageclass

Correct answer:

  • kubectl get sc
  • kubectl get storageclass

51. Which of the following statements best describes ETCD? Select the correct answer

  • Etcd serves as the backing datastore for kubernetes cluster data
  • ETCD must be deployed on all worker nodes in the cluster
  • ETCD is a distributed reliable key-value store

Correct answer:

  • Etcd serves as the backing datastore for kubernetes cluster data
  • ETCD is a distributed reliable key-value store

Explaination: A distributed key-value data store, It helps to maintain the cluster configuration and state. Intended for permanent data storage and retrieval, etcd stores metadata and other information consistently with a fault-tolerant method, including full replication.

  • Option B is incorrect because it is not a worker node component, it can be installed and configured in Master Nodes or can be configured on a separate node.

52. Which statements best describe Persistent Volume in kubernetes?

  • A PersistentVolume (PV) is a piece of storage in the cluster that has been provisioned by an administrator or dynamically provisioned using Storage Class
  • It is a resource in the cluster just like a node is a cluster resource.
  • We can create PVs with the same name in multiple namespaces.

Correct answer:

  • A PersistentVolume (PV) is a piece of storage in the cluster that has been provisioned by an administrator or dynamically provisioned using Storage Class
  • It is a resource in the cluster just like a node is a cluster resource.

53. Once the Persistent Volume Claim is created, you need to manually bind the persistent volumes to claim.

  • True
  • False

Correct answer:

  • False

Explaination: A PVC will be automatically bound to a PV on creation when a PV is available

54. Which statement best describes docker volume plugin?

  • Docker Engine volume plugins enables Engine deployments to be integrated with external storage systems such as Amazon EBS
  • The local volume plugin helps to create a volume on Docker host and store its data under the /var/lib/docker/volumes/ directory.
  • ZFS, BTRFS and Device Mapper are some of the supported volume drivers

Correct answer:

  • Docker Engine volume plugins enables Engine deployments to be integrated with external storage systems such as Amazon EBS
  • The local volume plugin helps to create a volume on Docker host and store its data under the /var/lib/docker/volumes/ directory.

55. How can the web application address redis?

  • Using the container ID generated by redis
  • Using the name redis
  • Using the internal IP address of the redis container
  • By exposing port 6379 of redis container on the host and then using hosts IP

Correct answer:

  • Using the name redis

Code:

version: "3.8" services: web: build: . depends_on: - db - redis volumes: - .:/code - logvolume01:/var/log ports: - "8080:80" redis: image: redis db: image: postgres volumes: logvolume01: {}


Mock Exam 3

1. Which command can be used to run an instance on swarm?

  • docker container run
  • docker container create
  • docker service create
  • docker swarm service create

Correct answer:

  • docker service create

2. What option may be used to change the default behaviour of a failed task during an update in swarm?

  • --update-failure-action
  • --update-parallelism
  • --update-delay
  • --placement-pref-add

Correct answer:

  • --update-failure-action

3. Which formula can be used to calculate the Quorum of N nodes?

  • N + 1
  • N+1 / 2
  • N / 2 +1
  • N /2 -1

Correct answer:

  • N / 2 +1

4. What component is responsible for instructing a worker to run a task?

  • scheduler
  • dispatcher
  • orchestrator
  • allocater

Correct answer:

  • scheduler

5. Which command can be used to check the restart policy of a container named webapp?

  • docker container inspect webapp
  • docker container info webapp
  • docker container check webapp

Correct answer:

  • docker container inspect webapp

6. Which command can be used to list the tasks in a stack named webapp?

  • docker stack deploy webapp
  • docker stack ls webapp
  • docker stack services webapp
  • docker stack ps webapp

Correct answer:

  • docker stack ps webapp

7. The routing mesh enables each node in the swarm to accept connections on published ports for any service running in the swarm, even if there’s no task running on the node.

  • True
  • False

Correct answer:

  • True

8. Which command can be used to increase the number of replicas from 2 to 4 of a service named webapp? Select the all right answer

  • docker service update --replicas=4 webapp
  • docker service update --replicas=2 webapp
  • docker service scale webapp=2
  • docker service scale webapp=4

Correct answer:

  • docker service update --replicas=4 webapp
  • docker service scale webapp=4

9. What is the flag that we can use to define a literal value from the command line while creating a ConfigMap?

  • --env
  • --from-literal
  • --literal
  • --text

Correct answer:

  • --from-literal

Explaination: You can use kubectl create configmap with the --from-literal argument to define a literal value from the command line:

10. What is the command to apply disk=ssd label to worker1 in a swarm cluster.

  • docker node update --label-add disk=ssd worker1
  • docker node update --label-rm disk=ssd worker1
  • docker service update --labels disk=ssd worker1
  • docker service update --container-label disk=ssd worker1

Correct answer:

  • docker node update --label-add disk=ssd worker1

11. After an update to a service named webapp we realized that something is wrong with the new version and we want to revert back to the old version. How can we achieve that?

  • docker service update rollback webapp
  • docker service rollback webapp
  • docker service rm webapp
  • docker service leave webapp

Correct answer:

  • docker service rollback webapp

12. Which command can be used to get the logs of a swarm service?

  • docker container logs SERVICE-NAME
  • docker service logs SERVICE-NAME
  • docker swarm log SERVICE-NAME
  • docker swarm logs SERVICE-NAME

Correct answer:

  • docker service logs SERVICE-NAME

13. Create a service using the my-web-server image and map UDP port 80 in the container to port 5000 on the overlay network.

  • docker service create -p 80:5000/udp my-web-server
  • docker service create --publish published=80,target=5000,protocol=udp my-web-server
  • docker service create -p 5000:80/udp my-web-server
  • docker service create --publish published=5000,target=80,protocol=udp my-web-server

Correct answer:

  • docker service create -p 5000:80/udp my-web-server
  • docker service create --publish published=5000,target=80,protocol=udp my-web-server

14. What is the recommended approach to load a set of configurations into the pod in the form of a file to the path /var/configs?

  • Add a separate env parameter for each config and use a startup script to write to a file
  • Create a ConfigMap with the required configurations, configure it as a volume in the pod definition file and then mount the volume as a file at /var/configs
  • Create a ConfigMap with the required configurations, configure it as an env variable in the pod definition file and use a startup script to write to a file

Correct answer:

  • Create a ConfigMap with the required configurations, configure it as a volume in the pod definition file and then mount the volume as a file at /var/configs

15. What are the 4 top level fields a kubernetes definition file for POD contains?

  • apiVersion
  • templates
  • metadata
  • labels
  • kind
  • spec
  • namespaces
  • containers

Correct answer:

  • apiVersion
  • metadata
  • kind
  • spec

Explaination: apiversion, kind, metadata and spec are the four top level fields a kubernetes definition file consists of.

  • Option A and B are incorrect because these are not part of the top level fields that a definition file consists of.

16. Which of the below statements are correct?

  • Traffic to port 39376 on the node hosting the pod in the cluster is routed to port 9376 on a POD with the label app web on the same node
  • Traffic to port 39376 on all nodes in the cluster is routed to port 9376 on a random POD with the label app web
  • Traffic to port 80 on the service is routed to port 9376 on a random POD with the label app web
  • Traffic to port 80 on the node is routed to port 9376 on the service

Correct answer:

  • Traffic to port 39376 on all nodes in the cluster is routed to port 9376 on a random POD with the label app web
  • Traffic to port 80 on the service is routed to port 9376 on a random POD with the label app web

Code: apiVersion: v1 kind: Service metadata: name: web-service labels: obj: web-service app: web spec: selector: app: web type: NodePort ports: - protocol: TCP port: 80 targetPort: 9376 nodePort: 39376

17. Which of the following is the correct format for CMD instruction

  • CMD ["executable","param1","param2"]
  • CMD ["param1","param2"]
  • CMD command param1 param2
  • CMD param1 param2

Correct answer:

  • CMD ["executable","param1","param2"]
  • CMD ["param1","param2"]
  • CMD command param1 param2

18. What is the command to stop all running containers on the host?

  • docker container stop $(docker container ls)
  • docker container rm $(docker container ls -q)
  • docker container stop $(docker container ls -q)
  • docker container stop --all

Correct answer:

  • docker container stop $(docker container ls -q)

19. While building a docker image from code stored in a remote URL, which command will be used to build from a directory called docker in the branch dev?

Correct answer:

20. Using RUN apt-get update && apt-get install -y ensures your Dockerfile installs the latest package versions everytime an image is built. This technique is known as …..

  • Fast build
  • Cache busting
  • Version pinning
  • Build-context

Correct answer:

  • Cache busting

21. Print the value of 'Architecture' and 'Os' of an image named webapp

  • docker image inspect webapp -f '{{.Os}}' -f '{{.Architecture}}'
  • docker image inspect webapp -f '{{.Os}} {{.Architecture}}'
  • docker image inspect webapp -f '{{.Os}}', -f '{{.Architecture}}'
  • docker image inspect webapp -f '{{.Os .Architecture}}'

Correct answer:

  • docker image inspect webapp -f '{{.Os}} {{.Architecture}}'

22. What are the features of docker trusted registry (DTR)?

  • Built-in Access Control
  • Image and Job Management
  • Security Scanning
  • Auto scaling applications
  • Image Signing

Correct answer:

  • Built-in Access Control
  • Image and Job Management
  • Security Scanning
  • Image Signing

23. Choose the correct statement regarding the following compose snippet

  • When the service is deployed it creates 4 containers in total
  • The webapp service has a health check configured that tests if the web application is alive every 45 seconds
  • Each time during the health check the webapp service waits for 60 seconds to receive a positive response from the curl command
  • The webapp can reach the database using the name dbservice

Correct answer:

  • The webapp service has a health check configured that tests if the web application is alive every 45 seconds
  • The webapp can reach the database using the name dbservice

Code: version: "3.8"

services: webapp: image: webapp ports: - "8080:80" networks: - app-net deploy: mode: replicated replicas: 2 healthcheck: test: ["CMD", "curl", "-f", "http://localhost"] interval: 45s timeout: 20s retries: 3 start_period: 60s

dbservice: image: mysql volumes: - db-data:/var/lib/mysql/data networks: - app-net

volumes: db-data:

networks: app-net:

24. What is the user/account and image/repository name for the image company/nginx?

  • image=company, user=nginx
  • image=company, user=company
  • image=nginx, user=nginx
  • image=nginx, user=company

Correct answer:

  • image=nginx, user=company

25. When a container is created using the image built with the following Dockerfile, what is the command used to RUN the application inside it

  • pip install flask
  • docker run app.py
  • app.py
  • python app.py

Correct answer:

  • python app.py

Code: FROM python:3.6 RUN pip install flask COPY . /opt/ EXPOSE 8080 WORKDIR /opt ENTRYPOINT ["python", "app.py"]

26. Which image is used to deploy the Docker Trusted Registry?

  • dtr
  • docker/dtr
  • ucp
  • docker/ucp

Correct answer:

  • docker/dtr

27. Where is the log of the webapp container, with id 78373635, stored on the Docker Host?

  • /var/lib/docker/containers/78373635/78373635.json
  • /var/log/docker/78373635.json
  • /etc/docker/78373635.json
  • /var/lib/docker/tmp/78373635/78373635.json

Correct answer:

  • /var/lib/docker/containers/78373635/78373635.json

28. Which of the statements best describes Roles in the Access control model?

  • Roles define what operations can be done by whom.
  • A role is a group of teams that share a specific set of permissions.
  • Most organizations use multiple roles to fine-tune the appropriate access.

Correct answer:

  • Roles define what operations can be done by whom.
  • Most organizations use multiple roles to fine-tune the appropriate access.

Explaination: A role is a set of permitted operations against a type of resource, like a container or volume, which is assigned to a user or a team with a grant.

29. Which of the following are the major components of Docker Engine - Enterprise?

  • A server which is a type of long-running program called a daemon process (the dockerd command).
  • A REST API which specifies interfaces that programs can use to talk to the daemon and instruct it what to do.
  • A command line interface (CLI) client (the docker command).

Correct answer:

  • A server which is a type of long-running program called a daemon process (the dockerd command).
  • A REST API which specifies interfaces that programs can use to talk to the daemon and instruct it what to do.
  • A command line interface (CLI) client (the docker command).

30. What are the prerequisites for restoring swarm?

  • You must restore the backup on the same Docker Engine version.
  • You must use the same IP as the node from which you made the backup.
  • If auto-lock was enabled on the old Swarm, the unlock key is required to perform the restore.

Correct answer:

  • You must restore the backup on the same Docker Engine version.
  • You must use the same IP as the node from which you made the backup.
  • If auto-lock was enabled on the old Swarm, the unlock key is required to perform the restore.

31. Which of the following steps are required on each manager node to restore data to a new swarm?

  • Shut down the Docker Engine on the node you select for the restore
  • Remove the /var/lib/docker directory on the new Swarm if it exists.
  • Remove the contents of the /var/lib/docker/swarm directory on the new Swarm if it exists.
  • Restore the /var/lib/docker/swarm directory with the contents of the backup
  • Start Docker on the new node. Unlock the swarm if necessary
  • Re-initialize the swarm so that the node does not attempt to connect to nodes that were part of the old swarm, and presumably no longer exist.

Correct answer:

  • Shut down the Docker Engine on the node you select for the restore
  • Remove the contents of the /var/lib/docker/swarm directory on the new Swarm if it exists.
  • Restore the /var/lib/docker/swarm directory with the contents of the backup
  • Start Docker on the new node. Unlock the swarm if necessary
  • Re-initialize the swarm so that the node does not attempt to connect to nodes that were part of the old swarm, and presumably no longer exist.

32. What is a linux feature that allows isolation of containers from the Docker host?

  • Control Groups (CGroups)
  • Namespaces
  • Kernel Capabilities
  • LXC

Correct answer:

  • Namespaces

33. Which environment variable will be used to connect a remote docker server?

  • DOCKER_REMOTE
  • DOCKER_HOST
  • DOCKER_CONFIG
  • DOCKER_SERVICE

Correct answer:

  • DOCKER_HOST

34. What is the command to perform a backup of DTR node?

  • Run the docker/dtr backup command
  • Run the docker/dtr-backup command
  • Run the docker/backup-dtr command
  • Run the docker/backup dtr command

Correct answer:

  • Run the docker/dtr backup command

35. Which component is responsible to serve the UCP components such as the web ui, the authentication api,metrics server, proxy and data stores used by UCP in the form of containers?

  • UCP Agent
  • Docker Enterprise Edition
  • Docker Community Edition
  • Docker Trusted Registry (DTR)

Correct answer:

  • UCP Agent

36. By default, all containers get the same share of CPU cycles. How to modify the shares?

  • docker container run --cpu-shares=512 webapp
  • docker container run --cpuset-cups=512 webapp
  • docker container run --cpu-quota=512 webapp
  • docker container run --cpus=512 webapp

Correct answer:

  • docker container run --cpu-shares=512 webapp

37. What component is responsible for managing CPU resources and allocating the time of the CPU between different processes?

  • Allocater
  • CFS
  • Controller
  • Allocater, Controller

Correct answer:

  • CFS

38. When you initialize a Docker Swarm cluster it creates a new network of type overlay which is an internal private network that spans across all the nodes participating in the swarm cluster.

  • True
  • False

Correct answer:

  • True

39. The built-in DNS server in Docker always runs at IP address …

  • 127.0.0.11
  • 127.0.0.1
  • 172.17.0.3
  • 172.17.0.1

Correct answer:

  • 127.0.0.11

40. What is the command to create an overlay network driver called my-overlay?

  • docker network create my-overlay
  • docker create network my-overlay
  • docker network create -d overlay my-overlay
  • docker network create overlay my-overlay

Correct answer:

  • docker network create -d overlay my-overlay

41. If the service type is NodePort, then Kubernetes will allocate a port on every worker node.

  • True
  • False

Correct answer:

  • True

42. Which among the following statements are true without any change made to the default behaviour of network policies in the namespace?

  • As soon as a network policy is associated with a POD traffic between all PODs in the namespace is denied
  • As soon as a network policy is associated with a POD all ingress and egress traffic to that POD are denied except allowed by the network policy
  • As soon as a network policy is associated with a POD all ingress and egress traffic to that POD are allowed except for the the ones blocked by the network policy

Correct answer:

  • As soon as a network policy is associated with a POD all ingress and egress traffic to that POD are denied except allowed by the network policy

43. What is the default range of ports that Kubernetes uses for NodePort if one is not specified?

  • 32767-64000
  • 30000-32767
  • 32000-3276
  • 80-8080

Correct answer:

  • 30000-32767

44. Which of the statements best describe "Resource sets" in Access Control Model?

  • To control user access, cluster resources are grouped into Docker Swarm collections or Kubernetes namespaces.
  • Together, collections and namespaces are named resource sets.
  • A group of teams that share a specific set of permissions

Correct answer:

  • To control user access, cluster resources are grouped into Docker Swarm collections or Kubernetes namespaces.
  • Together, collections and namespaces are named resource sets.

45. The communication between the swarm related services on different nodes in the swarm cluster are not secured by default.

  • True
  • False

Correct answer:

  • False

Explaination: The communication between the nodes in the swarm cluster are secured by authentication and encryption using TLS/SSL certificates

46. In which service does the DTR image scanning occur?

  • A service known as the dtr-jobrunner container
  • A service known as the dtr-registry container
  • A service known as the dtr-api container
  • A service known as the dtr-runner container

Correct answer:

  • A service known as the dtr-jobrunner container

Explaination: When you install DTR on a node, the dtr-jobrunner started and runs cleanup jobs in the background

47. Which of the following is a common workflow for RBAC in Docker EE is

  • Create users, teams and organization
  • Create custom roles with set of permissions
  • Combine resources sets using collection
  • Create a grant that combines subjects, roles and resource sets.

Correct answer:

  • Create users, teams and organization
  • Create custom roles with set of permissions
  • Combine resources sets using collection
  • Create a grant that combines subjects, roles and resource sets.

48. UCP has its own built-in authentication mechanism and integrates with LDAP and AD services.

  • True
  • False

Correct answer:

  • True

49. A client bundle is a group of certificates downloadable directly from the Docker Trusted Registry (DTR) user interface within the admin section for “My Profile”

  • True
  • False

Correct answer:

  • False

50. overlay2, aufs, and devicemapper all operate at the file level rather than the block level.

  • True
  • False

Correct answer:

  • False

Explaination: devicemapper operate at the block level rather than the file level

51. The volumes are mounted as “readonly” by default inside the container if no options are specified.

  • True
  • False

Correct answer:

  • False

Explaination: The volumes are mounted as “readwrite” by default…

52. Which among the below is a correct command to start a container named webapp with the volume vol3, mounted to the destination directory /opt in readonly mode?

  • docker run -d --name webapp --mount source=vol3,target=/opt,readonly httpd
  • docker run -d --name webapp -v vol3:/opt:ro httpd
  • docker run -d --name webapp -v vol3:/opt:readonly httpd
  • docker run -d --name webapp --volume vol3:/opt:ro httpd
  • docker run -d --name webapp --mount source=vol3,target=/opt,ro httpd

Correct answer:

  • docker run -d --name webapp --mount source=vol3,target=/opt,readonly httpd
  • docker run -d --name webapp -v vol3:/opt:ro httpd
  • docker run -d --name webapp --volume vol3:/opt:ro httpd

53. Which statements best describe emptyDir volume type?

  • An emptyDir volume is first created when a Pod is assigned to a node, and still exists after a pod termination.
  • An emptyDir volume is first created when a Pod is assigned to a node, and exists as long as that Pod is running on that node.
  • The emptyDir volume is initially empty
  • When a Pod is removed from a node for any reason, the data in the emptyDir is deleted permanently

Correct answer:

  • An emptyDir volume is first created when a Pod is assigned to a node, and exists as long as that Pod is running on that node.
  • The emptyDir volume is initially empty
  • When a Pod is removed from a node for any reason, the data in the emptyDir is deleted permanently

54. What is the sequence of operations to be followed while configuring a storage class for an application?

  • Create a storage class with a provisioner, create a persistent volume with definition using the storage class, create a PVC and then use the PVC in the volumes section in the pod definition file
  • Create a storage class with a provisioner, create a PVC with the storage class, and then use the PVC in the volumes section in the pod definition file
  • Create a storage class, and use it directly in the volumes section in the pod definition file

Correct answer:

  • Create a storage class with a provisioner, create a PVC with the storage class, and then use the PVC in the volumes section in the pod definition file

55. What is the command to delete the persistent volumes?

  • kubectl delete pv PV-NAME
  • kubectl del pv PV-NAME
  • kubectl rm pv PV-NAME
  • kubectl erase pv PV-NAME

Correct answer:

  • kubectl delete pv PV-NAME

Mock Exam 3 duplicate

1. What component is responsible for instructing a worker to run a task?

  • scheduler
  • dispatcher
  • orchestrator
  • allocater

Correct answer:

  • scheduler

2. What option may be used to change the default behaviour of a failed task during an update in swarm?

  • --update-failure-action
  • --update-parallelism
  • --update-delay
  • --placement-pref-add

Correct answer:

  • --update-failure-action

3. Which command can be used to check the restart policy of a container named webapp?

  • docker container inspect webapp
  • docker container info webapp
  • docker container check webapp

Correct answer:

  • docker container inspect webapp

4. Which command can be used to list the tasks in a stack named webapp?

  • docker stack deploy webapp
  • docker stack ls webapp
  • docker stack services webapp
  • docker stack ps webapp

Correct answer:

  • docker stack ps webapp

5. Which formula can be used to calculate the Quorum of N nodes?

  • N + 1
  • N+1 / 2
  • N / 2 +1
  • N /2 -1

Correct answer:

  • N / 2 +1

6. Which command can be used to run an instance on swarm?

  • docker container run
  • docker container create
  • docker service create
  • docker swarm service create

Correct answer:

  • docker service create

7. The routing mesh enables each node in the swarm to accept connections on published ports for any service running in the swarm, even if there’s no task running on the node.

  • True
  • False

Correct answer:

  • True

8. Which command can be used to increase the number of replicas from 2 to 4 of a service named webapp? Select the all right answer

  • docker service update --replicas=4 webapp
  • docker service update --replicas=2 webapp
  • docker service scale webapp=2
  • docker service scale webapp=4

Correct answer:

  • docker service update --replicas=4 webapp
  • docker service scale webapp=4

9. What is the command to apply disk=ssd label to worker1 in a swarm cluster.

  • docker node update --label-add disk=ssd worker1
  • docker node update --label-rm disk=ssd worker1
  • docker service update --labels disk=ssd worker1
  • docker service update --container-label disk=ssd worker1

Correct answer:

  • docker node update --label-add disk=ssd worker1

10. After an update to a service named webapp we realized that something is wrong with the new version and we want to revert back to the old version. How can we achieve that?

  • docker service update rollback webapp
  • docker service rollback webapp
  • docker service rm webapp
  • docker service leave webapp

Correct answer:

  • docker service rollback webapp

11. Which command can be used to get the logs of a swarm service?

  • docker container logs SERVICE-NAME
  • docker service logs SERVICE-NAME
  • docker swarm log SERVICE-NAME
  • docker swarm logs SERVICE-NAME

Correct answer:

  • docker service logs SERVICE-NAME

12. Create a service using the my-web-server image and map UDP port 80 in the container to port 5000 on the overlay network.

  • docker service create -p 80:5000/udp my-web-server
  • docker service create --publish published=80,target=5000,protocol=udp my-web-server
  • docker service create -p 5000:80/udp my-web-server
  • docker service create --publish published=5000,target=80,protocol=udp my-web-server

Correct answer:

  • docker service create -p 5000:80/udp my-web-server
  • docker service create --publish published=5000,target=80,protocol=udp my-web-server

13. What are the 4 top level fields a kubernetes definition file for POD contains?

  • apiVersion
  • templates
  • metadata
  • labels
  • kind
  • spec
  • namespaces
  • containers

Correct answer:

  • apiVersion
  • metadata
  • kind
  • spec

Explaination: apiversion, kind, metadata and spec are the four top level fields a kubernetes definition file consists of.

  • Option A and B are incorrect because these are not part of the top level fields that a definition file consists of.

14. What is the flag that we can use to define a literal value from the command line while creating a ConfigMap?

  • --env
  • --from-literal
  • --literal
  • --text

Correct answer:

  • --from-literal

Explaination: You can use kubectl create configmap with the --from-literal argument to define a literal value from the command line:

15. What is the recommended approach to load a set of configurations into the pod in the form of a file to the path /var/configs?

  • Add a separate env parameter for each config and use a startup script to write to a file
  • Create a ConfigMap with the required configurations, configure it as a volume in the pod definition file and then mount the volume as a file at /var/configs
  • Create a ConfigMap with the required configurations, configure it as an env variable in the pod definition file and use a startup script to write to a file

Correct answer:

  • Create a ConfigMap with the required configurations, configure it as a volume in the pod definition file and then mount the volume as a file at /var/configs

16. Which of the below statements are correct?

  • Traffic to port 39376 on the node hosting the pod in the cluster is routed to port 9376 on a POD with the label app web on the same node
  • Traffic to port 39376 on all nodes in the cluster is routed to port 9376 on a random POD with the label app web
  • Traffic to port 80 on the service is routed to port 9376 on a random POD with the label app web
  • Traffic to port 80 on the node is routed to port 9376 on the service

Correct answer:

  • Traffic to port 39376 on all nodes in the cluster is routed to port 9376 on a random POD with the label app web
  • Traffic to port 80 on the service is routed to port 9376 on a random POD with the label app web

Code: apiVersion: v1 kind: Service metadata: name: web-service labels: obj: web-service app: web spec: selector: app: web type: NodePort ports: - protocol: TCP port: 80 targetPort: 9376 nodePort: 39376

17. Choose the correct statement regarding the following compose snippet

  • When the service is deployed it creates 4 containers in total
  • The webapp service has a health check configured that tests if the web application is alive every 45 seconds
  • Each time during the health check the webapp service waits for 60 seconds to receive a positive response from the curl command
  • The webapp can reach the database using the name dbservice

Correct answer:

  • The webapp service has a health check configured that tests if the web application is alive every 45 seconds
  • The webapp can reach the database using the name dbservice

Code: version: "3.8"

services: webapp: image: webapp ports: - "8080:80" networks: - app-net deploy: mode: replicated replicas: 2 healthcheck: test: ["CMD", "curl", "-f", "http://localhost"] interval: 45s timeout: 20s retries: 3 start_period: 60s

dbservice: image: mysql volumes: - db-data:/var/lib/mysql/data networks: - app-net

volumes: db-data:

networks: app-net:

18. Which of the following is the correct format for CMD instruction

  • CMD ["executable","param1","param2"]
  • CMD ["param1","param2"]
  • CMD command param1 param2
  • CMD param1 param2

Correct answer:

  • CMD ["executable","param1","param2"]
  • CMD ["param1","param2"]
  • CMD command param1 param2

19. Print the value of 'Architecture' and 'Os' of an image named webapp

  • docker image inspect webapp -f '{{.Os}}' -f '{{.Architecture}}'
  • docker image inspect webapp -f '{{.Os}} {{.Architecture}}'
  • docker image inspect webapp -f '{{.Os}}', -f '{{.Architecture}}'
  • docker image inspect webapp -f '{{.Os .Architecture}}'

Correct answer:

  • docker image inspect webapp -f '{{.Os}} {{.Architecture}}'

20. What is the command to stop all running containers on the host?

  • docker container stop $(docker container ls)
  • docker container rm $(docker container ls -q)
  • docker container stop $(docker container ls -q)
  • docker container stop --all

Correct answer:

  • docker container stop $(docker container ls -q)

21. While building a docker image from code stored in a remote URL, which command will be used to build from a directory called docker in the branch dev?

Correct answer:

22. What is the user/account and image/repository name for the image company/nginx?

  • image=company, user=nginx
  • image=company, user=company
  • image=nginx, user=nginx
  • image=nginx, user=company

Correct answer:

  • image=nginx, user=company

23. What are the features of docker trusted registry (DTR)?

  • Built-in Access Control
  • Image and Job Management
  • Security Scanning
  • Auto scaling applications
  • Image Signing

Correct answer:

  • Built-in Access Control
  • Image and Job Management
  • Security Scanning
  • Image Signing

24. Using RUN apt-get update && apt-get install -y ensures your Dockerfile installs the latest package versions everytime an image is built. This technique is known as …..

  • Fast build
  • Cache busting
  • Version pinning
  • Build-context

Correct answer:

  • Cache busting

25. Which image is used to deploy the Docker Trusted Registry?

  • dtr
  • docker/dtr
  • ucp
  • docker/ucp

Correct answer:

  • docker/dtr

26. When a container is created using the image built with the following Dockerfile, what is the command used to RUN the application inside it

  • pip install flask
  • docker run app.py
  • app.py
  • python app.py

Correct answer:

  • python app.py

Code: FROM python:3.6 RUN pip install flask COPY . /opt/ EXPOSE 8080 WORKDIR /opt ENTRYPOINT ["python", "app.py"]

27. Which of the following are the major components of Docker Engine - Enterprise?

  • A server which is a type of long-running program called a daemon process (the dockerd command).
  • A REST API which specifies interfaces that programs can use to talk to the daemon and instruct it what to do.
  • A command line interface (CLI) client (the docker command).

Correct answer:

  • A server which is a type of long-running program called a daemon process (the dockerd command).
  • A REST API which specifies interfaces that programs can use to talk to the daemon and instruct it what to do.
  • A command line interface (CLI) client (the docker command).

28. Where is the log of the webapp container, with id 78373635, stored on the Docker Host?

  • /var/lib/docker/containers/78373635/78373635.json
  • /var/log/docker/78373635.json
  • /etc/docker/78373635.json
  • /var/lib/docker/tmp/78373635/78373635.json

Correct answer:

  • /var/lib/docker/containers/78373635/78373635.json

29. What are the prerequisites for restoring swarm?

  • You must restore the backup on the same Docker Engine version.
  • You must use the same IP as the node from which you made the backup.
  • If auto-lock was enabled on the old Swarm, the unlock key is required to perform the restore.

Correct answer:

  • You must restore the backup on the same Docker Engine version.
  • You must use the same IP as the node from which you made the backup.
  • If auto-lock was enabled on the old Swarm, the unlock key is required to perform the restore.

30. Which of the statements best describes Roles in the Access control model?

  • Roles define what operations can be done by whom.
  • A role is a group of teams that share a specific set of permissions.
  • Most organizations use multiple roles to fine-tune the appropriate access.

Correct answer:

  • Roles define what operations can be done by whom.
  • Most organizations use multiple roles to fine-tune the appropriate access.

Explaination: A role is a set of permitted operations against a type of resource, like a container or volume, which is assigned to a user or a team with a grant.

31. Which of the following steps are required on each manager node to restore data to a new swarm?

  • Shut down the Docker Engine on the node you select for the restore
  • Remove the /var/lib/docker directory on the new Swarm if it exists.
  • Remove the contents of the /var/lib/docker/swarm directory on the new Swarm if it exists.
  • Restore the /var/lib/docker/swarm directory with the contents of the backup
  • Start Docker on the new node. Unlock the swarm if necessary
  • Re-initialize the swarm so that the node does not attempt to connect to nodes that were part of the old swarm, and presumably no longer exist.

Correct answer:

  • Shut down the Docker Engine on the node you select for the restore
  • Remove the contents of the /var/lib/docker/swarm directory on the new Swarm if it exists.
  • Restore the /var/lib/docker/swarm directory with the contents of the backup
  • Start Docker on the new node. Unlock the swarm if necessary
  • Re-initialize the swarm so that the node does not attempt to connect to nodes that were part of the old swarm, and presumably no longer exist.

32. Which component is responsible to serve the UCP components such as the web ui, the authentication api,metrics server, proxy and data stores used by UCP in the form of containers?

  • UCP Agent
  • Docker Enterprise Edition
  • Docker Community Edition
  • Docker Trusted Registry (DTR)

Correct answer:

  • UCP Agent

33. Which environment variable will be used to connect a remote docker server?

  • DOCKER_REMOTE
  • DOCKER_HOST
  • DOCKER_CONFIG
  • DOCKER_SERVICE

Correct answer:

  • DOCKER_HOST

34. What is the command to perform a backup of DTR node?

  • Run the docker/dtr backup command
  • Run the docker/dtr-backup command
  • Run the docker/backup-dtr command
  • Run the docker/backup dtr command

Correct answer:

  • Run the docker/dtr backup command

35. What is a linux feature that allows isolation of containers from the Docker host?

  • Control Groups (CGroups)
  • Namespaces
  • Kernel Capabilities
  • LXC

Correct answer:

  • Namespaces

36. By default, all containers get the same share of CPU cycles. How to modify the shares?

  • docker container run --cpu-shares=512 webapp
  • docker container run --cpuset-cups=512 webapp
  • docker container run --cpu-quota=512 webapp
  • docker container run --cpus=512 webapp

Correct answer:

  • docker container run --cpu-shares=512 webapp

37. What component is responsible for managing CPU resources and allocating the time of the CPU between different processes?

  • Allocater
  • CFS
  • Controller
  • Allocater, Controller

Correct answer:

  • CFS

38. The built-in DNS server in Docker always runs at IP address …

  • 127.0.0.11
  • 127.0.0.1
  • 172.17.0.3
  • 172.17.0.1

Correct answer:

  • 127.0.0.11

39. What is the command to create an overlay network driver called my-overlay?

  • docker network create my-overlay
  • docker create network my-overlay
  • docker network create -d overlay my-overlay
  • docker network create overlay my-overlay

Correct answer:

  • docker network create -d overlay my-overlay

40. When you initialize a Docker Swarm cluster it creates a new network of type overlay which is an internal private network that spans across all the nodes participating in the swarm cluster.

  • True
  • False

Correct answer:

  • True

41. If the service type is NodePort, then Kubernetes will allocate a port on every worker node.

  • True
  • False

Correct answer:

  • True

42. What is the default range of ports that Kubernetes uses for NodePort if one is not specified?

  • 32767-64000
  • 30000-32767
  • 32000-3276
  • 80-8080

Correct answer:

  • 30000-32767

43. Which among the following statements are true without any change made to the default behaviour of network policies in the namespace?

  • As soon as a network policy is associated with a POD traffic between all PODs in the namespace is denied
  • As soon as a network policy is associated with a POD all ingress and egress traffic to that POD are denied except allowed by the network policy
  • As soon as a network policy is associated with a POD all ingress and egress traffic to that POD are allowed except for the the ones blocked by the network policy

Correct answer:

  • As soon as a network policy is associated with a POD all ingress and egress traffic to that POD are denied except allowed by the network policy

44. The communication between the swarm related services on different nodes in the swarm cluster are not secured by default.

  • True
  • False

Correct answer:

  • False

Explaination: The communication between the nodes in the swarm cluster are secured by authentication and encryption using TLS/SSL certificates

45. In which service does the DTR image scanning occur?

  • A service known as the dtr-jobrunner container
  • A service known as the dtr-registry container
  • A service known as the dtr-api container
  • A service known as the dtr-runner container

Correct answer:

  • A service known as the dtr-jobrunner container

Explaination: When you install DTR on a node, the dtr-jobrunner started and runs cleanup jobs in the background

46. Which of the statements best describe "Resource sets" in Access Control Model?

  • To control user access, cluster resources are grouped into Docker Swarm collections or Kubernetes namespaces.
  • Together, collections and namespaces are named resource sets.
  • A group of teams that share a specific set of permissions

Correct answer:

  • To control user access, cluster resources are grouped into Docker Swarm collections or Kubernetes namespaces.
  • Together, collections and namespaces are named resource sets.

47. Which of the following is a common workflow for RBAC in Docker EE is

  • Create users, teams and organization
  • Create custom roles with set of permissions
  • Combine resources sets using collection
  • Create a grant that combines subjects, roles and resource sets.

Correct answer:

  • Create users, teams and organization
  • Create custom roles with set of permissions
  • Combine resources sets using collection
  • Create a grant that combines subjects, roles and resource sets.

48. UCP has its own built-in authentication mechanism and integrates with LDAP and AD services.

  • True
  • False

Correct answer:

  • True

49. A client bundle is a group of certificates downloadable directly from the Docker Trusted Registry (DTR) user interface within the admin section for “My Profile”

  • True
  • False

Correct answer:

  • False

50. overlay2, aufs, and devicemapper all operate at the file level rather than the block level.

  • True
  • False

Correct answer:

  • False

Explaination: devicemapper operate at the block level rather than the file level

51. The volumes are mounted as “readonly” by default inside the container if no options are specified.

  • True
  • False

Correct answer:

  • False

Explaination: The volumes are mounted as “readwrite” by default…

52. Which among the below is a correct command to start a container named webapp with the volume vol3, mounted to the destination directory /opt in readonly mode?

  • docker run -d --name webapp --mount source=vol3,target=/opt,readonly httpd
  • docker run -d --name webapp -v vol3:/opt:ro httpd
  • docker run -d --name webapp -v vol3:/opt:readonly httpd
  • docker run -d --name webapp --volume vol3:/opt:ro httpd
  • docker run -d --name webapp --mount source=vol3,target=/opt,ro httpd

Correct answer:

  • docker run -d --name webapp --mount source=vol3,target=/opt,readonly httpd
  • docker run -d --name webapp -v vol3:/opt:ro httpd
  • docker run -d --name webapp --volume vol3:/opt:ro httpd

53. Which statements best describe emptyDir volume type?

  • An emptyDir volume is first created when a Pod is assigned to a node, and still exists after a pod termination.
  • An emptyDir volume is first created when a Pod is assigned to a node, and exists as long as that Pod is running on that node.
  • The emptyDir volume is initially empty
  • When a Pod is removed from a node for any reason, the data in the emptyDir is deleted permanently

Correct answer:

  • An emptyDir volume is first created when a Pod is assigned to a node, and exists as long as that Pod is running on that node.
  • The emptyDir volume is initially empty
  • When a Pod is removed from a node for any reason, the data in the emptyDir is deleted permanently

54. What is the command to delete the persistent volumes?

  • kubectl delete pv PV-NAME
  • kubectl del pv PV-NAME
  • kubectl rm pv PV-NAME
  • kubectl erase pv PV-NAME

Correct answer:

  • kubectl delete pv PV-NAME

55. What is the sequence of operations to be followed while configuring a storage class for an application?

  • Create a storage class with a provisioner, create a persistent volume with definition using the storage class, create a PVC and then use the PVC in the volumes section in the pod definition file
  • Create a storage class with a provisioner, create a PVC with the storage class, and then use the PVC in the volumes section in the pod definition file
  • Create a storage class, and use it directly in the volumes section in the pod definition file

Correct answer:

  • Create a storage class with a provisioner, create a PVC with the storage class, and then use the PVC in the volumes section in the pod definition file

Mock Exam 4

1. After restarting the docker service and trying to run docker service ls, you get an error "Error response from daemon: Swarm is encrypted and needs to be unlocked before it can be used. How can you solve this error?

  • docker swarm leave
  • docker swarm update
  • docker swarm lock
  • docker swarm unlock

Correct answer:

  • docker swarm unlock

2. How to get the Os field alone of the httpd image?

  • docker image inspect httpd -f '{{.Os}}'
  • docker image ls | grep Os
  • docker image history | grep Os
  • docker image inspect httpd -f '{{.OperatingSystem}}'

Correct answer:

  • docker image inspect httpd -f '{{.Os}}'

3. Which command can be used to stop (only and not delete) the whole stack of containers created by compose file?

  • docker-compose down
  • docker-compose stop
  • docker-compose destroy
  • docker-compose halt

Correct answer:

  • docker-compose stop

4. You are required to deploy an agent of splunk on all nodes in the swarm cluster to monitor the health of the nodes and gather logs. What is the best approach to achieve this?

  • Deploy the agent as a docker container on each node in the cluster. Use a cron job to set this up.
  • Deploy the agent as a global service in the swarm cluster
  • Deploy the agent as a replicated service with the replica count equal to the number of worker nodes in the swarm cluster

Correct answer:

  • Deploy the agent as a global service in the swarm cluster

5. What component is responsible for creating tasks in swarm

  • scheduler
  • dispatcher
  • orchestrator
  • allocater

Correct answer:

  • orchestrator

6. Which command can be used to deploy the STACKDEMO stack from a compose file? Select the all right answers

  • docker stack deploy --compose-file docker-compose.yml STACKDEMO
  • cat docker-compose.yml | docker stack deploy --compose-file - STACKDEMO
  • docker stack services --compose-file docker-compose.yml STACKDEMO
  • docker stack ps --compose-file docker-compose.yml STACKDEMO

Correct answer:

  • docker stack deploy --compose-file docker-compose.yml STACKDEMO
  • cat docker-compose.yml | docker stack deploy --compose-file - STACKDEMO

7. The services only under the same network will get resolved with their names so all of the micro-service component should be under the same network so that they can resolve each other.

  • True
  • False

Correct answer:

  • True

8. Create a replicated service webapp with 2 replicas.

  • docker service create --replicas=2 webapp
  • docker service create --mode=replicated --replicas=2 webapp
  • docker service create --mode=global --replicas=2 webapp
  • docker service create --replicas=2 webapp.

Correct answer:

  • docker service create --replicas=2 webapp
  • docker service create --mode=replicated --replicas=2 webapp

9. What is the command to run 3 instances of httpd on a swarm cluster?

  • docker swarm service create --instances=3 httpd</code
  • docker swarm service create --replicas=3 httpd
  • docker service create --instances=3 httpd
  • docker service create --replicas=3 httpd

Correct answer:

  • docker service create --replicas=3 httpd

10. Assume that you have 3 managers in your cluster, what will happen if 2 managers fail at the same time?

  • The services hosted on the available worker nodes will continue to run.
  • The services hosted on the available worker nodes will stop running.
  • New services/workers can be created or added.
  • New services/workers can’t be created or added.

Correct answer:

  • The services hosted on the available worker nodes will continue to run.
  • New services/workers can’t be created or added.

11. Map TCP port 80 in the container to port 8080 on the Docker host for connections to host IP 192.168.1.10.

  • -p 192.168.1.10:8080:80
  • -p 192.168.1.10:80:8080
  • -p 192.168.1.10:8080:80/tcp
  • -p 192.168.1.10:8080:8080

Correct answer:

  • -p 192.168.1.10:8080:80
  • -p 192.168.1.10:8080:80/tcp

12. what is the default Secret type if omitted from a Secret configuration file?

  • kubernetes.io/tls
  • kubernetes.io/ssh-auth
  • Opaque
  • kubernetes.io/dockercfg

Correct answer:

  • Opaque

13. Which of the following statements about kubernetes deployments are correct?

  • You describe a desired state in a Deployment, and the Deployment Controller changes the actual state to the desired state at a controlled rate.
  • You can define Deployments to create new ReplicaSets, or to remove existing Deployments and adopt all their resources with new Deployments.
  • You may manually update the ReplicaSets owned by a Deployment.
  • You should not manually update the ReplicaSets owned by a Deployment.

Correct answer:

  • You describe a desired state in a Deployment, and the Deployment Controller changes the actual state to the desired state at a controlled rate.
  • You can define Deployments to create new ReplicaSets, or to remove existing Deployments and adopt all their resources with new Deployments.
  • You should not manually update the ReplicaSets owned by a Deployment.

14. What command would you use to create a Deployment?

  • kubectl get deployments
  • kubectl get nodes
  • kubectl create
  • kubectl run

Correct answer:

  • kubectl create

Explaination: kubectl create is the command that will create a new deployment

  • Option A is incorrect because this get command will only list the existing Deployments
  • Option B is incorrect because this get command will only list the available Nodes where you can deploy applications
  • Option D is incorrect because this command will create a pod in kubernetes

15. Which statements best describe configmaps?

  • ConfigMap is an API object mainly used to store confidential data in key-value pairs.
  • ConfigMap is an API object mainly used to store non-confidential data in key-value pairs.
  • Pods can consume ConfigMaps as environment variables, command-line arguments, or as configuration files in a volume.
  • ConfigMap provides secrecy or encryption

Correct answer:

  • ConfigMap is an API object mainly used to store non-confidential data in key-value pairs.
  • Pods can consume ConfigMaps as environment variables, command-line arguments, or as configuration files in a volume.

Explaination: A ConfigMap allows you to decouple environment-specific configuration from your container images, so that your applications are easily portable.

16. What is the command to create a secret using the "kubectl create secret" command?

  • kubectl create secret test-secret --from-literal='username=my-app' --from-literal='password=39528$vdg7Jb'
  • kubectl create secret opaque test-secret --from-literal='username=my-app' --from-literal='password=39528$vdg7Jb'
  • kubectl create secret credentials test-secret --from-literal='username=my-app' --from-literal='password=39528$vdg7Jb'
  • kubectl create secret generic test-secret --from-literal='username=my-app' --from-literal='password=39528$vdg7Jb'

Correct answer:

  • kubectl create secret generic test-secret --from-literal='username=my-app' --from-literal='password=39528$vdg7Jb'

17. The health check on the web service is configured to run at an interval of every 30 seconds. What would happen if the web server takes 45 seconds to boot up the first time?

  • The web server container will be killed and restarted after 30 seconds
  • The health checks only start after 2 minutes, so the web server has sufficient time to boot up
  • The health checks runs every 5 seconds and will mark the container as failed after 5 attempts
  • The web service will go into an infinite loop

Correct answer:

  • The health checks only start after 2 minutes, so the web server has sufficient time to boot up

Code:

version: 3 services: redis: image: "redis:alpine" deploy: replicas: 3 db: image: postgres:9.4 deploy: replicas: 1 placement: constraints: - "node.role==manager" web: image: webapp deploy: replicas: 5 healthcheck: test: ["CMD", "curl", "-f", "http://localhost"] interval: 30s timeout: 5s retries: 5 start_period: 120s

18. Regarding the following YAML , What should we do to correct the syntax errors?

  • We need to use apiVersion as v1 but not v1/apps
  • kind should be Pod but not Pods
  • containers should be container
  • labels keyword should be inline with name under metadata

Correct answer:

  • We need to use apiVersion as v1 but not v1/apps
  • kind should be Pod but not Pods
  • labels keyword should be inline with name under metadata

Code: apiVersion: v1/apps kind: Pods metadata: name: apache labels: app: myapp spec: containers:

  • name: apache image: httpd

19. If CMD is used to provide default arguments for the ENTRYPOINT instruction, both the CMD and ENTRYPOINT instructions should be specified.

  • True
  • False

Correct answer:

  • True

20. Build an image using a context build under path /tmp/docker and name it webapp

  • docker build /tmp/docker</code
  • docker build /tmp/docker -t webapp
  • docker build webapp -t /tmp/docker
  • docker pull -it /tmp/docker bash

Correct answer:

  • docker build /tmp/docker -t webapp

21. How do you identify if a Docker file is configured to use multi-stage builds?

  • The Dockerfile has the tag multi-stage at the to
  • The Dockerfile has multiple FROM instructions
  • The Dockerfile has multiple RUN instructions
  • The Dockerfile is built from the scratch imag

Correct answer:

  • The Dockerfile has multiple FROM instructions

22. What is the command to remove all unused images on the Docker host?

  • docker image prune -a
  • docker image rm -a
  • docker image delete -a
  • docker rm image -a

Correct answer:

  • docker image prune -a

23. Which is the recommended approach to install packages following the best practices in Dockerfile?

  • "RUN apt-get update && apt-get install -y git httpd"
  • "RUN apt-get update && apt-get install -y \ git \ httpd"
  • "RUN apt-get update \ RUN apt-get install -y git \ RUN apt-get install -y httpd"

Correct answer:

  • "RUN apt-get update && apt-get install -y \ git \ httpd"

Explaination: this technique called cache busting which ensures your Dockerfile installs the latest package versions with no further coding or manual intervention

24. Display all layers of httpd image along with the size on each layer

  • docker image layers httpd
  • docker image history httpd
  • docker image inspect httpd
  • docker images history httpd

Correct answer:

  • docker image history httpd

25. Docker Trusted Registry (DTR) is a containerized application that runs on a Docker Universal Control Plane cluster.

  • True
  • False

Correct answer:

  • True

26. ... is one of the system requirements for UCP

  • The nodes must be Linux Kernel version 3.10 or higher
  • Each node must be configured with a static ip address
  • User namespaces should not be configured on any node
  • all nodes must have Docker Engine Enterprise installed

Correct answer:

  • The nodes must be Linux Kernel version 3.10 or higher
  • Each node must be configured with a static ip address
  • User namespaces should not be configured on any node
  • all nodes must have Docker Engine Enterprise installed

27. What is the command to push the image to a docker private registry?

  • docker push /username/docke-repo-name
  • docker push /docker-repo-name
  • docker upload /username/docker-repo-name
  • docker upload /docker-repo-name

Correct answer:

  • docker push /username/docke-repo-name

28. What is the default logging driver?

  • json-file
  • syslog
  • journald
  • splunk

Correct answer:

  • json-file

29. When you run the docker image inspect ubuntu command it gives the error “No such image”. Why is that?

  • Must run the command docker inspect ubuntu/ubuntu
  • Image Ubuntu does not have the latest tag
  • Must authenticate to docker hub first before running this command
  • Must run the command docker image history ubuntu

Correct answer:

  • Image Ubuntu does not have the latest tag

30. What is a linux feature that allows restriction of CPU and memory resources on docker containers?

  • Control Groups (CGroups)
  • Namespaces
  • Kernel Capabilities
  • LXC

Correct answer:

  • Control Groups (CGroups)

31. Which of the following are the steps that are required to set up UCP?

  • Make sure Docker EE is up and running and Pull the UCP image from the registry
  • Set the Admin Username and Password for UCP Console
  • Login to the Browser and provide the downloaded Docker EE License
  • Add more managers and workers as per requirement

Correct answer:

  • Make sure Docker EE is up and running and Pull the UCP image from the registry
  • Set the Admin Username and Password for UCP Console
  • Login to the Browser and provide the downloaded Docker EE License
  • Add more managers and workers as per requirement

32. Which of the following flags are required to install DTR as a docker container?

  • --dtr-external-url
  • --ucp-node
  • --ucp-username
  • --ucp-url

Correct answer:

  • --dtr-external-url
  • --ucp-node
  • --ucp-username
  • --ucp-url

33. To restore an existing UCP installation from a backup, you need to uninstall UCP from the swarm by using the uninstall-ucp command.

  • True
  • False

Correct answer:

  • True

34. The ... network disables all networking. Usually used in conjunction with a custom network driver

  • host
  • bridge
  • overlay
  • none

Correct answer:

  • none

35. Limit a container to only use the first CPU or core. Select the right command

  • docker container run --cpuset-shares=1 webapp
  • docker container run --cpus=0 webapp
  • docker container run --cpuset-cpus=0 webapp

Correct answer:

  • docker container run --cpuset-cpus=0 webapp

Explaination: The first CPU is numbered 0. A valid value might be 0-3 (to use the first, second, third, and fourth CPU) or 1,3 (to use the second and fourth CPU).

36. If you use the … network mode for a container, that container’s network stack is not isolated from the Docker host (the container shares the host’s networking namespace), and the container does not get its own IP-address allocated

  • host
  • bridge
  • overlay
  • NAT

Correct answer:

  • host

37. Macvlan network driver assigns a MAC address to each container’s virtual network interface, making it appear to be a physical network interface directly connected to the physical network.

  • True
  • False

Correct answer:

  • True

38. Assume that you have 1 CPU, which of the following commands guarantees the container at most 50% of the CPU every second?

  • docker run -it --cpu-shares=512 ubuntu /bin/bash
  • docker container run --cpuset-cups=.5 webapp
  • docker run -it --cpus=".5" ubuntu /bin/bash
  • docker run -it --cpus=".5" --cpuset-cups=1 ubuntu /bin/bash

Correct answer:

  • docker run -it --cpus=".5" ubuntu /bin/bash

39. Docker requires an external DNS server to be configured during installation to help the containers resolve each other using the container name.

  • True
  • False

Correct answer:

  • False

Explaination: Docker will by default check for a DNS server defined in /etc/resolv.conf in the host OS.

40. Which command is used to get the stream logs of the webapp container so that you can view the logs live?

  • docker container log webapp
  • docker container log -f webapp
  • docker container logs webapp
  • docker container logs -f webapp

Correct answer:

  • docker container logs -f webapp

41. What is the default traffic flow configuration between pods in a kubernetes cluster?

  • All traffic is allowed between different pods in the cluster
  • All traffic is denied between different pods in the cluster
  • Traffic between different pods must be explicitly allowed using rules

Correct answer:

  • All traffic is allowed between different pods in the cluster

42. By default all swarm service management traffic is encrypted using ... algorithm

  • TKIP
  • DES
  • AES
  • RSA

Correct answer:

  • AES

43. Which of the statements best describe "Grants" in the Access Control Model?

  • Grants define which users can access what resources in what way
  • A grant is made up of a role and a resource set.
  • A grant is made up of a subject, a role, and a resource set.
  • Grants are effectively Access Control Lists (ACLs) which provide comprehensive access policies for an entire organization when grouped together.

Correct answer:

  • Grants are effectively Access Control Lists (ACLs) which provide comprehensive access policies for an entire organization when grouped together.
  • A grant is made up of a subject, a role, and a resource set.

44. Which of the following statements are true about deploying workload via CLI on UCP Cluster?

  • With CLI you may use the docker command line interface to interact with the UCP cluster.
  • CLI access doesn't require authentication to the UCP Cluster.
  • CLI access requires authentication to the UCP Cluster.
  • Download the certificate from UCP Console and copy this over to the server from where you’d like to access and extract it to a path.
  • The docker host and docker_cert_path environment variables are automatically set by the application.

Correct answer:

  • With CLI you may use the docker command line interface to interact with the UCP cluster.
  • CLI access requires authentication to the UCP Cluster.
  • The docker host and docker_cert_path environment variables are automatically set by the application.

45. Once the image scan is complete, a report shows all the vulnerabilities detected categorized as __________.

  • Major
  • Minor
  • Critical
  • Warning

Correct answer:

  • Major
  • Minor
  • Critical

46. Using ... in Docker EE we can control who can access and make changes to your cluster and applications

  • DTR
  • UCP
  • Client bundle
  • RBAC

Correct answer:

  • RBAC

47. DTR offers a deeply integrated vulnerability scanner that analyzes container images by only manual user request.

  • True
  • False

Correct answer:

  • True

Explaination: DTR offers a deeply integrated vulnerability scanner that analyzes container images, either by manual user request or automatically whenever an image is uploaded to the registry.

48. To authorize access to cluster resources across your organization, which of the following high-level steps UCP administrators might take?

  • Add and configure subjects (users, teams, and service accounts).
  • Define custom roles (or use defaults) by adding permitted operations per type of resource.
  • Group cluster resources into resource sets of Swarm collections or Kubernetes namespaces.
  • Create grants by combining subject + role + resource set

Correct answer:

  • Add and configure subjects (users, teams, and service accounts).
  • Define custom roles (or use defaults) by adding permitted operations per type of resource.
  • Group cluster resources into resource sets of Swarm collections or Kubernetes namespaces.
  • Create grants by combining subject + role + resource set

49. What is the default path file to do any storage driver customization?

  • /var/lib/docker/daemon.json
  • /var/log/docker/daemon.json
  • /etc/docker/daemon.json
  • /home/docker/daemon.json

Correct answer:

  • /etc/docker/daemon.json

50. ... driver stores every image and container on its own virtual device. These devices are thin-provisioned copy-on-write snapshot devices

  • AUFS
  • overlay2
  • Device Mapper
  • OverlayFS

Correct answer:

  • Device Mapper

51. By default all files inside an image are in a writable layer.

  • True
  • False

Correct answer:

  • False

52. What is the command to remove unused volumes

  • docker container rm my-vol
  • docker volume rm my-vol
  • docker volume prune
  • docker volume rm --all

Correct answer:

  • docker volume prune

53. What is the status of a volume after it is created but not yet bound to a claim?

  • Available
  • Bound
  • Released
  • Failed

Correct answer:

  • Available

54. Which of the following is the etcd command line tool?

  • etcd
  • etcdctl
  • kubectl

Correct answer:

  • etcdctl

Explaination: The default client that comes with ETCD is the etcdctl client. You can use it to store and retrieve key-value pairs.

  • Option A is incorrect because etcd is a service
  • Option C is incorrect because kubectl is the kubernetes command-line tool.
  • Option D is incorrect because kubeadm is a tool which performs the actions necessary to get a minimum viable cluster up and running.

55. What are the types of volumes that kubernetes supports?

  • hostPath
  • configMap
  • emptyDir
  • local

Correct answer:

  • hostPath
  • configMap
  • emptyDir
  • local

Python PCEP Literals

1. …. is one of the literal types in Python.

  • None of the above
  • Boolean
  • String
  • Numeric

Correct answer:

  • Boolean
  • String
  • Numeric

2. What is the data type of print(type(45.50))?

  • integer
  • float
  • string
  • boolean

Correct answer:

  • float

3. What is the numerical value for boolean True?

  • 0
  • 1

Correct answer:

  • 1

4. Strings can be enclosed in double or single quotes.

  • True
  • False

Correct answer:

  • True

5. What is the data type of print(type(10))?

  • integer
  • float
  • string
  • boolean

Correct answer:

  • integer

6. What is the data type of print(type(1_00_0000_000))?

  • integer
  • string
  • boolean
  • None of the above

Correct answer:

  • integer

7. …. can be created by writing a text(a group of Characters ) surrounded by the single(") or double(" ")quotes.

  • String literals
  • Numeric literals
  • Boolean literals
  • Literal Collections

Correct answer:

  • String literals

Python PCEP Print Function

1. …. is a block of code that only runs when it is called and used to cause an effect or evaluate a value.

  • Variable
  • Function
  • Method
  • Tuple

Correct answer:

  • Function

2. The …. function prints the specified message to the screen, or another standard output device.

  • print()
  • return()
  • vars()
  • input()

Correct answer:

  • print()

3. What is the output of the following python code?

  • Hello
  • Hello future python!
  • python!
  • Hello python!

Correct answer:

  • Hello future python!

Code: print("Hello" + " " "future" + " " "python!")

4. What is the special character that is used for a new line?

  • \t
  • \r
  • \n
  • \d

Correct answer:

  • \n

5. What is the output of the following python code?

  • 1234#&
  • 1#2#3#4&
  • 1&2&3&4#
  • 1234sep='#'end='&'

Correct answer:

  • 1#2#3#4&

Code: print(1, 2, 3, 4, sep='#', end='&')

6. The output of the following code will be:

  • My age is 25
  • 25
  • TypeError
  • My age is + 25

Correct answer:

  • TypeError

Code: print('My age is ' + 25)

Explaination: TypeError: can only concatenate str (not "int") to str

7. Is it possible to pass multiple arguments to a function?

  • Yes
  • No

Correct answer:

  • Yes

Python PCEP Operators

1. What is the output of the following python code?

  • 8.0
  • 0.8
  • 8
  • 8.5

Correct answer:

  • 8

Code: print(2 ** 3)

2. What is the output of the following python code?

  • -3
  • 12
  • 10
  • 20

Correct answer:

  • 10

Code: print(2*(2+3))

3. What is the output of the following python code?

  • 1.5
  • 1.0
  • -1.5
  • -2.0

Correct answer:

  • 1.0

Code: print(6. // 4)

4. What is the output of the following python code?

  • 5.0
  • 0.5
  • 5
  • 5.5

Correct answer:

  • 5.0

Code: print(10 / 2)

Explaination: Hint: division operator always returns a float

5. What is the output of the following python code?

  • 8.0
  • 0.8
  • 8
  • 8.5

Correct answer:

  • 8.0

Code: print(2 ** 3.)

Explaination: Hint: If one of the values is a floating-point number, the result will be a floating-point number as well.

6. Fill in the missing operators:

  • / and *
  • // and *
  • % and /
  • * and /

Correct answer:

  • / and *

Code: 20 ... 5 ... 4 = 16.0

7. What is the output of the following python code?

  • -311029.0
  • 29.0
  • 50
  • -29.0

Correct answer:

  • -29.0

Code: print(10 - 6 ** 2 / 9 * 10 + 1)

8. What is the output of the following python code?

  • 0
  • 1
  • 2
  • 2.25

Correct answer:

  • 1

Code: print(9 % 4)

9. What does the following print?

  • 4
  • 5.0
  • 4.5
  • 7
  • None of the above

Correct answer:

  • 5.0

Code: x = 10 / 4 y = 5 / 2.0 print (x + y)

10. What is the output of the following python code?

  • 4
  • 3
  • 3.25
  • 4.25
  • None of the above

Correct answer:

  • 4.25

Code: print(13 / 4 + 13 % 4)

11. What is the value of the expression 100 / 50 ?

  • 2
  • 2.0
  • 4
  • 4.0

Correct answer:

  • 2.0

12. What is the output of print(2 * 3 ** 3 * 4)?

  • 216
  • 864
  • “2 * 3 ** 3 * 4”
  • 144

Correct answer:

  • 216

Python PCEP Variables

1. In Python, a variable must be declared before it is assigned a value:

  • True
  • False

Correct answer:

  • False

Explaination: Hint: Variables need not be declared or defined in advance in Python. To create a variable, you just assign it a value.

2. Which of the following statements assigns the value 50 to the variable x in Python:

  • x == 50
  • x : 50
  • x = 50
  • x >> 50

Correct answer:

  • x = 50

3. What is the output of the following python code?

  • 8
  • 16
  • 10
  • 12

Correct answer:

  • 16

Code: amount = 4 cost = 2 cost += 2 print(amount * cost)

4. True is what type of variable?

  • float
  • string
  • boolean
  • integer

Correct answer:

  • boolean

5. Which of the following is a valid variable name in Python?

  • do it
  • do+1
  • 1do
  • All of the above
  • None of the above

Correct answer:

  • None of the above

6. Which of the following is a keyword in Python?

  • int
  • float
  • return
  • All of the above
  • finally

Correct answer:

  • All of the above

7. Which of the following variable names are valid?

  • not = "Don't do that!"
  • name = "Lydia"
  • 2timesage = 44
  • Function = "function"

Correct answer:

  • name = "Lydia"
  • Function = "function"

8. Which of the following is correct regarding variables in Python?

  • Variable names in Python cannot start with a number. However, it can contain the number in any other position of the variable name.
  • Variable names can start with an underscore.
  • Data type of variable names should not be declared
  • All of the above

Correct answer:

  • All of the above

9. Which of the following are valid Python variable names?

  • Age
  • 1st_student
  • class
  • _st

Correct answer:

  • Age
  • _st

10. What would get printed to the console?

  • 22
  • 22.0
  • 88
  • 55.0

Correct answer:

  • 55.0

Code: age = 22 AGE = 44

age /= 2

print(age + AGE)

11. What is the output of the following python code?

  • 5
  • Jack
  • 5Jack
  • Error

Correct answer:

  • Jack

Code: y = 5 y = "Jack" print(y)


Python PCEP Comments

1. What is the output of the following python code?

  • Sally#employee name+#123
  • Sally#employee name#123
  • Sally+#123
  • Sally#123

Correct answer:

  • Sally#123

Code: name = "Sally"# employee name

data = "#123" print (name+data)

2. A comment in Python starts with the hash character(#) and extends to the end of the physical line.

  • True
  • False

Correct answer:

  • True

3. What is the output of the following python code?

  • 18
  • 7
  • 5+6+7
  • NameError

Correct answer:

  • NameError

Code: #x = 5 #y = 6 z = 7 print(x+y+z)

4. You can use Python comments inline, on independent lines, or on multiple lines to include larger documentation.

  • True
  • False

Correct answer:

  • True

5. What is the output of the following python code?

  • Hello, jack!
  • Hello, jack,Sally!
  • Hello, Sally!
  • Hello, jack!,Sally!

Correct answer:

  • Hello, Sally!

Code: #print("Hello, jack!") print("Hello, Sally!")

6. Which character is used in Python to make a single line comment?

  • /
  • //
  • #
  • !

Correct answer:

  • #

7. Comments can be used to ….

  • explain Python code
  • make the code more readable
  • comment out code that you don’t want to execute
  • None of the Above

Correct answer:

  • explain Python code
  • make the code more readable
  • comment out code that you don’t want to execute

8. What is the output of the following python code?

  • line1
  • line1
    line2
    line3
  • line1
    line2
    #line3
  • line1
    #line3

Correct answer:

  • line1
    #line3

Code: print("line1") #print("line2") print("#line3")


Python PCEP Input

1. What is the output of the following python code if we enter 25 as input?

  • 25
  • My age is: 25
  • input("My age is: " )
  • Error

Correct answer:

  • 25

Code: age =input("My age is: " ) print (age)

2. In Python3, Whatever you enter as input, the input() function converts it into a string.

  • True
  • False

Correct answer:

  • True

3. The input() method returns string value. So, if we want to perform arithmetic operations, we need to cast the value first.

  • True
  • False

Correct answer:

  • True

4. What is the output of the following python code if we enter “Hello Python” as input?

  • Hello Python#&
  • Hello Python
  • Hello#Python&
  • Hello Python&

Correct answer:

  • Hello Python&

Code: inputString = input('Enter a string: ') print(inputString, sep='#', end='&')

5. What will be printed when the following executes?

  • 5.5
  • 6
  • 5
  • 6.5

Correct answer:

  • 5

Code: print(int(15.5)-10)

6. What is the input function?

  • A function that allows us to ask the user to enter some data.
  • A function used to display numbers and text on the screen.
  • A piece of data that is shown on the screen.
  • To calculate something.

Correct answer:

  • A function that allows us to ask the user to enter some data.

Python PCEP String Methods

1. What is the output of the following python code if we enter 5 as input?

  • 15
  • NumNumNum
  • 555
  • Error

Correct answer:

  • 555

Code: Num = input("Enter a Number: ") print (Num * 3 )

2. What is the output of the following python code if we enter 5 as input?

  • 15
  • NumNumNum
  • 555
  • Error

Correct answer:

  • 15

Code: Num = input("Enter a Number: ") Num = int(Num) print ( Num * 3 )

3. Which operator you can use to perform string concatenation?

  • /
  • *
  • +
  • -

Correct answer:

  • +

4. Which method should you use in order to convert the input into a string correctly:

  • str
  • int
  • float
  • bin

Correct answer:

  • str

Code: year_of_birth = int(input("In what year were you born? "))

print("You were born in " + ...(year_of_birth))

5. What is the output of the following python code if we enter “HelloPython” as input?

  • HelloPython
  • Enter a string: HelloPython*2
  • HelloPythonHelloPython
  • HelloPython*2

Correct answer:

  • HelloPythonHelloPython

Code: inputString = input('Enter a string: ') print(inputString*2)

6. What is the output of the following python code?

  • 5Sally
  • 9
  • Error
  • 5+Sally

Correct answer:

  • 5Sally

Code: x = 5 y = "Sally" print(str(x) + y)

7. All string methods return new values and the original string values will be changed with the new values.

  • True
  • False

Correct answer:

  • False

Explaination: All string methods returns new values. They do not change the original string.

8. What will be printed when the following executes?

  • ha2
  • haha
  • ha*2
  • ha ha

Correct answer:

  • haha

Code: print("ha"*2)


Python PCEP Comparison Operators

1. What is the output of the following code?

  • 8
  • 12
  • 10
  • SyntaxError

Correct answer:

  • SyntaxError

Code: y = 20 x = y += 3 print(x)

2. What would get printed?

  • False
    True
  • True
    False
  • False
    False
  • True
    True

Correct answer:

  • False
    True

Code: min_score = 13 score = 13

print(score > min_score) print(score <= min_score)

3. What is the output when the following executes?

  • True
  • False

Correct answer:

  • True

Code: print(2 < 4)

4. What is the output of the following python code?

  • True
  • False
  • 7
  • 6

Correct answer:

  • True

Code: x = 6 y = 7 print(x != y)

5. What is the output when the following executes?

  • python
  • False
  • True
  • Error

Correct answer:

  • True

Code: 'python'>'Python'


Python PCEP Conditional Statements

1. What is the output of the following python code?

  • TRUE
  • TRUE
    FALSE
  • FALSE
    TRUE
  • TRUE
    FALSE
    TRUE

Correct answer:

  • FALSE
    TRUE

Code: if 4 + 5 == 10: print("TRUE") else: print("FALSE") print("TRUE")

2. What is the output of the following python code?

  • True
  • b is greater than a
  • False
  • IndentationError

Correct answer:

  • IndentationError

Code: a = 5 b = 10 if b > a: print("b is greater than a")

3. Which of the following is not a boolean expression?

  • True
  • 3 == 4
  • 3 + 4
  • 3 + 4 == 7

Correct answer:

  • 3 + 4

4. What is the output of the following python code?

  • This is always printed
  • The negative number -10 is not valid here.
  • The negative number -10 is not valid here.
    This is always printed

Correct answer:

  • The negative number -10 is not valid here.
    This is always printed

Code: x = -10 if x < 0: print("The negative number ", x, " is not valid here.") print("This is always printed")

5. What is the output of the following python code?

  • a and b are equal
  • b is greater than a
  • a is greater than b
  • a and b are equal, b is greater than a

Correct answer:

  • b is greater than a

Code: a = 5 b = 10 if b < a: print("a is greater than b") elif a == b: b = 5 print("a and b are equal") else: print("b is greater than a")

6. Given the nested if-else below, what will be the value x when the code executed successfully.

  • 0
  • 2
  • 3
  • 4

Correct answer:

  • 4

Code: x = 0 a = 6 b = 6 if a > 0: if b < 0: x = x + 6 elif a > 6: x = x + 5 else: x = x + 4 else: x = x + 3

print(x)

7. Which one of the following if statements will not execute successfully ?

  • 1st if statement
  • 2nd if statement
  • 3rd if statement
  • 4th if statement

Correct answer:

  • 2nd if statement
  • 3rd if statement

Code:

1st if statement

if True: print('hello')

2nd if statement

if (5,10): print('hello')

3rd if statement

if (yes): print('hello')

4th if statement

if (5,10): print('hello')

Explaination: 2nd statement: IndentationError: expected an indented block, 3rd statement: NameError: name 'yes' is not defined.

NOTE: The condition in if statement is (5,10), which is a tuple containing the values 5 and 10. In Python, non-empty containers like tuples are considered "truthy," meaning they are treated as true in a boolean context.

8. What does the following Python program display?

  • Am I here?
  • Or here?
  • Am I here?
    Or here?
  • Or here?
    Or over here?

Correct answer:

  • Or here?
    Or over here?

Code: x = 3 if ( x == 0 ): print("Am I here?") elif ( x == 3 ): print("Or here?") print("Or over here?")

9. What keyword would you use to add an alternative condition to an if statement?

  • else if
  • elseif
  • elif
  • None of the above

Correct answer:

  • elif

10. Which statement will check if a is equal to b?

  • if a = b:
  • if a == b:
  • if a === c:
  • if (a == b):

Correct answer:

  • if a == b:
  • if (a == b):

Explaination: In Python, you can also use parentheses around the condition in an if statement, and it will not affect the functionality. The parentheses can be used for readability or to clarify the order of operations in more complex conditions. So both the statements "if (a == b):" and "if a == b:" are correct.


Python PCEP Loops - While

1. What will be the output of the following Python code?

  • error
  • 2
    4
  • 2
    3
  • 2
    4
    6
    8
    10

Correct answer:

  • 2
    4

Code: i = 2 while True: if i%3 == 0: break print(i) i += 2

2. What will be the output of the following Python code?

  • error
  • 5
    6
    7
    8
  • 5
    6
  • 5
    6
    7
    8
    9
    10

Correct answer:

  • 5
    6
    7
    8

Code: i = 5 while True: if i % 0o11 == 0: break print(i) i += 1

3. What is the value of x ...

  • 49
  • 50
  • None of the above, this is an infinite loop
  • 51

Correct answer:

  • 50

Code: x = 0 while (x < 50): x+=2

print(x)

Explaination: In the "while" loop as per statement "x" is increased by 2. Like 2, 4, 6 ... 48 50.  Value 50 is not satisfying the given condition so it's exited from the loop and the final value we got for "x" is 50.

4. What is the output when this code executes?

  • 6
  • 1
  • 4
  • 5
  • None of the above

Correct answer:

  • 6

Code: x = 1 while ( x <= 5 ): x += 1 print(x)

5. What will be the output of the following Python code?

  • error
  • None of the above
  • 1
    2
    3
    4
    5
    6
  • 1
    2
    3
    4
    5
    6
    7

Correct answer:

  • 1
    2
    3
    4
    5
    6

Code: i = 1 while True: if i % 0o7 == 0: break print(i) i += 1

Explaination: Hint: Control exits the loop when i becomes 7.

6. What keyword would you use to add an alternative condition to an if statement?

  • else if
  • elseif
  • elif
  • None of the above

Correct answer:

  • elif

7. Which statement will check if a is equal to b?

  • if a = b:
  • if a == b:
  • if a === c:
  • if (a == b):

Correct answer:

  • if a == b:
  • if (a == b):

Explaination: In Python, you can also use parentheses around the condition in an if statement, and it will not affect the functionality. The parentheses can be used for readability or to clarify the order of operations in more complex conditions. So both the statements "if (a == b):" and "if a == b:" are correct.

8. What will be the output of the following Python code?

  • error
  • None of the above
  • 1
    2
  • 1
    2
    3

Correct answer:

  • 1
    2

Code: i = 1 while True: if i%3 == 0: break print(i) i += 1

9. What does the following Python program display?

  • 2
  • 5
  • 19
  • 32

Correct answer:

  • 32

Code: x = 1 while ( x < 20 ): x = x * 2 print(x)

10. What does the following code produce as output?

  • 12
  • 6
  • 3
  • 1

Correct answer:

  • 6

Code: i = 1 x = 3 sum = 0 while ( i <= x ): sum += i i += 1 print(sum)


Python PCEP Loops - For

1. What will be the output of the following Python code?

  • error
  • a
    b
    c
    d
  • A
    B
    C
    D
  • a
    B
    C
    D

Correct answer:

  • a
    b
    c
    d

Code: x = 'abcd' for i in x: print(i) x.upper()

2. What will be the output of the following Python code?

  • error
  • a
    b
    c
    d
  • A
    B
    C
    D
  • a
    B
    C
    D

Correct answer:

  • A
    B
    C
    D

Code: x = 'abcd' for i in x: print(i.upper())

Explaination: Hint: The instance of the string returned by upper() is being printed.

3. What will be the output of the following Python code?

  • a b c d
  • 0 1 2 3
  • error
  • a
    b
    c
    d
  • none of the above

Correct answer:

  • error

Code: x = 'abcd' for i in range(x): print(i)

Explaination: Hint: range(str) is not allowed.

4. We want to iterate over the values from 0 to 10, and print their values. However, we want to skip all the values that are even. How can we achieve this?

  • if num % 2 == 0: break;
  • if num % 2 == 0: continue;
  • if num % 2 != 0: print(num);
  • if num % 2 == 0: return

Correct answer:

  • if num % 2 != 0: print(num);
  • if num % 2 == 0: continue;

Code: for num in range(0, 11): #your answer should be here print(num)

5. What will be the output of the following Python code?

  • error
  • num
    num
    num
    num
  • 0
    1
    2
    3
  • 5
    6
    7
    8
    9
    10

Correct answer:

  • 5
    6
    7
    8
    9
    10

Code: x = 'abcd' for num in range(5, 11): print(num)

6. What will be the output of the following Python code snippet?

  • a b c d
  • 0 1 2 3
  • error
  • none of the mentioned

Correct answer:

  • error

Code: x = 'abcd' for i in range(len(x)): i.upper() print (x)

Explaination: Hint: Objects of type int have no attribute upper().

7. What will be the output of the following Python code?

  • error
  • 1
    2
    3
    4
  • a
    b
    c
    d
  • 0
    1
    2
    3

Correct answer:

  • 0
    1
    2
    3

Code: x = 'abcd' for i in range(len(x)): print(i)

8. What will be the output of the following Python code?

  • hello hello hello hello
  • 0 1 2 3
  • error
  • a b c d
  • hello
    hello
    hello
    hello

Correct answer:

  • hello
    hello
    hello
    hello

Code: x = 'abcd' for i in range(len(x)): print("hello")

9. What will be the output of the following Python code?

  • i i i i
  • Error!
  • 2 0 2 1
  • 0 1 2 3

Correct answer:

  • Error!

Code: x = 2021 for i in x: print(i)

Explaination: Hint: Objects of type int are not iterable instead a list, dictionary or a tuple should be used.


Python PCEP Lists

1. What will be the output of below Python code?

  • 5
  • 4
  • 6
  • none of the above

Correct answer:

  • 6

Code: numbers = [1, 2, 3, 4, 5] numbers[4] = 6 print(numbers[4])

2. What will be the output of below Python code?

  • 5
  • 1
  • 2
  • 4

Correct answer:

  • 5

Code: list1 = [1, 2, 3, 4, 5] print(list1[4])

3. Which of the following would give an error?

  • list1=[] ++
  • list1=[]
  • list1=[] + 2
  • list1=["USA","Canada","India"]

Correct answer:

  • list1=[] + 2
  • list1=[] ++

Explaination: can only concatenate list (not "int") to list.

4. What will be the output of below Python code?

  • [10, 13]
  • [10, 12, 14]
  • [11, 12, 13, 14]
  • [10, 11, 12, 13]

Correct answer:

  • [10, 13]

Code: list1 = [10, 11, 12, 13, 14] print(list1[::3])

5. What will be the output of below Python code?

  • [1, 2, 10, 4, 5]
  • [1, 2, 3, 4, 10]
  • [1, 2, 3, 4, 5]
  • [10, 2, 3, 4, 5]

Correct answer:

  • [10, 2, 3, 4, 5]

Code: list1 = [1, 2, 3, 4, 5] list1[0] = 10 print(list1)

6. Which of the following will reverse list1=[2,5,3,1]?

  • list1[::-1]
  • list1[::2]
  • list1[::1]
  • list1[2:4]

Correct answer:

  • list1[::-1]

Python PCEP Lists Methods

1. What will be the output of below Python code?

  • [24, 46, 56, 72]
  • [24, 46, 72, 56]
  • [56, 72, 24, 46]
  • [24, 46, 56]

Correct answer:

  • [24, 46, 56, 72]

Code: ages = [56, 72, 24, 46] ages.sort() print(ages)

2. What will be the output of below Python code?

  • ['UK', 8, 'India', 'Canada']
  • ['UK', 'India', 'Canada', 8]
  • ['UK', 1, 'India', 'Canada']
  • ['UK',1, 8, 'India', 'Canada']

Correct answer:

  • ['UK', 8, 'India', 'Canada']

Code: list1=['UK','India','Canada']

list1.insert(1,8)

print(list1)

Explaination: Hint: with insert method, we can insert a new item in between values so item 8 will be inserted into index 1

3. What will be the output of following Python code?

  • Go
  • Java
  • C
  • Rust

Correct answer:

  • C

Code: list1=["Go","Java","C","Rust"] print(min(list1))

4. What will be the output of below Python code?

  • [10, 20, 30, 40, 50]
  • [10, 20, 30, 40, 50, 60]
  • [60, 10, 20, 30, 40, 50]
  • [10, 20, 30, 40, 60]

Correct answer:

  • [10, 20, 30, 40, 50, 60]

Code: list1 = [10, 20, 30, 40, 50] list1.append(60) print(list1)

Explaination: Hint: with append method, we can append a new item at the end of the list

5. What will be the output of below Python code?

  • [1, 3, 4, 4]
  • [4, 4, 3, 1]
  • [1, 4, 4, 3]
  • [4, 3, 4, 1]

Correct answer:

  • [1, 3, 4, 4]

Code: num = [4, 4, 3, 1] num.sort() print(num)

6. What is the len(list1) for below value?

  • 5
  • 4
  • None
  • Error

Correct answer:

  • 5

Code: list1=['h', 'e', 'l', 'l', 'o']

7. What will be the output of following Python code?

  • Go
  • Java
  • C
  • Python

Correct answer:

  • Python

Code: list1=["Go","Java","C","Python"] print(max(list1))

8. What will be the output of below Python code?

  • [4, 4, 3]
  • [4, 4, 1]
  • [4, 3, 1]
  • [4, 4, 3, 1]

Correct answer:

  • [4, 4, 1]

Code: list1 = [4, 4, 3, 1] list1.pop(2) print(list1)


Python PCEP Iterating Lists

1. What will be printed by the following code when it executes?

  • 2
  • 11
  • 12
  • 19

Correct answer:

  • 19

Code: sum = 0 values = [2,9,1,7] for number in values: sum += number

print(sum)

2. for i in [9, 1, 5, 6]:, how many times a loop runs ?

  • 1
  • 2
  • 3
  • 4

Correct answer:

  • 4

3. What will be printed by the following code when it executes?

  • 2
  • 11
  • 12
  • 19

Correct answer:

  • 19

Code: sum = 0 values = [2,9,1,7] for number in values: sum = sum + number

print(sum)

4. Which of the following statements won’t be printed when this Python code is run?

  • Letter : K
  • Letter : u
  • Letter : e
  • Letter : d

Correct answer:

  • Letter : u

Code: for letter in 'KodeKloud': if letter == 'u': continue print('Letter : ' + letter)

5. for i in [1, 1, 7, 0, 6]:, how many times a loop run ?

  • 1
  • 3
  • 2
  • 5

Correct answer:

  • 5

6. How many asterisks will be printed when the following code executes?

  • 20
  • 16
  • 5
  • 4

Correct answer:

  • 16

Code: for x in [0, 2, 1, 3]: for y in [0, 4, 1, 2]: print('*')

7. How many asterisks will be printed when the following code executes?

  • 5
  • 4
  • 20
  • 16

Correct answer:

  • 16

Code: for x in [0, 1, 1, 3]: for y in [0, 2, 1, 2]: print('*')

8. Which of the following statements won’t be printed when this Python code is run?

  • Letter : K
  • Letter : o
  • Letter : e
  • Letter : d

Correct answer:

  • Letter : e

Code: for letter in 'KodeKloud': if letter == 'e': continue print('Letter : ' + letter)


Python PCEP Understanding Lists

1. Which of the following would give an error?

  • list1=[]
  • list1=[]*2
  • list1=["USA","Canada","India"]
  • None of the above

Correct answer:

  • None of the above

2. What will be the output of below Python code?

  • [10, 11, 12, 13, 14, 15]
  • [10, 11, 12, 15, 13, 14]
  • [15, 10, 11, 12, 13, 14]
  • [10, 11, 12, 13, 14]

Correct answer:

  • [10, 11, 12, 13, 14, 15]

Code: list1 = [10, 11, 12, 13, 14] list1.append(15) print(list1)

3. What will be the output of below Python code?

  • 10
  • 11
  • 12
  • 14

Correct answer:

  • 10

Code: list1 = [10, 11, 12, 13, 14] print(list1[0])

4. What will be the output of below Python code?

  • [1, 2, 3, 2, 5]
  • [8, 9, 10]
  • [4, 5, 6, 7]
  • [10, 11, 12, 13]

Correct answer:

  • [8, 9, 10]

Code: list1 = [[1,2,3,2,5],[4,5,6,7],[8,9,10]] for i in list1: if len(i)==3: print(i)

5. What will be the output of below Python code?

  • [1, 7, 0, 4]
  • [1, 4, 0]
  • [1, 7, 4, 0]
  • [4,0,7,1]

Correct answer:

  • [1, 7, 0, 4]

Code: list1=[4,0,7,1] print(list1[::-1])

6. What will be the output of below Python code?

  • [1, 2, 3, 2, 5]
  • [8, 9, 10]
  • [4, 5, 6, 7]
  • [10, 11, 12, 13]

Correct answer:

  • [4, 5, 6, 7]

Code: list1 = [[1,2,3,2,5],[4,5,6,7],[8,9,10]] for i in list1: if len(i)==4: print(i)

7. What will be the output of below Python code?

  • ['C', 'D', 'E']
  • ['B', 'C', 'D', 'E']
  • ['B', 'A', 'C', 'D', 'E']
  • ['A', 'B', 'C', 'D', 'E']

Correct answer:

  • ['B', 'C', 'D', 'E']

Code: letters = ["A", "B", "C", "D", "E"] print(letters[1:])

8. What will be the output of below Python code?

  • [1, 2, 3, 4]
  • [0, 1, 2, 3]
  • 0 1
    1 2
    2 3
    3 4
  • 1 0
    2 1
    3 2
    4 3

Correct answer:

  • 0 1
    1 2
    2 3
    3 4

Code: list1 = [1, 2, 3, 4] for i, j in enumerate(list1): print(i, j)

9. What will be the output of below Python code?

  • [0, 1, 2, 3]
  • [1, 2, 3, 4]
  • 0
    1
    2
    3
  • 1
    2
    3
    4
  • 0 1
    1 2
    2 3
    3 4

Correct answer:

  • 0 1
    1 2
    2 3
    3 4

Code: list1 = [1, 2, 3, 4] for index, j in enumerate(list1): print(index, j)

10. What will be the output of below Python code?

  • [10, 11, 12, 13, 14]
  • [10, 12, 14]
  • [11, 12, 13, 14]
  • [10, 11, 12, 13]

Correct answer:

  • [10, 11, 12, 13, 14]

Code: list1 = [10, 11, 12, 13, 14] print(list1[::1])


Python PCEP Slicing Lists

1. What will be the output of below Python code?

  • 0
  • 1
  • 9
  • 4

Correct answer:

  • 4

Code: my_list = [0, 1, 2, 3, 4] print(my_list[-1])

2. What will be the output of below Python code?

  • [0, 1, 2, 3, 4]
  • [0, 1, 2]
  • [2, 3]
  • [0, 1, 2, 3]

Correct answer:

  • [2, 3]

Code: my_list = [0, 1, 2, 3, 4] print(my_list[2:4])

3. What will be the output of below Python code?

  • [1, 66, "python"]
  • ['python', [11, 55, 'cat']]
  • [[11, 55, "cat"], [ ]]
  • [2.22, True]

Correct answer:

  • ['python', [11, 55, 'cat']]

Code: list1 = [1, 66, "python", [11, 55, "cat"], [ ], 2.22, True] print(list1[2:4])

4. What will be the output of below Python code?

  • [4, 3, 2, 1, 0]
  • [0, 2, 4, 1, 3]
  • [0, 3, 4]
  • [0, 1, 2, 3]

Correct answer:

  • [4, 3, 2, 1, 0]

Code: my_list = [0, 1, 2, 3, 4] print(my_list[::-1])

5. What will be the output of below Python code?

  • [1, 66, "python"]
  • ['python', [11, 55, 'cat']]
  • [[11, 55, "cat"], [ ]]
  • [1, 66, 'python', [11, 55, 'cat']]

Correct answer:

  • [1, 66, 'python', [11, 55, 'cat']]

Code: list1 = [1, 66, "python", [11, 55, "cat"], [ ], 2.22, True] print(list1[0:4])

6. What will be the output of below Python code?

  • [0, 2, 4, 3]
  • [0, 2, 4]
  • [0, 3, 4]
  • [0, 1, 2, 3]

Correct answer:

  • [0, 2, 4]

Code: my_list = [0, 1, 2, 3, 4] print(my_list[::2])

7. What will be the output of below Python code?

  • [0, 2]
  • [0, 2, 4]
  • [0, 3]
  • [0, 1, 2, 3]

Correct answer:

  • [0, 3]

Code: my_list = [0, 1, 2, 3, 4] print(my_list[::3])

8. What will be the output of below Python code?

  • Error!
  • ['python', [11, 55, 'cat']]
  • [[11, 55, "cat"], [ ]]
  • [1, 66, 'python', [11, 55, 'cat']]

Correct answer:

  • Error!

Code: list1 = [1, 66, "python", [11, 55, "cat"], [ ], 2.22, True] print(list1.upper())

Explaination: ‘list' object has no attribute 'upper'

9. What will be the output of below Python code?

  • [2, 3, 4, 'python']
  • [2, 3, 4]
  • [1, 2, 3, 4, 'python']
  • [0, 1, 2, 3, 4, 'python']

Correct answer:

  • [2, 3, 4, 'python']

Code: my_list = [0, 1, 2, 3, 4] my_list.append("python") print(my_list[2:])

10. What will be the output of below Python code?

  • [2, 3, 4, 'python']
  • [2, 3, 4]
  • [1, 2, 3, 4, 'python']
  • [0, 1, 2, 3, 4, 'python']

Correct answer:

  • [1, 2, 3, 4, 'python']

Code: my_list = [0, 1, 2, 3, 4] my_list.append("python") b = my_list[1:] print(b)


Python PCEP Finding in Lists

1. What is the output of the following code:

  • False
  • True
  • None

Correct answer:

  • True

Code: (4, 6) not in [(4, 7), (5, 6), "hello"]

2. Choose the correct answer if the following list contains the element 'A'. Check if you get "True" in the output.

  • 'A' in Li
  • A in Li
  • ‘A’ not in Li

Correct answer:

  • 'A' in Li

Code: Li = ['A','C','b', 1, 3, 4]

3. What will be the output of below Python code?

  • 4
  • 3
  • 2
  • 1

Correct answer:

  • 2

Code: my_list = [0, 1, 2, 3, 4] print(my_list.index(2))

4. What will be the output of the following Python code?

  • [0, [8, 9], 4, 1, 2]
  • [0, 4, 1, 2]
  • [0, 3, 8, 9]
  • [[8, 9], 3, 4, 1, 2]

Correct answer:

  • [0, 3, 8, 9]

Code: list1 = [0, 3, 4, 1, 2] list1[2:5]=[8,9] print(list1)

5. What will be the output of below Python code?

  • ["USA", "India", "Canada"]
  • ["USA", "Canada", "India"]
  • ['Canada', 'USA', 'India']
  • ['Canada', 'India', 'USA']

Correct answer:

  • ['Canada', 'USA', 'India']

Code: countries = ["USA", "Canada", "India"] countries[0], countries[1] = countries[1], countries[0] print(countries)

6. What will be the output of the following Python code?

  • [0, [8, 9], 4, 1, 2]
  • [0, 4, 1, 2]
  • [4, 1, 2]
  • [[8, 9], 3, 4, 1, 2]

Correct answer:

  • [0, [8, 9], 4, 1, 2]

Code: list1 = [0, 3, 4, 1, 2] list1[1]=[8,9] print(list1)

7. What will be the output of the following Python code?

  • [0, 3, [1, 2], 1, 2]
  • [0, 4, 1, 2]
  • [3, 4, 1, 2]
  • [0, 3, 1, 2, 2]

Correct answer:

  • [0, 3, 1, 2, 2]

Code: list1 = [0, 3, 4, 1, 2] list1[2:4]=[1,2] print(list1)

8. What will be the output of below Python code?

  • 4
  • 3
  • 2
  • 1

Correct answer:

  • 3

Code: my_list = [0, 3, 4, 1, 2] print(my_list.index(1))

9. What will be the output of the following Python code?

  • [9, 4, 6, 1, 2]
  • [3, 4, 6, 1, 2]
  • [3, 4, 1, 2]
  • [3, 9, 6, 1, 2]

Correct answer:

  • [9, 4, 6, 1, 2]

Code: list1=[3,4,6,1,2] list2=list1 list1[0]=9 print(list2)

10. What will be the output of the following Python code?

  • [9, 4, 6, 1, 2]
  • [3, 4, 6, 1, 2]
  • [3, 4, 1, 2]
  • [3, 9, 6, 1, 2]

Correct answer:

  • [3, 9, 6, 1, 2]

Code: list1=[3,4,6,1,2] list2=list1 list1[1]=9 print(list2)


Python PCEP Nested Lists - 2D

1. What will be the output of the following Python code?

  • 4
  • 2
  • 0
  • 1

Correct answer:

  • 0

Code: matrix = [[0, 1, 2], [0, 1, 2], [0, 1, 2]]

matrix2 = []

for submatrix in matrix: for val in submatrix: matrix2.append(val)

print(matrix2[0])

2. What will be the output of the following Python code?

  • 4
  • 2
  • 0
  • 1

Correct answer:

  • 2

Code: matrix = [[0, 1, 2], [0, 1, 2], [0, 1, 2]]

matrix2 = []

for submatrix in matrix: for val in submatrix: matrix2.append(val)

print(matrix2[2])

3. What will be the output of the following Python code?

  • 4
  • 2
  • 0
  • 1

Correct answer:

  • 2

Code: matrix = [[j for j in range(3)] for i in range(3)] print(matrix[1][2])

4. What will be the output of the following Python code?

  • ['Egypt', 'USA', 'India', 'Dubai', 'Spain']
  • ['Egypt', 'America', 'India', 'Dubai', 'London']
  • ['Egypt', 'USA', 'France', 'Dubai', 'Spain']
  • ['France', 'USA', 'India', 'England', 'Spain']

Correct answer:

  • ['Egypt', 'USA', 'India', 'Dubai', 'Spain']

Code: countries = [['Egypt', 'USA', 'India'], ['Dubai', 'America', 'Spain'], ['London', 'England', 'France']] countries2 = [country for sublist in countries for country in sublist if len(country) < 6] print(countries2)

5. What will be the output of the following Python code?

  • 4
  • 2
  • 0
  • 1

Correct answer:

  • 1

Code: matrix = [[j for j in range(4)] for i in range(4)] print(matrix[3][1])

6. What will be the output of the following Python code?

  • ['India']
  • ['Egypt']
  • ['Dubai']
  • ['USA']

Correct answer:

  • ['USA']

Code: countries = [['Egypt', 'USA', 'India'], ['Dubai', 'America', 'Spain'], ['London', 'England', 'France']] countries2 = [country for sublist in countries for country in sublist if len(country) < 4] print(countries2)

7. What will be the output of the following Python code?

  • 1
  • 0
  • 2
  • 3

Correct answer:

  • 3

Code: a = [] for i in range(5): a.append([]) for j in range(5): a[i].append(j)

print(a[2][3])

8. What will be the output of the following Python code?

  • 4
  • 2
  • 0
  • 1

Correct answer:

  • 1

Code: matrix = [[j for j in range(3)] for i in range(3)] print(matrix[2][1])

9. What will be the output of the following Python code?

  • 1
  • 0
  • 2
  • 3

Correct answer:

  • 3

Code: a = [] for i in range(5): a.append([]) for j in range(5): a[i].append(j)

print(a[3][3])

10. What will be the output of the following Python code?

  • [[0, 1], [0, 1]]
  • [[0, 2], [0, 2]]
  • [[1, 2], [1, 2]]
  • [[1, 1], [1, 1]]

Correct answer:

  • [[0, 1], [0, 1]]

Code: a = [] for i in range(2): a.append([]) for j in range(2): a[i].append(j)

print(a)

11. Choose the correct answer to define a list “Num” which contains numbers from 1-9 with 3 elements only in the row.

  • Num =[ [1,2,3] , [4,5,6,7] , [8,9] ]
  • Num =[ [1,2,3] , [4,5,6,] , [7,8,9] ]
  • Num =[ [1,2,3,4] , [4,5,6,7] , [8,9,6] ]
  • Num =[ [1,2,3,4] , [4,5,6] , [7,8,9] ]

Correct answer:

  • Num =[ [1,2,3] , [4,5,6,] , [7,8,9] ]

Python PCEP Nested Lists - 3D

1. Choose the correct answer to get the “Red” color from the following list:

  • print( Colors[0][2] )
  • print( Colors[2][0][2] )
  • print( Colors[2][1][2] )
  • print( Colors[2][0][1] )

Correct answer:

  • print( Colors[2][0][2] )

Code: Colors= [ [['Blue','Green','White','Black']], [['Green','Blue','White','Yellow']] , [['White','Blue','Red','Green']] ]

2. What will be the output of the following Python code?

  • 2
  • [0, 1, 2]
  • 0
  • 1

Correct answer:

  • [0, 1, 2]

Code: matrix = [[[0, 1, 2], [0, 1, 2], [0, 1, 2]], [[0, 1, 2], [0, 1, 2], [0, 1, 2]], [[0, 1, 2], [0, 1, 2], [0, 1, 2]]]

matrix2 = []

for submatrix in matrix: for val in submatrix: matrix2.append(val)

print(matrix2[2])

3. What will be the output of the following Python code?

  • [0, 1, 2]
  • 2
  • 0
  • 1

Correct answer:

  • 1

Code: matrix = [[[k for k in range(3)] for j in range(3)] for i in range(3)] print(matrix[1][1][1])

4. What will be the output of the following Python code?

  • [0, 1, 2]
  • 2
  • 0
  • 1

Correct answer:

  • 1

Code: matrix = [[[k for k in range(3)] for j in range(3)] for i in range(3)] print(matrix[0][0][1])

5. What will be the output of the following Python code?

  • [0, 1, 2]
  • 2
  • 0
  • 1

Correct answer:

  • [0, 1, 2]

Code: matrix = [[[k for k in range(3)] for j in range(3)] for i in range(3)] print(matrix[1][2])

6. What will be the output of the following Python code?

  • 4
  • 2
  • 0
  • 1

Correct answer:

  • 0

Code: matrix = [[[0, 1, 2], [0, 1, 2], [0, 1, 2]], [[0, 1, 2], [0, 1, 2], [0, 1, 2]], [[0, 1, 2], [0, 1, 2], [0, 1, 2]]]

matrix2 = []

for submatrix in matrix: for val in submatrix: matrix2.append(val)

print(matrix2[2][0])

7. Choose the correct code to get the third element in the second row, Regarding the following list :

  • print(Colors[2][3])
  • print(Colors[1][3])
  • print(Colors[1][2])
  • print(Colors[2][2])

Correct answer:

  • print(Colors[1][2])

Code: Colors = [ ['Red', 'Green', 'White', 'Black'], ['Green', 'Blue', 'White', 'Yellow'] ,['White', 'Blue', 'Green', 'Red'] ]

8. What will be the output of the following Python code?

  • 1
  • 2
  • 0
  • [0, 1, 2]

Correct answer:

  • [0, 1, 2]

Code: matrix = [[[k for k in range(3)] for j in range(3)] for i in range(3)] print(matrix[2][1])

9. What will be the output of the following Python code?

  • 4
  • 2
  • 0
  • 1

Correct answer:

  • 2

Code: matrix = [[[0, 1, 2], [0, 1, 2], [0, 1, 2]], [[0, 1, 2], [0, 1, 2], [0, 1, 2]], [[0, 1, 2], [0, 1, 2], [0, 1, 2]]]

matrix2 = []

for submatrix in matrix: for val in submatrix: matrix2.append(val)

print(matrix2[2][2])

10. What will be the output of the following Python code?

  • 4
  • 2
  • 0
  • 1

Correct answer:

  • 0

Code: matrix = [[[0, 1, 2], [0, 1, 2], [0, 1, 2]], [[0, 1, 2], [0, 1, 2], [0, 1, 2]], [[0, 1, 2], [0, 1, 2], [0, 1, 2]]] print(matrix[0][0][0])


Python PCEP Functions

1. Method is called by its name, but it is associated with an object.

  • True
  • False

Correct answer:

  • True

2. What is the output of the following snippet:

  • The tallest student is Jackson
  • The tallest student is Ella
  • Error
  • Jackson

Correct answer:

  • The tallest student is Jackson

Code: def my_function(*students): print("The tallest student is " + students[2])

my_function("James", "Ella", "Jackson")

Explaination: If the number of arguments is unknown, we can add a * before the parameter name.

3. Choose the correct answer which defines a function to get numeric input from the user:

  • def input_num(): return input(num)
  • def input_num(): return input()
  • def input_num(): int(input())
  • def input_num(): return int(input())

Correct answer:

  • def input_num(): return int(input())

4. The output of the following snippet of the code will be:

  • 0
  • 1
  • 2
  • 3

Correct answer:

  • 1

Code: a = 0 def add_one(a): return a+1

result = add_one(a) print(result)

5. Regarding the definition of the function and the sample input, Choose the correct value of the output.

  • 50
  • None
  • Error
  • 15

Correct answer:

  • Error

Code: Function : def multi_func(num1,num2): return num1 *num2 Sample input: print ( multi_func(5 , num1= 10) )

Explaination: The correct input should be print ( multi_func(5 , 10) ) Or print ( multi_func(num1=5 , num2=10) )

6. What is the error in the following snippet code:

  • The multi_func() function doesn’t have any parameters
  • The result is not defined as a global variable
  • The function return None
  • print() is not a built-in function

Correct answer:

  • The result is not defined as a global variable

Code: def multi_func(): result = int(input()) * 5 return result

print(result)

7. The function can have only one parameter. If any data (parameters) are passed, they are passed explicitly.

  • True
  • False

Correct answer:

  • False

Explaination: The function can have different parameters or may not have any at all. If any data (parameters) are passed, they are passed explicitly.

8. Define a function that gets the user input and multiply it by a number we passed to the function.

  • def multi_num(num): return int(input () ) * num
  • def multi_num(): return int(input (num) ) * 6
  • def multi_num(6): return int(input () ) * num
  • def multi_num(): return int(input () ) * num

Correct answer:

  • def multi_num(num): return int(input () ) * num

Code: Sample input: 6 Sample output:

print( multi_num(5) ) 30

9. What will be the result of calling the print_info function with the arguments 'john' and 19?

  • john 19
  • john 18
  • name 19
  • name age

Correct answer:

  • john 19

Code: def print_info(name, age=18): print(name, age)

print_info('john', 19)


Python PCEP Arguments

1. Define a function that gets the user input and add to it a number we passed to the function.

  • def add_num(num): return int(input () ) + num
  • def add_num(): return int(input (num) ) + 6
  • def add_num(6): return int(input () ) + num
  • def add_num(): return int(input () ) + num

Correct answer:

  • def add_num(num): return int(input () ) + num

Code: Sample input: 6 Sample output: print( add_num(5) ) 11

2. The output of the following snippet of the code will be:

  • [5,4,1]
  • [7,4,1]
  • [7,4,5]
  • [7,5,4]

Correct answer:

  • [7,4,5]

Code: nums= [7,4,1] def change_third_item(list): list[2] = 5

change_third_item(nums) print(nums)

3. Regarding the definition of the function and the sample input, Choose the correct value of the output.

  • 15
  • None
  • Error
  • 10

Correct answer:

  • 10

Code: Function : def add_func(num1,num2): return num1 + num2

Sample input: print ( add_func(5 , 5) )

4. Regarding the definition of the function and the sample input, Choose the correct value of the output.

  • 15
  • None
  • Error
  • 50

Correct answer:

  • Error

Code: Function : def add_func(num1,num2): return num1 + num2

Sample input: print ( add_func(5 , num1= 10) )

5. The output of the following snippet of the code will be:

  • 0
  • 1
  • 6
  • 3

Correct answer:

  • 6

Code: a = 0 def add_three(a): return a+3

result = add_three(3) print(result)

6. The output of the following snippet of the code will be:

  • john 19
  • john 18
  • name 19
  • name age

Correct answer:

  • john 18

Code: def print_name_age(name, age=19): print(name, age)

print_name_age('john', 18)

7. What is the output of the following snippet:

  • The tallest student is john
  • The tallest student is Ella
  • Error
  • mark

Correct answer:

  • The tallest student is john

Code: def my_function(*friends): print("The tallest student is " + friends[0])

my_function("john", "Ella", "mark")

8. The output of the following snippet of the code will be:

  • 0
  • 1
  • 2
  • 3

Correct answer:

  • 3

Code: a = 0 def add_three(a): return a+3

result = add_three(a) print(result)

9. What will be the result of calling the fullname_func function with the argument 'John'?

  • John
  • john Mark
  • John Mark
  • Mark

Correct answer:

  • John Mark

Code: def fullname_func(fname): print(fname + " Mark")

fullname_func("John")

10. What will be the result of calling the fullname_func function with the arguments 'John' and 'Mark'?

  • John
  • john Mark
  • John Mark
  • Mark

Correct answer:

  • John Mark

Code: def fullname_func(fname, lname): print(fname + " " + lname)

fullname_func("John", "Mark")


Python PCEP Return Statement

1. The output of the following snippet of the code will be:

  • 9
  • 5
  • 8
  • 6

Correct answer:

  • 6

Code: def my_function(x): return 10 - x

print(my_function(4))

2. The output of the following snippet of the code will be:

  • Hello, World
  • None
  • Error
  • return_greeting

Correct answer:

  • Hello, World

Code: def return_greeting(): return "Hello, World"

print(return_greeting())

3. The output of the following snippet of the code will be:

  • 9
  • 5
  • 8
  • 3

Correct answer:

  • 8

Code: def my_function(x): return 5 + x

print(my_function(3))

4. What will the following function return?

  • None
  • The value of x + y
  • The value of x
  • The value of y

Correct answer:

  • The value of x + y

Code: def add(x, y): return x+y

5. The output of the following snippet of the code will be:

  • The result is False
  • The result is True
  • The result is bool
  • The result is 0

Correct answer:

  • The result is True

Code: def is_true(a): return bool(a)

result = is_true(3<6) print("The result is", result)

6. The output of the following snippet of the code will be:

  • The result of 4 is 16
  • The result of 2 is 4
  • The result of num is result
  • The result of 4 is 2

Correct answer:

  • The result of 2 is 4

Code: def square(i): j = i * i return j

num = 2 result = square(num) print("The result of ", num, " is ", result)

7. The output of the following snippet of the code will be:

  • 5
  • 5.0
  • 8
  • 6.0

Correct answer:

  • 5.0

Code: def my_function(x): return 10 / x

print(my_function(2))

8. The output of the following snippet of the code will be:

  • 9
  • 4
  • 12
  • 8

Correct answer:

  • 9

Code: def square(i): j = i * i return j

print(square(3))

9. The output of the following snippet of the code will be:

  • The result is False
  • The result is True
  • The result is bool
  • The result is 0

Correct answer:

  • The result is False

Code: def is_true(a): return bool(a)

result = is_true(6<3) print("The result is", result)


Python PCEP List as Argument

1. What is the output of the following snippet:

  • 6.5
  • 6.25
  • 2.5
  • 5.5

Correct answer:

  • 6.5

Code: def mean_func(list1): return sum(list1) / len(list1)

print(mean_func([5, 6, 7, 8]))

2. What is the output of the following snippet:

  • 1 3 4
  • 2 3 4
  • 1 2 3
  • 2 1 4

Correct answer:

  • 2 3 4

Code: def my_function(numbers): for i in numbers: print(i+1, end=' ')

numbers = [1, 2, 3] my_function(numbers)

3. What is the output of the following snippet:

  • john emmy mark
  • john mark emmy
  • john mark
  • emmy mark

Correct answer:

  • john mark emmy

Code: def my_function(names): for i in names: print(i, end=' ')

names = ["john", "mark", "emmy"] my_function(names)

4. What is the output of the following snippet:

  • 3.5
  • 3.25
  • 2.5
  • 3

Correct answer:

  • 3.25

Code: def mean_func(list1): return sum(list1) / len(list1)

print(mean_func([5, 2, 2, 4]))

5. What is the output of the following snippet:

  • [1, 2, 3, 4, 5, 6]
  • [1, 2, 3]
  • [1, 3, 5]
  • [4, 5, 6]

Correct answer:

  • [1, 3, 5]

Code: def get_odd_func(numbers): odd_numbers = [num for num in numbers if num % 2] return odd_numbers

print(get_odd_func([1, 2, 3, 4, 5, 6]))

6. What is the output of the following snippet:

  • [7, 5, 9]
  • [7, 4, 5]
  • [4, 6, 8, 12]
  • [5, 6, 8, 12]

Correct answer:

  • [7, 5, 9]

Code: def get_odd_func(numbers): odd_numbers = [num for num in numbers if num % 2] return odd_numbers

print(get_odd_func([7, 4, 5, 6, 9, 8, 12]))

7. What is the output of the following snippet:

  • 1 2 3
  • 2 3 4
  • 12 14 16
  • 1 12 14

Correct answer:

  • 12 14 16

Code: def my_function(numbers): for i in numbers: print(i*2+10, end=' ')

numbers = [1, 2, 3] my_function(numbers)

8. What is the output of the following snippet:

  • [2, 4, 6]
  • [1, 2, 3]
  • [1, 3, 5]
  • [4, 5, 6]

Correct answer:

  • [2, 4, 6]

Code: def get_even_func(numbers): even_numbers = [num for num in numbers if not num % 2] return even_numbers

get_even_func([1, 2, 3, 4, 5, 6])

9. What is the output of the following snippet:

  • [1, 2,3]
  • [1,2,3[1,2,3]]
  • [1, 2, 3][1,2,3]
  • [1, 2, 3, 1, 2, 3]

Correct answer:

  • [1, 2, 3, 1, 2, 3]

Code: def double_list(numbers): return 2 * numbers

numbers = [1, 2, 3] print(double_list(numbers))


Python PCEP Scopes

1. What is the output of the following snippet:

  • 20
  • Error
  • 0
  • False

Correct answer:

  • Error

Code: def myfunc(): a = 20

myfunc() print(a)

Explaination: Hint: A variable created inside a function belongs to the local scope of that function, and can only be used inside that function.

2. What is the output of the following snippet:

  • 20 20
  • Error
  • 30 20
  • False

Correct answer:

  • 30 20

Code: x = 20 def my_function(): x = 30 print(x, end=' ')

my_function() print(x, end=' ')

3. What is the output of the following snippet:

  • Error
  • 20
  • False
  • 20 20

Correct answer:

  • 20 20

Code: x = 20 def my_function(): print(x, end=' ')

my_function() print(x, end=' ')

Explaination: Hint: A variable created outside of a function is global and can be used by anyone.

4. What is the output of the following snippet:

  • 0
  • Error
  • 20
  • False

Correct answer:

  • 20

Code: def my_function(): def my_inner_function(): x = 20 print(x) my_inner_function()

my_function()

5. What is the output of the following snippet:

  • 20
  • Error
  • 0
  • False

Correct answer:

  • 20

Code: def my_function(): x = 20 def my_inner_function(): print(x) my_inner_function() my_function()

Explaination: Hint: The local variable can be accessed from a function within the function.

6. What is the output of the following snippet:

  • 20
  • Error
  • 0
  • False

Correct answer:

  • 20

Code: def myfunc(): a = 20 print(a)

myfunc()

7. What is the output of the following snippet:

  • 0
  • Error
  • 20
  • False

Correct answer:

  • Error

Code: def my_function(): def my_inner_function(): x = 20 print(x) my_inner_function()

my_function()

8. What is the output of the following snippet:

  • 20 20
  • Error
  • 30 20
  • False

Correct answer:

  • 30 20

Code: x = 20 def my_function(): x = 30 print(x, end=' ')

my_function() print(x, end=' ')

9. What is the output of the following snippet:

  • 20
  • Error
  • 30
  • False

Correct answer:

  • 30

Code: def my_function(): global x x = 30

my_function() print(x)

10. What is the output of the following snippet:

  • 20
  • Error
  • 30
  • False

Correct answer:

  • 20

Code: x = 30 def my_function(): global x x = 20

my_function() print(x)


Python PCEP Arguments Explained

1. What is the output of the following snippet:

  • ('Hello', 'World!')
  • Hello, World!
  • Hello
  • Error

Correct answer:

  • Hello

Code: def my_function(*argv): print(argv[0])

my_function('Hello', 'World!')

2. What is the output of the following snippet:

  • Error
  • Welcome to Python!
  • First argument: Welcome to Python!
  • First argument: Welcome
    Next argument: to
    Next argument: Python!

Correct answer:

  • First argument: Welcome
    Next argument: to
    Next argument: Python!

Code: def my_function(arg1, *argv): print ("First argument:", arg1) for arg in argv: print("Next argument:", arg)

my_function('Welcome', 'to', 'Python!')

3. What is the output of the following snippet:

  • Hello World!
  • Hello
  • World!
  • Hello
    World!

Correct answer:

  • Hello
    World!

Code: def my_function(*argv):
for arg in argv:
print(arg)

my_function('Hello', 'World!')

Explaination: Hint: The syntax is to use the symbol * to take in a variable number of arguments

4. What is the output of the following snippet:

  • 5
  • 2
  • Error
  • 3

Correct answer:

  • 5

Code: def sum(a,b): return a+b

print(sum(2,3))

5. What is the output of the following snippet:

  • The older friend is 13 years
  • The older friend is 11 years
  • Error
  • The older friend is 12 years

Correct answer:

  • The older friend is 13 years

Code: def my_function(*ages): print("The older friend is " + ages[0] + " years")

my_function("13", "12", "11")

6. What is the output of the following snippet:

  • ('Hello', 'World!')
  • Hello, World!
  • ['Hello', 'World!']
  • Error

Correct answer:

  • ('Hello', 'World!')

Code: def my_function(*argv): print(argv)

my_function('Hello', 'World!')

7. What is the output of the following snippet:

  • 6
  • 2
  • Error
  • 3

Correct answer:

  • Error

Code: def sum(*args): for arg in args: result += arg return result

print(sum(2,3,1))

Explaination: Hint: UnboundLocalError: local variable 'result' referenced before assignment

8. What is the output of the following snippet:

  • 5.0
  • 4.0
  • Error
  • 2

Correct answer:

  • 4.0

Code: def division(a,b): return a/b

division(8,2)


Python PCEP Tuples

1. Write a Python program to create an empty tuple:

  • x = tuple(3)
  • x = ()
  • x = (2,3)
  • x = (0)

Correct answer:

  • x = ()

2. …. is one of the data types in Python that used to store collections of data.

  • List
  • Set
  • Dictionary
  • Tuple

Correct answer:

  • List
  • Set
  • Dictionary
  • Tuple

3. What is the output of the following command if the tuple1 has values (1,2,3,4,5) :

  • (1,2,3,4,6)
  • (6,)
  • (1,2,3,4,5,6)
  • AttributeError

Correct answer:

  • AttributeError

Code: print(tuple1.append(6))

4. Write a Python program to create a tuple with different data types:

  • x = ("john", True, 2.2, 2)
  • x = ("tuple", "john", "list")
  • x = (2.1, 3.2, 1.3)
  • x = (1, 2, 3)

Correct answer:

  • x = ("john", True, 2.2, 2)

Code: print(x)

5. Which of the following is used to create a tuple called tuple1 which contains numbers from 1 to 5?

  • tuple1 = (1,2,3,4,5)
  • tuple1 = 1,2,3,4,5
  • tuple1 = [1,2,3,4,5]
  • tuple1 = 1 2 3 4 5

Correct answer:

  • tuple1 = (1,2,3,4,5)
  • tuple1 = 1,2,3,4,5

6. A …. is a collection of items that are ordered, unchangeable, and allow duplicate values.

  • List
  • Set
  • Dictionary
  • Tuple

Correct answer:

  • Tuple

7. What is the output of the following command if the tuple1 has values (0,1,2,3,4,5) :

  • (0, 1, 2, 3)
  • (1,2,3,4)
  • (0,1,2,3,4,5)
  • (0,1,2,3,4)

Correct answer:

  • (0, 1, 2, 3)

Code: print(tuple1[0:4])

8. What is the output of the following snippet:

  • Error
  • (3)
  • 3
  • tuple(3)

Correct answer:

  • Error

Code: x = tuple(3) print(x)

9. What is the output of the following snippet:

  • (50, 40, 30, 20, 10)
  • (40, 20)
  • (10, 30, 50)
  • (10, 20, 30, 40, 50)

Correct answer:

  • (50, 40, 30, 20, 10)

Code: a = (10, 20, 30, 40, 50) a = a[::-1] print(a)

10. Access value 30 from the following tuple:

  • a[30]
  • a[0][0]
  • a[1][1]
  • a[1][0]

Correct answer:

  • a[1][1]

Code: a = (10, [20, 30], 40, 50)

11. Access value 30 from the following tuple:

  • a[30]
  • a[0]
  • a[1]
  • a[2]

Correct answer:

  • a[2]

Code: a = (10, 20, 30, 40, 50)


Python PCEP Dictionaries

1. A …. is a collection that is ordered, changeable, and does not allow duplicates.

  • List
  • Set
  • Dictionary
  • Tuple

Correct answer:

  • Dictionary

2. Dictionaries are used to store data values in key-value pairs.

  • True
  • False

Correct answer:

  • True

3. …. is one of the dictionary built-in methods.

  • dictionary.update()
  • dictionary.values()
  • dictionary.items()
  • dictionary.keys()

Correct answer:

  • dictionary.update()
  • dictionary.values()
  • dictionary.items()
  • dictionary.keys()

4. What is the output of the following snippet code:

  • {'brand': 'apple', 'ram': '3', 'year': 2020}
  • {'brand': 'apple', 'ram': '3', 'year': 2021}
  • {'brand': 'apple', 'ram': '3', 'year': 2020, 'year': 2021}
  • {'brand': 'apple', 'ram': '3'}

Correct answer:

  • {'brand': 'apple', 'ram': '3', 'year': 2021}

Code: testdict = { "brand": "apple", "ram": "3", "year": 2020, "year": 2021 }

print(testdict)

5. What is the output of the following snippet code:

  • {'brand': 'Samsung', 'ram': '3', 'Os': 'Android', 'year': 2020}
  • {'brand': 'Samsung', 'brand': 'oppo','ram': '3', 'Os': 'Android', 'year': 2020}
  • {'brand': 'oppo', 'ram': '3', 'Os': 'Android', 'year': 2020}
  • { 'ram': '3', 'Os': 'Android', 'year': 2020, 'brand': 'oppo' }

Correct answer:

  • {'brand': 'oppo', 'ram': '3', 'Os': 'Android', 'year': 2020}

Code: testdict = { "brand": "Samsung", "ram": "3", "Os": "Android", "year": 2020 }

testdict.update({'brand':'oppo' }) print(testdict)

6. Which of the following method is used to delete a brand's key and its value from the following dictionary:

  • del.testdict[0]
  • del testdict['brand':'oppo']
  • del.testdict['brand']
  • del testdict['brand']

Correct answer:

  • del testdict['brand']

Code: testdict = {'brand': 'oppo', 'ram': '3', 'Os': 'Android', 'year': 2020}

7. What is the output of the following snippet code:

  • dict_items([('brand', 'Samsung'), ('ram', '3'), ('Os', 'Android'), ('year', 2020)])
  • dict_keys(['brand', 'ram', 'Os', 'year'])
  • dict_keys(['Samsung', '3', 'Android', 2020])
  • (['brand', 'ram', 'Os', 'year'])

Correct answer:

  • dict_keys(['brand', 'ram', 'Os', 'year'])

Code: testdict = { "brand": "Samsung", "ram": "3", "Os": "Android", "year": 2020 }

print(testdict.keys())

8. What is the output of the following snippet code:

  • dict_items([('brand', 'Samsung'), ('ram', '3'), ('Os', 'Android'), ('year', 2020)])
  • dict_items([('brand': 'Samsung'), ('ram': '3'), ('Os': 'Android'), ('year': 2020)])
  • dict_keys(['brand', 'ram', 'Os', 'year'])
  • dict_values([('brand', 'Samsung'), ('ram', '3'), ('Os', 'Android'), ('year', 2020)])

Correct answer:

  • dict_items([('brand', 'Samsung'), ('ram', '3'), ('Os', 'Android'), ('year', 2020)])

Code: testdict = { "brand": "Samsung", "ram": "3", "Os": "Android", "year": 2020 }

print(testdict.items())

9. …. is one of the dictionary built-in methods that used to delete all items from the dictionary.

  • dictionary.prune()
  • dictionary.clear()
  • dictionary.delete()
  • dictionary.remove()

Correct answer:

  • dictionary.clear()

10. …. is one of the dictionary built-in methods that used to delete the last item from the dictionary.

  • dictionary.delitem()
  • dictionary.clear()
  • dictionary.pop()
  • dictionary.popitem()

Correct answer:

  • dictionary.popitem()

11. A dictionary is a collection that is ..., ... and ...

  • Ordered, changeable, does not allow duplicates
  • Unordered, changeable, does not allow duplicates
  • Ordered, immutable, does allow duplicates
  • Ordered, immutable, does not allow duplicates

Correct answer:

  • Ordered, changeable, does not allow duplicates

Python PCEP Python Internals

1. Python is ........

  • interpreted language
  • compiled language

Correct answer:

  • interpreted language

2. Which of the following translates and executes program code line by line rather than the whole program in one step?

  • Interpreter
  • Translator
  • Assembler
  • Compiler

Correct answer:

  • Interpreter

3. In Cython, the Code written in Python is converted to .........

  • Java language
  • C language
  • Ruby language
  • PHP language

Correct answer:

  • C language

4. What do you call a program that can directly execute instructions from a programming language ?

  • Translator
  • Assembler
  • Compiler
  • Interpreter

Correct answer:

  • Interpreter

Explaination: Hint: Interpreter is a program that can execute high-level language programs “directly,” without first being translated into machine language.

5. Which of the following isn’t a characteristic of High level languages?

  • platform independent
  • machine code
  • interactive execution
  • user-friendly

Correct answer:

  • machine code

6. Jython is designed to run on which platform?

  • Java
  • C
  • Ruby
  • PHP

Correct answer:

  • Java

7. cython can run on .......

  • Windows
  • MacOS
  • Linux
  • All the above

Correct answer:

  • All the above

Python PCEP Mock Exam 1

1. In Python, a variable must be declared before it is assigned a value:

  • False
  • True

Correct answer:

  • False

Explaination: Hint: Variables need not be declared or defined in advance in Python. To create a variable, you just assign it a value.

2. …. is one of the literal types in Python.

  • None of the above
  • Boolean
  • String
  • Numeric

Correct answer:

  • Boolean
  • String
  • Numeric

3. The …. function prints the specified message to the screen, or another standard output device.

  • print()
  • return()
  • vars()
  • input()

Correct answer:

  • print()

4. …. is a string method used to convert string into a lower case.

  • casefold()
  • islower()
  • lower()
  • tolower()

Correct answer:

  • casefold()
  • lower()

5. Which method should you use in order to convert the input into a string correctly:

  • str
  • int
  • float
  • bin

Correct answer:

  • str

Code: year_of_birth = int(input("In what year were you born? "))

print("You were born in " + ...(year_of_birth))

6. Which of the following statements assigns the value 50 to the variable x in Python:

  • x == 50
  • x : 50
  • x = 50
  • x >> 50

Correct answer:

  • x = 50

7. What is the output of the following python code?

  • Sally#employee name+#123
  • Sally#employee name#123
  • Sally+#123
  • Sally#123

Correct answer:

  • Sally#123

Code: name = "Sally"# employee name

data = "#123" print (name+data)

8. Fill out the missing operators:

  • / and *
  • // and *
  • % and /
  • * and /

Correct answer:

  • / and *

Code: 20 ... 5 ... 4 = 16.0

9. Given the nested if-else below, what will be the value x when the code executed successfully.

  • 0
  • 2
  • 3
  • 4

Correct answer:

  • 4

Code: x = 0 a = 6 b = 6 if a > 0: if b < 0: x = x + 6 elif a > 6: x = x + 5 else: x = x + 4 else: x = x + 3

print(x)

10. What will be the output of the following Python code?

  • error
  • 5
    6
    7
    8
  • 5
    6
  • 5
    6
    7
    8
    9
    10

Correct answer:

  • 5
    6
    7
    8

Code: i = 5 while True: if i%0o11 == 0: break print(i) i += 1

11. What will be the output of below Python code?

  • 5
  • 1
  • 2
  • 4

Correct answer:

  • 5

Code: list1 = [1, 2, 3, 4, 5] for i in list1: if i==5: print(i)

12. What is the output of the following nested loop:

  • SyntaxError: invalid syntax
  • 5
    6
    7
    8
  • 7
    8
  • 8
    7
    6
    5

Correct answer:

  • 5
    6
    7
    8

Code: for num in range(5, 9): for i in range(2, num): if num%i == 1: print(num) break

13. What does the following code produce as output?

  • 12
  • 6
  • 3
  • 1

Correct answer:

  • 6

Code: i = 1 x = 3 sum = 0 while ( i <= x ): sum += i i += 1 print(sum)

14. What would get printed:

  • False
    True
  • True
    True
  • True
    False
  • False
    False

Correct answer:

  • False
    True

Code: min_score = 13 score = 13

print(score > min_score) print(score <= min_score)

15. What will be the output of the below Python code?

  • ['UK', 8, 'India', 'Canada']
  • ['UK', 'India', 'Canada', 8]
  • ['UK', 1, 'India', 'Canada']
  • ['UK',1, 8, 'India', 'Canada']

Correct answer:

  • ['UK', 8, 'India', 'Canada']

Code: list1=['UK','India','Canada']

list1.insert(1,8)

print(list1)

16. for i in [9, 1, 5, 6]:, how many times a loop runs ?

  • 1
  • 2
  • 3
  • 4

Correct answer:

  • 4

17. What will be the output of below Python code?

  • [2, 3, 4, 'python']
  • [2, 3, 4]
  • [1, 2, 3, 4, 'python']
  • [0, 1, 2, 3, 4, 'python']

Correct answer:

  • [2, 3, 4, 'python']

Code: my_list = [0, 1, 2, 3, 4] my_list.append("python") print(my_list[2:])

18. What will be the output of below Python code?

  • 10
  • 11
  • 12
  • 14

Correct answer:

  • 10

Code: list1 = [10, 11, 12, 13, 14] print(list1[0])

19. What will be the output of below Python code?

  • ["USA", "India", "Canada"]
  • ["USA", "Canada", "India"]
  • ['Canada', 'USA', 'India']
  • ['Canada', 'India', 'USA']

Correct answer:

  • ['Canada', 'USA', 'India']

Code: countries = ["USA", "Canada", "India"] countries[0], countries[1] = countries[1], countries[0] print(countries)

20. What will be the output of the following Python code?

  • 4
  • 2
  • 0
  • 1

Correct answer:

  • 2

Code: matrix = [[[0, 1, 2], [0, 1, 2], [0, 1, 2]], [[0, 1, 2], [0, 1, 2], [0, 1, 2]], [[0, 1, 2], [0, 1, 2], [0, 1, 2]]]

matrix2 = []

for submatrix in matrix: for val in submatrix: matrix2.append(val)

print(matrix2[2][2])

21. The function can have only one parameter. If any data (parameters) are passed, they are passed explicitly.

  • True
  • False

Correct answer:

  • False

22. What will be the output of the following Python code?

  • 4
  • 2
  • 0
  • 1

Correct answer:

  • 2

Code: matrix = [[j for j in range(3)] for i in range(3)] print(matrix[1][2])

23. What will be the result of calling the fullname_func function with the arguments 'John' and 'Mark'?

  • John
  • john Mark
  • John Mark
  • Mark

Correct answer:

  • John Mark

Code: def fullname_func(fname, lname): print(fname + " " + lname)

fullname_func("John", "Mark")

24. The output of the following snippet of the code will be:

  • 9
  • 5
  • 8
  • 6

Correct answer:

  • 6

Code: def my_function(x): return 10 - x

print(my_function(4))

25. What is the output of the following snippet:

  • [2, 4, 6]
  • [1, 2, 3]
  • [1, 3, 5]
  • [4, 5, 6]

Correct answer:

  • [2, 4, 6]

Code: def get_even_func(numbers): even_numbers = [num for num in numbers if not num % 2] return even_numbers

get_even_func([1, 2, 3, 4, 5, 6])

26. What is the output of the following snippet:

  • (50, 40, 30, 20, 10)
  • (40, 20)
  • (10, 30, 50)
  • (10, 20, 30, 40, 50)

Correct answer:

  • (50, 40, 30, 20, 10)

Code: a = (10, 20, 30, 40, 50) a = a[::-1] print(a)

27. What is the output of the following snippet:

  • 20 20
  • Error
  • 30 20
  • False

Correct answer:

  • 30 20

Code: x = 20 def my_function(): x = 30 print(x, end=' ')

my_function() print(x, end=' ')

28. Write a Python program to create an empty tuple:

  • x = tuple(3)
  • x = ()
  • x = (2,3)
  • x = (0)

Correct answer:

  • x = ()

29. Which of the following method is used to delete a brand key and its value from the following dictionary:

  • del.testdict[0]
  • del testdict['brand':'oppo']
  • del.testdict['brand']
  • del testdict['brand']

Correct answer:

  • del testdict['brand']

Code: testdict = {'brand': 'oppo', 'ram': '3', 'Os': 'Android', 'year': 2020}

30. A dictionary is a collection that is ..., ... and ...

  • Ordered, changeable, does not allow duplicates
  • Unordered, changeable, does not allow duplicates
  • Ordered, immutable, does allow duplicates
  • Ordered, immutable, does not allow duplicates

Correct answer:

  • Ordered, changeable, does not allow duplicates

Python PCEP Operators 1

1. What will be the output of the following Python code?

  • True
  • You are not hungry
  • False
  • You are hungry

Correct answer:

  • You are hungry

Code: is_hungry = True if(not is_hungry): print("You are not hungry") else: print("You are hungry")

2. What will be the output of the following Python code?

  • True
  • You are not hungry
  • False
  • You are hungry

Correct answer:

  • You are not hungry

Code: is_hungry = False if(not is_hungry): print("You are not hungry") else: print("You are hungry")

3. Which of the following will evaluate to true?

  • True AND False
  • False or True
  • False AND (True or False)
  • False AND (False or True)

Correct answer:

  • False or True

4. What is the output of the following python code?

  • True
  • False
  • 12
  • 6

Correct answer:

  • True

Code: x = 6 print(x > 4 and x < 12)

5. Which python operator means 'bigger than or equal to'?

  • >=
  • >
  • <
  • <=

Correct answer:

  • >=

6. What is the output of the following python code?

  • True
  • False
  • 7
  • 6

Correct answer:

  • False

Code: x = 6 y = 7 print(x == y)

7. Which python operator means 'less than or equal to'?

  • >=
  • >
  • <
  • <=

Correct answer:

  • <=

8. What is the output of the following python code?

  • True
  • False
  • 12
  • 6

Correct answer:

  • True

Code: x = 6 print(x > 7 or x < 12)


Python PCEP Bitwise Operators

1. Bitwise shift operators (<<, >>) has higher precedence than Bitwise AND(&) operator.

  • False
  • True

Correct answer:

  • True

2. Bitwise _________ gives 1 if either of the bits is 1 and 0 when both of the bits are 1.

  • OR
  • AND
  • XOR
  • NOT

Correct answer:

  • XOR

3. What will be the output of the following Python code snippet if x=2?

  • 32
  • 16
  • 8
  • 4

Correct answer:

  • 8

Code: x << 2

4. Bitwise _________ gives 1 if either of the bits is 1 and 0 when both of the bits are 0.

  • OR
  • AND
  • XOR
  • NOT

Correct answer:

  • OR

5. What will be the output of the following Python expression?

  • 0 0 0 0 0 0 1 0
  • 1001
  • 0 0 0 0 1 0 0 1
  • 9

Correct answer:

  • 1001

Code: int(1001)

6. Bitwise _________ gives 1 if both of the bits is 1 and 0 when either of the bits are 0.

  • OR
  • AND
  • XOR
  • NOT

Correct answer:

  • AND

7. What will be the output of the following Python code snippet if x=2 ?

  • 32
  • 16
  • 8
  • 4

Correct answer:

  • 32

Code: x << 4

8. What will be the output of the following Python expression?

  • 14
  • 8
  • 12
  • 2

Correct answer:

  • 14

Code: 5^11

9. What will be the output of the following Python expression?

  • 14
  • 33
  • 44
  • 25

Correct answer:

  • 44

Code: print(22 << 1)

10. Which of the following represents the bitwise XOR operator?

  • &
  • ^
  • |
  • !

Correct answer:

  • ^

11. What will be the output of the following Python expression?

  • 201
  • -201
  • 200
  • -200

Correct answer:

  • -201

Code: ~200

12. Which operator is used by the or() function?

  • |
  • /
  • //
  • ||

Correct answer:

  • |

13. What will be the output of the following Python code?

  • a & b = 21
  • a & b = 4
  • a & b = 6
  • a & b = 12

Correct answer:

  • a & b = 4

Code: a = 20 b = 5 print("a & b =", a & b)

14. What will be the output of the following Python code?

  • a | b = 21
  • a | b = 8
  • a | b = 6
  • a | b = 12

Correct answer:

  • a | b = 21

Code: a = 20 b = 5 print("a | b =", a | b)


Python PCEP Mock Exam 2

1. What is the numerical value for boolean True?

  • 0
  • 1

Correct answer:

  • 1

2. What is the output of the following python code?

  • 1.5
  • 1.0
  • -1.5
  • -2.0

Correct answer:

  • 1.0

Code: print(6. // 4)

3. You have to import the print() function in the code so that you can access it.

  • True
  • False

Correct answer:

  • False

4. Which of the following is correct regarding variables in Python?

  • Variable names in Python cannot start with a number. However, it can contain the number in any other position of the variable name.
  • Variable names can start with an underscore.
  • Data type of variable names should not be declared
  • All of the above

Correct answer:

  • All of the above

5. What would get printed:

  • True
    True
  • True
    False
  • False
    True
  • False
    False

Correct answer:

  • False
    True

Code: min_score = 13 score = 13

print(score > min_score) print(score <= min_score)

6. What will be the output of the following Python code?

  • error
  • none of the above
  • 1
    2
  • 1
    2
    3

Correct answer:

  • 1
    2

Code: i = 1 while True: if i%3 == 0: break print(i) i += 1

7. In Python3, Whatever you enter as input, the input() function converts it into a string

  • True
  • False

Correct answer:

  • True

8. To have a multi-line comment in Python, we use triple single quotes at the beginning and at the end of the comment.

  • True
  • False

Correct answer:

  • True

9. What is the len(list1) of the following snippet:

  • 5
  • 4
  • None
  • Error

Correct answer:

  • 5

Code: list1 = ['h', 'e', 'l', 'l', 'o']

10. What will be the output of below Python code?

  • Error!
  • ['python', [11, 55, 'cat']]
  • [[11, 55, "cat"], [ ]]
  • [1, 66, 'python', [11, 55, 'cat']]

Correct answer:

  • Error!

Code: list1 = [1, 66, "python", [11, 55, "cat"], [ ], 2.22, True] print(list1.upper())

11. We want to iterate over the values from 0 to 10, and print their values. However, we want to skip all the values that are even. How can we achieve this?

  • if num % 2 == 0: break;
  • if num % 2 == 0: continue;
  • if num % 2 != 0: print(num);
  • if num % 2 == 0: return

Correct answer:

  • if num % 2 != 0: print(num);

Code: for num in range(0, 11): #your answer should be here print(num)

12. What will be the output of below Python code?

  • [1, 2, 10, 4, 5]
  • [1, 2, 3, 4, 10]
  • [1, 2, 3, 4, 5]
  • [10, 2, 3, 4, 5]

Correct answer:

  • [10, 2, 3, 4, 5]

Code: list1 = [1, 2, 3, 4, 5] list1[0] = 10 print(list1)

13. What will be the output of below Python code?

  • [1, 2, 3, 2, 5]
  • [8, 9, 10]
  • [4, 5, 6, 7]
  • [10, 11, 12, 13]

Correct answer:

  • [8, 9, 10]

Code: list1 = [[1,2,3,2,5],[4,5,6,7],[8,9,10]] for i in list1: if len(i)==3: print(i)

14. What will be the output of the following Python code?

  • 2
  • [0, 1, 2]
  • 0
  • 1

Correct answer:

  • [0, 1, 2]

Code: matrix = [[[0, 1, 2], [0, 1, 2], [0, 1, 2]], [[0, 1, 2], [0, 1, 2], [0, 1, 2]], [[0, 1, 2], [0, 1, 2], [0, 1, 2]]]

matrix2 = []

for submatrix in matrix: for val in submatrix: matrix2.append(val)

print(matrix2[2])

15. What will be the output of the following Python code?

  • 4
  • 2
  • 0
  • 1

Correct answer:

  • 1

Code: matrix = [[j for j in range(4)] for i in range(4)] print(matrix[3][1])

16. What is the output of the following code:

  • False
  • True

Correct answer:

  • True

Code: (4, 6) not in [(4, 7), (5, 6), "hello"]

17. Choose the correct answer which defines a function to get numeric input from the user.

  • def input_num(): return input ()
  • def input_num(): return int(input () )
  • def input_num(): int(input () )
  • def input_num(): return input (num)

Correct answer:

  • def input_num(): return int(input () )

18. What is the output of the following snippet:

  • 0
  • Error
  • 20
  • False

Correct answer:

  • Error

Code: def my_function(): def my_inner_function(): x = 20 print(x) my_inner_function()

my_function()

19. What is the output of the following snippet:

  • [7, 5, 9]
  • [7, 4, 5]
  • [4, 6, 8, 12]
  • [5, 6, 8, 12]

Correct answer:

  • [7, 5, 9]

Code: def get_odd_func(numbers): odd_numbers = [num for num in numbers if num % 2] return odd_numbers

print(get_odd_func([7, 4, 5, 6, 9, 8, 12]))

20. What is the output of the following command if the tuple1 has values (1,2,3,4,5) :

  • (1,2,3,4,6)
  • (6,)
  • (1,2,3,4,5,6)
  • AttributeError

Correct answer:

  • AttributeError

Code: print(tuple1.append(6))

21. The output of the following snippet of the code will be:

  • 0
  • 1
  • 2
  • 3

Correct answer:

  • 3

Code: a = 0 def add_three(a): return a+3

result = add_three(a) print(result)

22. The output of the following snippet of the code will be:

  • 9
  • 4
  • 12
  • 8

Correct answer:

  • 9

Code: def square(i): j = i * i return j

print(square(3))

23. Access value 30 from the following tuple:

  • a[30]
  • a[0][0]
  • a[1][1]
  • a[1][0]

Correct answer:

  • a[1][1]

Code: a = (10, [20, 30], 40, 50)

24. What is the output of the following snippet code:

  • dict_items([('brand', 'Samsung'), ('ram', '3'), ('Os', 'Android'), ('year', 2020)])
  • dict_keys(['brand', 'ram', 'Os', 'year'])
  • dict_keys(['Samsung', '3', 'Android', 2020])
  • (['brand', 'ram', 'Os', 'year'])

Correct answer:

  • dict_keys(['brand', 'ram', 'Os', 'year'])

Code: testdict = { "brand": "Samsung", "ram": "3", "Os": "Android", "year": 2020 }

print(testdict.keys())

25. What is the output of the following snippet:

  • The older friend is 13 years
  • The older friend is 11 years
  • Error
  • The older friend is 12 years

Correct answer:

  • The older friend is 12 years

Code: def my_function(*ages): print("The older friend is " + ages[1] + " years")

my_function("13", "12", "11")

26. Which of the following isn’t a characteristic of High level languages?

  • platform independent
  • machine code
  • interactive execution
  • user-friendly

Correct answer:

  • machine code

27. What is the output of the following snippet:

  • Error
  • (3)
  • 3
  • tuple(3)

Correct answer:

  • Error

Code: x = tuple(3) print(x)


Python PCEP Mock Exam 3

1. You have to import the print() function in the code so that you can access it.

  • True
  • False

Correct answer:

  • False

2. What is the data type of print(type(100_25))?

  • integer
  • float
  • string
  • boolean
  • none of the above

Correct answer:

  • integer

3. Which of the following variable names are valid?

  • not = "Don't do that!"
  • name = "Kodekloud"
  • 2timesage = 44
  • Function = "function"

Correct answer:

  • name = "Kodekloud"
  • Function = "function"

4. What is the output of the following python code?

  • TRUE
  • FALSE
    TRUE
  • TRUE
    FALSE
  • TRUE
    FALSE
    TRUE

Correct answer:

  • FALSE
    TRUE

Code: if 4 + 5 == 10: print("TRUE") else: print("FALSE") print("TRUE")

5. Comments can be used to ….

  • explain Python code
  • make the code more readable
  • comment out code that you don’t want to execute
  • None of the Above

Correct answer:

  • explain Python code
  • make the code more readable
  • comment out code that you don’t want to execute

6. What is the output of the following python code?

  • 5.0
  • 0.5
  • 5
  • 5.5

Correct answer:

  • 5.0

Code: print(10 / 2)

7. What is the output of print(2 * 3 ** 3 * 4)?

  • 216
  • 864
  • “2 * 3 ** 3 * 4”
  • 144

Correct answer:

  • 216

8. The input() method returns string value. So, if we want to perform arithmetic operations, we need to cast the value first.

  • True
  • False

Correct answer:

  • True

9. What will be the output of the following Python code?

  • error
  • A
    B
    C
    D
  • a
    B
    C
    D
  • a
    b
    c
    d

Correct answer:

  • A
    B
    C
    D

Code: x = 'abcd' for i in x: print(i.upper())

10. What will be the output of the following Python code?

  • error
  • none of the above
  • 1
    2
  • 1
    2
    3

Correct answer:

  • 1
    2

Code: i = 1 while True: if i%3 == 0: break print(i) i += 1

11. What will be the output of below Python code?

  • [1, 2, 3, 4, 11, 10]
  • [10, 2, 3, 4, 5]
  • [1, 2, 3, 4, 10, 11]
  • [1, 2, 3, 4, 10]

Correct answer:

  • [1, 2, 3, 4, 10, 11]

Code: list1 = [1, 2, 3, 4, 5] list1[4] = 10 list1.append(11) print(list1)

12. What will be the output of below Python code?

  • [24, 46, 56, 72]
  • [24, 46, 72, 56]
  • [56, 72, 24, 46]
  • [24, 46, 56]

Correct answer:

  • [24, 46, 56, 72]

Code: ages = [56, 72, 24, 46] ages.sort() print(ages)

13. What will be the output of below Python code?

  • [1, 2, 3, 4]
  • [0, 1, 2, 3]
  • 0 1
    1 2
    2 3
    3 4
  • 1 0
    2 1
    3 2
    4 3

Correct answer:

  • 0 1
    1 2
    2 3
    3 4

Code: list1 = [1, 2, 3, 4] for i, j in enumerate(list1): print(i, j)

14. What will be the output of below Python code?

  • [5]
  • [4, 5]
  • [3, 4, 5]
  • [2, 3, 4, 5]

Correct answer:

  • [5]

Code: numbers = [1, 2, 3, 4, 5] print(numbers[4:])

15. Which of the following statements won’t be printed when this Python code is run?

  • Letter : K
  • Letter : o
  • Letter : e
  • Letter : d

Correct answer:

  • Letter : e

Code: for letter in 'KodeKloud': if letter == 'e': continue print('Letter : ' + letter)

16. What will be the output of below Python code?

  • [1, 66, "python"]
  • ['python', [11, 55, 'cat']]
  • [[11, 55, "cat"], [ ]]
  • [1, 66, 'python', [11, 55, 'cat']]

Correct answer:

  • [1, 66, 'python', [11, 55, 'cat']]

Code: list1 = [1, 66, "python", [11, 55, "cat"], [ ], 2.22, True] print(list1[0:4])

17. What will be the output of below Python code?

  • 4
  • 3
  • 2
  • 1

Correct answer:

  • 2

Code: my_list = [0, 1, 2, 3, 4] print(my_list.index(2))

18. What will be the output of the following Python code?

  • 2
  • 0
  • 1
  • Error

Correct answer:

  • 2

Code: matrix = [[0, 1, 2], [0, 1, 2], [0, 1, 2]]

matrix2 = []

for submatrix in matrix: for val in submatrix: matrix2.append(val)

print(matrix2[2])

19. What will be the output of the following Python code?

  • [0, 1, 2]
  • 2
  • 0
  • 1

Correct answer:

  • 1

Code: matrix = [[[k for k in range(3)] for j in range(3)] for i in range(3)] print(matrix[1][1][1])

20. Define a function that gets the user input and multiply it by a number we passed to the function.

  • def multi_num(num): return int(input () ) * num
  • def multi_num(): return int(input (num) ) * 6
  • def multi_num(6): return int(input () ) * num
  • def multi_num(): return int(input () ) * num

Correct answer:

  • def multi_num(num): return int(input () ) * num

Code: Sample input: 6 Sample output: print( multi_num(5) ) 30

21. What will be the output of the following Python code?

  • 4
  • 2
  • 0
  • 1- [ ] 4

Correct answer:

  • 0

Code: matrix = [[[0, 1, 2], [0, 1, 2], [0, 1, 2]], [[0, 1, 2], [0, 1, 2], [0, 1, 2]], [[0, 1, 2], [0, 1, 2], [0, 1, 2]]] print(matrix[0][0][0])

22. What is the output of the following snippet:

  • The tallest student is john
  • The tallest student is Ella
  • Error
  • mark

Correct answer:

  • The tallest student is Ella

Code: def my_function(*friends): print("The tallest student is " + friends[1])

my_function("john", "Ella", "mark")

23. What will the following function return?

  • None
  • The value of x + y
  • The value of x
  • The value of y

Correct answer:

  • The value of x + y

Code: def add(x, y): return x+y

24. What is the output of the following snippet:

  • 3.5
  • 3.25
  • 2.5
  • 3

Correct answer:

  • 3.25

Code: def mean_func(list1): return sum(list1) / len(list1)

print(mean_func([5, 2, 2, 4]))

25. What is the output of the following snippet:

  • 20
  • Error
  • 0
  • False

Correct answer:

  • 20

Code: def my_function(): x = 20 def my_inner_function(): print(x) my_inner_function() my_function()

26. What is the output of the following command if the tuple1 has values (0,1,2,3,4,5) :

  • (0, 1, 2, 3)
  • (1,2,3,4)
  • (0,1,2,3,4,5)
  • (0,1,2,3,4)

Correct answer:

  • (0, 1, 2, 3)

Code: print(tuple1[0:4])

27. cython can run on .......

  • Windows
  • MacOS
  • Linux
  • All the above

Correct answer:

  • All the above

28. Write a Python program to create a tuple with different data types:

  • x = ("john", True, 2.2, 2)
  • x = ("tuple", "john", "list")
  • x = (2.1, 3.2, 1.3)
  • x = (1, 2, 3)

Correct answer:

  • x = ("john", True, 2.2, 2)

Code: print(x)

29. …. is one of the dictionary built-in methods.

  • dictionary.update()
  • dictionary.values()
  • dictionary.items()
  • dictionary.keys()

Correct answer:

  • dictionary.update()
  • dictionary.values()
  • dictionary.items()
  • dictionary.keys()

Python PCEP Mock Exam 4

1. What is the output of the following python code if we enter 5 as input?

  • 15
  • NumNumNum
  • 555
  • Error

Correct answer:

  • 555

Code: Num = input("Enter a Number: ") print (Num * 3 )

2. What is the output of the following python code?

  • Hello, jack!
  • Hello, jack,Sally!
  • Hello, Sally!
  • Hello, jack!,Sally!

Correct answer:

  • Hello, Sally!

Code: #print("Hello, jack!") print("Hello, Sally!")

3. A …. is a collection of items that is both unordered, unindexed and used to store multiple items in a single variable.

  • List
  • Set
  • Dictionary
  • Tuple

Correct answer:

  • Set

4. Is it possible to pass multiple arguments to a function?

  • Yes
  • No

Correct answer:

  • Yes

5. In Python, a string is:

  • An immutable sequence of characters, delimited by quotes
  • A mutable sequence of characters, delimited by quotes
  • An immutable sequence of characters, optionally delimited by quotes
  • A mutable sequence of characters, optionally delimited by quotes

Correct answer:

  • An immutable sequence of characters, delimited by quotes

6. Which of the following is a valid variable name in Python?

  • do it
  • do+1
  • 1do
  • All of the above
  • None of the above

Correct answer:

  • None of the above

7. What is the output when this code executes?

  • 6
  • 1
  • 4
  • 5

Correct answer:

  • 6

Code: x = 1 while ( x <= 5 ): x += 1 print(x)

8. What does the following Python program display?

  • Am I here?
  • Or here?
  • Am I here?
    Or here?
  • Or here?
    Or over here?

Correct answer:

  • Or here?
    Or over here?

Code: x = 3 if ( x == 0 ): print("Am I here?") elif ( x == 3 ): print("Or here?") print("Or over here?")

9. What will be the output of the following Python code?

  • error
  • 0
    1
    2
    3
  • 1
    2
    3
    4
  • a
    b
    c
    d

Correct answer:

  • 0
    1
    2
    3

Code: x = 'abcd' for i in range(len(x)): print(i)

10. What will be the output of below Python code?

  • [4, 4, 3]
  • [4, 4, 1]
  • [4, 3, 1]
  • [4, 4, 3, 1]

Correct answer:

  • [4, 4, 1]

Code: list1 = [4, 4, 3, 1] list1.pop(2) print(list1)

11. What will be the output of following Python code?

  • Go
  • Java
  • C
  • Python

Correct answer:

  • Python

Code: list1=["Go","Java","C","Python"] print(max(list1))

12. Which of the following will reverse list1=[2,5,3,1]?

  • list1[::-1]
  • list1[::2]
  • list1[::1]
  • list1[2:4]

Correct answer:

  • list1[::-1]

13. What will be the output of below Python code?

  • [10, 11, 12, 13, 14]
  • [10, 12, 14]
  • [11, 12, 13, 14]
  • [10, 11, 12, 13]

Correct answer:

  • [10, 11, 12, 13, 14]

Code: list1 = [10, 11, 12, 13, 14] print(list1[::1])

14. How many asterisks will be printed when the following code executes?

  • 20
  • 16
  • 5
  • 4

Correct answer:

  • 16

Code: for x in [0, 2, 1, 3]: for y in [0, 4, 1, 2]: print('*')

15. What will be the output of below Python code?

  • [1, 66, "python"]
  • ['python', [11, 55, 'cat']]
  • [[11, 55, "cat"], [ ]]
  • [2.22, True]

Correct answer:

  • ['python', [11, 55, 'cat']]

Code: list1 = [1, 66, "python", [11, 55, "cat"], [ ], 2.22, True] print(list1[2:4])

16. What will be the output of the following Python code?

  • [0, [8, 9], 4, 1, 2]
  • [0, 4, 1, 2]
  • [4, 1, 2]
  • [[8, 9], 3, 4, 1, 2]

Correct answer:

  • [0, [8, 9], 4, 1, 2]

Code: list1 = [0, 3, 4, 1, 2] list1[1]=[8,9] print(list1)

17. What will be the output of the following Python code?

  • [0, [8, 9], 4, 1, 2]
  • [0, 4, 1, 2]
  • [0, 3, 8, 9]
  • [[8, 9], 3, 4, 1, 2]

Correct answer:

  • [0, 3, 8, 9]

Code: list1 = [0, 3, 4, 1, 2] list1[2:5]=[8,9] print(list1)

18. What will be the output of the following Python code?

  • ['Egypt', 'USA', 'India', 'Dubai', 'Spain']
  • ['Egypt', 'America', 'India', 'Dubai', 'London']
  • ['Egypt', 'USA', 'France', 'Dubai', 'Spain']
  • ['France', 'USA', 'India', 'England', 'Spain']

Correct answer:

  • ['Egypt', 'USA', 'India', 'Dubai', 'Spain']

Code: countries = [['Egypt', 'USA', 'India'], ['Dubai', 'America', 'Spain'], ['London', 'England', 'France']] countries2 = [country for sublist in countries for country in sublist if len(country) < 6] print(countries2)

19. What will be the output of the following Python code?

  • 4
  • 2
  • 0
  • 1

Correct answer:

  • 0

Code: matrix = [[0, 1, 2], [0, 1, 2], [0, 1, 2]]

matrix2 = []

for submatrix in matrix: for val in submatrix: matrix2.append(val)

print(matrix2[0])

20. What is the error in the following snippet code:

  • The multi_func() function doesn’t have any parameters
  • The result is not defined as a global variable
  • The function return None
  • print() is not a built-in function

Correct answer:

  • The result is not defined as a global variable

Code: def multi_func(): result = int(input()) * 5 return result

print(result)

21. What will be the output of the following Python code?

  • [0, 1, 2]
  • 2
  • 0
  • 1

Correct answer:

  • [0, 1, 2]

Code: matrix = [[[k for k in range(3)] for j in range(3)] for i in range(3)] print(matrix[1][2])

22. Regarding the definition of the function and the sample input, Choose the correct value of the output.

  • 15
  • None
  • Error
  • 50

Correct answer:

  • Error

Code: Function : def add_func(num1,num2): return num1 + num2

Sample input: print ( add_func(5 , num1= 10) )

23. The output of the following snippet of the code will be:

  • The result is False
  • The result is True
  • The result is bool
  • The result is 0

Correct answer:

  • The result is True

Code: def is_true(a): return bool(a)

result = is_true(3<6) print("The result is", result)

24. What is the output of the following snippet:

  • john emmy mark
  • john mark emmy
  • john mark
  • emmy mark

Correct answer:

  • john mark emmy

Code: def my_function(names): for i in names: print(i, end=' ')

names = ["john", "mark", "emmy"] my_function(names)

25. What is the output of the following snippet:

  • 20
  • Error
  • 0
  • False

Correct answer:

  • 20

Code: def myfunc(): a = 20 print(a)

myfunc()

26. Which of the following is used to create a tuple called tuple1 which contains numbers from 1 to 5:

  • tuple1 = (1,2,3,4,5)
  • tuple1 = 1,2,3,4,5
  • tuple1 = [1,2,3,4,5]
  • tuple1 = 1 2 3 4 5

Correct answer:

  • tuple1 = (1,2,3,4,5)
  • tuple1 = 1,2,3,4,5

27. What is the output of the following snippet code:

  • {'brand': 'apple', 'ram': '3', 'year': 2020}
  • {'brand': 'apple', 'ram': '3', 'year': 2021}
  • {'brand': 'apple', 'ram': '3', 'year': 2020, 'year': 2021}
  • {'brand': 'apple', 'ram': '3'}

Correct answer:

  • {'brand': 'apple', 'ram': '3', 'year': 2021}

Code: testdict = { "brand": "apple", "ram": "3", "year": 2020, "year": 2021 }

print(testdict)

28. What is the output of the following snippet:

  • Error
  • Welcome to Python!
  • First argument: Welcome to Python!
  • First argument: Welcome
    Next argument: to
    Next argument: Python!

Correct answer:

  • First argument: Welcome
    Next argument: to
    Next argument: Python!

Code: def my_function(arg1, *argv): print ("First argument:", arg1) for arg in argv: print("Next argument:", arg)

my_function('Welcome', 'to', 'Python!')

29. …. is one of the dictionary built-in methods that used to delete all items from the dictionary.

  • dictionary.prune()
  • dictionary.clear()
  • dictionary.delete()
  • dictionary.remove()

Correct answer:

  • dictionary.clear()

Python PCEP Mock Exam 5

1. What is the output of the following python code if we enter “HelloPython” as input?

  • HelloPython
  • Enter a string: HelloPython*2
  • HelloPythonHelloPython
  • HelloPython*2

Correct answer:

  • HelloPythonHelloPython

Code: inputString = input('Enter a string: ') print(inputString*2)

2. What is the output of the following python code?

  • 8.0
  • 0.8
  • 8
  • 8.5

Correct answer:

  • 8

Code: print(2 ** 3)

3. What is the output of the following python code?

  • line1 line2 line3
  • line1
  • line1
    #line3
  • line1
    line2
    #line3

Correct answer:

  • line1
    #line3

Code: print("line1") #print("line2") print("#line3")

4. The output of the following code will be:

  • My age is 25
  • 25
  • TypeError
  • My age is + 25

Correct answer:

  • TypeError

Code: print('My age is ' + 25)

5. Which operator you can use to perform string concatenation?

  • /
  • *
  • +
  • -

Correct answer:

  • +

6. What is the output of the following python code?

  • 8
  • 12
  • 10
  • SyntaxError

Correct answer:

  • SyntaxError

Code: y = 20 x = y += 3 print(x)

7. True is what type of variable?

  • float
  • string
  • boolean
  • integer

Correct answer:

  • boolean

8. What is the output of the following snippet code:

  • 0o11 0x12b 6
  • 9 299 6
  • 11 12 6
  • Error

Correct answer:

  • 9 299 6

Code: x = 0o11 y = 0x12b z = 6 print(x, y, z)

9. Which one of the following if statements will not execute successfully?

  • if (5,10):
      print('hello')
  • if (yes):
      print('hello')
  • if True:
      print('hello')
  • if (5,10):
    print('hello')

Correct answer:

  • if (yes):
      print('hello')
  • if (5,10):
    print('hello')

Explaination: if(yes):
  print('hello')

The above code will give IndentationError: expected an indented block,

if(5,10):print('hello') The above code will give NameError: name 'yes' is not defined

10. What is the value of x?

  • 49
  • 50
  • None of the above, this is an infinite loop
  • 51

Correct answer:

  • 50

Code: x = 0 while (x < 50): x+=2

print(x)

Explaination: In the "while" loop as per statement "x" is increased by 2. Like 2, 4, 6 ... 48 50.  Value 50 is not satisfying the given condition so it's exited from the loop and the final value we got for "x" is 50.

11. What will be the output of the following python code?

  • abcd
  • ABCD
  • error
  • none of the mentioned

Correct answer:

  • abcd

Code: x = 'abcd' for i in range(len(x)): x[i].upper() print(x)

12. Which of the following would give an error?

  • list1=[] ++
  • list1=[]
  • list1=[] + 2
  • list1=["USA","Canada","India"]

Correct answer:

  • list1=[] + 2
  • list1=[] ++

13. What will be the output of below Python code?

  • 0
  • 1
  • 9
  • 4

Correct answer:

  • 4

Code: my_list = [0, 1, 2, 3, 4] print(my_list[-1])

14. What will be printed by the following code when it executes?

  • 2
  • 11
  • 12
  • 19

Correct answer:

  • 19

Code: sum = 0 values = [2,9,1,7] for number in values: sum = sum + number

print(sum)

15. What will be the output of below Python code?

  • 25
  • Error!
  • 20
  • 21

Correct answer:

  • 25

Code: list1=[7,8,1,3,9] list1.remove(3) print(sum(list1))

16. What will be the output of below python code?

  • [0, 1, 2, 3, 4]
  • [0, 1, 2]
  • [2, 3]
  • [0, 1, 2, 3]

Correct answer:

  • [2, 3]

Code: my_list = [0, 1, 2, 3, 4] print(my_list[2:4])

17. What will be the output of the following Python code?

  • [0, 3, [1, 2], 1, 2]
  • [0, 4, 1, 2]
  • [3, 4, 1, 2]
  • [0, 3, 1, 2, 2]

Correct answer:

  • [0, 3, 1, 2, 2]

Code: list1 = [0, 3, 4, 1, 2] list1[2:4]=[1,2] print(list1)

18. What will be the output of the following Python code?

  • [9, 4, 6, 1, 2]
  • [3, 4, 6, 1, 2]
  • [3, 4, 1, 2]
  • [3, 9, 6, 1, 2]

Correct answer:

  • [9, 4, 6, 1, 2]

Code: list1=[3,4,6,1,2] list2=list1 list1[0]=9 print(list2)

19. What will be the output of the following Python code?

  • 1
  • 0
  • 2
  • 3

Correct answer:

  • 3

Code: a = [] for i in range(5): a.append([]) for j in range(5): a[i].append(j)

print(a[2][3])

20. Choose the correct answer to define a list "Num", which contains numbers from 1-9 with 3 elements only in the row.

  • Num =[ [1,2,3] , [4,5,6,7] , [8,9] ]
  • Num =[ [1,2,3] , [4,5,6,] , [7,8,9] ]
  • Num =[ [1,2,3,4] , [4,5,6,7] , [8,9,6] ]
  • Num =[ [1,2,3,4] , [4,5,6] , [7,8,9] ]

Correct answer:

  • Num =[ [1,2,3] , [4,5,6,] , [7,8,9] ]

21. The output of the following snippet code will be:

  • Hello, World
  • None
  • Error
  • return_greeting

Correct answer:

  • Hello, World

Code: def return_greeting(): return "Hello, World"

print(return_greeting())

22. The output of the following snippet of the code will be:

  • 0
  • 1
  • 2
  • 3

Correct answer:

  • 1

Code: a = 0 def add_one(a): return a+1

result = add_one(a) print(result)

23. Choose the correct code to get the third element in the second row, Regarding the following list :

  • print(Colors[2][3])
  • print(Colors[1][3])
  • print(Colors[1][2])
  • print(Colors[2][2])

Correct answer:

  • print(Colors[1][2])

Code: Colors = [ ['Red', 'Green', 'White', 'Black'], ['Green', 'Blue', 'White', 'Yellow'] ,['White', 'Blue', 'Green', 'Red'] ]

24. What is the output of the following snippet:

  • [1, 2,3]
  • [1,2,3[1,2,3]]
  • [1, 2, 3][1,2,3]
  • [1, 2, 3, 1, 2, 3]

Correct answer:

  • [1, 2, 3, 1, 2, 3]

Code: def double_list(numbers): return 2 * numbers

numbers = [1, 2, 3] print(double_list(numbers))

25. What is the output of the following snippet:

  • 20
  • Error
  • 0
  • False

Correct answer:

  • Error

Code: def myfunc(): a = 20

myfunc() print(a)

26. …. is one of the data types in Python that used to store collections of data.

  • List
  • Set
  • Dictionary
  • Tuple

Correct answer:

  • List
  • Set
  • Dictionary
  • Tuple

27. Dictionaries are used to store data values in key-value pairs.

  • True
  • False

Correct answer:

  • True

28. What is the output of the following snippet:

  • 6
  • 2
  • Error
  • 3

Correct answer:

  • 6

Code: def sum(*args): result = 0 for arg in args: result += arg return result

print(sum(2,3,1))


tej-singh-test

1. Which of the following statements are correct? Select all that apply.

  • statement1
  • statement2
  • statement3
  • statement4

Correct answer:

  • statement1
  • statement2

Explaination: Good Testing
Good Testing

2. We have the following VNets in Azure. For which scenarios can we establish peering? question-image

  • A, B, C and D
  • A and B
  • A and C
  • A, C, and D

Correct answer:

  • A and C

Explaination: In scenario B, the address spaces are overlapping so we cannot establish peering. In scenario-D, the CIDR for VNet-a is /30; in Azure we can only create till /29. Since the network itself cannot be created, peering cannot be established.

3. One of your Linux virtual machines has the following NSGs attached to it. question-image
You are not able to connect to the VM over SSH. How can you fix this?

  • Change the priority of rule 1 of subnet level NSG to 100
  • Delete rule 1 from NIC level NSG
  • Change the source of rule 1 of subnet level NSG
  • Delete the NIC level NSG

Correct answer:

  • Delete rule 1 from NIC level NSG

Explaination: Delete rule 1 from the NIC level so NSG will allow SSH traffic.

4. You have the following resources in Azure:

  • Blob container – imgfiles
  • File share – executables
  • VM – VM-01
  • Azure Database for MySQL – wordpress

  • Which of the following can be backed up to a recovery services vault?

    • File share and VM
    • Blob container, file share, VM, and Azure Database for MySQL
    • File share, VM, and Azure Database for MySQL
    • VM and Azure Database for MySQL

    Correct answer:

    • File share and VM

    Explaination: In the Recovery Service vault, we can only backup VMs and file shares. For the Blob container and Azure Database for MySQL, you need to use the Backup vault.


    Lab MCQ IAC and Terraform Basics

    1. Which of the following statements is true?

    • Ansible cannnot be used to provision resources on the cloud
    • Ansible uses declarative approach
    • Ansible uses procedural approach
    • Ansible can only be used to as a configuration management tool

    Correct answer:

    • Ansible uses procedural approach

    Explaination: As explained in the lecture, Ansible makes use of a procedural approach. This means that an Ansible playbook should specifically contain all the steps needed achieve a task.

    2. What does “IaC” stand for?

    • Infrastructure as Code
    • Initialization as Code
    • Code as Infrastructure
    • None of the above

    Correct answer:

    • Infrastructure as Code

    Explaination: IaC stands for Infrastructure as Code.

    3. Which of the following statements is true?

    • Terraform can only be installed on Windows OS
    • Terraform cannot be installed on Solaris or OpenBSD
    • Terraform can only be installed on Linux Distributions
    • Terraform cannot be installed on MacOS
    • None of the Above

    Correct answer:

    • None of the Above

    Explaination: Terraform can be installed on all major Linux Distributions, Windows, MacOS, Solaris and OpenBSD. Hence the correct answer here is "None of the Above"

    Documentation Link: https://www.terraform.io/downloads.html

    4. What allows Terraform to make use of a declarative approach?

    • Terraform uses multiple providers that supports all major cloud providers
    • Terraform makes use of a state file
    • Terraform uses JSON instead of YAML
    • Terraform uses modules unlike Ansible

    Correct answer:

    • Terraform makes use of a state file

    Explaination: Terraform uses a state file that contains data related to every resource provisioned by terraform. This state file along with the configuration files gives a clear definition of what the infrastructure should look like at any given point in time.

    5. Select the file extension used by terraform configuration files.

    • .TF
    • .YAML
    • .TOML
    • .DAT
    • None of the Above

    Correct answer:

    • .TF

    6. A Junior DevOps engineer has just joined your organization. He is exploring ways to automate the existing process of infrastructure provisioning and management using code. As his tech lead, what suggestions in general would you like to provide him?

    • Use any technique that would ensure no human interference and should be automating resources.
    • Utilize bash scripting to codify infrastructure and use it to define, provision, configure, update and destroy infrastructure resources.
    • Run a POC using a single tool and stick to it for all tasks
    • Explore the requirements and utilize the correct IaC tools that check all the required boxes.
    • Use any IaC tool out there as they are all the same.

    Correct answer:

    • Explore the requirements and utilize the correct IaC tools that check all the required boxes.

    Explaination: As we learnt in the lecture, there are several categories of IaC tools and several different tools available in the market within a category. For optimum results, we should first explore the requirements and chose the tool or tools that can meet all the requirements.

    7. What is Immutable Infrastructure?

    • Resources once deployed are not intended to be changed
    • Resources cannot be migrated to another platform
    • Any aspect of a resource can be updated in place anytime
    • Resources strictly provisioned by Terraform

    Correct answer:

    • Resources once deployed are not intended to be changed

    Explaination: Immutable infrastructure is another paradigm in which it ensures that resources are never modified after they have been deployed. If a change is to be made, a new instance of that resource will be provisioned in place of the old one.

    8. Your company has recently been contracted to oversee a business transformation project for a large bank. This project requires a lot of the legacy banking applications to be migrated to several different cloud platforms - AWS, Azure, GCP to name a few. The solution architects of your team have decided to go with Terraform as their choice for the infrastructure provisioning. Why do you think they went with this choice?

    • Terraform is the ideal choice for Configuration Management as well as Provisioning
    • They just went with their gut feeling
    • Terraform is vendor agnostic and supports multiple providers which is a good fit for this project.
    • Disagree with the choice - should have used CloudFormation

    Correct answer:

    • Terraform is vendor agnostic and supports multiple providers which is a good fit for this project.

    Explaination: The support for multiple providers that helps in managing third party platforms (including AWS, Azure and GCP) using the api makes Terraform a logical choice as a provisioning tool.

    9. What should be the very first command that should be run after writing a new Terraform configuration or cloning an existing one from version control?

    • Terraform init
    • Terraform plan
    • Terraform apply
    • Terraform get

    Correct answer:

    • Terraform init

    10. Observe the below code snippet and choose correct options:

    • "local_file" is a provider with resource name "games"
    • The resource name "games" is a user-defined value
    • "local_file" is the resource type and "local" is the provider
    • This code creates the file "/root/favorite-games" with terraform apply

    Correct answer:

    • This code creates the file "/root/favorite-games" with terraform apply
    • "local_file" is the resource type and "local" is the provider
    • The resource name "games" is a user-defined value

    Code: resource "local_file" "games" { file = "/root/favorite-games" content = "FIFA 21" }

    11. Which of the options can be used to run a terraform apply without confirmation?

    • -auto-approve
    • -approve
    • -auto-approve=yes
    • -auto-approve=true

    Correct answer:

    • -auto-approve

    Documentation Link: https://www.terraform.io/docs/cli/commands/apply.html#auto-approve

    12. Choose the correct terraform command to display the blueprint of the infrastructure to be applied.

    • terraform init
    • terraform apply
    • terraform plan
    • terraform show

    Correct answer:

    • terraform plan

    13. What is the order of commands to be run in a core terraform workflow?

    • terraform validate -> terraform init -> terraform apply
    • terraform init -> terraform plan -> terraform apply
    • terraform init -> terraform validate -> terraform apply
    • Order of commands don’t matter in a terraform workflow
    • terraform init -> terraform fmt -> terraform apply

    Correct answer:

    • terraform init -> terraform plan -> terraform apply

    14. After testing a sample terraform code, the user now wants to get rid of everything that was provisioned. Which of the following does he need to execute in order to accomplish this?

    • terraform refresh
    • terraform state rm
    • terraform destroy
    • terraform workspace delete

    Correct answer:

    • terraform destroy

    15. What does the "terraform show" command use to provide details of the Infrastructure?

    • Configuration Files
    • State File
    • Provider Plugins
    • Terraform Workspace

    Correct answer:

    • State File

    Explaination: The "terraform show" command inspects the state file and displays the resource details

    16. You have been working on a terraform configuration file. When you run terraform plan, you see an output as shown below that states that the resource "local_file.pet must be replaced". What is the cause for this?

    • file_content was changed
    • directory_permissions was changed
    • file_permissions was changed
    • terraform init was not run
    • file_permission was changed

    Correct answer:

    • file_permission was changed

    Code:

    local_file.pet must be replaced

    -/+ resource "local_file" "pet" {         content              = "We love pets!"         directory_permission = "0777"       ~ file_permission      = "0777" -> "0700" # forces replacement         filename             = "/root/pet.txt"       ~ id                   = "5f8fb950ac60f7f23ef968097cda0a1fd3c11bdf" -> (known after apply)     }

    17. Upon running "terraform init" within a configuration directory, you see an output as shown below. What is the provider and version that was initialized?

    • local v1.4.0
    • random v1.2
    • aws v2.1
    • local v1.0.0

    Correct answer:

    • local v1.4.0

    Code: Initializing the backend...

    Initializing provider plugins...

    • Finding latest version of hashicorp/local...
    • Installing hashicorp/local v1.4.0...
    • Installed hashicorp/local v1.4.0 (signed by HashiCorp)

    The following providers do not have any version constraints in configuration, so the latest version was installed.

    To prevent automatic upgrades to new major versions that may contain breaking changes, we recommend adding version constraints in a required_providers block in your configuration, with the constraint strings suggested below.

    • hashicorp/local: version = "~> 1.4.0"

    Terraform has been successfully initialized!

    18. A simple terraform configuration file is given below. What is the name of the resource that will be created?

    • pet
    • local_file
    • pets.txt
    • local

    Correct answer:

    • pet

    Code: resource "local_file" "pet" {​ filename = "/root/pets.txt"​ content = "We love pets!"​ ​ }

    Explaination: The name of the resource is "pet" which is a local_file type resource.

    19. What is the resource type used by this sample configuration file?

    • google_compute_instance
    • my-testvm
    • test-vm
    • google

    Correct answer:

    • google_compute_instance

    Code: resource "google_compute_instance" "my-testvm" { count = 3 name = my-testvm${count.index + 1}" machine_type = var.instance_type zone = var.zone tags = ["testvm"] }

    20. Which of the following is an "argument" used in the sample terraform configuration given below?

    • ami
    • t2.micro
    • ami-0edab43b6fa892279
    • webserver
    • aws_instance

    Correct answer:

    • ami

    Code: resource "aws_instance" "webserver" {   ami           = "ami-0edab43b6fa892279"   instance_type = "t2.micro" }


    Lab MCQ Providers

    1. Where can we declare the version of the provider that is required by a terraform configuration? Choose the most appropriate answer.

    • Under the providers block
    • As a variable
    • As an provider alias
    • Under the required_providers block
    • While running terraform init

    Correct answer:

    • Under the required_providers block

    Explaination: The required providers for a configuration can be declared inside the required_providers block which is nested inside the terraform block.

    Example:

    terraform { required_providers { mycloud = { source = "mycorp/mycloud" version = "~> 1.0" } } }

    Documentation Link: https://www.terraform.io/docs/language/providers/requirements.html#requiring-providers

    2. Choose the easiest way to list the versions of all installed plugins in terraform along with terraform versions.

    • Run terraform version command
    • Search the contents of the .terraform directory for plugin versions
    • There is no easy way to accomplish this
    • All of the above

    Correct answer:

    • Run terraform version command

    Explaination: The terraform version command provides the version of terraform as well as the version of the provider plugins that are downloaded in the configuration directory.

    For example, the below command shows that the version of aws provider is v3.69.0 and that of local provider is v2.1.0

    iac-server $ terraform version Terraform v0.13.3

    • provider registry.terraform.io/hashicorp/aws v3.69.0
    • provider registry.terraform.io/hashicorp/local v2.1.0

    3. Your team has deployed an EKS cluster in the AWS cloud using terraform. To the existing configuration, you have added a new resource block for the "kubernetes_deployment" type resource. When you run terraform apply, you see an error that states - “Failed to instantiate provider”. What could be the reson for this error?

    • Restart the machine and it should work
    • There is no provider with the name kubernetes
    • A terraform plan was not run to generate the execution plan
    • EKS cluster was not provisioned correctly
    • The aws module was not initialized for the configuration
    • The kubernetes provider was not initialized for the configuration

    Correct answer:

    • The kubernetes provider was not initialized for the configuration

    Explaination: Since the EKS cluster was already provisioned and the error was displayed only after adding the resource block for the "kubernetes_deployment", it would appear that a "terraform init" command was not run to download the provider plugin for the kubernetes provider.

    4. Whenever the target APIs change or when new functionality is added, the provider maintainers may update new versions for a provider. This may lead to unexpected infrastructure changes. What is the best approach to overcome this?

    • Never touch what you don’t understand
    • Use required_providers block to clearly define the provider version you want to use
    • API changes does not affect the provider usage within terraform
    • There would be no issue as terraform always downloads the latest version of the provider

    Correct answer:

    • Use required_providers block to clearly define the provider version you want to use

    Explaination: The functionality of a provider plugin may vary drastically from one version to another. Our terraform configuration may not work as expected when using a version different than the one it was written in. As a best practice, always declare the exact version of the provider we want to use within the required_providers block.

    5. Observe the below code and determine the providers used.

    • Local_file and random_pet
    • Pet_name and my-pet
    • Local and random
    • Local_file, random_pet, pet_name, my-pet

    Correct answer:

    • Local and random

    Code: resource "local_file" "pet_name" { content = "We love pets!" filename = "/root/pets.txt" } resource "random_pet" "my-pet" { prefix = "Mrs" separator = "." length = "1" }

    6. The terraform providers command shows information about the provider requirements of the configuration in the current working directory. True or False?

    • True
    • False

    Correct answer:

    • True

    Explaination: True. The "terraform providers" command displays the providers needed by the configuration.

    For example:

    iac-server $ terraform providers

    Providers required by configuration: . ├── provider[registry.terraform.io/hashicorp/local] └── provider[registry.terraform.io/hashicorp/aws]

    Documentation Link: https://www.terraform.io/docs/cli/commands/providers.html

    7. Select the reasons why we may need to specify the provider's argument?

    • It’s just a practice we need to blindly follow
    • No specific reason
    • To use multiple configurations of the same provider
    • To change the default Provider Configurations
    • To use multiple provider plugins in the same configuration

    Correct answer:

    • To use multiple configurations of the same provider
    • To change the default Provider Configurations

    Explaination: There are two reasons to use a provider argument in the configuration.

    1. To override the default provider configuration. For example, the default configuration may be to deploy resources in the "us-east-1" region. If the requirement is to deploy resources in a different region, we can use the provider argument to override the default.

    2. In some cases, a configuration may need to use multiple versions of the same provider. For example - a resource that deploys to the "us-east-1" and another resource within the same configuration that deploys to the "us-west-2" region.

    Documentation Link: https://www.terraform.io/docs/language/meta-arguments/module-providers.html#when-to-specify-providers


    MCQ Version Constraints aliases

    1. Which of the following are valid when using version constraints with a provider?

    • Use of comparison operators
    • All of the above
    • Combining comparison operations to use a specific version within a range
    • Using the ~> operator
    • Using pessimistic operator
    • Using the "!=" operator

    Correct answer:

    • All of the above

    Documentation Link: https://www.terraform.io/docs/language/expressions/version-constraints.html

    2. Which block is used to configure settings related to Terraform itself?

    • terraform
    • source
    • providers
    • resource

    Correct answer:

    • terraform

    Documentation Link: https://www.terraform.io/docs/language/settings/index.html

    3. Providers use a ______-based architecture that is available for most infrastructure platforms within the public Terraform registry.

    • plugin
    • module
    • platform
    • software
    • infrastructure

    Correct answer:

    • plugin

    Documentation Link: https://www.terraform.io/docs/extend/how-terraform-works.html

    4. A version constraint is a string literal containing one or more conditions, which are separated by commas. True or False?

    • True
    • False

    Correct answer:

    • True

    Documentation Link: https://www.terraform.io/docs/language/expressions/version-constraints.html#version-constraint-syntax

    5. Which among the following is not a valid operator in terraform version constraints:

    • =
    • !=
    • <=
    • >=
    • ==

    Correct answer:

    • ==

    Documentation Link: https://www.terraform.io/docs/language/expressions/version-constraints.html#version-constraint-syntax

    6. Which "terraform command" from the following downloads the latest version of the provider plugins?

    • terraform plan
    • terraform init
    • terraform apply
    • terraform pull

    Correct answer:

    • terraform init

    Documentation Link: https://www.terraform.io/docs/cli/commands/init.html

    7. Where can we make use of version constraints?

    • a. Modules
    • b. Provider requirements
    • c. The required_version setting in the terraform block
    • d. All of the above

    Correct answer:

    • d. All of the above

    Explaination: Version constraints can be used anywhere terraform allows us to specify versions. Most commonly they can be set at:

    1. Within the provider version configuration (Inside the required_providers block nested inside the terraform block)
    2. The "required_version" argument which is used to set the version of Terraform to use.
    3. Within modules. This is where we specify the version of module to be used.

    Documentation Link: https://www.terraform.io/docs/language/expressions/version-constraints.html

    8. Your team assigned you the task of developing a terraform configuration to provision a bunch of services on GCP. You did everything to the point but forgot to mention the provider's version in the terraform block. What default behavior would you expect from terraform:

    • a. Terraform init will fail
    • b. Terraform will download and use the latest version of providers used in the configuration
    • c. Terraform init will succeed but an apply will fail because of unsupported provider versions
    • d. None of the above
    • e. All of the above

    Correct answer:

    • b. Terraform will download and use the latest version of providers used in the configuration

    Explaination: Terraform will download the latest version for all the providers used within the configuration. The version downloaded may or may not work well with the configuration developed.


    Lab MCQ Variables

    1. A variable block is given below. Inspect it and choose the valid options.

    • Invalid. We cannot use "providers" as a variable name
    • Valid. The "default" argument is optional
    • Invalid. "default" argument is not used
    • Invalid. Incorrect "type" used

    Correct answer:

    • Invalid. We cannot use "providers" as a variable name

    Code: variable "providers" { type = string }

    Explaination: We can use any name for a variable except for: source, version, providers, count, for_each, lifecycle, depends_on and locals.

    We have used the variable name as "providers". This is not a valid identifier

    Documentation Link: https://www.terraform.io/docs/language/values/variables.html#declaring-an-input-variable

    2. Inspect the below code and choose expected behavior when you run a terraform plan or apply:

    • user will be prompted to enter a value for the variable "is_this_correct"
    • Terraform plan or apply will work as is
    • Error response as the "default" argument is not used
    • Error as the variable block is incorrect

    Correct answer:

    • user will be prompted to enter a value for the variable "is_this_correct"

    Code: variable "is_this_correct" { }

    Explaination: The given variable block is valid. However, since we have not supplied the default value for the variable, the user will be prompted to enter it when running terraform plan or apply.

    3. The label after the variable keyword should be unique among all variables.

    • a. Should be unique among the variables in the same module
    • b.You can create just two variables of the same label
    • Both the statements (a) and (b) are true
    • None of the above

    Correct answer:

    • a. Should be unique among the variables in the same module

    Explaination: A variable name or a label must be unique within the same module or configuration.

    Documentation Link: https://www.terraform.io/docs/language/values/variables.html#declaring-an-input-variable

    4. If both the "type" and the "default" argument are specified inside the variable block, the given default value must be convertible to the specified type. True or False?

    • True
    • False

    Correct answer:

    • True

    Explaination: For example consider the following variable block:

    variable "max_number" { type = number default = "100" }

    Here, the type is a "number" however, the default value is expressed as a string since it is enclosed in double-quotes. In this case, terraform will convert the value to a number by default.

    However, the following variable declaration is invalid:

    variable "istrue" { type = bool default = 1 }

    Here the default value is a number but the type is "boolean". Terraform cannot convert a number to a boolean.

    5. Each output value exported by a module must be declared using an ______ block.

    • output
    • input
    • variable
    • resource
    • data

    Correct answer:

    • output

    Documentation Link: https://www.terraform.io/docs/language/values/outputs.html#declaring-an-output-value

    6. Which keyword is reserved for declaring variables in the terraform configuration files?

    • variable
    • var
    • Use the syntax var.<variable_name>
    • variable block does not need a keyword
    • user-defined keyword

    Correct answer:

    • variable

    Explaination: The variable block begins with the "variable" keyword followed by a user defined name/label for the variable.

    Documentation Link: https://www.terraform.io/docs/language/values/variables.html#declaring-an-input-variable

    7. We just created an environment variable named “TF_VAR_content=foo-3” and ran the following command: terraform apply -var "content=foo-4" .Determine the content of file foo.txt

    • foo-4
    • foo-3
    • foo
    • foo-1

    Correct answer:

    • foo-4

    Code: resource "local_file" "foo" { content = var.content filename = “/random/foo.txt” }

    variable "content" { type = string description = "Content of the file to be created"

    validation { condition = substr(var.content, 0, 4) == "foo-" error_message = "The content value must be a valid word starting "foo-"." } }

    Explaination: The variables passed with the -var or -var-file command line flags have the highest priority and will take precedence over environment variables. As such, the file will be created with "foo-4" as the content.

    Documentation Link: https://www.terraform.io/docs/language/values/variables.html#variable-definition-precedence

    8. What is the expected outcome of a 'terraform apply -var "content=random-string"' using the below configuration?

    • File “foo.txt” with content “random-string” will be created.
    • It will throw an error as we have a custom validation rule before the variable declaration.
    • Wrong declaration of variable
    • Operation will fail as the variable used does not match the validation rule

    Correct answer:

    • Operation will fail as the variable used does not match the validation rule

    Code: resource "local_file" "foo" { content = var.content filename = “/random/foo.txt” }

    variable "content" { type = string description = "Content of the file to be created"

    validation { condition = substr(var.content, 0, 4) == "foo-" error_message = "The content value must be a valid word starting "foo-"." } }

    Explaination: The validation rule used with the variable called "content" expects the value to start with "foo=". Since this does not match the value we supplied with the -var flag (random-string), the operation will fail.

    Sample output:


    iac-server $ terraform apply -var "content=random-string"

    Error: Invalid value for variable

    on variables.tf line 6: 6: variable "content" {

    The content value must be a valid word starting "foo-".

    This was checked by the validation rule at variables.tf:10,3-13.

    9. Which of the following statements are true regarding output variables?

    • Running terraform plan will not render outputs
    • None of the above
    • Running the "terraform apply" will render the output variables defined
    • Running the "terraform plan" will render the output variables defined
    • Running the "terraform apply" will not render the output variables defined
    • Running the "terraform output" will render the output variables defined

    Correct answer:

    • Running terraform plan will not render outputs
    • Running the "terraform apply" will render the output variables defined
    • Running the "terraform output" will render the output variables defined

    Documentation Link: https://www.terraform.io/docs/language/values/outputs.html#declaring-an-output-value

    10. Select the optional arguments that are available for the output block.

    • description
    • sensitive
    • depends_on
    • All of the above

    Correct answer:

    • All of the above

    Documentation Link: https://www.terraform.io/docs/language/values/outputs.html#optional-arguments


    Lab MCQ Resource Attributes and Deps

    1. Which option best describes the meaning of interpolation syntax?

    • A way to reference variables, attributes of resources, and call functions
    • A way to declare values to variables
    • A way to provide runtime options with terraform operations
    • None of the above

    Correct answer:

    • A way to reference variables, attributes of resources, and call functions

    Explaination: Interpolation syntax allows us to reference variables, resource attributes and even make use of built-in functions in terraform.

    Documentation Link: https://www.terraform.io/docs/language/expressions/strings.html#interpolation

    2. Which among the following best explains the need of the dependency concept in terraform?

    • Terraform functions error-free even without the notion of dependency
    • Allows resources to be created in the correct order
    • Allows resources to be destroyed in the correct order
    • Allows resources to be created and destroyed in the correct order

    Correct answer:

    • Allows resources to be created and destroyed in the correct order

    3. Inspect the below code block and determine the resource attribute that creates a dependency between the given resources.

    • aws_subnet.cidr_block
    • aws_vpc.cidr_block
    • aws_vpc.backend-vpc.id
    • aws_vpc.backend_vpc.cidr_block
    • aws_subnet.private-subnet1.cidr_block

    Correct answer:

    • aws_vpc.backend-vpc.id

    Code: resource "aws_vpc" "backend-vpc" { cidr_block = "10.0.0.0/16" tags = { Name = "backend-vpc" } } resource "aws_subnet" "private-subnet1" { vpc_id = aws_vpc.backend-vpc.id cidr_block = "10.0.2.0/24" tags = { Name = "private-subnet1" } }

    Explaination: The aws_subnet type resource called private-subnet1 makes use of the resource attribute "aws_vpc.backend-vpc.id".

    4. Which meta-argument is used when Terraform cannot infer dependencies between different parts of your infrastructure?

    • depend_on
    • depends_on
    • depends-on
    • depend-on
    • resource attribute reference

    Correct answer:

    • depends_on

    Documentation Link: https://www.terraform.io/docs/language/meta-arguments/depends_on.html

    5. What is the generic way to reference attributes within the terraform expression?

    • None of the above
    • RESOURCE_TYPE.ATTRIBUTE.NAME
    • RESOURCE_TYPE.NAME.ATTRIBUTE
    • RESOURCE_TYPE.NAME

    Correct answer:

    • RESOURCE_TYPE.NAME.ATTRIBUTE

    Documentation Link: https://www.terraform.io/docs/language/expressions/references.html#resources

    6. Terraform resources and data sources make all of their arguments available as readable attributes, and also typically export additional read-only attributes. True or False?

    • True
    • False

    Correct answer:

    • True

    Explaination: Both resources and datasources export arguments as readable attributes.

    Documentation Link: https://www.terraform.io/docs/language/expressions/references.html#references-to-resource-attributes


    Lab MCQ Datasources

    1. We have a local file resource with certain content. Once this resource is provisioned, the file is created in the /root directory and the information about this file is also stored in the Terraform state file. Now let's create a new file using a simple shell script in the same directory /root. Quite evidently, this file is outside the control and management of Terraform at this point in time. How would you include the second file in your Terraform configuration?

    • By creating a resource type object inside the main.tf file.
    • By creating a data type object inside the main.tf file
    • Terraform automatically syncs the files under the same directory
    • Terraform doesn't provide such functionality

    Correct answer:

    • By creating a data type object inside the main.tf file

    2. Which of the following statements is true for the terraform data block?

    • Reads data provisioned using other tools, such as Puppet, CloudFormation , SaltStack, Ansible etc
    • Reads data provisioned using ad-hoc scripts as well as and manually provisioned infrastructure
    • All of the above
    • Reads resources created by terraform by other configuration directories.

    Correct answer:

    • All of the above

    3. Why does terraform incorporate the concept of data sources?

    • It allows Terraform to read attributes from resources which are provisioned within its control
    • It allows Terraform to read attributes from resources which are provisioned outside its control.
    • It allows Terraform to import attributes from resources provisioned using ad-hoc scripts only
    • All of the above

    Correct answer:

    • It allows Terraform to read attributes from resources which are provisioned outside its control.

    4. Choose the suitable options that best describe the data source block

    • It only creates the Infrastructure objects
    • It only updates the Infrastructure objects
    • It only destroys the Infrastructure objects
    • It only reads the Infrastructure objects

    Correct answer:

    • It only reads the Infrastructure objects

    5. The data read from a data source is available under the "______ object" in Terraform.

    • data
    • resource
    • terraform
    • local

    Correct answer:

    • data

    6. The behavior of __________ data sources is the same as all other data sources, but their result data exists only temporarily during a Terraform operation, and is re-calculated each time a new plan is created.

    • remote-only
    • local-only
    • Both
    • None

    Correct answer:

    • local-only

    7. Each data source in turn belongs to a provider.

    • True
    • False

    Correct answer:

    • True

    8. Data resources have the different dependency resolution behavior as defined for managed resources

    • True
    • False

    Correct answer:

    • False

    9. A data source can be created using the data block.

    • True
    • False

    Correct answer:

    • True

    10. When a module has multiple configurations for the same provider, which meta-argument can you use to specify the configuration?

    • provider
    • providers
    • specific_provider
    • None

    Correct answer:

    • providers

    11. What is the form of the reference expression used for the data block?

    • data.[NAME].[TYPE].[ATTRIBUTE]
    • data.[TYPE].[NAME]
    • data.[TYPE].[NAME].[ATTRIBUTE]
    • [TYPE].[NAME].[ATTRIBUTE]

    Correct answer:

    • data.[TYPE].[NAME].[ATTRIBUTE]

    12. Choose the meta-argument which is not supported by the data block.

    • depends_on
    • count
    • for_each
    • provider
    • lifecycle

    Correct answer:

    • lifecycle

    Lab MCQ Terraform State

    1. Unlike the configuration files, why it's not a good idea to store the state file in a version control system?

    • It would mostly contain sensitive information pertaining to our infrastructure
    • Version control systems such as GitHub do not support state locking
    • Very difficult to maintain the integrity of the state file
    • All of the above.

    Correct answer:

    • All of the above.

    2. What purpose does the terraform.tfstate file serve?

    • map real world resources to your configuration
    • keep track of metadata
    • to improve performance for large infrastructures
    • All of the above

    Correct answer:

    • All of the above

    3. How does Terraform protect itself where concurrent operations are run against the same configuration?

    • Users need to take precautions
    • Terraform does it automatically with no additional configuration
    • It uses the concept of state-locking for all backends
    • Terraform will lock your state for all operations that could write state, if supported by your backend

    Correct answer:

    • Terraform will lock your state for all operations that could write state, if supported by your backend

    4. Areas of Terraform's behavior that are not determined by the backend:

    • Where state is stored
    • Where operations are performed
    • Both
    • None

    Correct answer:

    • None

    5. Name the file that is created by default when you run the terraform apply command for the first time

    • terraform.state
    • state.tf
    • terraform.tf
    • terraform.tfstate

    Correct answer:

    • terraform.tfstate

    6. What steps are needed in order to change the backend in terraform? For instance : local to remote

    • Adding a terraform block only, would be enough
    • Add a backend block within a terraform block
    • Specifying the backend block within the terraform block is followed by reinitialization of the backend using terraform init.
    • Any one of the options is enough.

    Correct answer:

    • Specifying the backend block within the terraform block is followed by reinitialization of the backend using terraform init.

    7. Which option can be used to disable the state locking for most commands?

    • -state-lock
    • -lock=yes
    • -lock
    • -locked

    Correct answer:

    • -lock

    8. You wanted to play with terraform to check what it has to offer. After a while you remembered that you didn’t specify any configuration for the backend. What default behaviour is expected here of terraform?

    • Terraform will use a local backend, which requires no configuration
    • Terraform will use a remote backend, which requires no configuration.
    • Terraform will randomly use a backend from a pool of local or remote ones
    • None of the above

    Correct answer:

    • Terraform will use a local backend, which requires no configuration

    9. A requirement has come up which requires you to inspect the state file of terraform configuration. Your terraform script is already configured to work with the remote backend. Which of the following commands would you use to view a specific field in the state file

    • terraform state mv
    • terraform state list
    • terraform state show
    • terraform state pull

    Correct answer:

    • terraform state pull

    10. Choose the appropriate option which lists all the resources recorded within the Terraform state file

    • state mv
    • state list
    • state show
    • state pull

    Correct answer:

    • state list

    11. What are the steps required to remove a resource from the management of terraform?

    • Use terraform rm command
    • Use the terraform state rm command followed by manual removal of corresponding resources from the configuration file as well
    • Remove the corresponding resource from the configuration file
    • All are true under certain case-scenarios
    • None of the options are correct

    Correct answer:

    • Use the terraform state rm command followed by manual removal of corresponding resources from the configuration file as well

    12. Which of the following is not the valid sub-command of terraform state command?

    • state mv
    • state list
    • state show
    • state pull
    • state rm
    • state replace

    Correct answer:

    • state replace

    13. Which of the following terraform state sub-commands list detailed information about a resource from the state file?

    • mv
    • list
    • show
    • pull

    Correct answer:

    • show

    Lab MCQ Terraform Commands

    1. Which command can be used to create a visual representation of our terraform resources?

    • terraform view
    • terraform console
    • terraform map
    • terraform graph

    Correct answer:

    • terraform graph

    2. Your friend was working on a terraform project but he is unable to execute the terraform apply command successfully. As having experience in automation he asks you for help. On further investigation he reported that he already initialized the directory and also ran terraform validate command. Even terraform plan also ran with no errors. What could be at fault here?

    • This is because the terraform validate command only carries out a general verification of the configuration.
    • There could be some issue with the value that arguments expect for a specific resource.
    • He just found a new bug in terraform
    • All the statements are true except the bug one.

    Correct answer:

    • All the statements are true except the bug one.

    3. terraform plan and terraform apply both refresh the state before their execution. Which option could be used to disable this default behaviour?

    • -refresh=disable
    • -refresh=no
    • -refresh=false
    • -no-refresh=true

    Correct answer:

    • -refresh=false

    4. Two teams are working on a single terraform project that concerns the provisioning of various services on the AWS cloud platform. Your team just handed over the remaining last bits of the project that needs to be cross-checked. While going through the configuration files you want to look if they consist of any syntax discrepancies and fix some indentation issues that are hampering the readability of files. Select from the following that can solve the issue at hand:

    • terraform validate to check for syntax errors and terraform fmt to convert code to canonical format.
    • terraform check to check for syntax errors and terraform format to convert code for better readability.
    • terraform plan will validate any errors as well as format the code before creating the execution plan.
    • It’s better to go through each line and check yourself than to trust terraform binaries.

    Correct answer:

    • terraform validate to check for syntax errors and terraform fmt to convert code to canonical format.

    5. The terraform providers ______ command can automatically populate a directory that will be used as a local filesystem mirror in the provider installation configuration.

    • mirror
    • populate
    • download
    • pull

    Correct answer:

    • mirror

    6. Is it necessary to initialize the terraform configuration directory prior to execution of terraform validate.

    • True
    • False

    Correct answer:

    • True

    7. Choose the valid subcommand for terraform providers :

    • terraform providers mirror
    • terraform providers lock
    • terraform providers schema
    • All the above are correct

    Correct answer:

    • All the above are correct

    8. You are working in collaboration with your team on some project involving automation using terraform. One of the team members modified a resource on the real cloud infrastructure on the azure platform. You want those resources to be reflected in your local machine. Which of the following would you go with:

    • terraform refresh as it modifies the state as well as the configuration files in the local configuration directory.
    • terraform refresh as it only modifies the state file on your local machine.
    • It is best to ask for the changes made by the developer directly.
    • There is no need to do anything as the state files are synced at regular intervals of 15 minute.

    Correct answer:

    • terraform refresh as it only modifies the state file on your local machine.

    9. Every terraform command listed is useful for inspecting infrastructure:- output, graph, show, state list, state show

    • True
    • False

    Correct answer:

    • True

    10. The terraform graph command is used to generate a visual representation in which format?

    • YAML
    • JSON
    • TOML
    • DOT

    Correct answer:

    • DOT

    11. Applying a Terraform configuration will:

    • Create resources that exist in the configuration but are not associated with a real infrastructure object in the state
    • Destroy resources that exist in the state but no longer exist in the configuration.
    • Update in-place resources whose arguments have changed
    • Destroy and re-create resources whose arguments have changed but which cannot be updated in-place due to remote API limitations
    • All of the above

    Correct answer:

    • All of the above

    Lab MCQ Terraform Taint and Logging

    1. Which environment variable should be used to export the logs to a specific path?

    • TF_LOG
    • var.TF_LOG
    • VAR_TF_LOG
    • TF_LOG_PATH

    Correct answer:

    • TF_LOG_PATH

    2. Can you export the debug logs from terraform only by setting the TF_LOG_PATH environment variable?

    • True
    • False

    Correct answer:

    • False

    3. Which Log Level provides the most details when you run terraform commands?

    • LOG_LEVEL=5
    • --v=5
    • WARN
    • ERROR
    • TRACE

    Correct answer:

    • TRACE

    4. Your team is working collaboratively on a project that uses terraform scripts heavily. In your team one team member was not familiar with terraform, so he was making the required changes manually, using the GUI console of that specific cloud provider on the resources provisioned using terraform. Since these unmanaged changes are hampering the efficiency of the team , you want to revert these changes. How would you go about doing this?

    • Manually remove these resources using the same GUI console used to provision it
    • Use terraform destroy and then terraform apply commands in this specific order
    • You will taint the resources that you want removed on the next terraform apply.
    • All of the above

    Correct answer:

    • Use terraform destroy and then terraform apply commands in this specific order
    • You will taint the resources that you want removed on the next terraform apply.

    5. The terraform ______command informs Terraform that a particular object has become degraded or damaged.

    • taint
    • mark
    • hold
    • None of the above

    Correct answer:

    • taint

    6. How would you achieve the force replacement of a particular object even though there are no configuration changes? Choose the most appropriate option among the following:

    • There is no function in the terraform
    • Using option -replace with terraform apply command
    • Using terraform taint is the only way possible
    • Usage of terraform apply -replace=”<resource_name>” is preferred over terraform taint`
    • None of the above

    Correct answer:

    • Usage of terraform apply -replace=”<resource_name>” is preferred over terraform taint`

    Documentation Link: https://www.terraform.io/docs/cli/commands/taint.html

    7. Choose the invalid log level values for the TF_LOG environment variable.

    • DEBUG
    • INFO
    • WARN
    • ERROR
    • JSON
    • None of the above

    Correct answer:

    • None of the above

    Explaination: You can set TF_LOG to one of the log levels (in order of decreasing verbosity) TRACE, DEBUG, INFO, WARN or ERROR to change the verbosity of the logs. Also if we set TF_LOG to JSON, it output logs at the TRACE level or higher, and uses a parseable JSON encoding as the formatting.

    8. Which environment variable is exported to set a different log level in the terraform?

    • TF_LOG
    • var.TF_LOG
    • VAR_TF_LOG
    • TF_LOG_PATH

    Correct answer:

    • TF_LOG

    Lab MCQ import and workspaces

    1. When we start off and create a configuration in terraform, what is the workspace that is created, to begin with?

    • local
    • remote
    • default
    • cloud

    Correct answer:

    • default

    2. Choose the statement among the following that terraform workspace deals with:

    • Maintaining separate cache of plugins and modules for each working directory
    • Maintaining multiple directories can waste bandwidth and disk space.
    • Update your configuration code from version control separately for each directory
    • Reinitialize each directory separately when changing the configuration
    • All of the above

    Correct answer:

    • All of the above

    3. You can use ________ to manage multiple non-overlapping groups of resources with the same configuration.

    • workspaces
    • Modules
    • Multiple State files
    • None of the options

    Correct answer:

    • workspaces

    4. Every initialized working directory has at least one workspace.

    • True
    • False

    Correct answer:

    • True

    5. For a given working directory, how many workspaces can be selected at a time?

    • One
    • Two
    • Three
    • Depends on user preference

    Correct answer:

    • One

    6. We can delete the default terraform workspace.

    • True
    • False

    Correct answer:

    • False

    7. Select the invalid subcommand for terraform workspace among the following:

    • list
    • new
    • rename
    • show
    • delete
    • select

    Correct answer:

    • rename

    8. Within your Terraform configuration, how can you include the name of the current workspace.

    • Using ${workspace} interpolation sequence
    • Using ${workspace.workspace_name} interpolation sequence
    • Using ${terraform.workspace} interpolation sequence
    • None of the above

    Correct answer:

    • Using ${terraform.workspace} interpolation sequence

    9. A developer working on a complex set of infrastructure changes needs to freely experiment with changes without affecting the default workspace. How can he achieve that?

    • Create a new temporary workspace
    • Create a new terraform configuration directory with the same configuration files
    • No option but to use the default workspace
    • Using temporary workspace is preferred over duplication of configuration files.

    Correct answer:

    • Using temporary workspace is preferred over duplication of configuration files.

    10. The example below will import an AWS instance into the aws_instance resource named bar into a module named foo.

    • True
    • False

    Correct answer:

    • True

    Code: terraform import module.foo.aws_instance.bar i-abcd1234

    11. For local state, Terraform stores the workspace states in a directory called :

    • terraform.tfstate
    • terraform.tfstate.d
    • tfstate.d
    • None of the above

    Correct answer:

    • terraform.tfstate.d

    12. Command used to import existing resources into Terraform

    • terraform pull
    • terraform state pull
    • terraform import
    • terraform imports

    Correct answer:

    • terraform import

    13. What is the usage pattern of the terraform import command?

    • terraform import [options] ADDRESS ID
    • terraform import [options] ID ADDRESS
    • terraform import [options] ADDRESS
    • Any one of the above statement could be used

    Correct answer:

    • terraform import [options] ADDRESS ID

    14. What ways do you have to bring resources created by other methods into terraform?

    • Use data sources
    • Use terraform import
    • Updating terraform configuration only
    • All of the above

    Correct answer:

    • Use data sources
    • Use terraform import

    15. Select the statements valid for data sources and the terraform import command?

    • Data sources help us to make use of the attributes of the data source that is not managed by Terraform at this stage.
    • Terraform import brings a resource completely in the management and control of Terraform
    • Data sources and terraform import command both satisfy the same goal
    • None of the above

    Correct answer:

    • Data sources help us to make use of the attributes of the data source that is not managed by Terraform at this stage.
    • Terraform import brings a resource completely in the management and control of Terraform

    16. Choose the correct options from the following:

    • Terraform import updates the configuration files as well as updates the state file with the details of the infrastructure being imported
    • Terraform import does not update the configuration files at all, only updates the state file with the details of the infrastructure being imported.
    • Terraform import only updates the configuration files and doesn't touch the state file at all.
    • None of the above

    Correct answer:

    • Terraform import does not update the configuration files at all, only updates the state file with the details of the infrastructure being imported.

    17. You intend to import two resources to your terraform configuration. You executed only the terraform import command until now and it worked. Will the terraform apply work if executed now?

    • It will throw an error
    • Works like a charm
    • We haven’t updated the resource with correct argument values yet
    • None of the options

    Correct answer:

    • It will throw an error
    • We haven’t updated the resource with correct argument values yet

    Lab MCQ Terraform Modules

    1. Select the sources that terraform can load modules from.

    • Local relative paths
    • Remote repositories
    • Both
    • None of the above

    Correct answer:

    • Both

    2. Modules can be used to create lightweight abstractions, so that you can describe your infrastructure in terms of its architecture, rather than directly in terms of physical objects.

    • True
    • False

    Correct answer:

    • True

    3. What is a root module?

    • The terraform configuration directory under /root/ is called root module.
    • The current terraform configuration directory consisting of .tf files forms the root module.
    • Both
    • None of the above

    Correct answer:

    • The current terraform configuration directory consisting of .tf files forms the root module.

    4. Which module can call other modules and connect them together by passing output values from one as input values to another.

    • root
    • child
    • default
    • provider

    Correct answer:

    • root

    5. Modules can also call other modules using a _________ block

    • modules
    • module
    • Only the root module can call other modules
    • None of the above

    Correct answer:

    • module

    6. When we introduce _______ blocks, our configuration becomes hierarchical rather than flat.

    • module
    • root module
    • child module
    • None of the above

    Correct answer:

    • module

    7. What do we call this flat type of module usage:

    • module composition
    • dependency inversion
    • module gathering
    • None of the above

    Correct answer:

    • module composition

    Code: module "network" { source = "./modules/aws-network" ... }

    module "consul_cluster" { source = "./modules/aws-consul-cluster" ... }

    8. What are some of the problems that terraform module addresses?

    • Complex configuration files
    • Duplicate code
    • Increased risk. (like updating the resource)
    • Limitation on reusability
    • All of the above

    Correct answer:

    • All of the above

    9. Select the types of terraform modules based on the credibility tier.

    • Verified
    • Non-verified
    • Official
    • Community

    Correct answer:

    • Verified
    • Community
    • Official

    10. Choose the ways available to download the module in your current terraform configuration directory.

    • terraform init
    • terraform get
    • terraform pull
    • terraform module pull

    Correct answer:

    • terraform init
    • terraform get

    11. Not specifying any version leads to what kind of behaviour of terraform.

    • It downloads the latest version available for that module.
    • Throws an error
    • We can specify the version along with the source argument. No extra arguments are needed
    • None of the above

    Correct answer:

    • It downloads the latest version available for that module.

    Lab MCQ Loops

    1. Resources using the for_each appear as a ______ of objects when used in expressions.

    • map

    Correct answer:

    • map

    2. Which of the following combinations of meta-arguments are correct.

    • depends_on, lifecycles, count, for_each
    • depend_on, lifecycles, count, for_each
    • depend_on, lifecycle, count, for-each
    • depends_on, lifecycle, count, for_each

    Correct answer:

    • depends_on, lifecycle, count, for_each

    3. What is the difference between for and for_each meta-argument

    • for provisions similar resources in module and resource blocks whereas for_each creates a list or map by iterating over a collection, such as another list or map.
    • for_each provisions similar resources in module and resource blocks whereas for creates a list or map by iterating over a collection, such as another list or map.
    • for_each and for both provide the same functionality in terraform
    • There is no meta-argument named for in terraform.

    Correct answer:

    • for_each provisions similar resources in module and resource blocks whereas for creates a list or map by iterating over a collection, such as another list or map.

    4. A given resource or module block cannot use both count and for_each simultaneously.

    • True
    • False

    Correct answer:

    • True

    5. Choose the correct option that best represents the meaning of count keyword:

    • Create resources in the format of a list, each identified by its index
    • Create resources in the format of a map.
    • Both are true under certain conditions
    • None of the options

    Correct answer:

    • Create resources in the format of a list, each identified by its index

    6. What are the characteristics of infrastructure objects created using for_each meta-argument when the configuration is applied:

    • Each is separately created
    • Each is separately updated
    • Each is separately destroyed
    • All of the above

    Correct answer:

    • All of the above

    7. Choose the meta-arguments specific to loops in terraform

    • for
    • for_each
    • count
    • All of the above

    Correct answer:

    • All of the above

    8. The for_each meta-argument accepts:

    • map
    • set of strings
    • list of strings
    • Only alphanumeric characters

    Correct answer:

    • map
    • set of strings

    9. Which built-in function can be used in the count meta-argument to dynamically determine the size of the variable.

    • length()
    • sizeof()
    • len()
    • size()

    Correct answer:

    • length()

    10. In blocks where for_each is set, an additional _____ object is available in expressions, so you can modify the configuration of each instance.

    • each
    • item
    • value
    • key

    Correct answer:

    • each

    11. for_each value must be known before Terraform performs any remote resource actions.

    • True
    • False

    Correct answer:

    • True

    Lab MCQ Provisioners

    1. Provisioners should only be considered as a Last Resort.

    • True
    • False

    Correct answer:

    • True

    2. Expressions in provisioner blocks cannot refer to their parent resource by name. They can use special _______ objects.

    • self
    • Only the name of the resource without specifying its type
    • There is no such special object
    • None of the above

    Correct answer:

    • self

    3. Fill the blank with the suitable choice:

    • destroy
    • create
    • apply
    • plan

    Correct answer:

    • destroy

    Code: resource "aws_instance" "web" {

    ...

    provisioner "local-exec" { when = ________ command = "echo 'Destroy-time provisioner'" } }

    4. By default, provisioners that fail will also cause the Terraform apply itself to fail, which argument can we use to change this behaviour?

    • on_failure
    • fail
    • failure_status
    • None of the above

    Correct answer:

    • on_failure

    5. Which statement best explains terraform provisioners?

    • used to model specific actions only on the local machine
    • used to model specific actions only on the remote machine
    • used to model specific actions on the local machine or on a remote machine
    • None of the above

    Correct answer:

    • used to model specific actions on the local machine or on a remote machine

    6. Which of the following provisioners does not need a connection block defined?

    • local-exec
    • remote-exec
    • Both
    • None

    Correct answer:

    • local-exec

    7. What are the possible consequences of making heavy usage of provisioners within your terraform script?

    • Add a considerable amount of complexity and uncertainty to Terraform usage
    • Terraform cannot model the actions of provisioners as part of a plan
    • Use of provisioners requires coordinating many more details than Terraform usage usually requires
    • All of the options

    Correct answer:

    • All of the options

    8. Where should you add a provisioner block?

    • Nested block inside the resource block
    • Outside the resource block
    • Nested block inside the provider block
    • Inside the terraform block

    Correct answer:

    • Nested block inside the resource block

    9. What are the valid values available for argument on_failure:

    • continue
    • true
    • fail
    • false

    Correct answer:

    • continue
    • fail

    10. Which keyword is used for provisioner utilization within terraform script?

    • provision
    • provisioner
    • provider
    • terraform

    Correct answer:

    • provisioner

    11. Select the types of provisioners available:

    • local-exec
    • remote-exec
    • file
    • all of the above

    Correct answer:

    • all of the above

    12. What happens when provisioners fail to execute successfully?

    • Terraform will taint the resource that will be replaced on the next run
    • Resources will be created but without the changes mentioned in the provisioner block
    • It will show an error message showing the user to taint the resource manually
    • None of the above

    Correct answer:

    • Terraform will taint the resource that will be replaced on the next run

    13. How can you invoke the provisioner at the time when resources get destroyed?

    • using when = destroy within the provisioner block
    • Provisioners are invoked by default when resources are destroyed
    • using invoke = destroy within the provisioner block
    • None of the above

    Correct answer:

    • using when = destroy within the provisioner block

    Lab MCQ Lifecycle Rules

    1. Configuration _____ is the possibility that each of the servers vary from one another maybe in software, or configuration, or operating system etc.

    • Drift
    • shift
    • change
    • None of the above

    Correct answer:

    • Drift

    2. What are the common issues that come with configuration drift?

    • Make it difficult to plan and carry out subsequent updates.
    • Troubleshooting issues would also be a difficult task
    • All of the above
    • Can leave the infrastructure in a complex state

    Correct answer:

    • All of the above

    3. Which of the following statements is FALSE about Immutable infrastructure?

    • It doesn’t let us to execute in-place updates of the resources anymore
    • It ensures updating this way will not lead to failures
    • It takes care that infrastructure is in a simple and easy-to-understand state
    • All are true

    Correct answer:

    • It ensures updating this way will not lead to failures

    4. Select the available arguments that are available for the lifecycle meta-argument

    • create_before_destroy
    • ignore_change
    • prevent_destroy
    • ignore_changes
    • destroy_after_create

    Correct answer:

    • create_before_destroy
    • prevent_destroy
    • ignore_changes

    5. Chose the option that best describes “in-place updates”:

    • The underlying infrastructure remains the same
    • Software and configuration of operating system changes as part of the update
    • Both
    • Neither

    Correct answer:

    • Both

    6. Which argument of the lifecycle meta-argument supports a list as a value ?

    • create_before_destroy
    • ignore_changes
    • prevent_destroy
    • All the options

    Correct answer:

    • ignore_changes

    Explaination: ignore_changes (list of attribute names) - By default, Terraform detects any difference in the current settings of a real infrastructure object and plans to update the remote object to match configuration.

    7. Choose the possible scenario that the lifecycle block of the terraform resource satisfies

    • When you want the updated version of the resource to be created first before the older one is deleted.
    • When you don’t want the resource to be deleted at all.
    • Neither
    • Both

    Correct answer:

    • Both

    Lab MCQ Functions

    1. Which terraform command can be used to experiment with the behavior of Terraform's built-in functions?

    • terraform console
    • terraform validate
    • terraform check
    • terraform terminal

    Correct answer:

    • terraform console

    Explaination: This command provides an interactive command-line console for evaluating and experimenting with expressions. This is useful for testing interpolations before using them in configurations, and for interacting with any values currently saved in state.

    2. General syntax for function calls is :

    • Function name followed by comma-separated arguments in parentheses.
    • Function name followed by space-separated arguments in parentheses
    • Both
    • None

    Correct answer:

    • Function name followed by comma-separated arguments in parentheses.

    3. We cannot use the file or templatefile function to read files that our configuration might generate dynamically on disk as part of the plan or apply steps.

    • True
    • False

    Correct answer:

    • True

    Documentation Link: https://www.terraform.io/language/expressions/function-calls#when-terraform-calls-functions

    4. If the arguments for passing to a function are available in the form of list or tuple value, how would you expand that inside the function?

    • Provide the list value as an argument and follow it with the “...” symbol
    • Provide the list value as an argument and follow it with the keyword “expand”.
    • Terraform doesn’t support expanding arguments this way
    • None of the above

    Correct answer:

    • Provide the list value as an argument and follow it with the “...” symbol

    5. Choose the built-in function that returns the closest whole number that is greater than or equal to the given value:

    • ceil()
    • floor()
    • low()
    • high()

    Correct answer:

    • ceil()

    6. The Terraform language supports user-defined functions

    • True
    • False

    Correct answer:

    • False

    7. Choose the built-in function that produces a list by dividing a given string at all occurrences of a given separator:

    • split(separator, string)
    • trim(separator, string)
    • format(separator, string)
    • None of the above

    Correct answer:

    • split(separator, string)

    8. Passing an object containing a sensitive input variable to the keys() function will result in a list that is _________ .

    • Sensitive
    • Non-sensitive
    • Random output
    • None of the above.

    Correct answer:

    • Sensitive

    9. Select the correct options that produce a string by concatenating together all elements of a given list of strings with the given delimiter:

    • join(separator, list)
    • attach(separator, list)
    • concat(separator, list)
    • None of the above

    Correct answer:

    • join(separator, list)

    10. Which of the following function is no longer available in terraform:

    • map()
    • tomap()
    • zipmap()
    • None of the above

    Correct answer:

    • map()

    Documentation Link: https://www.terraform.io/language/functions/map#map-function

    11. Which of the following can be used to determine the length of a given list, map, or string.

    • length()
    • len()
    • size()
    • count()

    Correct answer:

    • length()

    Lab MCQ Dynamic Blocks

    1. Select the options that does not support dynamic block:

    • provisioner
    • provider
    • dynamic
    • data
    • resource
    • locals

    Correct answer:

    • locals

    Explaination: A dynamic block can only generate arguments that belong to the resource type, data source, provider or provisioner being configured. It is not possible to generate meta-argument blocks such as lifecycle and provisioner blocks , since Terraform must process these before it is safe to evaluate expressions.

    2. Which nested argument defines the body of each generated block under dynamic block.

    • body
    • content
    • data
    • None of the above

    Correct answer:

    • content

    3. You can dynamically construct repeatable nested blocks using which special block type:

    • dynamic
    • generate
    • local
    • None of the above

    Correct answer:

    • dynamic

    Explaination: You can dynamically construct repeatable nested blocks like setting using a special "dynamic block" type, which is supported inside "resource", "data", "provider", and "provisioner" blocks.

    4. Can we use dynamic blocks to generate meta-argument blocks such as lifecycle and provisioner blocks?

    • True
    • False

    Correct answer:

    • False

    Explaination: A dynamic block can only generate arguments that belong to the resource type, data source, provider, or provisioner being configured. It is not possible to generate meta-argument blocks such as lifecycle and provisioner blocks, since Terraform must process these before it is safe to evaluate expressions.

    5. Is it possible to declare the dynamic block inside another dynamic block?

    • Yes
    • No

    Correct answer:

    • Yes

    Explaination: Some providers define resource types that include multiple levels of blocks nested inside one another. You can generate these nested structures dynamically when necessary by nesting dynamic blocks in the content portion of other dynamic blocks.

    Documentation Link: https://developer.hashicorp.com/terraform/language/expressions/dynamic-blocks#multi-level-nested-block-structures

    6. Select the best practices around using dynamic block.

    • Use them when you need to hide details in order to build a clean user interface for a reusable module.
    • Overuse of dynamic blocks can make configuration hard to read and maintain
    • Always write nested blocks out literally where possible.
    • All of the options

    Correct answer:

    • All of the options

    Documentation Link: https://www.terraform.io/language/expressions/dynamic-blocks#best-practices-for-dynamic-blocks


    Lab MCQ Terraform Cloud

    1. Terraform Cloud is an application that helps teams use Terraform together.

    • True
    • False

    Correct answer:

    • True

    2. Which of the following is true for terraform cloud?

    • It manages Terraform runs in a consistent and reliable environment
    • It includes easy access to shared state and secret data, access controls for approving changes to infrastructure
    • It provides a private registry for sharing Terraform modules
    • It has detailed policy controls for governing the contents of Terraform configurations
    • All of the above

    Correct answer:

    • All of the above

    Documentation Link: https://learn.hashicorp.com/tutorials/terraform/cloud-sign-up?in=terraform/cloud-get-started#what-is-terraform-cloud

    3. Remote Terraform execution is sometimes referred to as "____________".

    • remote operations
    • remote workflows
    • remote pipelines
    • None of the above

    Correct answer:

    • remote operations

    4. By default terraform cloud runs terraform on:

    • its own cloud infrastructure
    • on your own isolated, private, or on-premises infrastructure
    • You need to specify each time you run terraform commands
    • None of the above

    Correct answer:

    • its own cloud infrastructure

    5. What is Sentinel?

    • Policy as code framework for HashiCorp Enterprise Products
    • Infrastructure as code framework for Terraform
    • Both
    • None of the above

    Correct answer:

    • Policy as code framework for HashiCorp Enterprise Products

    6. What concept is used by terraform cloud to manage infrastructure collections instead of directories?

    • Workspaces
    • Different accounts
    • Different repositories
    • None of the above

    Correct answer:

    • Workspaces

    7. Which of the following options doesn’t involve when using Sentinel with Terraform Cloud:

    • Defining the policies
    • Managing policies for organizations
    • Enforcing policy checks on runs
    • Mocking Sentinel Terraform data
    • None of the above.

    Correct answer:

    • None of the above.

    8. Terraform Enterprise and Terraform Cloud are the same application

    • True
    • False

    Correct answer:

    • True

    9. Is Terraform Cloud workspaces same as Terraform CLI Workspaces.

    • Yes
    • No

    Correct answer:

    • No

    10. What are the advantages of using Terraform Cloud's private registry:

    • Helps you share Terraform providers and Terraform modules across your organization
    • Includes support for versioning, a searchable list of available providers and modules
    • Includes support for a configuration designer to help you build new workspaces faster
    • All of the above

    Correct answer:

    • All of the above

    11. Which feature is used to manage how members of your organization can use modules from the terraform private registry?

    • Using IAM policies
    • Using sentinel policies
    • Terraform provides no such feature
    • None of the above

    Correct answer:

    • Using sentinel policies

    Python PCAP Mock Exam 1

    1. What does the pyc extension for Python files mean?

    A. compiled python code

    B. python interpreted code

    C. files generated each time we run our python files

    D. files generated when we import a module for the first time

    • A, D
    • B, C
    • A, C
    • B, D

    Correct answer:

    • A, D

    2. "from all.foo import bar" will import:

    • entity bar from module all from package foo
    • entity bar from module foo from package all
    • entity foo from module bar from package all
    • entity foo from module all from package bar

    Correct answer:

    • entity bar from module foo from package all

    3. What is the output of pip list?

    • a list of the installed local packages
    • a list of available pip commands
    • a list of packages available online
    • a list of recently installed packages

    Correct answer:

    • a list of the installed local packages

    4. Which of the following variables outputs the name of a python module?

    • __name__
    • __main__
    • __modulename__
    • __main_name__

    Correct answer:

    • __name__

    5. What is true of the following statements with regard to the platform module?

    A. system returns OS name

    B. version returns OS version

    C. processor returns the number of processes running on our OS

    D. version returns python version

    • A, B
    • C, D
    • A, D
    • B, C

    Correct answer:

    • A, B

    6. What is inside the __pycache__ directory?

    • pyc files created after we import a module
    • pyc files created when we run our code
    • pyc files created by the __init__ directory of a package
    • pyc files created when we run our python files

    Correct answer:

    • pyc files created after we import a module

    7. What is the output of the following snippet?

    • 0**0**
    • 0**1**, or 1**0**
    • 1**1**
    • 0**1**, or 1**0**, or 1**1**, or 0**0**

    Correct answer:

    • 0**1**, or 1**0**, or 1**1**, or 0**0**

    Code: from random import randint

    for i in range(2): print(randint(0, 1), end='**')

    8. How can we list all properties of a module?

    • dir()
    • list
    • __dir__
    • dict

    Correct answer:

    • dir()

    9. What is the output of the following code snippet?

    • 1
    • 0
    • Error
    • False

    Correct answer:

    • 1

    Code: import math

    res = math.pi != math.pow(2, 4) print(int(res))

    10. What is the correct term in the world of exceptions?

    • an exception is raised
    • an exception is thrown
    • an exception is handled

    Correct answer:

    • an exception is raised

    11. What is the output of the following code snippet:

    • d
    • f
    • b
    • 5

    Correct answer:

    • f

    Code: print(chr(ord('a') + 5))

    12. In case we have multiple exception branches in our code, which one is going to be executed?

    • As many as required in handling the various errors
    • The first matching exception branch
    • The last matching exception branch

    Correct answer:

    • The first matching exception branch

    13. What is the output of the following code snippet:

    • False
    • True

    Correct answer:

    • False

    Code: print("abcd" > "abcde")

    14. What is an alternative name to PyPi?

    • Cheese Shop
    • Spec and Eggs
    • Monty Python
    • Python shop

    Correct answer:

    • Cheese Shop

    15. The except branch without a name … :

    • should be the first branch of a try/except block
    • should be the last branch of a try/except block
    • no specific order is required for all the exception branches

    Correct answer:

    • should be the last branch of a try/except block

    16. What is true of the following statements?

    A. isalnum() is a function

    B. isalnum() is a method

    C. isalnum() returns True if a string contains alphanumeric values

    D. isalnum() returns True if a string contains only numbers

    • B, C
    • B, D
    • A, C
    • A, D

    Correct answer:

    • B, C

    17. What is the output of the following code snippet:

    • 1
    • 3
    • 2
    • 0

    Correct answer:

    • 1

    Code: print(ord('f') - ord('e'))

    18. Select the options which will return an error:

    • 'python'.rfind('')
    • 'python'.sort()
    • 'python'.index('')

    Correct answer:

    • 'python'.sort()

    19. What is the output of the following code snippet?

    • did something go wrong?
    • random takes at least one argument
    • exiting the code
    • None of these

    Correct answer:

    • None of these

    Code: import random

    try: random.random() except TypeError: print("random takes at least one argument") else: print("did something go wrong?") finally: print("exiting the code")

    20. What is the output of the following string method?

    • 'error' : error :
    • ('error',) : error :
    • error : error :
    • error, : error :

    Correct answer:

    • ('error',) : error :

    Code: try: raise Exception("error") except Exception as e: print(e.args, e.str(), sep=' : ' ,end=' : ')

    21. What is the outcome of the following code?

    • 3 (1, 2, 3)
    • TypeError: object of type 'Exception' has no len()
    • (1, 2, 3)
    • 3, 1, 2, 3

    Correct answer:

    • 3 (1, 2, 3)

    Code: try: raise Exception(1,2,3) except Exception as e: print(len(e.args), e)

    22. What is the result of the following code?

    • it will raise an error
    • alpha
    • beta

    Correct answer:

    • alpha

    Code: class Alpha: def str(self): return 'alpha'

    class Beta: def str(self): return 'beta'

    class C(Alpha, Beta): def str(self): pass

    o = C() print(o)

    23. What is the output of the following code?

    • False
    • True
    • it will raise an exception

    Correct answer:

    • it will raise an exception

    Code: class A: def init(self): pass

    a = A(1)

    24. What is the output of the following string method?

    • SyntaxError
    • True
    • False
    • TypeError

    Correct answer:

    • True

    Code: ("¾").isnumeric()

    25. What is the result of the following code?

    • 3
    • 2
    • 1
    • code is erroneous

    Correct answer:

    • 3

    Code: class A: def init(self, a = 1): self.a = a def swap(self, a): self.a *= a return a

    a = A(2) print(a.swap(a.a + 1))

    26. What is the result of the following code?

    • ee
    • e
    • an empty line

    Correct answer:

    • e

    Code: class E(Exception): def init(self,msg): Exception.init(self,msg * 2) self.args = (msg,)

    try: raise E('e') except E as e: print(e) except Exception as e: print(e)

    27. What is the result of the following code?
    a.
    A__init__(self, b)

    b.
    A__init__(self)

    c.
    super().init(b)

    d.
    super().init(a)

    • A, C
    • B, D
    • A, D
    • B, C

    Correct answer:

    • A, C

    Code: class A: def init(self, a): self.a = a

    class B(A): def init(self, b): # Put the correct line here self.b = b

    28. What is the result of the following code?

    • k
    • h
    • it will raise an error

    Correct answer:

    • h

    Code: class A: def str(self): return 'k'

    class B(A): def str(self): return 'h'

    class C(B): pass

    c = C() print(c)

    29. What is the result of the following code?

    • the code is erroneous
    • 3
    • 2
    • ValueError

    Correct answer:

    • 3

    Code: class A: A = 0 def init(self,v = 0): self.Y = v A.A += v

    a = A() b = A(1) c = A(2) print(c.A)

    30. What is the result of the following code?

    • a generator object
    • the code will raise an exception
    • 0 1 2
    • [0, 1, 2]

    Correct answer:

    • 0 1 2

    Code: def fun(): for num in range(3): yield num

    for i in fun(): print(i, end=" ")

    31. What is the result of the following code?

    • ception, unhandled exception
    • ceptionextion
    • tionextion
    • tionex

    Correct answer:

    • ceptionextion

    Code: def f(n): try: x = n / n except: print("ex",end='') else: print("cep",end='') finally: print("tion",end='')

    f(1) f(0)

    32. Which of the following statements are true?

    A.
    the map() function takes only two arguments

    B.
    the map() function may take more than two arguments

    C.
    the filter() function returns an iterator

    D.
    both map() and filter() functions' arguments order are first "iterable" then the "function"

    • B, D
    • A, C
    • B, C

    Correct answer:

    • B, C

    33. What is the result of the following code?

    • 3 5
    • 1, 7, 9
    • 5 3
    • [1. 7, 9]

    Correct answer:

    • 3 5

    Code: numbers = (1, 3, 5, 7, 9)

    def filter_nums(num): nums = (0, 5, 17, 3) if num in nums: return True else: return False

    filtered = filter(filter_nums, numbers) for num in filtered: print(num, end=" ")

    34. Which is the correct option to complete the following code?

    # output should be
    (5, 7)

    • o = tuple(filter(lambda x: x==1 and x==3, tup))
    • o = list(filter(lambda x: x>1 and x>3, tup))
    • o = tuple(filter(lambda x: x-1 and x-3, tup))
    • o = list(filter(lambda x: x-1 and x-3, tup))

    Correct answer:

    • o = tuple(filter(lambda x: x-1 and x-3, tup))

    Code: tup = (1, 3, 5, 7)

    35. What is the result of the following code?

    • b'\x00\x00'
    • 2
    • bytearray(b'\x00\x00')

    Correct answer:

    • bytearray(b'\x00\x00')

    Code: b = bytearray(2) print(b)

    36. Assuming the following code is executed, which of the following commands would delete exercises?

    • os.rmdir("./python/*")
    • os.rmdir("./exercises")
    • os.removedirs("./python/exercises")
    • None of these

    Correct answer:

    • None of these

    Code: import os

    os.mkdir('python') os.chdir('python') os.mkdir('exercises') os.chdir('exercises') f = open('f', 'w') f.close() os.chdir('../')

    37. How can we read a bytes file in Python?

    • with the function read(bytearray)
    • with the function readlines(bytearray)
    • with the function readinto(bytearray)
    • with the function readbytes()

    Correct answer:

    • with the function readinto(bytearray)

    38. How can we execute command line code from within Python?

    • os.system("ls -a")
    • os.machine("ls -a")
    • os.path("ls -a")
    • os("ls -a")

    Correct answer:

    • os.system("ls -a")

    Code: import os

    39. Which option can replace the list comprehension and return the same output?

    • foo = filter(lambda x: x % 2 == 0 [x for x in range(5)])
    • foo = map(lambda x: x % 2 == 0 [x for x in range(5)])
    • foo = map(lambda x: x % 2 == 0, [x for x in range(5)])
    • foo = filter(lambda x: x % 2 == 0, [x for x in range(5)])

    Correct answer:

    • foo = filter(lambda x: x % 2 == 0, [x for x in range(5)])

    Code: foo = (x for x in range(5) if x % 2 == 0) for i in foo: print(i)

    40. Assuming the below code has been executed:

    How should we call the closure function html() so that the output is:
    <b>Python</b>

    • html('<b>')

      html('python')
    • html('<b>')

      h = tag('python')
    • h = html('<b>')

      h('python')
    • h = html('<b>', '</b>')

      h('python')

    Correct answer:

    • h = html('<b>')

      h('python')

    Code: def html(t): t2 = t[0] + '/' + t[1:]

    def bold(str):
        return t + str.title() + t2
    return bold
    

    Python PCAP Mock Exam 2

    1. How is the python dedicated repository for libraries called?

    • PyPi
    • PyCode
    • pyRepo
    • PyLab

    Correct answer:

    • PyPi

    2. What is true of the following statements?

    • modules can contain other modules
    • modules can contain packages
    • packages can contain modules

    Correct answer:

    • packages can contain modules

    3. How do we mark a module property as private?

    A. with prefix __

    B. with prefix _

    C. #

    D. triple quotes

    • A, B
    • A, C
    • D, B

    Correct answer:

    • A, B

    4. How can we import hypot from math?

    • from math import hypot
    • import hypot from math
    • import math.hypot

    Correct answer:

    • from math import hypot

    5. What is a namespace in Python?

    • a space in which a collection of names exist
    • a space with a name
    • a collection of variables

    Correct answer:

    • a space in which a collection of names exist

    6. pip means

    • python installation of packages
    • py installation process
    • pip install packages

    Correct answer:

    • pip install packages

    7. What is the output of the following code snippet?

    • it would return one of the numbers in [0, 5, 10]
    • it would return one of the numbers in [0, 5, 10, 15]
    • it would return one of the numbers in [5, 10, 15]

    Correct answer:

    • it would return one of the numbers in [0, 5, 10]

    Code: from random import randrange

    randrange(0, 15, 5)

    8. Which of the following options return True?

    • math.trunc(5.5) > math.floor(5.5)
    • math.ceil(0.2) == math.floor(1.2)
    • math.factorial(2) == math.floor(1.8)
    • math.hypot(3,4) != math.sqrt(25)

    Correct answer:

    • math.ceil(0.2) == math.floor(1.2)

    9. What is true about the __init__ directory in Python projects?

    A. It contains info about a python package

    B. It contains code that needs to run upon the import of a package's modules

    C. It is added as a distinguisher between a package and a module directory

    D. It may be empty

    • A, B
    • B, C
    • B, C, D
    • A, B, C

    Correct answer:

    • B, C, D

    10. Which of the options can complete the following import when we want to call the function fun of module mod?

    • mod.fun
    • mod().fun()
    • mod.fun()
    • mod fun()

    Correct answer:

    • mod.fun()

    Code: import mod

    11. Which of the following statements are correct?

    A. We can only have one except branch in our try/except block

    B. We can have more than one except branch in our try/except block

    C. We can have multiple name exceptions branches as long as they have unique names

    D. We can have multiple name exceptions handling and they may have unique names

    • A, D
    • B, D
    • B, C
    • A, C

    Correct answer:

    • B, C

    12. Where should we place the code that handles an exception?

    • inside the 'except as Exception' branch
    • inside the 'try:' branch
    • inside the 'else:' branch after a try/except block
    • inside the 'finally:' branch after a try/except block

    Correct answer:

    • inside the 'except as Exception' branch

    13. The expression:

    • is True
    • is False
    • returns an error

    Correct answer:

    • is True

    Code: 'aBc' > 'ABC'

    14. ASCII stands for:

    • American Standard Code for Information Interchange
    • American Studies and Code for Information Interchanged
    • American Standard Computer for Information Intelligence
    • Asynchronous Standard Computer Information Intelligence

    Correct answer:

    • American Standard Code for Information Interchange

    15. What is the output of the following code snippet?

    • Am error
    • Arithmetics error
    • Zero error
    • TypeError

    Correct answer:

    • Arithmetics error

    Code: try: print(1/0) except ArithmeticError: print("Arithmetics error") except ZeroDivisionError: prin("Zero error") except Exception: print("An error")

    16. Which of the following exceptions are specific and are not parents to other subclass exceptions?

    A. IndexError

    B. ImportError

    C. ValueError

    D. AttributeError

    • B, C
    • A, D
    • A, B
    • B, D

    Correct answer:

    • A, D

    17. What is the output of:

    • True
    • False
    • 0
    • 1

    Correct answer:

    • False

    Code: 'Rose' > 'Roses'

    18. What is the output of the following code snippet?

    • APNUF
    • PNUF
    • FUNPPNUF
    • ANUF

    Correct answer:

    • APNUF

    Code: string = 'FUNPARK'[:5:] string = string[-1] + string[-2::-1] print(string)

    19. What is the output of the following code snippet?

    • 0
    • 1
    • 3
    • 33

    Correct answer:

    • 0

    Code: x = str(1 // 3) dummy = '' for i in x: x = x + dummy

    print(x[-1])

    20. What is the purpose of the function super() in the subclass?

    • it changes the inheritance chain
    • we can access the parent's class properties and methods when building the subclass
    • it is a convention to make our subclass inheritance more clear

    Correct answer:

    • we can access the parent's class properties and methods when building the subclass

    21. How can we check whether a class E is a subclass of A?

    • issubclass(E, A)
    • isinstance(E, A)
    • hassubclass(A, E)

    Correct answer:

    • issubclass(E, A)

    22. What is the output of the following code?

    • test exception

      RuntimeError No active exception to reraise

      AttributeError: 'RuntimeError' object has no attribute 'message'
    • test exception

      error custom exception custom message
    • test exception

      error custom exception custom message

      Done
    • test exception

      Unhanddled exception

    Correct answer:

    • test exception

      RuntimeError No active exception to reraise

      AttributeError: 'RuntimeError' object has no attribute 'message'

    Code: class E(Exception): def init(self, message): self.message = message

    def __str__(self):
        return 'custom exception'
    

    try: print('test exception') raise except BaseException as e: print('error', e, e.message) else: print('Done')

    23. Which of the following options return 18 if the code below is executed:

    class Rectangle():
            def init(self, length, width):
                    self.length = length
                    self.width = width

            def surface(self):
                    return self.length * self.width

    • A, D
    • A, B
    • B, C

    Correct answer:

    • A, B

    Code:

    | A. |

    class Cube(Rectangle): def density(self, height): surface = super().surface() return surface * height

    c = Cube(3, 2) c.density(3)


    | B. |

    class Cube(Rectangle): def init(self, height, length, width): self.height = height super().init(length, width)

    def density(self):
        surface = super().surface()
        return surface * self.height
    

    c = Cube(3, 2) c.density(3)


    | C. |

    class Cube(Rectangle): def init(self, height): self.height = height

    def density(self):
        surface = Rectangle.surface()
        return surface * self. height
    

    c = Cube(3, 2) c.density(3)


    | D. |

    class Cube(Rectangle): def init(self, height): self.height = height

    def density(self):
        surface = super.surface()
        return surface * self. height
    

    c = Cube(3, 2) c.density(3)

    24. A variable that is part of an object is called:

    • an instance variable
    • an object variable
    • a class variable

    Correct answer:

    • an instance variable

    25. What we call a stack in data structure, we can also call:

    • LIFO
    • FILO
    • There is no such thing

    Correct answer:

    • LIFO

    26. What is the result of the following code?

    • True
    • False
    • it will raise an error

    Correct answer:

    • True

    Code: class A: pass

    class B(A): pass

    class C(B): pass

    class D(C, B): pass

    print(issubclass(C,A))

    27. What is the result of the following code?

    • test

      error custom exception my message
    • test

      error custom exception my message

      done
    • test

      error E my message

    Correct answer:

    • test

      error custom exception my message

    Code: class E(Exception): def init(self, message): self.message = message

    def __str__(self):
        return 'custom exception'
    

    try: print('test') raise E('my message') except BaseException as e: print('error', e, e.message) else: print('Done')

    28. Which of the following code snippets won't raise an unhandled exception?

    • A
    • B
    • C
    • They will all raise an unhandled exception

    Correct answer:

    • B

    Code:

    | A. |

    try: x = y + 1 except NameError, SystemError: x = y + 1


    | B. |

    try: x = y + 1 except (NameError, SystemError): y = 1

    | C. |

    try: x = y + 1 except (NameError, SystemError): y = y + 1

    29. Assuming the following code is executed, which of the following options return True:

    A. 'val' in a.__dict__

    B. 'Var' in a.__dict__

    C. 'var' in A.__dict__

    D. 'Var' in A.__dict__

    • A, D
    • B, C

    Correct answer:

    • A, D

    Code: class A: Var = 1 def init(self, val) self.val = value = 2

    a = A()

    30. Which of the following statements are true?

    A. the map() function creates a copy of its iterable to apply the function argument

    B. A list comprehension can become a generator when we replace the square brackets with parentheses

    C. lambda functions cannot take more than certain number of arguments

    D. the yield keyword is interchangeable with the return keyword

    • B, D
    • A, C
    • B, A

    Correct answer:

    • B, A

    31. Assuming the code below has been executed, select the answers that won't raise a MRO error:-

    A. class Multi(A, B): pass

    B. class Multi2(C, A): pass

    C. class Multi3(D, B): pass

    D. class Multi4(B, C): pass

    • B, C
    • C, D
    • A, C
    • A, B

    Correct answer:

    • B, C

    Code: class A: pass

    class B(A): pass

    class C(B): pass

    class D(C, B): pass

    32. What is the result of the following code if "bar" exists?

    • EEXIST, short for FileExistsError
    • DEXIST, short for DirectoryExistsError
    • the bar directory will be overwritten
    • python will prompt for user's confirmation

    Correct answer:

    • EEXIST, short for FileExistsError

    Code: try: os.mkdir("foo/bar") except Exception as e: print(e.message)

    33. What is the result of the following code?

    • obr
    • fb
    • fbfbfbfbfbfb
    • obrobrobrobrobrobr

    Correct answer:

    • fb

    Code: def iter(): s = 'foobar' for letter in s[::3]: yield letter

    for i in iter(): print(i, end='')

    34. Which option can fill in the missing line?

    # result should be (1, 4, 27)

    • bar = tuple(map(lambda a: a**a, my_list))
    • bar = list(map(lambda a: a**a, my_list))
    • bar = tuple(map(lambda a: a*a, my_list))

    Correct answer:

    • bar = tuple(map(lambda a: a**a, my_list))

    Code: my_list = [1, 2, 3]

    Add line of code here

    print(bar)

    35. Which of the following statements are true?

    A. lambda functions are anonymous functions

    B. lambda functions are like other python functions

    C. lambda functions can evaluate only one expression

    D. lambda functions can take only up to two arguments

    • A, C
    • A, D
    • B, C
    • C, D

    Correct answer:

    • A, C

    36. What is the result of the following code?

    • ['.', 'file.txt', 'tmp']
    • ['file.txt', 'tmp']
    • ['tmp', 'file.txt']

    Correct answer:

    • ['file.txt', 'tmp']

    Code: import os

    os.mkdir("foo") os.chdir("foo") os.mkdir("tmp") f = open("file.txt", "w") f.close() os.listdir()

    37. How can we open a non-human readable file in Python?

    • A
    • B
    • C

    Correct answer:

    • A

    Code:

    | A. |

    f = open("bytes.jpeg", "rb") bf = bytearray(f.read(100))


    | B. |

    f = open("bytes.jpeg", "rb") bf = bytearray(f)


    | C. |

    f = open("bytes.jpeg", "r") bf = bytearray(f.read())

    38. What is the result of the following code?

    • ***
    • **
    • *
    • ****

    Correct answer:

    • ***

    Code: def foobar(p): def bar(): return '*' * p return bar

    foo = foobar(1) bar = foobar(2) print(foo() + bar())

    39. What is the result of the following code?

    • ++++++
    • ++++
    • ++
    • it will throw an error

    Correct answer:

    • ++++++

    Code: def my_fun(n): a = '+' for i in range(n): a *= 2 yield a

    for i in my_fun(2): print(i, end='')

    40. Assuming the following code is executed, which of the following statements are correct?

    A. opens the file file.txt in write mode

    B. deletes the file contents if the file file.txt already exists

    C. leaves the file contents unchanged if the file file.txt already exists

    D. creates the file file.txt if it does not exist

    E. raises the FileNotFoundError exception if the file does not exist

    • A, C, E
    • A, B, E
    • A, B, D

    Correct answer:

    • A, B, D

    Code: f = open("file.txt", "w") f.close()

    Explaination: f = open("file.txt", "w") f.close()


    Terraform Mock Exam 1

    1. What is Immutable Infrastructure?

    • Resources once deployed are not intended to be changed
    • Resources cannot be migrated to another platform
    • Any aspect of a resource can be updated in place anytime
    • Resources strictly provisioned by Terraform

    Correct answer:

    • Resources once deployed are not intended to be changed

    Explaination: Immutable infrastructure is another paradigm in which it ensures that resources are never modified after they have been deployed. If a change is to be made, a new instance of that resource will be provisioned in place of the old one.

    2. Select the file extension used by terraform configuration files.

    • .TF
    • .YAML
    • .TOML
    • .DAT
    • None of the Above

    Correct answer:

    • .TF

    3. What does “IaC” stand for?

    • Infrastructure as Code
    • Initialization as Code
    • Code as Infrastructure
    • None of the above

    Correct answer:

    • Infrastructure as Code

    Explaination: IaC stands for Infrastructure as Code.

    4. A simple terraform configuration file is given below. What is the name of the resource that will be created?

    • pet
    • local_file
    • pets.txt
    • local

    Correct answer:

    • pet

    Code: resource "local_file" "pet" {​ filename = "/root/pets.txt"​ content = "We love pets!"​ ​ }

    Explaination: The name of the resource is "pet" which is a local_file type resource.

    5. Which "terraform command" from the following downloads the latest version of the provider plugins?

    • terraform plan
    • terraform init
    • terraform apply
    • terraform pull

    Correct answer:

    • terraform init

    Documentation Link: https://www.terraform.io/docs/cli/commands/init.html

    6. Choose the correct terraform command to display the blueprint of the infrastructure to be applied.

    • terraform init
    • terraform apply
    • terraform plan
    • terraform show

    Correct answer:

    • terraform plan

    7. Observe the below code and determine the providers used.

    • Local_file and random_pet
    • Pet_name and my-pet
    • Local and random
    • Local_file, random_pet, pet_name, my-pet

    Correct answer:

    • Local and random

    Code: resource "local_file" "pet_name" { content = "We love pets!" filename = "/root/pets.txt" } resource "random_pet" "my-pet" { prefix = "Mrs" separator = "." length = "1" }

    8. Whenever the target APIs change or when new functionality is added, the provider maintainers may update new versions for a provider. This may lead to unexpected infrastructure changes. What is the best approach to overcome this?

    • Never touch what you don’t understand
    • Use required_providers block to clearly define the provider version you want to use
    • API changes does not affect the provider usage within terraform
    • There would be no issue as terraform always downloads the latest version of the provider

    Correct answer:

    • Use required_providers block to clearly define the provider version you want to use

    Explaination: The functionality of a provider plugin may vary drastically from one version to another. Our terraform configuration may not work as expected when using a version different than the one it was written in. As a best practice, always declare the exact version of the provider we want to use within the required_providers block.

    9. Where can we make use of version constraints?

    • a. Modules
    • b. Provider requirements
    • c. The required_version setting in the terraform block
    • d. All of the above

    Correct answer:

    • d. All of the above

    Explaination: Version constraints can be used anywhere terraform allows us to specify versions. Most commonly they can be set at:

    1. Within the provider version configuration (Inside the required_providers block nested inside the terraform block)
    2. The "required_version" argument which is used to set the version of Terraform to use.
    3. Within modules. This is where we specify the version of module to be used.

    Documentation Link: https://www.terraform.io/docs/language/expressions/version-constraints.html

    10. Which keyword is reserved for declaring variables in the terraform configuration files?

    • variable
    • var
    • Use the syntax var.<variable_name>
    • variable block does not need a keyword
    • user-defined keyword

    Correct answer:

    • variable

    Explaination: The variable block begins with the "variable" keyword followed by a user defined name/label for the variable.

    Documentation Link: https://www.terraform.io/docs/language/values/variables.html#declaring-an-input-variable

    11. The label after the variable keyword should be unique among all variables.

    • a. Should be unique among the variables in the same module
    • b.You can create just two variables of the same label
    • Both the statements (a) and (b) are true
    • None of the above

    Correct answer:

    • a. Should be unique among the variables in the same module

    Explaination: A variable name or a label must be unique within the same module or configuration.

    Documentation Link: https://www.terraform.io/docs/language/values/variables.html#declaring-an-input-variable

    12. Your team assigned you the task of developing a terraform configuration to provision a bunch of services on GCP. You did everything to the point but forgot to mention the provider's version in the terraform block. What default behavior would you expect from terraform:

    • a. Terraform init will fail
    • b. Terraform will download and use the latest version of providers used in the configuration
    • c. Terraform init will succeed but an apply will fail because of unsupported provider versions
    • d. None of the above
    • e. All of the above

    Correct answer:

    • b. Terraform will download and use the latest version of providers used in the configuration

    Explaination: Terraform will download the latest version for all the providers used within the configuration. The version downloaded may or may not work well with the configuration developed.

    13. A variable block is given below. Inspect it and choose the valid options.

    • Invalid. We cannot use "providers" as a variable name
    • Valid. The "default" argument is optional
    • Invalid. "default" argument is not used
    • Invalid. Incorrect "type" used

    Correct answer:

    • Invalid. We cannot use "providers" as a variable name

    Code: variable "providers" { type = string }

    Explaination: We can use any name for a variable except for: source, version, providers, count, for_each, lifecycle, depends_on and locals.

    We have used the variable name as "providers". This is not a valid identifier

    Documentation Link: https://www.terraform.io/docs/language/values/variables.html#declaring-an-input-variable

    14. Inspect the below code block and determine the resource attribute that creates a dependency between the given resources.

    • aws_subnet.cidr_block
    • aws_vpc.cidr_block
    • aws_vpc.backend-vpc.id
    • aws_vpc.backend_vpc.cidr_block
    • aws_subnet.private-subnet1.cidr_block

    Correct answer:

    • aws_vpc.backend-vpc.id

    Code: resource "aws_vpc" "backend-vpc" { cidr_block = "10.0.0.0/16" tags = { Name = "backend-vpc" } } resource "aws_subnet" "private-subnet1" { vpc_id = aws_vpc.backend-vpc.id cidr_block = "10.0.2.0/24" tags = { Name = "private-subnet1" } }

    Explaination: The aws_subnet type resource called private-subnet1 makes use of the resource attribute "aws_vpc.backend-vpc.id".

    15. What is the generic way to reference attributes within the terraform expression?

    • None of the above
    • RESOURCE_TYPE.ATTRIBUTE.NAME
    • RESOURCE_TYPE.NAME.ATTRIBUTE
    • RESOURCE_TYPE.NAME

    Correct answer:

    • RESOURCE_TYPE.NAME.ATTRIBUTE

    Documentation Link: https://www.terraform.io/docs/language/expressions/references.html#resources

    16. We just created an environment variable named “TF_VAR_content=foo-3” and ran the following command: terraform apply -var "content=foo-4" .Determine the content of file foo.txt

    • foo-4
    • foo-3
    • foo
    • foo-1

    Correct answer:

    • foo-4

    Code: resource "local_file" "foo" { content = var.content filename = “/random/foo.txt” }

    variable "content" { type = string description = "Content of the file to be created"

    validation { condition = substr(var.content, 0, 4) == "foo-" error_message = "The content value must be a valid word starting "foo-"." } }

    Explaination: The variables passed with the -var or -var-file command line flags have the highest priority and will take precedence over environment variables. As such, the file will be created with "foo-4" as the content.

    Documentation Link: https://www.terraform.io/docs/language/values/variables.html#variable-definition-precedence

    17. Each output value exported by a module must be declared using an ______ block.

    • output
    • input
    • variable
    • resource
    • data

    Correct answer:

    • output

    Documentation Link: https://www.terraform.io/docs/language/values/outputs.html#declaring-an-output-value

    18. Select the optional arguments that are available for the output block.

    • description
    • sensitive
    • depends_on
    • All of the above

    Correct answer:

    • All of the above

    Documentation Link: https://www.terraform.io/docs/language/values/outputs.html#optional-arguments

    19. We have a local file resource with certain content. Once this resource is provisioned, the file is created in the /root directory and the information about this file is also stored in the Terraform state file. Now let's create a new file using a simple shell script in the same directory /root. Quite evidently, this file is outside the control and management of Terraform at this point in time. How would you include the second file in your Terraform configuration?

    • By creating a resource type object inside the main.tf file.
    • By creating a data type object inside the main.tf file
    • Terraform automatically syncs the files under the same directory
    • Terraform doesn't provide such functionality

    Correct answer:

    • By creating a data type object inside the main.tf file

    20. Choose the meta-argument which is not supported by the data block.

    • depends_on
    • count
    • for_each
    • provider
    • lifecycle

    Correct answer:

    • lifecycle

    21. What steps are needed in order to change the backend in terraform? For instance : local to remote

    • Adding a terraform block only, would be enough
    • Add a backend block within a terraform block
    • Specifying the backend block within the terraform block is followed by reinitialization of the backend using terraform init.
    • Any one of the options is enough.

    Correct answer:

    • Specifying the backend block within the terraform block is followed by reinitialization of the backend using terraform init.

    22. Name the file that is created by default when you run the terraform apply command for the first time

    • terraform.state
    • state.tf
    • terraform.tf
    • terraform.tfstate

    Correct answer:

    • terraform.tfstate

    23. Which of the following is not the valid sub-command of terraform state command?

    • state mv
    • state list
    • state show
    • state pull
    • state rm
    • state replace

    Correct answer:

    • state replace

    24. You wanted to play with terraform to check what it has to offer. After a while you remembered that you didn’t specify any configuration for the backend. What default behaviour is expected here of terraform?

    • Terraform will use a local backend, which requires no configuration
    • Terraform will use a remote backend, which requires no configuration.
    • Terraform will randomly use a backend from a pool of local or remote ones
    • None of the above

    Correct answer:

    • Terraform will use a local backend, which requires no configuration

    25. Which command can be used to create a visual representation of our terraform resources?

    • terraform view
    • terraform console
    • terraform map
    • terraform graph

    Correct answer:

    • terraform graph

    26. terraform plan and terraform apply both refresh the state before their execution. Which option could be used to disable this default behaviour?

    • -refresh=disable
    • -refresh=no
    • -refresh=false
    • -no-refresh=true

    Correct answer:

    • -refresh=false

    27. Every terraform command listed is useful for inspecting infrastructure:- output, graph, show, state list, state show

    • True
    • False

    Correct answer:

    • True

    28. Can you export the debug logs from terraform only by setting the TF_LOG_PATH environment variable?

    • True
    • False

    Correct answer:

    • False

    29. Every initialized working directory has at least one workspace.

    • True
    • False

    Correct answer:

    • True

    30. Which environment variable is exported to set a different log level in the terraform?

    • TF_LOG
    • var.TF_LOG
    • VAR_TF_LOG
    • TF_LOG_PATH

    Correct answer:

    • TF_LOG

    31. We can delete the default terraform workspace.

    • True
    • False

    Correct answer:

    • False

    32. For local state, Terraform stores the workspace states in a directory called :

    • terraform.tfstate
    • terraform.tfstate.d
    • tfstate.d
    • None of the above

    Correct answer:

    • terraform.tfstate.d

    33. You intend to import two resources to your terraform configuration. You executed only the terraform import command until now and it worked. Will the terraform apply work if executed now?

    • It will throw an error
    • Works like a charm
    • We haven’t updated the resource with correct argument values yet
    • None of the options

    Correct answer:

    • It will throw an error
    • We haven’t updated the resource with correct argument values yet

    34. Modules can also call other modules using a _________ block

    • modules
    • module
    • Only the root module can call other modules
    • None of the above

    Correct answer:

    • module

    35. Select the types of terraform modules based on the credibility tier.

    • Verified
    • Non-verified
    • Official
    • Community

    Correct answer:

    • Verified
    • Community
    • Official

    36. A given resource or module block cannot use both count and for_each simultaneously.

    • True
    • False

    Correct answer:

    • True

    37. The for_each meta-argument accepts:

    • map
    • set of strings
    • list of strings
    • Only alphanumeric characters

    Correct answer:

    • map
    • set of strings

    38. Which statement best explains terraform provisioners?

    • used to model specific actions only on the local machine
    • used to model specific actions only on the remote machine
    • used to model specific actions on the local machine or on a remote machine
    • None of the above

    Correct answer:

    • used to model specific actions on the local machine or on a remote machine

    39. Where should you add a provisioner block?

    • Nested block inside the resource block
    • Outside the resource block
    • Nested block inside the provider block
    • Inside the terraform block

    Correct answer:

    • Nested block inside the resource block

    40. Fill the blank with the suitable choice:

    • destroy
    • create
    • apply
    • plan

    Correct answer:

    • destroy

    Code: resource "aws_instance" "web" {

    ...

    provisioner "local-exec" { when = ________ command = "echo 'Destroy-time provisioner'" } }

    41. Select the types of provisioners available:

    • local-exec
    • remote-exec
    • file
    • all of the above

    Correct answer:

    • all of the above

    42. Chose the option that best describes “in-place updates”:

    • The underlying infrastructure remains the same
    • Software and configuration of operating system changes as part of the update
    • Both
    • Neither

    Correct answer:

    • Both

    43. What happens when provisioners fail to execute successfully?

    • Terraform will taint the resource that will be replaced on the next run
    • Resources will be created but without the changes mentioned in the provisioner block
    • It will show an error message showing the user to taint the resource manually
    • None of the above

    Correct answer:

    • Terraform will taint the resource that will be replaced on the next run

    44. Which argument of the lifecycle meta-argument supports a list as a value ?

    • create_before_destroy
    • ignore_changes
    • prevent_destroy
    • All the options

    Correct answer:

    • ignore_changes

    Explaination: ignore_changes (list of attribute names) - By default, Terraform detects any difference in the current settings of a real infrastructure object and plans to update the remote object to match configuration.

    45. Select the available arguments that are available for the lifecycle meta-argument

    • create_before_destroy
    • ignore_change
    • prevent_destroy
    • ignore_changes
    • destroy_after_create

    Correct answer:

    • create_before_destroy
    • prevent_destroy
    • ignore_changes

    46. The Terraform language supports user-defined functions

    • True
    • False

    Correct answer:

    • False

    47. General syntax for function calls is :

    • Function name followed by comma-separated arguments in parentheses.
    • Function name followed by space-separated arguments in parentheses
    • Both
    • None

    Correct answer:

    • Function name followed by comma-separated arguments in parentheses.

    48. Inspect the following code and select what will happen if we run a terraform init for this configuration:

    • Valid code. Terraform init will work
    • Invalid default value for variable
    • Invalid default value but terraform will convert the value to the type specified
    • None of the above

    Correct answer:

    • Invalid default value for variable

    Code: variable "is_true" { type = bool default = 1 }

    Explaination: The default value for this variable is a number and the type is set to a boolean. Terraform init will fail with an error as shown below:


    The Terraform configuration must be valid before initialization so that Terraform can determine which modules and providers need to be installed.

    Error: Invalid default value for variable

    on variables.tf line 20, in variable "istrue": 20: default = 1

    This default value is not compatible with the variable's type constraint: bool required.

    49. Passing an object containing a sensitive input variable to the keys() function will result in a list that is _________ .

    • Sensitive
    • Non-sensitive
    • Random output
    • None of the above.

    Correct answer:

    • Sensitive

    50. Which of the following can be used to determine the length of a given list, map, or string.

    • length()
    • len()
    • size()
    • count()

    Correct answer:

    • length()

    51. Select the options that does not support dynamic block:

    • provisioner
    • provider
    • dynamic
    • data
    • resource
    • locals

    Correct answer:

    • locals

    Explaination: A dynamic block can only generate arguments that belong to the resource type, data source, provider or provisioner being configured. It is not possible to generate meta-argument blocks such as lifecycle and provisioner blocks , since Terraform must process these before it is safe to evaluate expressions.

    52. Can we use dynamic blocks to generate meta-argument blocks such as lifecycle and provisioner blocks?

    • True
    • False

    Correct answer:

    • False

    Explaination: A dynamic block can only generate arguments that belong to the resource type, data source, provider, or provisioner being configured. It is not possible to generate meta-argument blocks such as lifecycle and provisioner blocks, since Terraform must process these before it is safe to evaluate expressions.

    53. By default terraform cloud runs terraform on:

    • its own cloud infrastructure
    • on your own isolated, private, or on-premises infrastructure
    • You need to specify each time you run terraform commands
    • None of the above

    Correct answer:

    • its own cloud infrastructure

    54. What is Sentinel?

    • Policy as code framework for HashiCorp Enterprise Products
    • Infrastructure as code framework for Terraform
    • Both
    • None of the above

    Correct answer:

    • Policy as code framework for HashiCorp Enterprise Products

    55. Select the workflows that Terraform cloud utilizes to manage Terraform runs:

    • UI/VCS-driven run workflow
    • API-driven run workflow
    • CLI-driven run workflow
    • None of the above

    Correct answer:

    • UI/VCS-driven run workflow
    • API-driven run workflow
    • CLI-driven run workflow

    56. Is Terraform Cloud workspaces same as Terraform CLI Workspaces.

    • Yes
    • No

    Correct answer:

    • No

    57. You were working with different terraform scripts which are provisioning various sets of resources , you need to look up for some additional details related to one specific resource from the state file. Which terraform command will help you achieve this?

    • terraform state list ADDRESS
    • terraform state show ADDRESS
    • terraform show ADDRESS
    • terraform get ADDRESS

    Correct answer:

    • terraform state show ADDRESS

    58. terraform import command updates the configuration files as well as the state file, with the details of the infrastructure being imported.

    • True
    • False

    Correct answer:

    • False

    59. In the UI and VCS workflow, every workspace is associated with a specific branch of a VCS repo of Terraform configurations.

    • True
    • False

    Correct answer:

    • True

    Explaination: In the UI and VCS workflow, every workspace is associated with a specific branch of a VCS repo of Terraform configurations. Terraform Cloud registers webhooks with your VCS provider when you create a workspace, then automatically queues a Terraform run whenever new commits are merged to that branch of workspace's linked repository.

    60. “alias” and “version” are the meta-arguments which are available for all provider blocks?

    • True
    • False

    Correct answer:

    • True

    Linux Basics

    1. In the command “echo -n hello”, what is “-n”

    • command
    • argument
    • option

    Correct answer:

    • option

    2. Which command would you use to find out the type of a command?

    • type
    • file
    • echo
    • cd
    • pwd

    Correct answer:

    • type

    3. Which directory contains the user home directories by default?

    • home
    • /home
    • /root
    • home-directory

    Correct answer:

    • /home

    4. Which symbol represents a user’s home directory in Linux?

    • $
    • ~
    • :
    • /

    Correct answer:

    • ~

    5. In the command “echo -n hello”, what is “echo”

    • argument
    • switch
    • option
    • flag
    • command

    Correct answer:

    • command

    Terraform Mock Exam 2

    1. What does “IaC” stand for?

    • Infrastructure as Code
    • Initialization as Code
    • Code as Infrastructure
    • None of the above

    Correct answer:

    • Infrastructure as Code

    Explaination: IaC stands for Infrastructure as Code.

    2. Name the file that is created by default when you run the terraform apply command for the first time

    • terraform.state
    • state.tf
    • terraform.tf
    • terraform.tfstate

    Correct answer:

    • terraform.tfstate

    3. Every initialized working directory has at least one workspace.

    • True
    • False

    Correct answer:

    • True

    4. Select the reasons why we may need to specify the provider's argument?

    • It’s just a practice we need to blindly follow
    • No specific reason
    • To use multiple configurations of the same provider
    • To change the default Provider Configurations
    • To use multiple provider plugins in the same configuration

    Correct answer:

    • To use multiple configurations of the same provider
    • To change the default Provider Configurations

    Explaination: There are two reasons to use a provider argument in the configuration.

    1. To override the default provider configuration. For example, the default configuration may be to deploy resources in the "us-east-1" region. If the requirement is to deploy resources in a different region, we can use the provider argument to override the default.

    2. In some cases, a configuration may need to use multiple versions of the same provider. For example - a resource that deploys to the "us-east-1" and another resource within the same configuration that deploys to the "us-west-2" region.

    Documentation Link: https://www.terraform.io/docs/language/meta-arguments/module-providers.html#when-to-specify-providers

    5. What are the possible consequences of making heavy usage of provisioners within your terraform script?

    • Add a considerable amount of complexity and uncertainty to Terraform usage
    • Terraform cannot model the actions of provisioners as part of a plan
    • Use of provisioners requires coordinating many more details than Terraform usage usually requires
    • All of the options

    Correct answer:

    • All of the options

    6. When we introduce _______ blocks, our configuration becomes hierarchical rather than flat.

    • module
    • root module
    • child module
    • None of the above

    Correct answer:

    • module

    7. What are the common issues that come with configuration drift?

    • Make it difficult to plan and carry out subsequent updates.
    • Troubleshooting issues would also be a difficult task
    • All of the above
    • Can leave the infrastructure in a complex state

    Correct answer:

    • All of the above

    8. Which option best describes the meaning of interpolation syntax?

    • A way to reference variables, attributes of resources, and call functions
    • A way to declare values to variables
    • A way to provide runtime options with terraform operations
    • None of the above

    Correct answer:

    • A way to reference variables, attributes of resources, and call functions

    Explaination: Interpolation syntax allows us to reference variables, resource attributes and even make use of built-in functions in terraform.

    Documentation Link: https://www.terraform.io/docs/language/expressions/strings.html#interpolation

    9. Which argument of the lifecycle meta-argument supports a list as a value ?

    • create_before_destroy
    • ignore_changes
    • prevent_destroy
    • All the options

    Correct answer:

    • ignore_changes

    Explaination: ignore_changes (list of attribute names) - By default, Terraform detects any difference in the current settings of a real infrastructure object and plans to update the remote object to match configuration.

    10. Which terraform command can be used to experiment with the behavior of Terraform's built-in functions?

    • terraform console
    • terraform validate
    • terraform check
    • terraform terminal

    Correct answer:

    • terraform console

    Explaination: This command provides an interactive command-line console for evaluating and experimenting with expressions. This is useful for testing interpolations before using them in configurations, and for interacting with any values currently saved in state.

    11. If the arguments for passing to a function are available in the form of list or tuple value, how would you expand that inside the function?

    • Provide the list value as an argument and follow it with the “...” symbol
    • Provide the list value as an argument and follow it with the keyword “expand”.
    • Terraform doesn’t support expanding arguments this way
    • None of the above

    Correct answer:

    • Provide the list value as an argument and follow it with the “...” symbol

    12. You can dynamically construct repeatable nested blocks using which special block type:

    • dynamic
    • generate
    • local
    • None of the above

    Correct answer:

    • dynamic

    Explaination: You can dynamically construct repeatable nested blocks like setting using a special "dynamic block" type, which is supported inside "resource", "data", "provider", and "provisioner" blocks.

    13. Which of the following function is no longer available in terraform:

    • map()
    • tomap()
    • zipmap()
    • None of the above

    Correct answer:

    • map()

    Documentation Link: https://www.terraform.io/language/functions/map#map-function

    14. Which of the following is true for terraform cloud?

    • It manages Terraform runs in a consistent and reliable environment
    • It includes easy access to shared state and secret data, access controls for approving changes to infrastructure
    • It provides a private registry for sharing Terraform modules
    • It has detailed policy controls for governing the contents of Terraform configurations
    • All of the above

    Correct answer:

    • All of the above

    Documentation Link: https://learn.hashicorp.com/tutorials/terraform/cloud-sign-up?in=terraform/cloud-get-started#what-is-terraform-cloud

    15. Select the best practices around using dynamic block.

    • Use them when you need to hide details in order to build a clean user interface for a reusable module.
    • Overuse of dynamic blocks can make configuration hard to read and maintain
    • Always write nested blocks out literally where possible.
    • All of the options

    Correct answer:

    • All of the options

    Documentation Link: https://www.terraform.io/language/expressions/dynamic-blocks#best-practices-for-dynamic-blocks

    16. Is it possible to declare the dynamic block inside another dynamic block?

    • Yes
    • No

    Correct answer:

    • Yes

    Explaination: Some providers define resource types that include multiple levels of blocks nested inside one another. You can generate these nested structures dynamically when necessary by nesting dynamic blocks in the content portion of other dynamic blocks.

    Documentation Link: https://developer.hashicorp.com/terraform/language/expressions/dynamic-blocks#multi-level-nested-block-structures

    17. What are the advantages of using Terraform Cloud's private registry:

    • Helps you share Terraform providers and Terraform modules across your organization
    • Includes support for versioning, a searchable list of available providers and modules
    • Includes support for a configuration designer to help you build new workspaces faster
    • All of the above

    Correct answer:

    • All of the above

    18. Select the workflows that Terraform cloud utilizes to manage Terraform runs:

    • UI/VCS-driven run workflow
    • API-driven run workflow
    • CLI-driven run workflow
    • None of the above

    Correct answer:

    • UI/VCS-driven run workflow
    • API-driven run workflow
    • CLI-driven run workflow

    19. In the UI and VCS workflow, every workspace is associated with a specific branch of a VCS repo of Terraform configurations.

    • True
    • False

    Correct answer:

    • True

    Explaination: In the UI and VCS workflow, every workspace is associated with a specific branch of a VCS repo of Terraform configurations. Terraform Cloud registers webhooks with your VCS provider when you create a workspace, then automatically queues a Terraform run whenever new commits are merged to that branch of workspace's linked repository.

    20. A terraform configuration can consist of multiple files and directories.

    • True
    • False

    Correct answer:

    • True

    Explaination: A Terraform module can use module calls to explicitly include other modules into the configuration. These child modules can come from local directories (nested in the parent module's directory, or anywhere else on disk), or from external sources like the Terraform Registry.

    Documentation Link: https://www.terraform.io/language/files#directories-and-modules

    21. Terraform assumes an empty default configuration for any provider that is not explicitly configured.

    • True
    • False

    Correct answer:

    • True

    Explaination: Unlike many other objects in the Terraform language, a provider block may be omitted if its contents would otherwise be empty. Terraform assumes an empty default configuration for any provider that is not explicitly configured.

    22. Which provider is used in the below code snippet:

    • local
    • aws_instance
    • aws
    • aws.west

    Correct answer:

    • aws.west

    Code: resource "aws_instance" "foo" { provider = aws.west

    ...

    }

    Explaination: To use an alternate provider configuration for a resource or data source, set its provider meta-argument to a .

    Documentation Link: https://www.terraform.io/language/providers/configuration#selecting-alternate-provider-configurations

    23. The Terraform language is ___________ :

    • Declarative
    • Imperative
    • Both
    • None of the options

    Correct answer:

    • Declarative

    Explaination: Terraform directly describes the end state of the system without defining the steps to reach there. It works at a high level of abstraction to describe what services and resources should be created and defined

    24. How does terraform allow you to review changes before Terraform creates, updates, or destroys infrastructure?

    • By generating an execution plan and asking for approval before implementing infrastructure changes.
    • By creating a graph to help in visualizing what is to be implemented.
    • Users need to cross-check the files in the current configuration directory themselves.
    • Terraform doesn't provide review capability.

    Correct answer:

    • By generating an execution plan and asking for approval before implementing infrastructure changes.

    25. What will happen if Terraform isn't able to obtain acceptable versions of external dependencies, or if it doesn't have an acceptable version of itself?

    • It will attempt to download the newest version that meets the applicable constraints.
    • It won't proceed with any plans, applies, or state manipulation actions
    • It will ignore such errors and proceed without warning
    • None of the options

    Correct answer:

    • It won't proceed with any plans, applies, or state manipulation actions

    Explaination: Both the root module and any child module can constrain the acceptable versions of Terraform and any providers they use. Terraform considers these constraints equal, and will only proceed if all of them can be met.

    26. What is the default behaviour of Terraform when it doesn't have an acceptable version of a required plugin or module?

    • It will attempt to download the newest version that meets the applicable constraints.
    • It won't proceed with any plans, applies, or state manipulation actions
    • It will attempt to create that plugin or module itself
    • None of the options

    Correct answer:

    • It will attempt to download the newest version that meets the applicable constraints.

    27. The default argument within the variable block should satisfy which of the following conditions:

    • default argument requires a literal value
    • It cannot reference other objects in the configuration.
    • If present, the variable is considered to be optional.
    • default value will be used if no value is set when calling the module or running Terraform.
    • All of the options

    Correct answer:

    • All of the options

    Documentation Link: https://www.terraform.io/language/values/variables#default-values

    28. Select the correct options about the local values among the following:

    • Local values are created by a locals block
    • Local values are created by a local block
    • Local values are referenced as attributes on an object named local
    • Local values are referenced as attributes on an object named locals
    • Terraform supports local values creation with both local as well as locals keyword

    Correct answer:

    • Local values are created by a locals block
    • Local values are referenced as attributes on an object named local

    Explaination: Local values are created by a locals block (plural), but you reference them as attributes on an object named local (singular). Make sure to leave off the "s" when referencing a local value!

    29. Select the most appropriate options among the following:

    • Resources declared using data block are known as data resources.
    • Resources declared by a resource block are known as managed resources.
    • Managed resources are often referred to just as resources when the meaning is clear from context.
    • data resources cause Terraform to create, update, and delete infrastructure objects.
    • Managed resources cause Terraform only to read objects

    Correct answer:

    • Resources declared using data block are known as data resources.
    • Resources declared by a resource block are known as managed resources.
    • Managed resources are often referred to just as resources when the meaning is clear from context.

    30. Choose the correct option for referencing local values from the below code snippet:

    • local.common_tags
    • locals.common_tags
    • common_tags.locals
    • common_tags.local

    Correct answer:

    • local.common_tags

    Code: locals {

    Common tags to be assigned to all resources

    common_tags = { Service = local.service_name Owner = local.owner } }

    resource "aws_instance" "example" {

    ...

    tags = ____________ }

    Explaination: Local values are created by a locals block (plural), but you reference them as attributes on an object named local (singular). Make sure to leave off the "s" when referencing a local value!

    31. What are the options that best correspond to the definition of local-only data sources:

    • It is the same as all other data sources, but their result data exists only temporarily during a Terraform operation.
    • Local-only data sources are exactly the same as normal data sources.
    • It is re-calculated each time a new plan is created.
    • Local-only data sources behave similarly to local values declared using locals block.

    Correct answer:

    • It is the same as all other data sources, but their result data exists only temporarily during a Terraform operation.
    • It is re-calculated each time a new plan is created.

    Explaination: The behavior of local-only data sources is the same as all other data sources, but their result data exists only temporarily during a Terraform operation, and is re-calculated each time a new plan is created.

    Documentation Link: https://www.terraform.io/language/data-sources#local-only-data-sources

    32. Local values can be helpful to avoid repeating the same values or expressions multiple times in a configuration.

    • True
    • False

    Correct answer:

    • True

    Explaination: Local values can be helpful to avoid repeating the same values or expressions multiple times in a configuration, but if overused they can also make a configuration hard to read by future maintainers by hiding the actual values used.

    33. Terraform recommends treating the state itself as sensitive data if you manage any sensitive data with Terraform (like database passwords, user passwords, or private keys etc).

    • True
    • False

    Correct answer:

    • True

    Documentation Link: https://www.terraform.io/language/state/sensitive-data#sensitive-data-in-state

    34. Terraform expects a _________ mapping between configured resource instances and remote objects.

    • One-to-one
    • One-to-many
    • Many-to-many
    • Many-to-one

    Correct answer:

    • One-to-one

    Explaination: Terraform expects that each remote object is bound to only one resource instance, which is normally guaranteed by Terraform being responsible for creating the objects and recording their identities in the state.

    Documentation Link: https://www.terraform.io/language/state/purpose#mapping-to-the-real-world

    35. You recently joined an organization with the capacity of devops-engineer. Your team has been working on various projects and you were assigned one that involves heavy usage of terraform configuration files. You wanted to extract the list of resources that have been provisioned till date using this terraform configuration. What terraform command would you make use of to achieve this?

    • terraform state list
    • terraform state show
    • terraform list
    • terraform show

    Correct answer:

    • terraform state list

    Explaination: The command will list all resources in the state file matching the given addresses (if any). If no addresses are given, all resources are listed.

    36. Select the appropriate option to correct the below code snippet:

    • Variable declaration is not done correctly. The var keyword should be used instead of variable.
    • Invalid argument types used.
    • default argument is not used . It will throw an error as it is not optional.
    • There is no issue with the given code.

    Correct answer:

    • Invalid argument types used.

    Code: variable "image_id" { types = string description = "The id of the machine image (AMI) to use for the server." }

    Documentation Link: https://www.terraform.io/language/values/variables#declaring-an-input-variable

    37. Provisioners can only be used to model specific actions on a remote machine in order to prepare servers or other infrastructure objects for service.

    • True
    • False

    Correct answer:

    • False

    Explaination: Provisioners can be used to model specific actions on the "local machine" or on a "remote machine" in order to prepare servers or other infrastructure objects for service.

    38. What steps are needed to enable state-locking to protect state file from concurrent operations against the same terraform configuration?

    • We can enable state-locking using -lock=true
    • Terraform enables it automatically for all backends
    • Terraform enables it automatically if your backends have support for it.
    • None of the options are true

    Correct answer:

    • Terraform enables it automatically if your backends have support for it.

    Explaination: If supported by your backend, Terraform will lock your state for all operations that could write state. This prevents others from acquiring the lock and potentially corrupting your state.

    Documentation Link: https://www.terraform.io/language/state/locking#state-locking

    39. Which variable block argument prevents terraform from showing sensitive data in plan or apply output?

    • sensitive_content = true
    • sensitive = true
    • No such argument exists
    • private_content = true

    Correct answer:

    • sensitive = true

    Explaination: Setting a variable as "sensitive" prevents Terraform from showing its value in the "plan" or "apply" output, when you use that variable elsewhere in your configuration.

    40. Which environment variable needs to be defined in terraform for the persistence of the logged output?

    • TF_LOG_PATH
    • LOG_PATH
    • TF_LOG
    • None of the options

    Correct answer:

    • TF_LOG_PATH

    Explaination: To persist logged output you can set TF_LOG_PATH in order to force the log to always be appended to a specific file when logging is enabled. Note that even when TF_LOG_PATH is set, TF_LOG must be set in order for any logging to be enabled.

    41. What is the significance of -chdir option in terraform?

    • It instructs Terraform to change its working directory to the given directory before running the given subcommand.
    • It picks up the terraform binary from the directory specified by the -chdir option.
    • No such option exists within terraform.
    • -chdir option instructs terraform to download the provider plugin from the directory specified on the command line.

    Correct answer:

    • It instructs Terraform to change its working directory to the given directory before running the given subcommand.

    Explaination: The chdir option instructs Terraform to change its working directory to the given directory before running the given subcommand. This means that any files that Terraform would normally read or write in the current working directory will be read or written in the given directory instead.

    42. Logging can not be enabled separately for the provider plugins using the TF_LOG_PROVIDER environment variable.

    • True
    • False

    Correct answer:

    • False

    Explaination: Logging can be enabled separately for terraform itself and the provider plugins using the TF_LOG_CORE or TF_LOG_PROVIDER environment variables. These take the same level arguments as TF_LOG, but only activate a subset of the logs.

    43. Which command applies a subset of the Terraform language style conventions, along with other minor adjustments for readability.

    • terraform fmt
    • terraform console
    • terraform plan
    • terraform validate

    Correct answer:

    • terraform fmt

    Explaination: The "terraform fmt" command is used to rewrite Terraform configuration files to a canonical format and style. This command applies a subset of the Terraform language style conventions, along with other minor adjustments for readability.

    44. Choose the appropriate option among the following for the below command:

    • It will output the value of the variable NAME for the root module.
    • It will display all the outputs for the root module.
    • It will display all the outputs from the state file named NAME instead of terraform.tfstate.
    • None of the options are correct.

    Correct answer:

    • It will output the value of the variable NAME for the root module.

    Code: terraform output [options] [NAME]

    45. Choose the suitable options for the terraform plan command.

    • Reads the current state of any already-existing remote objects to make sure that the Terraform state is up-to-date
    • Compares the current configuration to the prior state and noting any differences
    • Proposes a set of change actions that should, if applied, make the remote objects match the configuration
    • All the options are correct.

    Correct answer:

    • All the options are correct.

    Documentation Link: https://www.terraform.io/cli/commands/plan#command-plan

    46. The __________ displays the current version of Terraform and of all installed plugins.

    • terraform version
    • terraform -version
    • terraform version -all
    • None of the options are correct

    Correct answer:

    • terraform version

    47. The lifecycle block and its contents are available for all resource blocks regardless of type.

    • True
    • False

    Correct answer:

    • True

    Explaination: lifecycle is a nested block that can appear within a resource block. The lifecycle block and its contents are meta-arguments, available for all resource blocks regardless of type.

    Documentation Link: https://www.terraform.io/language/meta-arguments/lifecycle#the-lifecycle-meta-argument

    48. Choose among the following that holds true for terraform default workspace.

    • It is the default workspace.
    • This workspace cannot be deleted.
    • Only default workspace uses the terraform.tfstate file.
    • None of the options are correct.
    • This workspace can be renamed

    Correct answer:

    • It is the default workspace.
    • This workspace cannot be deleted.

    Explaination: Terraform starts with a single workspace named "default". This workspace is special both because it is the default and also because it cannot ever be deleted. If you've never explicitly used workspaces, then you've only ever worked on the "default" workspace.

    Documentation Link: https://www.terraform.io/language/state/workspaces#using-workspaces

    49. Choose the correct command which is used to list all existing workspaces.

    • terraform workspace show
    • terraform workspace list
    • terraform workspace list -all
    • None of the options are correct.

    Correct answer:

    • terraform workspace list

    50. ________ are the main way to package and reuse resource configurations with Terraform.

    • Modules
    • Workspaces
    • None of the options are correct.
    • Both of the options are correct.

    Correct answer:

    • Modules

    51. Is it possible for a Terraform configuration to have no modules and still works?

    • It will work with no errors.
    • Terraform configuration needs at least one module .i.e. Root module.
    • Terraform configuration needs at least one child module along with the root module.
    • None of the options are correct.

    Correct answer:

    • Terraform configuration needs at least one module .i.e. Root module.

    Explaination: Every Terraform configuration has at least one module, known as its root module, which consists of the resources defined in the .tf files in the main working directory.

    Documentation Link: https://www.terraform.io/language/modules/syntax#module-blocks

    52. The splat expression patterns shown below is not applicable for which among the following:

    • Lists
    • Sets
    • Tuples
    • Maps
    • None of the options

    Correct answer:

    • Maps

    Code: var.list[*].id

    Explaination: The splat expression patterns shown above apply only to lists, sets, and tuples. To get a similar result with a map or object value you must use for expressions.

    53. Which among the following is similar to below code expressions:

    • var.list[*].id
    • var.list(*).id
    • var.*(list).id
    • var.*.id
    • None of the above

    Correct answer:

    • var.list[*].id

    Code: [for o in var.list : o.id]

    Explaination: The special [*] symbol iterates over all of the elements of the list given to its left and accesses from each one the attribute name given on its right.

    54. Choose the suitable options among the following for the below code snippet:

    • Instructs Terraform to plan to replace the single resource instance with the given address.
    • For Terraform v0.15.2 and later, terraform recommend using the -replace option with terraform apply instead of taint.
    • Terraform recommends to use terraform taint instead of -replace option.
    • All of the options
    • None of the options.

    Correct answer:

    • Instructs Terraform to plan to replace the single resource instance with the given address.
    • For Terraform v0.15.2 and later, terraform recommend using the -replace option with terraform apply instead of taint.

    Code: terraform apply -replace="aws_instance.example[0]"

    Explaination: Terraform recommends the -replace option because the change will be reflected in the Terraform plan, letting you understand how it will affect your infrastructure before you take any externally-visible action. When you use terraform taint, other users could create a new plan against your tainted object before you can review the effects.

    55. Which among the following are the techniques that could be used to safely and securely manage secrets inside terraform?

    • Environment Variables
    • Encrypted Files (e.g., KMS, PGP, SOPS)
    • Secret Stores (e.g., Vault, AWS Secrets manager)
    • Store Secrets in plain text
    • Store Terraform state in a backend that supports encryption.

    Correct answer:

    • Secret Stores (e.g., Vault, AWS Secrets manager)
    • Store Terraform state in a backend that supports encryption.
    • Encrypted Files (e.g., KMS, PGP, SOPS)
    • Environment Variables

    Documentation Link: https://blog.gruntwork.io/a-comprehensive-guide-to-managing-secrets-in-your-terraform-code-1d586955ace1

    56. Select the appropriate options for which we can make use of version constraints:

    • Workspaces
    • Modules
    • Provider requirements
    • Only provider requirements.
    • The required_version setting in the terraform block

    Correct answer:

    • Modules
    • Provider requirements
    • The required_version setting in the terraform block

    Documentation Link: https://www.terraform.io/language/expressions/version-constraints#version-constraints

    57. Choose the suitable option that could be used to access one of the module's output values:

    • module.[MODULE NAME].[OUTPUT NAME]
    • module.[MODULE NAME].[VARIABLE NAME]
    • module.[VARIABLE NAME].[MODULE NAME]
    • module.[OUTPUT NAME].[MODULE NAME]

    Correct answer:

    • module.[MODULE NAME].[OUTPUT NAME]

    Documentation Link: https://www.terraform.io/language/expressions/references#child-module-outputs

    58. Considering provisioners are the best way to solve your problem, in what way could you make use of provisioner block.

    • Nested block inside the resource block
    • Outside the resource block
    • Nested block inside the provider block
    • Inside the terraform block

    Correct answer:

    • Nested block inside the resource block

    59. What is the type of the resource given in the below code snippet:

    • Managed resource
    • Data resource
    • Both options are correct
    • None of the options are correct

    Correct answer:

    • Data resource

    Code: data "aws_ami" "amazon_linux" { most_recent = true owners = ["amazon"]

    filter { name = "name" values = ["amzn2-ami-hvm-*-x86_64-gp2"] } }

    Explaination: A data source is accessed via a special kind of resource known as a data resource, declared using a data block.

    60. Name the embedded policy-as-code framework integrated with the HashiCorp Enterprise products.

    • Sentinel
    • Open Policy Agent (OPA)
    • HashiCorp Boundary
    • Checkov by Bridgecrew

    Correct answer:

    • Sentinel

    Explaination: Sentinel is an embedded policy-as-code framework integrated with the HashiCorp Enterprise products. It enables fine-grained, logic-based policy decisions, and can be extended to use information from external sources.

    Documentation Link: https://www.terraform.io/cloud-docs/sentinel#sentinel-overview


    None


    sample-vijin

    1. Test image Sample Image

    • a
    • b
    • c
    • d

    Correct answer:

    • a

    managing-azure-active-directory

    1. What is the maximum number of methods we can set for password reset?

    • 1
    • 2
    • 4
    • 6

    Correct answer:

    • 2

    Explaination: Though we can make multiple methods available to the users, we can use one or two methods for a password reset, hence the maximum number is 2.

    2. With Azure AD Free edition, we can have B2B collaboration.

    • True
    • False

    Correct answer:

    • True

    Explaination: It is True as all editions of Azure AD support B2B collaboration.

    3. If you are deleting a user from Azure AD, how long will Azure AD will retain the user?

    • 10 days
    • 15 days
    • 30 days
    • 60 days

    Correct answer:

    • 30 days

    Explaination: Azure AD will retain the deleted user for 30 days, during that time you can restore the user if needed.

    4. Which type of user account is owned by Abigail Richards? question-image

    • Member identity
    • Cloud identity
    • Guest identity
    • Directory Synchronized identity

    Correct answer:

    • Cloud identity

    Explaination: Abigail is a cloud identity as the user type is Member and Directory synced flag is set to No. Guest identities will have the user type as Guest and Directory synchronized users will have the Directory synced flag set to Yes.

    5. You would like to add external users to your directory in bulk. Which of the following bulk operations will you use to accomplish this task?

    • Bulk export
    • Bulk create
    • Bulk add
    • Bulk invite

    Correct answer:

    • Bulk invite

    Explaination: Since you are adding external users, you need to use the “Bulk invite” option. If you were adding cloud identities in bulk, then you need to use “Bulk create” option.

    6. Which feature in Azure AD can be used to enforce device management?

    • Azure Domain Join
    • Azure AD Directory Services
    • Azure AD Join
    • Azure AD login

    Correct answer:

    • Azure AD Join

    Explaination: Azure AD Join can be used to join our devices to Azure AD using a Work or School account for device management.

    7. Which of the following statements is false? Select one.

    • Azure AD uses Kerberos.
    • Azure AD is a managed service.
    • Azure AD uses REST API calls for querying.
    • Azure AD uses OAuth.

    Correct answer:

    • Azure AD uses Kerberos.

    Explaination: Kerberos is used by Active Directory Domain Services; Azure AD uses OAuth authorization.

    8. Your organization wants to use Identity Governance in Azure AD. Which Azure AD edition will you recommend for this?

    • Free
    • Microsoft 365 Apps
    • Premium P1
    • Premium P2

    Correct answer:

    • Premium P2

    Explaination: Only Azure AD Premium P2 supports Identity Governance.

    9. Which protocol is used by Active Directory Domain services for querying objects?

    • HTTP
    • HTTPS
    • REST
    • LDAP

    Correct answer:

    • LDAP

    Explaination: ADDS uses LDAP for querying, on the other hand, Azure AD uses HTTP/HTTPS.

    10. Which users will be part of the “Finance” group if the dynamic query for the group is user.department –eq "Finance" –and user.country –eq "US"? question-image

    • 1 and 4
    • 2, 4, and 5
    • 3 and 5
    • 3, 4, and 5

    Correct answer:

    • 3 and 5

    Explaination: Dynamic query will pick the users whose department is Finance and country is US.


    subscription-and-governance

    1. You need to group your subscription based on department, which of the following need to be used?

    • Management groups
    • Subscription groups
    • Resource groups
    • Business groups

    Correct answer:

    • Management groups

    Explaination: Management groups offer a scope above subscriptions by which you will be able to group subscriptions together.

    2. What’s the maximum number of tags you can assign to a resource?

    • 20
    • 40
    • 50
    • 60

    Correct answer:

    • 50

    Explaination: Maximum number of tags is 50.

    3. You are running production critical workloads in Azure, and you need to make sure that the resources are protected from accidental changes and deletion. Which of the following should you use?

    • Read-only lock
    • Delete lock
    • Tag
    • Policy

    Correct answer:

    • Read-only lock

    Explaination: Read only lock is required as you are intending to avoid both accidental changes and deletion.

    4. Chris is the owner of the subscription, and he wants to assign a role to Alex. Alex is responsible for managing user access to Azure resources. The role should comply with the principle of least privilege. Which role should Chris assign to Alex?

    • Owner
    • Administrator
    • User access owner
    • User access administrator

    Correct answer:

    • User access administrator

    Explaination: User Access Administrator can manage user access to Azure resources. Owner can also do the same, but the Owner role will make Alex over-privileged.

    5. Which service in Azure is used to manage access to Azure resources?

    • Azure Management groups
    • RBAC
    • Policy
    • Tags

    Correct answer:

    • RBAC

    Explaination: RBAC is used to manage access to resources.

    6. You deployed a production webserver on Azure Ubuntu Linux Virtual Machine. Your manager is planning to perform cost cutting and asked you to optimize the cost of the VM. Which of the following methods can be used to save the cost?

    • Azure Visual Studio subscription
    • Azure Dev/Test subscription
    • Reserved Instances
    • Azure Hybrid Benefit

    Correct answer:

    • Reserved Instances

    Explaination: Azure Visual Studio subscription and Azure Dev/Test subscription don’t have any SLA and are not recommended for production workloads. As Ubuntu doesn’t require any license, Azure Hybrid Benefit is not applicable. The only option is to buy a reserved instance.

    7. You need to make sure that the tags applied to the resource group is getting inherited to the underlying resources. How can we accomplish this?

    • No change is required, tags applied at higher scopes will be inherited to underlying resources.
    • Azure Policy needs to be implemented to inherit the tags.
    • Use inherit option in Azure to inherit if needed.
    • You cannot assign tags to resource groups, tag resources individually.

    Correct answer:

    • Azure Policy needs to be implemented to inherit the tags.

    Explaination: Tags are not inherited by default; we need to use Azure Policy to make sure the tags are inherited. Alternatively, we can use scripting to copy the tags from resource group and apply to the resources, but it’s a lengthy process.

    8. Which of the following statements about Azure subscription is not true?

    • Logical boundary for our resources.
    • Azure Subscription provides billing boundary.
    • All resources will be mapped to a subscription.
    • Only one subscription can be created inside an account

    Correct answer:

    • Only one subscription can be created inside an account

    Explaination: An account can have multiple subscriptions.

    9. Your organization is going for PCI: DSS compliance and there are several policies that your organization wants to enforce to their Azure environment. They are looking for an easier solution to assign multiple policies and evaluate them. What will you suggest?

    • Use Azure Policy Developer Console
    • Use Azure Initiative
    • Use Azure Policy bulk processing
    • There is no way to assign and manage multiple policies.

    Correct answer:

    • Use Azure Initiative

    Explaination: Initiative can be used to chain policies, assign them, and evaluate the overall compliance.

    10. Which of the following statements about Azure Cost Management is false?

    • Cost Management can be used export Azure usage to storage account.
    • We can create budgets and cost alerts in Cost Management.
    • We can analyse AWS and GCP cost in Azure Cost Management.
    • Cost Management offers API to download the usage programmatically.

    Correct answer:

    • We can analyse AWS and GCP cost in Azure Cost Management.

    Explaination: As of now, we can only analyze AWS cost in Azure Cost Management; GCP is not supported yet.


    implementing-virtual-networking

    1. Which of the following statements is false? Select all that apply.

    • Azure Firewall is a Layer 4 firewall-as-a-service solution
    • Azure Firewall supports public IP
    • Azure Firewall has built in threat intelligence
    • Azure Firewall doesn’t require dedicated subnet

    Correct answer:

    • Azure Firewall is a Layer 4 firewall-as-a-service solution
    • Azure Firewall doesn’t require dedicated subnet

    Explaination: Azure Firewall is a Layer 7 firewall, and it requires a dedicated subnet.

    2. Which of the following statement is false?

    • Virtual Networks are representation of cloud network.
    • Virtual Network is a global service in Azure used to connect to other virtual networks and on-premises environment.
    • Virtual network can be divided to small sub networks called subnets.
    • A subscription is required to create an Azure virtual network.

    Correct answer:

    • Virtual Network is a global service in Azure used to connect to other virtual networks and on-premises environment.

    Explaination: Virtual Network is not a global service, it’s a regional service.

    3. You are setting up a service endpoint between your VM-1 deployed in East US and storage account in West US. Which IP address will be used by the VM to connect to the storage account using service endpoint?

    • Public IP of the VM
    • Private IP of the VM
    • NAT IP of the VM
    • Cross region is not possible with Service Endpoints

    Correct answer:

    • Private IP of the VM

    Explaination: The VM will be using its private IP to communicate with the storage account using a service endpoint.

    4. In Azure, without the need for deploying a NAT gateway, all VMs can communicate to the internet. What is the reason for this?

    • System route
    • Built in NAT gateway
    • VPN
    • Built in internet gateway

    Correct answer:

    • System route

    Explaination: With the help of system routes, VMs can communicate to the internet without the need to deploy any additional infrastructure.

    5. You need to assign a static zone redundant IP address to one of your DNS servers to ensure that the IP address is not getting changed during planned reboot events. Which Public IP SKU should be selected for this IP?

    • Basic
    • Premium
    • Reserved
    • Standard

    Correct answer:

    • Standard

    Explaination: Standard SKU supports zone redundancy and static IP allocation.

    6. Your organization is planning to host DNS in Azure by which VMs can resolve names of other VMs. Which of the following services should be used to create a DNS zone for name resolution in an Azure virtual network?

    • DNS zones
    • Private DNS zones
    • Virtual DNS
    • Delegated DNS zone

    Correct answer:

    • Private DNS zones

    Explaination: Private DNS zones can be created to provide name resolution for services deployed in a virtual network.

    7. You are setting up a hybrid environment. Your webservers are deployed in on-premises infrastructure, and you have a SQL Database deployed in Azure. You have already setup the VPN connection and the webserver can connect to resources in the Azure virtual network. Since Azure SQL Database is a PaaS solution and it’s not directly integrated to the virtual network, you cannot connect to it using a private IP. Your security asked you to find a way to connect to PaaS services via private IP. What is your recommendation?

    • Use Service Endpoint
    • Use ExpressRoute
    • Use Private Link
    • Use Private DB Connection

    Correct answer:

    • Use Private Link

    Explaination: Private Link connection will create an interface for the SQL service in the virtual network and the on-premises resources can connect to it using the private IP.

    8. You have created a DNS zone in Azure called “kodekloudlabs.com”. You added records of your public-facing webservers to the DNS zone. When you try to resolve the DNS names from your Windows computer, they are not getting resolved. What could be the reason?

    • You need to create an on-premises DNS server to resolve the domain name
    • You need to make sure that the requests are going to the Azure provided name servers for resolution
    • You need to change the visibility of your Azure zone to public
    • Try ipconfig /flushdns and retry querying the record

    Correct answer:

    • You need to make sure that the requests are going to the Azure provided name servers for resolution

    Explaination: For the name resolution to work, we need to make sure that the queries are pointed to the name servers provided by Azure.

    9. VM1 is deployed to subnet-1 in VNet-1. We have NSG-1 assigned to subnet-1 and NSG-2 assigned to NIC of VM1. You need to confirm if inbound RDP traffic will be allowed by looking at the following inbound rules:
    question-image
    Select true if traffic is allowed, else select false.

    • True
    • False

    Correct answer:

    • True

    Explaination: Inbound traffic will hit NSG-1 and because of rule 102 traffic will be allowed. Then the traffic will be evaluated by NSG-2, because of rule 104 traffic will be allowed to the VM.

    10. You are not able to connect to one of your VMs on port 22. Following is the NSG inbound rules attached to VM NIC: question-image
    What should be done to establish SSH connectivity to the VM?

    • Change priority to 102 to 100
    • Add a new rule with priority of 105 to allow SSH (22)
    • Add a new rule with priority of 1 to allow SSH (22)
    • Change Action of 101 to Allow

    Correct answer:

    • Change priority to 102 to 100

    Explaination: As the rule 101 is blocking port range 15-24, communication via 22 will be denied. Changing the action of this rule to “Allow” will allow all the ports mentioned in the destination port. As the priority value starts from 100, we cannot add a new rule with allow action. Rules 103 and 104 will be never evaluated as 101 includes the IPs and ports specified in 103 and 104. Based on options, the best choice is to change the priority of 102 to 100.


    chapter-7

    1. You are setting up Windows Server in Azure and would like to establish command line connectivity to the Windows VM. Which is the default port used for this?

    • 3389
    • 22
    • 21
    • 5986

    Correct answer:

    • 5986

    Explaination: WinRM is used to take command line connectivity to Windows VMs, the default port used by WinRM is 5986.

    2. Currently, your organization is using jumpbox VMs to connect to the virtual machines that are deployed in the VNet. Your security team would like to eliminate these jumpbox VMs and replace them with a PaaS solution for better security. Which solution would you suggest?

    • Azure Bastion
    • Azure Firewall
    • Azure Load Balancer
    • Azure Private Link

    Correct answer:

    • Azure Bastion

    Explaination: Azure Bastion is a PaaS solution that can replace jumpbox VMs and the need to manage the public IPs. Connectivity to VMs can be established directly from Azure Portal with the help of Bastion host.

    3. Which of the following statements about Azure Bastion is true? Select all that apply.

    • Azure Bastion can be deployed to any subnet where your VMs are deployed to connect to the VMs.
    • Azure Bastion is PaaS solution.
    • Azure Bastion can be used for Windows VMs only.
    • Azure Bastion (standard tier) can automatically scale in and out based on the number of requests.

    Correct answer:

    • Azure Bastion is PaaS solution.
    • Azure Bastion (standard tier) can automatically scale in and out based on the number of requests.

    Explaination: Azure Bastion requires a dedicated subnet called AzureBastionSubnet, it cannot be deployed alongside with other VMs. Also Azure Bastion can be used for both Linux and Windows VMs.

    4. Your organization needs to encrypt data-in-use due to the sensitivity of the data your organization is handling. Which of the following computing options should you use to achieve this?

    • Azure Disk Encryption
    • Storage Service Encryption
    • Confidential Computing
    • Transparent Data Encryption

    Correct answer:

    • Confidential Computing

    Explaination: Confidential computing offers encryption for data-in-use and it’s ideal for organization that handle sensitive data.

    5. You are deploying DS2v2 VM in East US with a single disk, and your application is quite I/O intensive. Which disk tier will be ideal for your virtual machine?

    • Ultra SSD
    • Super Fast SSD
    • Premium SSD
    • Standard SSD

    Correct answer:

    • Premium SSD

    Explaination: Premium SSDs are apt for applications which are I/O intensive. Though Ultra-disks has higher IOPS compared to Premium SSDs, they are not available for DSv2 family and cannot be used as an OS disk.

    6. What is the SLA offered by Microsoft if you are deploying two or more Virtual Machines across an availability set?

    • 99.00%
    • 99.90%
    • 99.95%
    • 99.99%

    Correct answer:

    • 99.95%

    Explaination: Availability set offers 99.95% SLA.

    7. You are using Availability Set and your application team is insisting on creating the availability to 99.99%. What is the best way to increase SLA for your application?

    • Deploy more instances
    • Use Availability Zones
    • Increase the number of fault domains and update domains
    • Roll back to single VMs and use Azure Load Balancer

    Correct answer:

    • Use Availability Zones

    Explaination: By leveraging Availability Zones, we can increase the SLA to 99.99% and we can save our VMs from datacenter failures.

    8. Currently, your organization's web application is running on single VMs and in Microsoft documentation, you found that there is a service called Virtual Machine Scale Set. What are the advantages of using Virtual Machine Scale Set compared to Virtual Machines? Select all that apply.

    • Virtual Machine Scale Set can automatically change the number of instances based on demand
    • Virtual Machine scale set can be easily integrated with Azure Load Balancer or Application Gateway and there is no need to update the backend pool if the number of instances change.
    • Marketplace and custom images can be scaled with Virtual Machine Scaleset.
    • Cost optimization

    Correct answer:

    • Virtual Machine Scale Set can automatically change the number of instances based on demand
    • Virtual Machine scale set can be easily integrated with Azure Load Balancer or Application Gateway and there is no need to update the backend pool if the number of instances change.
    • Marketplace and custom images can be scaled with Virtual Machine Scaleset.
    • Cost optimization

    Explaination: All options are correct.


    load-balancing

    1. You created two App Services in East US region and are trying to load balance the request with the help of Azure Load Balancer. However, when you configure the backend pool for load balancer, you are not able to find the App Services. You confirmed that these are deployed in the same subscription, resource group and region as load balancer.

    • Make sure App Service is not in stopped state.
    • Ensure you are using the Standard or Premium tier of App Service Plan
    • Contact Microsoft support
    • Azure Load Balancer only supports Virtual Machines and Virtual Machine Scale Set

    Correct answer:

    • Azure Load Balancer only supports Virtual Machines and Virtual Machine Scale Set

    Explaination: Azure Load Balancer only supports VMs and VMSS. For App Services, you can consider using other load balancing solutions.

    2. You are setting up a load balancer with the default session persistence settings. What are the factors that will be considered for routing the traffic to backend servers with the default session persistence settings?

    • Source IP, Destination IP, Protocol, Source Port, Destination Port
    • Source, Destination IP, Source Port, Destination Port
    • Source IP, Destination IP
    • Source IP, Destination IP, Protocol

    Correct answer:

    • Source IP, Destination IP, Protocol, Source Port, Destination Port

    Explaination: By default, Azure Load Balancer uses 5-tuple hash which comprises of Source IP, Destination IP, Protocol, Source Port, and Destination Port.

    3. Azure Application Gateway is a Layer ____ load balancer.

    • 4
    • 5
    • 6
    • 7

    Correct answer:

    • 7

    Explaination: Azure Application Gateway is a Layer-7 Load Balancer.

    4. Azure Load Balancer is a Layer ________ load balancer.

    • 3
    • 4
    • 5
    • 7

    Correct answer:

    • 4

    Explaination: Azure Load Balancer is an L4 Load Balancer.

    5. While deploying Azure Load Balancer, you came to know there are multiple SKUs for Azure Load Balancer. Your application is a production application that requires 99.99% SLA. Which SKU would you choose?

    • Basic
    • Standard
    • Premium
    • Production

    Correct answer:

    • Standard

    Explaination: Azure Load Balancer is offered in Basic and Standard SKU. Only the Standard SKU offers SLA.

    6. Which of the following features are supported by Azure Application Gateway? Select all that apply.

    • URL Redirect
    • SSL termination
    • HTTP header rewrite
    • Custom error pages

    Correct answer:

    • URL Redirect
    • SSL termination
    • HTTP header rewrite
    • Custom error pages

    Explaination: All of the above features are supported by Azure Application Gateway.

    7. One of your applications behind Application Gateway was attacked by attackers and your security team found that they used cross-site scripting to attack the application. Which optional component of Application Gateway should be enabled to avoid these kinds of attacks?

    • Application Proxy
    • DDOS Protection
    • Web Application Firewall
    • Azure Firewall

    Correct answer:

    • Web Application Firewall

    Explaination: WAF (Web Application Firewall) can be used to protect your web applications from cross site scripting and other known vulnerabilities.

    8. Which of the following statements about Azure Application Gateway is true? Select all that apply

    • Azure Application Gateway supports Azure Virtual Machines, Azure VMSS, App Services and App Service deployment slots as backend pools.
    • Azure Application Gateway cannot be used to load balance requests to on-premises application.
    • Behind a single Application Gateway, multiple sites can be hosted.
    • We cannot create empty backend pools in Application Gateway.

    Correct answer:

    • Azure Application Gateway supports Azure Virtual Machines, Azure VMSS, App Services and App Service deployment slots as backend pools.
    • Behind a single Application Gateway, multiple sites can be hosted.

    Explaination: Azure Application Gateway can be used to load balance requests to on-premises or non-Azure web applications. We can create empty backend pools in Application Gateway and backend servers can be added later.

    9. Which of the following is considered as a DNS resolver in Azure?

    • Azure Load Balancer
    • Azure Traffic Manager
    • Azure Application Gateway
    • Azure Front Door

    Correct answer:

    • Azure Traffic Manager

    Explaination: Azure Traffic Manager distributes traffic optimally to services across Azure regions and is a DNS resolver.

    10. If we take all the load balancing solutions in Azure, which of the following can be used for public facing non-Azure applications? Select all that apply.

    • Azure Load Balancer
    • Azure Traffic Manager
    • Azure Application Gateway
    • Azure Front Door

    Correct answer:

    • Azure Traffic Manager
    • Azure Application Gateway
    • Azure Front Door

    Explaination: All load balancing solutions except Azure Load Balancer can be used with non-Azure applications.


    intersite-connectivity

    1. Which would be the cheapest method to establish private connectivity between two virtual networks in Azure? The estimated data transfer is 10 GB per month.

    • VNet-to-VNet connection
    • ExpressRoute
    • Site-to-Site connection
    • Virtual Network Peering

    Correct answer:

    • Virtual Network Peering

    Explaination: Virtual Network Peering is cheap as we need to pay only for the ingress and egress data. In the case of gateways, there will be a fixed charge for gateways in addition to the egress cost.

    2. You would like to set up an architecture where you can use the gateway deployed in the peered network to send traffic to another destination, say, on-premises. Which feature should you enable while setting up peering?

    • Gateway transfer
    • Gateway transit
    • Route table
    • Transit route

    Correct answer:

    • Gateway transit

    Explaination: Gateway transit needs to be enabled to route the traffic from a peered network through the gateway to another destination.

    3. What is the maximum number of peering a single virtual network can have?

    • 100
    • 200
    • 400
    • 500

    Correct answer:

    • 500

    Explaination: You can have up to 500 peering per virtual network.

    4. Which of the following connections can be used as a failover path for ExpressRoute to on-premise site?

    • Point-to-Site
    • Site-to-Site
    • ExpressRoute failover
    • Gateway transit

    Correct answer:

    • Site-to-Site

    Explaination: Site-to-site and ExpressRoute connections can co-exist and S2S can act as a failover path for ExpressRoute.

    5. XYZ Inc. has offices in NYC, LAX and DAL. In addition to deployments in these on-premises offices they have deployment in Azure as well. They need to set-up Site-to-Site connection from Azure to each of their offices. As of now, they only have one virtual network in Azure; how many Virtual Network Gateways and Local Network Gateways are required in Azure to set-up the connectivity?

    • 3 VPN Gateways and 3 Local Network Gateways
    • 1 VPN Gateway and 3 Local Network Gateways
    • 3 VPN Gateways and 1 Local Network Gateways
    • 1 VPN Gateway and 1 Local Network Gateway

    Correct answer:

    • 1 VPN Gateway and 3 Local Network Gateways

    Explaination: You can have only one Virtual Network Gateway per virtual network, however, we can establish multiple connections to the single gateway. The number of connections is dependent on the SKU of the VPN Gateway. Since there are three offices, you need to have three local network gateways in Azure referencing each of the IP/FQDN of on-premises devices in-office.

    6. We have the following VNets in Azure. For which scenarios can we establish peering? question-image

    • A, B, C and D
    • A and B
    • A and C
    • A, C, and D

    Correct answer:

    • A and C

    Explaination: In scenario B, the address spaces are overlapping so we cannot establish peering. In scenario-D, the CIDR for VNet-a is /30; in Azure we can only create till /29. Since the network itself cannot be created, peering cannot be established.

    7. There are three virtual networks in Azure, vnet-a is peered with vnet-b and vnet-b is peered with vnet-c. The resources deployed in vnet-a can communicate with resources in vnet-c.

    • True
    • False

    Correct answer:

    • False

    Explaination: Virtual Network Peering is non-transitive.


    automating-deployment-and-configuration

    1. You need to pass a value during the ARM template deployment. How do we define this in the template?

    • Use parameters
    • Store as a variable and modify as required
    • Create a function which accepts the value
    • Create a dynamic variable

    Correct answer:

    • Use parameters

    Explaination: With the help of parameters, we can provide values at the time of template execution.

    2. Which PowerShell command is used to deploy an ARM template?

    • New-AzTemplateDeployment
    • New-AzGroupTemplateDeployment
    • New-AzResourceGroupTemplate
    • New-AzResourceGroupDeployment

    Correct answer:

    • New-AzResourceGroupDeployment

    Explaination: New-AzResourceGroupDeployment command can be used to deploy an ARM template using PowerShell.

    3. In your organization, there is a need to create a custom Linux image. This image should contain the Apache, PHP and MySQL installation. Also, the default files should be modified with your own HTML files. This custom image will be used with Virtual Machine Scale Set. Your Azure administrator already created a VM with the required software and files. What type of image should you create?

    • Snapshot
    • Specialized image
    • Backup image
    • Generalized image

    Correct answer:

    • Generalized image

    Explaination: Generalized image needs to be created. VMs created from this image require a hostname, admin user, and other VM related setup. This image can be used to create VMs or VMSS.

    4. Which of the following connections can be used as a failover path for ExpressRoute to on-premise site?

    • Point-to-Site
    • Site-to-Site
    • ExpressRoute failover
    • Gateway transit

    Correct answer:

    • Site-to-Site

    Explaination: Site-to-site and ExpressRoute connections can co-exist and S2S can act as a failover path for ExpressRoute.

    5. You would like to export all the resources in a resource group to an ARM template. Which of the following methods can be used. Select all that apply.

    • Use Deployments in Resource Group blade and export the templates
    • Use Export template option in Resource Group blade
    • Use az group export command in Azure CLI
    • Use Export-AzResourceGroupTemplate command in Azure PowerShell

    Correct answer:

    • Use Export template option in Resource Group blade
    • Use az group export command in Azure CLI

    Explaination: We can use the export option in Azure Portal or use the az group export command in Azure CLI. If you want to export using Azure PowerShell, then you need to use the Export-AzResourceGroup command.

    6. Your Windows administrator would like to create multiple domain controllers and file servers using Azure VMs. They already have a PowerShell script for this, the script requires reboot and has complex installation. Which extension would you prefer to accomplish this task?

    • Custom Script Extension
    • PowerShell Remoting Extension
    • Configuration Management Extension
    • Desired State Configuration Extension

    Correct answer:

    • Desired State Configuration Extension

    Explaination: DSC extension can be used for complex installations that require reboot.

    7. What is the maximum run window we have for Custom Script Extension before it hits timeout?

    • 1.5 hours
    • 1 hour
    • 30 minutes
    • 15 minutes

    Correct answer:

    • 1.5 hours

    Explaination: CSE can run scripts up to 90 minutes, anything more that will be returned as a timed out operation.


    securing-storage

    1. You have successfully set up the storage account with GZRS redundancy. How many copies of data will be created by Azure for this redundancy?

    • 3
    • 4
    • 5
    • 6

    Correct answer:

    • 6

    Explaination: GZRS will have six copies of data, three in the primary region and three in the secondary region.

    2. What type of encryption is used by Storage Service Encryption?

    • 128 bit RSA
    • 128 bit AES
    • 256 bit AES
    • 512 bit AES

    Correct answer:

    • 256 bit AES

    Explaination: SSE uses 256-bit AES encryption, which is one of the strongest block ciphers.

    3. Which of the following statement is incorrect?

    • SSE allows you to use Microsoft-managed keys and Customer-managed keys
    • SSE can be disabled for testing purposes from Azure Portal if required
    • Customer-managed keys only supports encryption of files and blobs
    • SSE automatically decrypts the data when you want to access it

    Correct answer:

    • SSE can be disabled for testing purposes from Azure Portal if required

    Explaination: SSE cannot be disabled.

    4. Your organization would like to set-up Geo-Zone-Redundant storage account. Which type of storage account do you recommend for this redundancy?

    • Premium Blob Storage
    • StorageV1
    • StorageV2
    • Premium File Storage

    Correct answer:

    • StorageV2

    Explaination: General Purpose v2 or StorageV2 accounts are needed to use GZRS or RA-GZRS redundancy.

    5. In Azure Disk Encryption for Linux VMs, which tool is used for encryption?

    • BitLocker
    • Crypt-Linux
    • DM-Crypt
    • Crypto

    Correct answer:

    • DM-Crypt

    Explaination: DM-Crypt is used for Linux VMs and BitLocker is used for Windows VMs.

    6. In your development environment, your developers require a storage account which offers at least 99.999999999999 (12 “9s”) of durability. Which type of redundancy should you choose? Make sure your choice is the cheapest one.

    • LRS
    • ZRS
    • GRS
    • GZRS

    Correct answer:

    • ZRS

    Explaination: ZRS offers 99.999999999999% durability, while GRS and GZRS offers 99.(16 9’s) of durability. LRS being the cheapest option offers only 99.(“11 9s”) hence we cannot choose that. The right answer is ZRS.

    7. Your organization follows the principle of least privilege and uses custom RBAC roles to segregate the roles and responsibilities. You need to make sure that your storage admins are able to view, read, and copy the storage account keys. Which action should you add to your custom role?

    • Microsoft.Storage/storageAccounts/listkeys/action
    • Microsoft.Storage/storageAccounts/keys/*
    • Microsoft.Storage/storageAccounts/keys/action
    • Microsoft.Storage/storageAccounts/listkeys

    Correct answer:

    • Microsoft.Storage/storageAccounts/listkeys/action

    Explaination: Users with Microsoft.Storage/storageAccounts/listkeys/action permission will be able to view, read, and copy the storage account keys.

    8. You are partnering with another organization to develop a C# application for your organization. They need a storage account to write logs from development and they need access to the storage account for 31 days. Due to organizational policies, you cannot set up guest accounts for these developers in your tenant. Which authorization method should you use?

    • Storage keys
    • Azure AD + RBAC
    • Storage Access Signature
    • Just in time access

    Correct answer:

    • Storage Access Signature

    Explaination: With the help of SAS, we will be able to provide time bound access to our storage account.

    9. To which all-storage account services can we enable anonymous access?

    • Blobs
    • Files
    • Queues
    • Tables

    Correct answer:

    • Blobs

    Explaination: We can set up anonymous access only for Blob service.

    10. As per your organizational policy, you need to rotate the storage account keys every 60 days. What all things you need to consider before making this change? Select all that apply.

    • All applications using the storage account keys will no longer be able to access the storage account
    • There will be a minor downtime during the process and users accessing storage account using Azure AD will be affected.
    • All SAS token generated with the keys will be revoked
    • No impact on storage account

    Correct answer:

    • All applications using the storage account keys will no longer be able to access the storage account
    • All SAS token generated with the keys will be revoked

    Explaination: Rotating the storage account keys will revoke all SAS tokens and stop applications from accessing the storage account as they are still using old keys. You can consider storing the keys in Key Vault so that the application can obtain the keys from the vault. Users using Azure AD will not be impacted as storage account keys are not used in Azure AD authentication.


    administering-azure-blobs-and-azure-files

    1. Your storage administrator has set the public access level of a blob container to “Blob”. What does that mean?

    • Users will have anonymous read access to a single blob
    • Users will have read access to all blobs in the storage account
    • Users will have read access to blobs in the container
    • Users will have read access to all containers and blobs

    Correct answer:

    • Users will have read access to blobs in the container

    Explaination: Setting the access level of a container to blob will allow anonymous read access to blobs in the container, however, they will not be able to list the blobs in the container. For this, you require anonymous read access at the container level.

    2. You started using blob access tier, however, the manual conversion of access tiers is not feasible considering the amount of data. You are looking for a solution by which you can automatically transition between the access tiers. What do you recommend?

    • Import/Export tool
    • AzCopy
    • Lifecycle management
    • CORS

    Correct answer:

    • Lifecycle management

    Explaination: Lifecycle Management can be used to transition blobs automatically to the next access tier and eventually delete (if required) based on the last modified date.

    3. To which all-storage account services can we enable anonymous access?

    • Blobs
    • Files
    • Queues
    • Tables

    Correct answer:

    • Blobs

    Explaination: We can set up anonymous access only for Blob service.

    4. One of your applications is writing a lot of data to an Azure Storage account. Only a part of it’s accessed regularly, rest of the data remain in the storage account. You should consider which feature of blob storage to optimize the cost of the storage?

    • Use Blob Scavenging option
    • Use Blob Access Tiers
    • Use Blob Access Policy
    • Use Blob Clean up tool

    Correct answer:

    • Use Blob Access Tiers

    Explaination: With the help of access tier, you can transition data between hot, cool, and archive based on the frequency of access.

    5. Now that you are aware of Lifecycle Management, you started implementing it for all storage accounts from Azure Portal. One of your old storage accounts, which is a Premium General Purpose v1 storage account deployed in East US, cannot use this feature. What could be the reason?

    • GPv1 doesn’t support lifecycle management
    • You need to have dedicated storage permission like Storage Blob Data Contributor to enable this feature
    • By default, lifecycle management is disabled for GPv1, however, this can be enabled from storage account properties
    • You cannot enable from Azure Portal, v1 account requires PowerShell or CLI to enable lifecycle management

    Correct answer:

    • GPv1 doesn’t support lifecycle management

    Explaination: GPv1 storage accounts don't support lifecycle management.

    6. Your storage administrator created a file share for you and when you mount it to your on-premises Windows server which is behind a firewall, you are not able to connect to the share. What should be done?

    • Put the Windows server in DMZ
    • Open port 445 on the firewall
    • Provide the Azure AD credentials to complete the setup
    • Add Windows file server role to the server

    Correct answer:

    • Open port 445 on the firewall

    Explaination: Azure File share uses SMB and requires port 445 to be open.

    7. Which one of the following is not a use case of Azure Blob Storage?

    • Embed images or documents in webpages
    • Stream video and audio directly to browser
    • Store files for distributed access in websites
    • Mount as a common storage for virtual machines

    Correct answer:

    • Mount as a common storage for virtual machines

    Explaination: Blob Storage cannot be mounted as a shared storage for virtual machines, for that, you need to use Azure File Storage.


    managing-storage

    1. You have a few GBs of data that needs to be copied to Azure Blobs everyday at 4:00 AM. Which tool do you recommend for this?

    • Import/Export tool
    • Storage Explore
    • Azure Portal
    • AZCopy

    Correct answer:

    • AZCopy

    Explaination: Since we want to copy the data everyday at 4:00 AM, we are looking for more automation. We can write an AZCopy script and create a scheduled task or cron job to copy the data everyday at 4:00 AM.

    2. Which tool is used to prepare the disks in the Import/Export tool?

    • AzImportExport tool
    • WAImportExport tool
    • PSImportExport tool
    • ImportExport tool

    Correct answer:

    • WAImportExport tool

    Explaination: The WAImportExport tool is used to prepare the disks, copy the contents and generate the journal files.


    azure-app-service

    1. One of your production applications requires App Service Backup. The connected MySQL PaaS database is of size 8.3 GB. How can we back this up?

    • Use App Service Backup which supports backup of application and connected database
    • Use Azure Site Recovery and setup backup for the database
    • Use Azure Backup for Database
    • Databases cannot be used with Azure App Services

    Correct answer:

    • Use Azure Backup for Database

    Explaination: The maximum backup database size supported by Azure App Service is 4 GB since the size is larger than that, you need to use Azure Backup for Database.

    2. Following the PaaS first approach, you started using Azure App Services. Before moving to production, you need to test your applications on Azure App Service. As per your development team, they require dedicated compute which is ideal for development and testing. What tier do you suggest? Make sure your suggestion is the cheapest option.

    • Free
    • Shared
    • Basic
    • Standard

    Correct answer:

    • Basic

    Explaination: The Basic plan provides dedicated compute and is recommended for all development and testing purposes. Even though Free and Shared are recommended for development and they are cheap, they are using shared compute.

    3. You have a production application with the name kodekloud and the URL for the app is https://kodekloudsales.azurewebsites.net. You would like to set up a custom domain name sales.kodekloud.com. Which record type should you add to verify the ownership before you configure the alias?

    • CNAME
    • SRV
    • A
    • TXT

    Correct answer:

    • TXT

    Explaination: You need to add the unique ID as the value of the TXT record in your domain to verify the domain ownership.

    4. You have a webapp with the URL: kodekloud-courses.azurewebsites.net. You created a deployment slot named "dev". What would be the URL to the slot?

    • dev-kodekloud-courses.azurewebsites.net
    • kodekloud-courses-dev.azurewebsites.net
    • kodekloud-courses.dev.azurewebsites.net
    • dev.kodekloud-courses.azurewebsites.net

    Correct answer:

    • kodekloud-courses-dev.azurewebsites.net

    Explaination: The name of the slot will be added as a suffix to the production slot.

    5. Your production application is facing performance issues while too many users are accessing your application. Currently, your application is running on a Basic App Service Plan. As per your analysis, you require five instances to handle the load. Suggest a solution for this and make sure your choice is the cheapest one.

    • Enable autoscaling for Basic tier
    • Upgrade to Isolated tier
    • Upgrade to Premium tier
    • Upgrade to Standard tier

    Correct answer:

    • Upgrade to Standard tier

    Explaination: Basic doesn’t offer auto scaling, you need to upgrade to Standard as it offers a maximum of five instances and is cheaper, considering other tiers that support autoscaling.

    6. Out of the following CI/CD methods, which are considered as manual deployment methods? Select all that apply.

    • Bitbucket
    • OneDrive
    • Dropbox
    • External Git

    Correct answer:

    • OneDrive
    • Dropbox
    • External Git

    Explaination: All choices except Bitbucket are manual deployment methods. Bitbucket, Git, GitHub, and Azure Repos are considered as automated deployment options.

    7. Which of the following can be swapped during a deployment slot swap?

    • Connection strings
    • Custom domain names
    • TLS/SSL settings
    • CORS

    Correct answer:

    • Connection strings

    Explaination: Connection strings can be swapped during a deployment slot swap, rest of the choices cannot be swapped.

    8. What factor determines the number of deployment slots you can have for an App Service?

    • Tier of the App Service Plan
    • Operating System of the plan
    • Runtime of the webapp
    • Location of the webapp

    Correct answer:

    • Tier of the App Service Plan

    Explaination: App Service Plan tier decides the number of deployment slots you can have for a webapp. Deployment slot is supported only from Standard plan onwards.


    configuring-containers

    1. You are planning to deploy Azure Kubernetes Services. As per specifications, you would require a three node cluster. How the pricing for AKS is calculated for compute resources?

    • Pay for the number of nodes and Azure managed nodes
    • Pay for AKS, based on the tier you will be charged. There is no additional compute cost
    • Pay for the three nodes
    • Pay for Azure managed node only

    Correct answer:

    • Pay for the three nodes

    Explaination: You need to pay only for the number of customer managed nodes, there is no cost for the Microsoft managed node.

    2. You need to open a specific port in your AKS cluster for internal communication. Which service should you use?

    • Ingress Controller
    • ClusterIP
    • NodePort
    • LoadBalancer

    Correct answer:

    • ClusterIP

    Explaination: ClusterIP facilitates internal communication with other apps in your cluster. There is no external access.

    3. For creating a Kubernetes object, you need to write the manifest files. Which extensions are supported for the manifest file? Select all that apply.

    • YAML
    • JSON
    • XML
    • ARM

    Correct answer:

    • YAML
    • JSON

    Explaination: Kubernetes supports YAML and JSON languages for writing manifests.

    4. Which of the following methods can be used to deploy a container group? Select all that apply.

    • Azure PowerShell
    • YAML
    • Azure Portal
    • Azure Resource Manager templates

    Correct answer:

    • YAML
    • Azure Resource Manager templates

    Explaination: We can use YAML and ARM templates to deploy Container Groups. If your container groups include Azure resources like file share, then ARM template is the better option.

    5. While setting up the networking for AKS, you need to make sure each pod in your cluster get an IP address from the virtual network. Which network configuration should you select?

    • Kubenet
    • Kube-proxy
    • Azure CNI
    • Kubelet

    Correct answer:

    • Azure CNI

    Explaination: Azure CNI networking plug-in allows cluster to use a new or existing VNet with customizable addresses. Application pods are connected directly to the VNet, which allows for native integration with VNet features.

    6. Which service is used for AKS bursting?

    • Azure Virtual Machines
    • Azure Virtual Machines Scale Set
    • Azure Container Registry
    • Azure Container Instances

    Correct answer:

    • Azure Container Instances

    Explaination: Azure Container Instances are used to create virtual nodes during AKS bursting due to the low start-up time compared to virtual machines.

    7. What do we call the smallest unit of application instance which is a collection of one or more containers?

    • Pod
    • Deployment
    • Service
    • Replica Set

    Correct answer:

    • Pod

    Explaination: Pod is the single instance of your application which is a collection of one or more containers.

    8. Which of the following statement is incorrect?

    • Azure Container Instances is a PaaS solution
    • You can only have public IPs for ACI
    • You can use Azure Files as persistent storage for ACI
    • ACI can use images stored in Azure Container Registry

    Correct answer:

    • You can only have public IPs for ACI

    Explaination: Azure Container Instance can have public IPs as well as private IPs.


    implement-backup-and-recovery

    1. Which agent should you use to back-up on-premises files and folders?

    • MABS
    • MARS
    • waagent
    • MMA

    Correct answer:

    • MARS

    Explaination: Microsoft Azure Recovery Services (MARS) is used to backup on-premises files and folders to Recovery Services Vault.

    2. What is the default redundancy for a newly created Recovery Services Vault?

    • LRS
    • ZRS
    • GRS
    • GZRS

    Correct answer:

    • GRS

    Explaination: Recovery Service Vaults are created with the default redundancy as Geo-redundant storage.

    3. We have the following resources in Azure. Which of the following can be backed up to vault-01? question-image

    • db-vm only
    • db-vm and share01
    • share01 and web-vm
    • db-vm, share01, and web-vm

    Correct answer:

    • db-vm and share01

    Explaination: Since the vault-01 is in East US, we will be able to select the resources that are there in East US only.

    4. You have the following resources in Azure:

  • Blob container – imgfiles
  • File share – executables
  • VM – VM-01
  • Azure Database for MySQL – wordpress

  • Which of the following can be backed up to a recovery services vault?

    • File share and VM
    • Blob container, file share, VM, and Azure Database for MySQL
    • File share, VM, and Azure Database for MySQL
    • VM and Azure Database for MySQL

    Correct answer:

    • File share and VM

    Explaination: In the Recovery Service vault, we can only backup VMs and file shares. For the Blob container and Azure Database for MySQL, you need to use the Backup vault.

    5. Following is the contents of Recovery Services vaults in one of the subscriptions: question-image
    All of these vaults were created with the default redundancy GRS. Which all vaults can be converted to LRS vaults?

    • Vault-01 and Vault-02
    • Vault-04 only
    • Vault-02 and Vault-03
    • Vault-03 only

    Correct answer:

    • Vault-03 only

    Explaination: We can convert GRS vault to the LRS vault before we protect any resources. In this case, vault-03 is empty, which means we can still convert that to LRS.

    6. You have on-premises and Azure VMs that require backup. You are planning to use Microsoft Azure Backup Server to configure the backup. Which of the following on-premises workloads are not supported by MABS?

    • Windows Server
    • Linux Servers on Hyper-V
    • Oracle workloads
    • Exchange servers

    Correct answer:

    • Oracle workloads

    Explaination: Oracle workloads are not supported by MABS.


    network-monitoring-and-resource-monitoring

    1. Users claim that some of the DNS queries to one of your public facing DNS servers running on Azure VM are failing. You need to check if the requests are hitting the Azure VM. How can we troubleshoot this?

    • Use NSG flow logs and verify if the clients are reachable from the DNS server
    • Use IP flow to confirm if the port 53 is open for DNS
    • Use Effective Security Rules to verify if the DNS port is open
    • Use Packet Capture to confirm if the request from the clients are hitting the server

    Correct answer:

    • Use Packet Capture to confirm if the request from the clients are hitting the server

    Explaination: Use Packet Capture on the DNS server and verify if the requests are hitting the server.

    2. You are using Azure Virtual Desktop and users are complaining that a couple of websites take longer to load. They don’t experience the same when they access these websites from their laptops. You need to troubleshoot this by finding the latency and connectivity to the endpoint. Which tool should you use?

    • Connection Monitor
    • Packet capture
    • IP Flow verify
    • Topology

    Correct answer:

    • Connection Monitor

    Explaination: Connection Monitor can be used to check the connectivity and latency between your virtual machines and IP addresses/ FQDNs.

    3. Your organization is using ExpressRoute to connect to on-premises. Your network administrators stated that they are seeing performance issues with the circuit. Which tool should you use to troubleshoot this?

    • ExpressRoute troubleshoot
    • Connection Monitor
    • VPN diagnostics
    • NSG flow logs

    Correct answer:

    • VPN diagnostics

    Explaination: VPN diagnostics can be run against any gateway to get performance and other relevant metrics. The collected data will be stored in a storage account.

    4. One of your route tables was deleted and you need to filter the activity logs to find who deleted it. Which category should you select to filter the logs?

    • Alert
    • Policy
    • Resource Health
    • Administrative

    Correct answer:

    • Administrative

    Explaination: All operations made using Azure Resource Manager will be logged in the Administrative category.

    5. When it comes to the billing of Log Analytics which all meters are considered? Select all that apply.

    • Data ingestion
    • Connected sources
    • Data retention
    • Number of queries

    Correct answer:

    • Data ingestion
    • Data retention

    Explaination: Microsoft charges for the amount of data ingested and for the number of days data is stored. Retention up to 31 days is free of cost.

    6. What is the default retention period for activity logs?

    • 30 days
    • 60 days
    • 90 days
    • 120 days

    Correct answer:

    • 90 days

    Explaination: Activity Logs are stored for 90 days, you can ingest the logs to storage account if you need retention more than 90 days.

    7. In the action group, what are the supported notification methods? Select all that apply.

    • Secure webhook
    • Webhook
    • Automation Runbook
    • Event Grid

    Correct answer:

    • Secure webhook
    • Webhook
    • Automation Runbook

    Explaination: Supported actions are Secure Webhook, Webhook, Logic App, Function App, Automation Runbook and ITSM.

    8. You are ingesting "cron" logs from your Linux servers to Log Analytics. Which table should you query to get the ingested logs?

    • Heartbeat
    • Syslog
    • Cron
    • Perf

    Correct answer:

    • Syslog

    Explaination: Cron is one of the facilities provided by syslog, all data ingested will be stored in the syslog table.

    9. Your organization uses Service Now to log internal IT events. You need to set up an alert for high CPU utilization for your production server. When this alert is fired, you need to create a ticket in ServiceNow. What should you do?

    • In Action groups, use ITSM
    • Create an Event Hub and send the event to Service Now
    • Trigger emails to admins, so that they can create a ticket
    • Use runtime integration

    Correct answer:

    • In Action groups, use ITSM

    Explaination: Use ITSM to send alerts to your IT service management tools.

    10. Which one of the following is an Application Performance Monitoring tool?

    • Azure Log Analytics
    • Azure Monitor
    • Azure Application Insights
    • Azure Application Metrics

    Correct answer:

    • Azure Application Insights

    Explaination: Azure Application Insights is an APM tool that can be used to monitor your application.

    11. Name the datastores used by Azure Monitor to store the collected data? Select all that apply.

    • Workspace
    • Metrics
    • Activity Logs
    • Logs

    Correct answer:

    • Metrics
    • Logs

    Explaination: Metrics and Logs are the two datastores used by Azure Monitor to store the data collected from a variety of sources.


    hashicorp-access-control

    1. As part of an internal initiative your organization has decided to implement the Vault Enterprise feature of Control Groups. The goal is to add a layer of protection for certain activities in Vault. Which of the following statements most accurately describes the function of a Control Group?

    • Control Groups are a different way of managing access to items in Vault.
    • Control Groups enable fine grained control through "policy as code".
    • Control Groups help organize Vault identities into logical groups to more easily manage access.
    • Control Groups add additional authorization factors to be required before satisfying a request.

    Correct answer:

    • Control Groups add additional authorization factors to be required before satisfying a request.

    2. An internal compliance initiative has been adopted at your organization, and the head of the compliance team is interested in how Sentinel can integrate with Vault. Sentinel can provide a rich set of access control functionality that goes beyond the standard Vault ACL policies. What are the two additional policy types that can be used with Sentinel? (Select two)

    • Role Governing Policies (RGPs)
    • Secret Governing Policies (SGPs)
    • Authentication Governing Policies (AGPs)
    • Endpoint Governing Policies (EGPs)

    Correct answer:

    • Role Governing Policies (RGPs)
    • Endpoint Governing Policies (EGPs)

    3. Your organization has begun using Vault Namespaces to more securely segment data with multi-tenancy. A Vault namespace was created named NA at the root level. A secret lives at the secret/database/postgres path in the NA namespace. Assuming that a Vault policy was granting the read permission, which of the following scenarios would properly grant access to that secret. (Select three)

    • A Vault policy created at the root level with permissions on the secret/database/postgres path.
    • A Vault policy created at the root level with permissions on the NA/secret/database/postgres path.
    • A Vault policy created in the NA Namespace with permissions on the secret/database/postgres path.
    • A Vault policy created in the NA Namespace with permissions on the NA/secret/database/postgres path.
    • A Vault policy created at the root level with permissions on the +/secret/database/postgres path.

    Correct answer:

    • A Vault policy created at the root level with permissions on the NA/secret/database/postgres path.
    • A Vault policy created in the NA Namespace with permissions on the secret/database/postgres path.
    • A Vault policy created at the root level with permissions on the +/secret/database/postgres path.

    4. You are currently working on constructing Vault policies to allow other teams to manage secrets for their specific applications. The acme-secret-manager policy should grant sufficient permissions to create new secrets, revise existing secrets, and delete secrets under the secret/finance/acme/ path, as well as ALL child paths. Which Vault policy stanza below would grant the required permissions while ALSO following the concept of "least privilege"? (select one)

    • path "secret/finance/acme/" {capabilities = ["create", "update", "delete"]}
    • path "secret/finance/acme/*" {capabilities = ["create", "update", "delete"]}
    • path "secret/finance/acme/*" {capabilities = ["list", "read", "create", "update", "delete"]}
    • path "secret/finance/acme/+" {capabilities = ["create", "update", "delete"]}
    • path "secret/finance/acme*" {capabilities = ["create", "update", "delete"]}

    Correct answer:

    • path "secret/finance/acme/*" {capabilities = ["create", "update", "delete"]}

    hashicorp-scale-performance

    1. Your organization has already implemented Vault Enterprise and plans to use Performance Replication between the North America and European regions. Due to GDPR compliance, you need to ensure that certain secret data is not replicated from the European region to North America once replication is enabled. Which Vault feature would allow you to enable replication, while also ensuring that specific data in Europe is NOT replicated to North America?

    • Endpoint Governing Policies (EGPs)
    • Paths filters
    • Namespaces
    • Vault tokens with "token bound CIDRs"

    Correct answer:

    • Paths filters

    Explaination: EGPs are an integration with Sentinel to restrict access based on paths in Vault.

    The paths filter feature enables users to allow or deny which secrets engines are replicated between clusters, and is the best choice.

    Vault Namespaces are used for secure tenet isolation, but due not inherently prevent data from being replicated without paths filters.

    Tokens with bound CIDRs restrict the range of client IPs allowed to use that token, and would not prevent data from being replicated.

    2. Your organization has recently integrated Vault with a large scale container based application. The application frequently spins up a large number of containers and all will request a token from Vault. Your team has noticed that this activity has a noticeable impact on performance and the storage backend of the Vault cluster. To reduce that impact you are exploring the use of batch tokens. Which statement is true regarding the benefits of batch tokens?

    • Batch tokens can be set as "periodic", essentially making tokens never expire as long as they are renewed within the TTL.
    • Batch tokens are actually more "heavyweight" than service tokens and require multiple writes to create tokens.
    • You can create batch tokens to act as root tokens.
    • Batch token creations can scale with the number of performance standby nodes.

    Correct answer:

    • Batch token creations can scale with the number of performance standby nodes.

    Explaination: Batch tokens cannot be created as periodic tokens.

    Batch tokens are more "lightweight" than service tokens and have no storage cost for token creations.

    Batch tokens cannot be root tokens. Additionally, you should almost never use root tokens during day-to-day operations.

    Typical service tokens require a write/create operation, which would need to be forwarded to the leader node. Batch tokens are encrypted blobs that carry enough information for them to be used for Vault actions, and can scale with the number of performance standby nodes in the cluster.

    3. Your team has recently upgraded from open source Vault to Vault Enterprise in order to utilize performance standby nodes. Which of the following is true regarding performance standby nodes?

    • Performance standby nodes will attempt to locally process client read requests and automatically forward write requests to the leader/active node.
    • Performance standby nodes are only available when using the Consul storage backend.
    • Performance standby nodes scale the overall performance of the Vault cluster by handling both read and write requests locally.
    • Performance standbys can only be used when Performance replication is ALSO enabled.

    Correct answer:

    • Performance standby nodes will attempt to locally process client read requests and automatically forward write requests to the leader/active node.

    Explaination: Performance standby nodes only handle read requests locally.

    Performance standbys can be used with any storage backend that support "high availability" mode, including Integrated Storage (Raft), Consul, ZooKeeper and etcd.

    Performance standby nodes will only handle read requests locally and forward write requests to the leader node.

    Performance standbys DO NOT require any sort of replication to be enabled.

    4. You are currently working with the executive team to grow the usage of Vault Enterprise to multiple cloud regions and data-centers across your infrastructure. The goal is to have applications in multiple clouds, in multiple regions, all interact with Vault to retrieve secrets. In addition you want to ensure applications can communicate with Vault in the local region to reduce latency for network requests. What would be the best solution the meet these requirements?

    • Increase the number of nodes in the Vault cluster and use performance standbys to increase performance for the new load from applications.
    • Create new Vault clusters in each region that applications reside. Then enable Disaster Recovery Replication on the new clusters, allowing client requests to be handled locally.
    • Create new Vault clusters in each region that applications reside. Then enable Performance Replication on the new clusters, allowing client requests to be handled locally.
    • Create multiple secret engine mount points on a per-region basis. Each region will have dedicated secret engine mount points, splitting the load of requests from new applications.

    Correct answer:

    • Create new Vault clusters in each region that applications reside. Then enable Performance Replication on the new clusters, allowing client requests to be handled locally.

    Explaination: Performance standbys increase the performance in a single Vault cluster, but do not meet the requirement of needing to handle Vault requests locally in each region.

    DR clusters act as "warm standbys" and cannot handle Vault requests.

    PR clusters replicate Vault data to new regions, as well as enabling the handling of client requests locally.

    Multiple secret engine mount points would not meet the requirements outlined.


    hashicorp-hsm

    1. Due to a new compliance initiative, the ACME company would like to increase security and compliance for their Vault environment. They have sought out your guidence regarding the use of a Hardware Security Module (HSM). They want clarification regarding the availability of their HSM once it is integrated with their Vault cluster as the seal mechanism. ACME currently believes that there is no need for the HSM to be online and available to Vault once the Vault cluster has been unsealed.

    • True
    • False

    Correct answer:

    • False

    Explaination: False: The HSM is used for the auto-unseal process, but is also used for other potential operations during normal activity. Such as generating various CSPs or for entropy augmentation, any write operations on mount points with seal wrapping enabled, and Vault token generations with entropy augmentation enabled.

    2. Your organization has already configured the current Vault environment to use an HSM as the seal mechanism for your Vault cluster. Your manager now wants to explore the use of seal wrapping. What statement most accurately describes the benefits of using seal wrapping with an HSM.

    • Seal wrapping adds an extra layer of security by adding an extra layer to unseal keys. Essentially requiring two different sets of unseal keys to be supplied to unseal the Vault cluster.
    • Seal wrapping is the default encryption used to encrypt Vault data, and does not require a Vault Enterprise license.
    • Seal wrapping adds an extra layer of protection by wrapping values with an extra layer of encryption, and when used with an HSM, conforms with FIPS 140-2 directives on Key Storage and Key Transport.
    • Seal wrapping adds an extra layer of protection by wrapping values with an extra layer of encryption, but does not provide any accredited or certified benefits.

    Correct answer:

    • Seal wrapping adds an extra layer of protection by wrapping values with an extra layer of encryption, and when used with an HSM, conforms with FIPS 140-2 directives on Key Storage and Key Transport.

    Explaination: Seal wrapping is involved with wrapping RECOVERY keys in an extra layer of protection, but would not create a second set of unseal keys.

    Seal wrapping requires a Vault Enterprise license.

    Seal wrapping is a mechanism to wrap values with an extra layer of encryption. Vault's Seal Wrap feature has been evaluated by Leidos for compliance with FIPS 140-2 requirements. When used with a FIPS 140-2-compliant HSM, Vault will store Critical Security Parameters (CSPs) in a manner that is compliant with KeyStorage and KeyTransit requirements.

    Vault's Seal Wrap feature has been evaluated by Leidos for compliance with FIPS 140-2 requirements.

    3. Many organizations seek to reduce the operational complexity of running Vault by using auto-unseal to automatically unseal the Vault cluster without needing to supply unseal keys. Your leadership team wants to use an HSM in the current Vault environment, and believes that Vault supports the use of an HSM for auto-unseal.

    • True
    • False

    Correct answer:

    • True

    Explaination: True: Vault supports the use of an HSM, as well as various cloud KMS services for auto-unseal.


    hashicorp-vault-agent

    1. Your organization has begun using the Vault Agent to more easily integrate applications with Vault for secure secrets. Use the provided Vault Agent configuration below to answer. Based on the above configuration, the Vault Agent will authenticate to Vault, retrieve a Vault token, and then exit/shutdown the Vault Agent process.

    • True
    • False

    Correct answer:

    • False

    Code:

    listener "tcp" {
      address = "127.0.0.1:8200"
    }
    
    vault {
      address = "https://vault-demo.com:8200"
    }
    
    ### Depending on how difficult we want to make the question this can be removed. Default value/behavior is false.
    exit_after_auth = false
    
    auto_auth {
      method "approle" {
        config = {
          role_id_file_path = "./roleid"
          secret_id_file_path = "./secretid"
          remove_secret_id_file_after_reading  = false
        }
      }
    }
    
    sink {
      type = "file"
      config = {
        path = "/opt/sink_file_1.txt"
        mode = "0640"
      }
    }
    
    template {
      source = "./test.tmpl"
      destination = "./test.txt"
    }
    

    2. Below is an example Vault Agent template configuration. Given the provided example, select all answers that are correct. (Select three)

    • The path of the secret in Vault is secret/data/app1
    • The secret in Vault contains a key with the name ID
    • The secret in Vault contains a key with the name username
    • The secret in Vault contains a key with the name color
    • The path of the secret in Vault is Data/data/app1

    Correct answer:

    • The path of the secret in Vault is secret/data/app1
    • The secret in Vault contains a key with the name username
    • The secret in Vault contains a key with the name color

    Code:

    {{ with secret "secret/data/app1" }}
    ID: {{ .Data.data.username }}
    Color: {{ .Data.data.color }}
    {{ end }}
    

    3. Your organization has begun using the Vault Agent to more easily integrate applications with Vault for secure secrets. Use the provided Vault Agent configuration below to answer. Based on the configuration the Vault Agent will attempt to connect to the Vault cluster at which address?

    • https://127.0.0.1:8200.
    • It is using a Unix socket listener on localhost.
    • The configuration file does not contain that information and needs to be configured in the unit file or startup command.
    • https://vault-demo.com:8200.

    Correct answer:

    • https://vault-demo.com:8200.

    Code:

    listener "tcp" {
      address = "127.0.0.1:8200"
    }
    
    vault {
      address = "https://vault-demo.com:8200"
    }
    
    ### Depending on how difficult we want to make the question this can be removed. Default value/behavior is false.
    exit_after_auth = false
    
    auto_auth {
      method "approle" {
        config = {
          role_id_file_path = "./roleid"
          secret_id_file_path = "./secretid"
          remove_secret_id_file_after_reading  = false
        }
      }
    }
    
    sink {
      type = "file"
      config = {
        path = "/opt/sink_file_1.txt"
        mode = "0640"
      }
    }
    
    template {
      source = "./test.tmpl"
      destination = "./test.txt"
    }
    

    4. Your organization has begun using the Vault Agent to more easily integrate applications with Vault for secure secrets. Use the provided Vault Agent configuration below to answer. Based on the configuration, which of the following statements are correct? (Select two)

    • The Vault Agent will store the Vault token retrieved during authentication and make it readable to ALL users on the system.
    • The Vault Agent will attempt to use templating configurations found in the ./test.tmpl file.
    • The Vault Agent will store the Vault token retrieved during authentication and make it readable to the file owner and members of the same group as the file owner.
    • The Vault Agent is using response wrapping to more securely authenticate to Vault with a role ID and secret ID.
    • The Vault Agent will attempt to use templating instructions found in the ./test.txt file.

    Correct answer:

    • The Vault Agent will attempt to use templating configurations found in the ./test.tmpl file.
    • The Vault Agent will store the Vault token retrieved during authentication and make it readable to the file owner and members of the same group as the file owner.

    Code:

    listener "tcp" {
      address = "127.0.0.1:8200"
    }
    
    vault {
      address = "https://vault-demo.com:8200"
    }
    
    ### Depending on how difficult we want to make the question this can be removed. Default value/behavior is false.
    exit_after_auth = false
    
    auto_auth {
      method "approle" {
        config = {
          role_id_file_path = "./roleid"
          secret_id_file_path = "./secretid"
          remove_secret_id_file_after_reading  = false
        }
      }
    }
    
    sink {
      type = "file"
      config = {
        path = "/opt/sink_file_1.txt"
        mode = "0640"
      }
    }
    
    template {
      source = "./test.tmpl"
      destination = "./test.txt"
    }
    

    5. Which of the following auto-auth methods is NOT a valid option for the Vault Agent to use to authenticate to Vault. (Select one)

    • AWS
    • Kubernetes
    • LDAP
    • Azure
    • AppRole

    Correct answer:

    • LDAP

    hashicorp-security

    1. Many organizations are moving to hosting applications in Kubernetes clusters. When it comes to Vault, it is important to understand additional considerations when hosting services in a container based environment. Which of the following items is NOT a recommended step to mitigate potential security vulnerabilities when running Vault on Kubernetes?

    • Ensure mlock is enabled
    • Ensure end-to-end encryption via the use of TLS certificates
    • Ensure the Vault process is not running as the root user
    • Offload TLS by ensuring that traffic is terminated at load balancers

    Correct answer:

    • Offload TLS by ensuring that traffic is terminated at load balancers

    Explaination: It is always recommended to NOT terminate TLS at load balancers to ensure that the Vault traffic is always encrypted in transit.

    2. The Real Good Foods Company has also approached you regarding the patterns of authentication applications use to integrate with Vault. Currently a vast majority of their applications run in either AWS or GCP. They are considering the use of the platform integration model, but have heard that cloud based auth providers like AWS, GCP, and Azure, are not recommended and that AppRole auth is more secure. True or false, AppRole auth is recommended for use over third-party/cloud auth methods.

    • True: AppRole should be used over third-party or cloud auth providers
    • False: Cloud based or third-party auth providers should be used when possible, and use AppRole as a fallback

    Correct answer:

    • False: Cloud based or third-party auth providers should be used when possible, and use AppRole as a fallback

    Explaination: False; If another platform method of authentication is available via a trusted third-party authenticator, it is best practice to use that instead of AppRole. In some situations it may not be possible to use a trusted third-party auth provider, and AppRole exists for those cases.

    3. You have been hired by the Real Good Foods Company to assist with improving their current usage of Vault. A number of applications are already integrated with Vault, but they want to ensure the interactions and workflows they use are secure. Which of the following choices is NOT a good goal for secure introduction of Vault clients?

    • Using short TTLs on tokens and leases wherever possible
    • Using hardcoded credentials in code to ensure uptime
    • Using a trusted platform to verify the identity of applications/clients
    • Using a trusted orchestrator to inject secrets to applications

    Correct answer:

    • Using hardcoded credentials in code to ensure uptime

    Explaination: You should try to avoid the use of hardcoded credentials whenever possible. All other choices are great goals for the secure introduction of Vault clients.

    4. You are currently working to onboard applications to leverage Vault for secure secret storage. You have been told to utilize a "trusted orchestrator" to handle the way these applications get their secrets. Which of the following is an example of the "trusted orchestrator" model for secure introduction of Vault clients?

    • The Vault Agent using auto-auth
    • Using a cloud provider like AWS to gather metadata for an EC2 instance to verify application identities during authentication
    • Terraform using an existing token with capabilities to generate AppRole credentials, and injecting them into an application build
    • The Github authentication method

    Correct answer:

    • Terraform using an existing token with capabilities to generate AppRole credentials, and injecting them into an application build

    Explaination: The Terraform example best represents the use of a "trusted orchestrator". The Vault agent is another method of securely introducing Vault clients, and "Using a cloud provider like AWS to gather metadata for an EC2 instance to verify application identities during authentication" describes the "platform integration" model. The remaining option is just the Github auth method and does not describe the trusted orchestrator model.


    hashicorp-monitor

    1. You have been tasked with increasing the visibility your organization has about the Vault environment. As part of this task you need to configure Vault telemetry settings. Where would you find telemetry settings to forward telemetry data to a collector agent?

    • In the Vault UI under the "Status" menu
    • sys/telemetry
    • The Vault configuration file
    • sys/tools/telemetry

    Correct answer:

    • The Vault configuration file

    Explaination: Telemetry is configured in the Vault configuration file using the telemetry stanza.

    2. As part of a new compliance standard you have recently turned on one audit device using the file audit method. After a few days you start getting messages from your team that they cannot interact with Vault and it appears that the service is down. After some initial investigation you discover that the Vault service is running, but you get errors when you run any sort of Vault command. What is the most likely cause?

    • The new audit device detected malicious activity and automatically locked down your Vault environment
    • After enabling the audit device the servers hosting Vault could not handle the additional resource intensive load and are unresponsive
    • Drive space on the server has filled up and the file audit method cannot write to the log file, causing to Vault stop handling requests
    • It is likely just some sort of network issue that will resolve itself

    Correct answer:

    • Drive space on the server has filled up and the file audit method cannot write to the log file, causing to Vault stop handling requests

    Explaination: The key piece here is that you just turned on a SINGLE audit device a few days ago. If there are any audit devices enabled, Vault requires that it can write to the log before completing ANY client requests. There is no built-in feature to monitor and lock down Vault, so that option is not true. It may be possible for the servers hosting the Vault to be unable to handle the load and become unresponsive, but unlikely if you are able to login to the server and verify the Vault service is running. "It is likely just some sort of network issue that will resolve itself," is just wishful thinking and is more than likely not true.

    3. Your security and compliance team has concerns regarding Vault audit logs, and the potential of storing sensitive information in plain text. In what case will Vault audit logs store sensitive information like secrets and tokens in plain text?

    • Sensitive information is hashed, and never stored in plain text
    • Only when using the "File" audit method
    • Only when using the "Syslog" audit method
    • Only when using the "Socket" audit method

    Correct answer:

    • Sensitive information is hashed, and never stored in plain text

    Explaination: Sensitive information is hashed with a salt using HMAC-SHA256 to ensure secrets and tokens are never in plain text.

    4. Your security and compliance team has approached you with questions regarding logs that are currently being collected from Vault. They are interested in understanding what sort of information different Vault logs contain. Which statement best describes the difference between audit and telemetry logs?

    • Audit logs are a detailed log of all authenticated requests and responses to Vault​, and telemetry simply tracks Raft leadership elections and changes.
    • Audit logs are a collection of various runtime metrics about the performance of different components of the Vault environment​, and telemetry logs are a detailed log of all authenticated requests and responses to Vault​​.
    • Audit logs only contain information about initial client authentication requests, all other authenticated requests and responses are in telemetry logs.
    • Audit logs are a detailed log of all authenticated requests and responses to Vault​, and telemetry logs are a collection of various runtime metrics about the performance of different components of the Vault environment​.

    Correct answer:

    • Audit logs are a detailed log of all authenticated requests and responses to Vault​, and telemetry logs are a collection of various runtime metrics about the performance of different components of the Vault environment​.

    Explaination: Audit logs contain detailed info about ALL authenticated requests and responses to Vault, essentially the who, what, when, and where. Telemetry logs contain various runtime metrics like how much memory the Vault process is using, as well as endpoint usage and performance.


    hashicorp-basics

    1. Due to an internal compliance audit at your client Binford Tools, they have contacted you about performing a rotate and rekey in their Vault environment. They are unsure if and when they will need their current unseal keys during these processes. True or false, BOTH the rotate and rekey operations require a threshold of key holders with key shares to be performed?

    • True
    • False

    Correct answer:

    • False

    Explaination: False: Only the Rekey operation requires a threshold of key holders with key shares to be performed. Since the encryption key is never available to users or operators, the rotate operations does NOT require a threshold of key holders.

    2. Your management team has approached you regarding the Vault environment at your organization. They recently heard something about an "auto unseal" feature, and what options are available to enable it. Which of the following options is NOT a supported method for auto unseal?

    • Shamir
    • Cloud Key Management Services (KMS) like AWS KMS
    • Vault Transit Secret Engine
    • Hardware Security Module (HSM)

    Correct answer:

    • Shamir

    Explaination: Shamir is the default seal mechanism for Vault but does not support auto unseal. When using Shamir a threshold of key shares must be supplied to unseal Vault. All other options support auto unseal.

    3. Vance Refrigeration has an Enterprise Architect that had previously deployed Vault a few years ago using Consul as the storage backend. He is unsure what Integrated Storage (Raft) is, and wants to know why they should use it. Which of the following is NOT a benefit of deploying Vault with Raft as the storage backend, compared to Consul?

    • Using Raft reduces the number of network ports used for communication
    • Raft can reduce operational costs by lowering the total number of nodes/VMs required for an HA cluster
    • Raft stores all data in memory
    • Raft stores data locally and reduces extra network hops when data needs to be retrieved from the storage backend.

    Correct answer:

    • Raft stores all data in memory

    Explaination: Raft stores data on local disk rather NOT in memory (Consul does). All other options are valid benefits for using Raft as the storage backend.

    4. You are currently working with Vance Refrigeration on deploying a highly scalable Vault environment with Integrated Storage (Raft) as the storage backend. Performance is a key factor for the team, as they want to ensure Vault is available when clients need to requests secrets from Vault. When deploying a Vault cluster with Raft, which hardware resource is TYPICALLY the key bottleneck for performance?

    • CPU
    • Network Throughput
    • Disk IOPS
    • Memory

    Correct answer:

    • Disk IOPS

    Explaination: Since Integrated Storage stores all data on a local disk, Vault servers should have a relatively high-performance hard disk optimized for high IOPS.

    5. You can only UPGRADE from KV version-1 TO KV version-2, and not DOWNGRADE from KV version-2 TO KV version-1.

    • True
    • False

    Correct answer:

    • True

    Explaination: True: You can upgrade a KV-v1 secret engine mount to KV-v2, but it is not possible to downgrade a KV-v2 secret engine mount to KV-v1.

    6. There is sometimes confusion when it comes to "rekey" and "rotate" operations in Vault. While the commands sound similar, it is important to understand the key differences between these unique operations. What statement most accurately describes the difference between a "rekey" and "rotate" operations.

    • Rekey is used to generate new unseal/recovery keys, and rotate is used to generate a new root key.
    • Rekey is used to generate a new root key and unseal/recovery keys, and rotate is used to change the encryption key used to encrypt data written to the storage backend.
    • Rekey is used to generate a new root key, and rotate is used to generate new unseal/recovery keys.
    • Rekey is used to change the encryption key used to encrypt data written to the storage backend, and rotate is used to generate a new root key and unseal/recovery keys.

    Correct answer:

    • Rekey is used to generate a new root key and unseal/recovery keys, and rotate is used to change the encryption key used to encrypt data written to the storage backend.

    Explaination: Rekeying is the process of generating a new root key and the unseal/recovery key shares used to reconstruct the root key. Rotating is used to change the underlying key used to encrypt/decrypt Vault data. New keys are added to the keyring and old values can still be decrypted with the old key.


    hashicorp-ha

    1. You have been approached by a member of your team that wants to implement an "active-active" architecture of your Vault clusters to maintain high-availability. Vault currently supports active-active implementations where multiple clusters can act as the primary; true or false.

    • True
    • False

    Correct answer:

    • False

    Explaination: False: The replication model is not designed for active-active and enabling two primaries should never be done. It is known as a "split-brain" scenario and could result in data loss.

    2. Your operations team has been experiencing outages lately on numerous applications. Your manager has approached you regarding the Vault environment to ensure it is highly available and fault tolerant. Currently the primary Vault cluster is using Integrated Storage (Raft) in a three (3) node cluster. In the current configuration, how many Vault nodes could you lose and still have an available Vault service?

    • 1
    • 2
    • 3
    • In a 3 node cluster you cannot lose ANY nodes

    Correct answer:

    • 1

    Explaination: In order to maintain a quorum and have Vault service requests you can lose 1 node, and the remaining two nodes will handle requests. A quorum is a majority of members from a peer set: for a set of size n, quorum requires at least (n+1)/2 members. So a 3 node cluster requires 2 nodes (3+1)/2 = 2

    3. Your team has been running Vault for a few months and have created demos for onboarding a few applications team. You have now been tasked with making sure that Vault is ready for a full production deployment. Given the below configuration information, what would be the easiest change to ensure Vault is highly available and ready for production?

    • Switch to using Consul as a storage backend
    • Increase the number of Vault nodes in the cluster from 5 to 7
    • Migrate the Vault deployment to a public cloud with a shared responsibility model
    • Switch the seal mechanism from Shamir to one supporting auto-unseal

    Correct answer:

    • Switch the seal mechanism from Shamir to one supporting auto-unseal

    Code:

    • Running in a five (5) node cluster
    • Using Integrated Storage (Raft) as the storage backend
    • Using Shamir as the seal type
    • Virtual machines hosting the Vault service are running in an on-prem datacenter

    Explaination: Raft as a storage backend has become the standard approach and will be more than adequate for nearly any production deployment, so Consul is not necessary. A 5 node Vault cluster should meet the needs for the vast majority of deployments, and adding additional nodes would be a very rare circumstance. There is no real benefit between using private vs public cloud. Moving from Shamir to an auto-unseal is the clear answer, as it is a relatively simple change and would ensure Vault is unsealed automatically following any service restarts.

    4. Your team has recently upgraded to Vault Enterprise, in part to take advantage of Disaster Recovery (DR) replication. During a discovery meeting one of the on-call managers asked a question regarding DR clusters and if applications would need to re-authenticate in the event of promoting the DR to act as a primary. DR clusters mirror the tokens and leases for applications and users usually interacting with the primary cluster; true or false.

    • True: DR clusters mirror tokens and leases, so applications would NOT need to re-authenticate
    • False: DR clusters keep track of their own tokens and leases, and applications WOULD need to re-authenticate

    Correct answer:

    • True: DR clusters mirror tokens and leases, so applications would NOT need to re-authenticate

    Explaination: True: DR clusters act as a warm standby and duplicate all the data of the primary, including tokens and leases.


    hashicorp-agent

    1. Your organization has begun using the Vault Agent to more easily integrate applications with Vault for secure secrets. Use the provided Vault Agent configuration below to answer. Based on the configuration the Vault Agent will attempt to connect to the Vault cluster at which address?

    • https://127.0.0.1:8200.
    • It is using a Unix socket listener on localhost.
    • The configuration file does not contain that information and needs to be configured in the unit file or startup command.
    • https://vault-demo.com:8200.

    Correct answer:

    • https://vault-demo.com:8200.

    Code:

    listener "tcp" {
      address = "127.0.0.1:8200"
    }
    
    vault {
      address = "https://vault-demo.com:8200"
    }
    
    ### Depending on how difficult we want to make the question this can be removed. Default value/behavior is false.
    exit_after_auth = false
    
    auto_auth {
      method "approle" {
        config = {
          role_id_file_path = "./roleid"
          secret_id_file_path = "./secretid"
          remove_secret_id_file_after_reading  = false
        }
      }
    }
    
    sink {
      type = "file"
      config = {
        path = "/opt/sink_file_1.txt"
        mode = "0640"
      }
    }
    
    template {
      source = "./test.tmpl"
      destination = "./test.txt"
    }
    

    2. Your organization has begun using the Vault Agent to more easily integrate applications with Vault for secure secrets. Use the provided Vault Agent configuration below to answer. Based on the configuration, which of the following statements are correct? (Select two)

    • The Vault Agent will store the Vault token retrieved during authentication and make it readable to ALL users on the system.
    • The Vault Agent will attempt to use templating configurations found in the ./test.tmpl file.
    • The Vault Agent will store the Vault token retrieved during authentication and make it readable to the file owner and members of the same group as the file owner.
    • The Vault Agent is using response wrapping to more securely authenticate to Vault with a role ID and secret ID.
    • The Vault Agent will attempt to use templating instructions found in the ./test.txt file.

    Correct answer:

    • The Vault Agent will attempt to use templating configurations found in the ./test.tmpl file.
    • The Vault Agent will store the Vault token retrieved during authentication and make it readable to the file owner and members of the same group as the file owner.

    Code:

    listener "tcp" {
      address = "127.0.0.1:8200"
    }
    
    vault {
      address = "https://vault-demo.com:8200"
    }
    
    ### Depending on how difficult we want to make the question this can be removed. Default value/behavior is false.
    exit_after_auth = false
    
    auto_auth {
      method "approle" {
        config = {
          role_id_file_path = "./roleid"
          secret_id_file_path = "./secretid"
          remove_secret_id_file_after_reading  = false
        }
      }
    }
    
    sink {
      type = "file"
      config = {
        path = "/opt/sink_file_1.txt"
        mode = "0640"
      }
    }
    
    template {
      source = "./test.tmpl"
      destination = "./test.txt"
    }
    

    3. Your organization has begun using the Vault Agent to more easily integrate applications with Vault for secure secrets. Use the provided Vault Agent configuration below to answer. Based on the above configuration, the Vault Agent will authenticate to Vault, retrieve a Vault token, and then exit/shutdown the Vault Agent process.

    • True
    • False

    Correct answer:

    • False

    Code:

    listener "tcp" {
      address = "127.0.0.1:8200"
    }
    
    vault {
      address = "https://vault-demo.com:8200"
    }
    
    ### Depending on how difficult we want to make the question this can be removed. Default value/behavior is false.
    exit_after_auth = false
    
    auto_auth {
      method "approle" {
        config = {
          role_id_file_path = "./roleid"
          secret_id_file_path = "./secretid"
          remove_secret_id_file_after_reading  = false
        }
      }
    }
    
    sink {
      type = "file"
      config = {
        path = "/opt/sink_file_1.txt"
        mode = "0640"
      }
    }
    
    template {
      source = "./test.tmpl"
      destination = "./test.txt"
    }
    

    4. Which of the following auto-auth methods is NOT a valid option for the Vault Agent to use to authenticate to Vault. (Select one)

    • AWS
    • Kubernetes
    • LDAP
    • Azure
    • AppRole

    Correct answer:

    • LDAP

    5. Below is an example Vault Agent template configuration. Given the provided example, select all answers that are correct. (Select three)

    • The path of the secret in Vault is secret/data/app1
    • The secret in Vault contains a key with the name ID
    • The secret in Vault contains a key with the name username
    • The secret in Vault contains a key with the name color
    • The path of the secret in Vault is Data/data/app1

    Correct answer:

    • The path of the secret in Vault is secret/data/app1
    • The secret in Vault contains a key with the name username
    • The secret in Vault contains a key with the name color

    Code:

    {{ with secret "secret/data/app1" }}
    ID: {{ .Data.data.username }}
    Color: {{ .Data.data.color }}
    {{ end }}
    

    azure-prac-exam

    1. You are planning to create an Azure Virtual Machine Scale Set using PowerShell. Which command should you use?

    • New-AzVMSS
    • Set-AzVMScaleSet
    • New-AzVMScaleSet
    • New-AzVM -Type ScaleSet

    Correct answer:

    • New-AzVMSS

    2. You have a VM named VM-1 in the East US region. VM-1 has a network interface named NIC1, this interface is attached to a subnet called “default” which is part of virtual network VNET-01. VM-1 is using a managed disk. You have another virtual network in the West US called VNET-02, you need to move the VM to VNET-02. Which of the following two actions should you perform?

    • Deallocate the VM-1
    • Delete VM-1 and retain the disk
    • Add a new NIC in VNET-02, attach to VM-1 and remove the one in VNET-01
    • Create a new VM using the disk in West US

    Correct answer:

    • Delete VM-1 and retain the disk
    • Create a new VM using the disk in West US

    3. Your business unit uses different virtual machines for your applications. You were asked by your manager to consolidate the cost for these VMs. These VMs are part of different resource groups. What is the easiest way to track the cost for these VMs in Azure Cost Management?

    • Use Azure Policy to group the VMs and calculate the cost
    • Assign tags at the resource level
    • Assign tags at the resource group level
    • Calculate the cost individually and sum up the cost

    Correct answer:

    • Assign tags at the resource level

    Explaination: Tags assigned at the resource group level will not be visible in Azure Cost Management, we need to use tags at the resource level to track cost.

    4. Your security team is planning to audit the sign-in logs in Azure AD by ingesting that to a Log Analytics workspace. Which of the following configurations should be done to achieve this?

    • Ingestion configuration
    • Data source setting
    • Diagnostic setting
    • Data monitor setting

    Correct answer:

    • Diagnostic setting

    5. Which of the following statements about custom domains is true?

    • You can use TXT record to verify the domain
    • You can have only domain attached to the Azure AD tenant
    • You can remove onmicrosoft.com domain from Azure AD after adding a custom domain
    • You can use MX record to verify the domain

    Correct answer:

    • You can use TXT record to verify the domain
    • You can use MX record to verify the domain

    6. Your team hired a new VM administrator to manage the production VMs which are deployed in PROD-RG. You need to assign a role to the new hire by which the administrator should be able to manage all aspects of the VMs including network and storage in PROD-RG. Which of the following roles gives the right amount of access to the user?

    • Provide Contributor role at the resource group level
    • Provide Virtual Machine Contributor role at the resource group level
    • Provide Owner role at the resource group level
    • Provide Virtual Machine Operator role at the subscription level

    Correct answer:

    • Provide Contributor role at the resource group level

    Explaination: The Owner role will give additional rights to the user such as access delegation. In this case, the Contributor is the least privilege we can give.

    7. Your organization has two subscriptions, prod-sub and dev-sub. In prod-sub, you have all your production resources and they are protected using resource locks to avoid any accidental changes or deletion. However, the dev-sub doesn’t have any locks, you need to make sure all the resources in the subscription are protected from accidental deletion and at the same time users should be able to modify the resources as required. What is the easiest solution for this?

    • Use ReadOnly resource lock at the subscription scope
    • Use ReadOnly resource lock for all resource groups
    • Use Delete lock at the subscription scope
    • Use Delete lock for all resource groups

    Correct answer:

    • Use Delete lock at the subscription scope

    Explaination: Delete lock will stop accidental deletion of resources and at the same time resources can be modified. Since the locks are inherited, we can apply at the subscription scope which will cover our current resource group and even the future ones.

    8. Your organization would like to create some containers using Azure Container Instances. These containers require persistent storage. Which Azure services can be used to create persistent storage for the containers?

    • Azure Container
    • Azure Files
    • Azure Data Lake Storage Gen2
    • Azure Data Box

    Correct answer:

    • Azure Files

    9. Which table in Log Analytics should you check if the agent is sending data to the Log Analytics workspace?

    • Health
    • Heartbeat
    • AgentLogs
    • Syslog

    Correct answer:

    • Heartbeat

    10. Which of the following statements about scaling is correct. Select all that apply.

    • Vertical scaling would require VM reboot
    • Vertical scaling has an upper limit, you cannot scale beyond that
    • Vertical scaling is same as autoscaling
    • Vertical scaling can be done on selected VM sizes only

    Correct answer:

    • Vertical scaling would require VM reboot
    • Vertical scaling has an upper limit, you cannot scale beyond that

    11. Your development team wants to use Azure Queue Storage for their application. One of the development teams asked to share the access key and endpoint for the service. You created a storage account called “devkodekloudapp”. You were able to find the access key from Azure Portal. What will be endpoint to access queue storage?

    Correct answer:

    12. You purchased a domain called kodekloud.com from a domain registrar and created a DNS zone in Azure DNS. You added an A record for www which will resolve to 13.11.13.12, which is one of your public facing web servers. You asked your users to test if they are able to access www.kodekloud.com. The clients were not able to resolve the name. What should you do? Select all that apply.

    • Make sure public access is enabled in Azure DNS
    • Create a Private Azure DNS zone
    • Reboot the client machines to flush the cache
    • Add the name servers in Azure DNS to domain registrar

    Correct answer:

    • Add the name servers in Azure DNS to domain registrar

    13. You added a ReadOnly lock to one of your Azure VMs running SQL database. Which of the following operations cannot be performed on the database? Select all that apply.

    • Drop a table
    • Delete database
    • Restart the VM
    • Delete VM

    Correct answer:

    • Restart the VM
    • Delete VM

    14. In an ARM template, what's the right way to declare a variable “role” with the value “database”?

    • variable: {“role” : “database”}
    • variables: {“role” : “database”}
    • variables: (“role” : “database”)
    • variable: [“role” : “database”]

    Correct answer:

    • variables: {“role” : “database”}

    15. Which service is responsible for providing cost recommendations?

    • Azure Cost Management
    • Azure Monitor
    • Azure Advisor
    • Azure Cost Advisor

    Correct answer:

    • Azure Advisor

    16. Your organization deployed an AKS cluster in Azure and the operations team started to create pods in the cluster. One of the Kubernetes administrators needs to access the cluster from his local computer. The user is able to run kubectl commands from cloud shell, but when the user tries from the Linux terminal, it says kubectl is not recognized. User reached out to you to fix this, how can you resolve this? Azure CLI is already installed on the computer

    • Download the credentials using az aks get-credentials command and try again
    • Update AKS cluster
    • Install AKS CLI tools using az aks install-cli
    • SSH to the node and verify if the kube-proxy service is running

    Correct answer:

    • Install AKS CLI tools using az aks install-cli

    17. If you are using the Microsoft Azure Recovery Services Agent, how many backups will be taken per day?

    • 1
    • 2
    • 3
    • 4

    Correct answer:

    • 3

    18. You are planning to use Azure Virtual WAN for connecting your branch offices to Azure via S2S VPN. Due to the cost constraints, you were asked by the management to choose the cheapest SKU that supports S2S. Which SKU will you choose?

    • Basic
    • Standard
    • Standard V2
    • Premium

    Correct answer:

    • Basic

    19. Your organization wants to use the self-service password reset option for all cloud identities in Azure AD. Which license should you choose?

    • Microsoft 365 Apps
    • Azure AD Free
    • Azure AD Premium P1
    • Azure AD Premium P2

    Correct answer:

    • Azure AD Premium P2

    20. What is the retention period for the metrics collected by Azure Monitor?

    • 30 days
    • 60 days
    • 90 days
    • 120 days

    Correct answer:

    • 90 days

    21. Your application development team wants to use Azure Storage Service where they can store application binaries, embed them in a webpage and access via HTTP/HTTPS. Which service should you recommend?

    • Blob
    • File
    • Queue
    • Table

    Correct answer:

    • Blob

    azure-practice-test-1

    1. You would like to control the way the traffic is getting distributed to the backend VMs. Which option in Azure Load Balancer should be configured to control this?

    • TCP timeout
    • Session stickiness
    • Session affinity
    • Session persistence

    Correct answer:

    • Session persistence

    Explaination: The distribution mode of the load balancer can be changed using session persistence.

    2. Which port is used to establish WinRM to Windows machines?

    • 3389
    • 5999
    • 5987
    • 5986

    Correct answer:

    • 5986

    Explaination: WinRM communication is facilitated over TCP port 5986; you need to ensure that this port is opened for communication in your NSG.

    3. After creating the load balancer when you reviewed the Azure NSG for the VM, what would you be able to see?

    • Inbound NAT rule
    • DNAT rule
    • SNAT rule
    • Load balancing rule

    Correct answer:

    • Inbound NAT rule

    Explaination: Inbound NAT rules are used to specify a backend resource to route traffic to.

    4. ARM is an example of a(n) ____________________________ solution for Azure.

    • Template
    • Infrastructure-as-code
    • Platform-as-a-service
    • Infrastructure-as-a-service

    Correct answer:

    • Infrastructure-as-code

    Explaination: ARM templates are JSON files where you define what you want to deploy to Azure. Templates help you implement an infrastructure-as-code solution for Azure.

    5. Your organization would like to use self-service password reset, and hybrid users should be able to reset their on-premises password. However, you are not able to use this feature due to licensing issues. Which license should you purchase to use this feature?

    • Azure AD P2
    • Azure AD P1
    • Azure AD Free
    • Azure AD M2

    Correct answer:

    • Azure AD P2

    Explaination: SSPR is available from the Free license; however, if the hybrid users need to reset their password and write back to on-premises, then they need a Premium P2 license.

    6. Which of the following facts about Azure AD is not true?

    • Azure AD uses a flat hierarchy.
    • Kerberos and OpenID Connect authentication are supported.
    • LDAP is not used in Azure AD.
    • Group Policy doesn’t exist.

    Correct answer:

    • Kerberos and OpenID Connect authentication are supported.

    Explaination: Though OpenID Connect is used for authentication, Azure AD doesn’t use Kerberos. So, option B is not true.

    7. Your company has a virtual network with the specifications below. When you were writing a PowerShell script, you needed to provide the resource ID of the virtual network. Which of the following is the right one?

    • /subscription/00000-00001-00002-00003/resourcegroups/clz-01/providers/Microsoft.Network/virtualNetworks/vnet-hub
    • /subscriptions/00000-00001-00002-00003/resourcegroups/clz-01/providers/Microsoft.Network/virtualNetworks/vnet-hub
    • /subscription/00000-00001-00002-00003/clz-01/providers/Microsoft.Network/virtualNetworks/vnet-hub
    • /subscriptions/00000-00001-00002-00003/resourcegroups/clz-01 /Microsoft.Network/virtualNetworks/vnet-hub

    Correct answer:

    • /subscriptions/00000-00001-00002-00003/resourcegroups/clz-01/providers/Microsoft.Network/virtualNetworks/vnet-hub

    Code: Name: vnet-hub Resource Group: clz-01 Subscription ID: 00000-00001-00002-00003

    Explaination: If you have a virtual network with the name vnet-hub, then the resource ID will be /subscriptions//resourcegroups// providers/Microsoft.Network/virtualNetworks/vnet-hub.

    8. Your organization has decided to migrate from IaaS to an App Service offering. For your apps, management requires high performance, security, and isolation. Which App Service Plan tier should you use?

    • Standard
    • Premium
    • Isolated
    • Premium V2

    Correct answer:

    • Isolated

    Explaination: An isolated plan offers high performance, security, isolation, and native virtual network deployment.

    9. Your organization wants to store binaries and executables for downloads over HTTP/HTTPS. However, they are confused with the storage options in Azure. Which storage service would you suggest?

    • Queues
    • Tables
    • Blobs
    • Files

    Correct answer:

    • Blobs

    Explaination: Blob storage can be used for storing binaries and executables for downloads over HTTP/HTTPS.

    10. Does Azure App Service support Azure Marketplace images?

    • Yes
    • No

    Correct answer:

    • Yes

    Explaination: Popular applications like WordPress, Joomla, and Drupal can be deployed to App Services from Azure Marketplace.

    11. In which of the following backup scenarios can you use the MARS agent?

    • SharePoint backup
    • VMware backup
    • Azure Files backup
    • On-premises files and folders

    Correct answer:

    • On-premises files and folders

    Explaination: MARS can be used to back up files and folders only.

    12. Which of the following data can be collected using Azure Monitor? (Select all that apply.)

    • Application monitoring data
    • Guest OS monitoring data
    • Resource monitoring data
    • Subscription monitoring data

    Correct answer:

    • Application monitoring data
    • Guest OS monitoring data
    • Resource monitoring data
    • Subscription monitoring data

    Explaination: Azure Monitor can collect all the aforementioned data sources along with tenant monitoring data.

    13. What is the durability offered by GRS storage?

    • 99.99999999999 (11 nines)
    • 99.99999999999999 (14 nines)
    • 99.9999999999999999 (16 nines)
    • 99.999999999999999999 (18 nines)

    Correct answer:

    • 99.9999999999999999 (16 nines)

    Explaination: GRS offers a durability of 99.9999999999999999 percent (16 nines) over a given year.

    14. Cost data exported from Azure Cost Management will be stored in the ____________________.

    • Azure Log Analytics workspace
    • Power BI workspace
    • Azure Event Hub
    • Azure Storage account

    Correct answer:

    • Azure Storage account

    Explaination: The export feature in Azure Cost Management can be used to export the billing data to an Azure storage account.

    15. Your management has requested to collect all logs related to health events for resources that are part of your subscription. Which category should you select to get this data from the Activity Log?

    • Administrative
    • Resource health
    • Service health
    • Subscription health

    Correct answer:

    • Resource health

    Explaination: The resource health category logs all the health events happening to resources that are there in your subscription.

    16. What is the maximum number of gateways you can add to a virtual network?

    • 500
    • 100
    • 10
    • 1

    Correct answer:

    • 1

    Explaination: You can have only one VPN gateway per virtual network. However, you can establish multiple connections to it.

    17. Which of the following PowerShell commands can be used to create a virtual network? (Select all that apply.)

    • New-AzureVNet
    • New-AzureVirtualNetwork
    • New-AzVirtualNetwork
    • New-AzNetwork

    Correct answer:

    • New-AzVirtualNetwork

    Explaination: The New-AzVirtualNetwork command is used to create a virtual network.

    18. Which of the following statements is false?

    • The ARM template can be used for creating Azure resources only; resource groups and subscriptions should be deployed using PowerShell or the CLI.
    • The ARM template is an example of declarative automation.
    • The ARM templates can be exported and reused in different subscriptions.
    • The ARM template has an option to preview the changes before the deployment.

    Correct answer:

    • The ARM template can be used for creating Azure resources only; resource groups and subscriptions should be deployed using PowerShell or the CLI.

    Explaination: ARM templates can be used to create resources, resource groups, and subscriptions.

    19. Which of the following facts about resource groups is true? (Select all that apply.)

    • A resource group is a global service and can be used to group resources from multiple regions.
    • Resource groups will help manage the lifecycle of resources.
    • Resource groups can act as a scope for managing access.
    • Deleting the resource group deletes all the resources that are part of the resource group.

    Correct answer:

    • Resource groups will help manage the lifecycle of resources.
    • Resource groups can act as a scope for managing access.
    • Deleting the resource group deletes all the resources that are part of the resource group.

    Explaination: Though we can use resource groups to group resources from multiple regions, a resource group is not a global service. Every resource group will have a region where it will store the metadata about the resources that are part of the group.

    20. What is the key length of the key pairs used for Azure Linux virtual machines?

    • 1024-bit
    • 2048-bit
    • 4096-bit
    • 128-bit

    Correct answer:

    • 2048-bit

    Explaination: Azure uses a 2048-bit key length and SSH-RSA format for public and private keys.

    21. Your organization is creating a virtual machine with a public IP address. You need to make sure that the public IP address is zone redundant. Which of the following SKU and assignment types should you select to achieve this?

    • Basic dynamic
    • Basic static
    • Standard dynamic
    • Standard static

    Correct answer:

    • Standard static

    Explaination: Standard SKU comes only with static IP assignment, and it offers zone redundancy.

    22. You are planning to set up a Log Analytics workspace for collecting logs. Your manager asked you to prepare a budget for Log Analytics. What are two meters you should include as part of the Log Analytics cost calculation?

    • Data queries
    • Data ingestion
    • Data retention
    • Data sources

    Correct answer:

    • Data ingestion
    • Data retention

    Explaination: The Log Analytics cost is calculated using the amount of data ingested and the number of days the data is retained for (data retention). Thirty-one days of retention is free of cost.

    23. Which of the statements about MARS is not true?

    • MARS can be used to back up files and folders stored in physical Windows servers.
    • MARS can back up files without the need to deploy the Backup server.
    • MARS can back up files stored in RedHat VMs.
    • File, folder, and volume level restore is available in MARS.

    Correct answer:

    • MARS can back up files stored in RedHat VMs.

    Explaination: Linux workloads are not supported in MARS.

    24. Your organization wants to store binaries and executables for downloads over HTTP/HTTPS. However, they are confused with the storage options in Azure. Which storage service would you suggest?

    • Queues
    • Tables
    • Blobs
    • Files

    Correct answer:

    • Blobs

    Explaination: Blob storage can be used for storing binaries and executables for downloads over HTTP/HTTPS.

    25. You are using deployment slots for your web apps. Currently, you are using the Standard plan, and when you swapped the slots, CORS settings were not swapped. What could be the reason?

    • CORS swap is supported only from the Premium tier onward.
    • CORS settings cannot be swapped during slot swap.
    • Enable the CORS Across Slots option from app configuration settings.
    • Enable CORS Across Slots option from the app general settings.

    Correct answer:

    • CORS settings cannot be swapped during slot swap.

    Explaination: CORS settings cannot be swapped during a deployment slot swap.

    26. Which of the following user types cannot be created from the Azure portal? (Select all that apply.)

    • Cloud identities
    • Guest accounts
    • M365 cloud identities
    • Directory synchronized users

    Correct answer:

    • Directory synchronized users

    Explaination: Directory-synchronized users cannot be created from the Azure portal; these users should be synchronized from an on-premises domain controller with the help of the Azure AD Connect tool.

    27. After creating the load balancer when you reviewed the Azure NSG for the VM, what can you see?

    • Inbound NAT rule
    • DNAT rule
    • SNAT rule
    • Load balancing rule

    Correct answer:

    • Inbound NAT rule

    Explaination: Inbound NAT rules are used to specify a backend resource to route traffic to.

    28. You want to use an ARM template to deploy a VM. You need to make sure that the password should be added as a parameter to the template. What parameter type should you choose to make sure that the password is secure?

    • secureString
    • secureObject
    • passwordString
    • notClearTextString

    Correct answer:

    • secureString

    Explaination: To mark a string as secure, we need to set the object as secureString.

    29. For using Azure Bastion, you need to create a dedicated subnet. What should be the name and minimum size of the subnet?

    • AzureBastionSubnet (minimum /27)
    • BastionSubnet (minimum /26)
    • AzureBastion (minimum /27)
    • AzureBastionSubnets (minimum /26)

    Correct answer:

    • AzureBastionSubnet (minimum /27)

    Explaination: To work with Azure Bastion, you need to deploy the Bastion host to the virtual network where your VM is deployed to. Azure Bastion requires a dedicated subnet of minimum size /27 called AzureBastionSubnet.

    30. You need to establish a highly available site-to-site connection to an on-premises environment. Which of the following topologies offers the highest availability?

    • Active-passive
    • Active-cold standby
    • Active-active
    • Passive-passive

    Correct answer:

    • Active-active

    Explaination: Site-to-site connections will be established from both instances to your on-premises VPN device if you are using an active-active configuration.

    31. Which of the following facts about management groups is true? (Select all that apply.)

    • Using the management group, you can logically group subscriptions.
    • You can easily apply policies and access a set of subscriptions.
    • Budgets can be created at the management group level, which is ideal for teams and projects having multiple subscriptions.
    • The management group can be created to isolate the resources that you don’t want to be part of any subscription.

    Correct answer:

    • Budgets can be created at the management group level, which is ideal for teams and projects having multiple subscriptions.
    • You can easily apply policies and access a set of subscriptions.
    • Using the management group, you can logically group subscriptions.

    Explaination: All resources need to be part of a subscription; we cannot deploy resources to a management group.

    32. You are planning to restore an Azure VM that you were backing up to a Recovery Services Vault. As part of the restore process, you would like to mount the restore point as a drive to our VM and recover files. Which option should you select while restoring the VM?

    • Volume recovery
    • File recovery
    • Folder recovery
    • File system recovery

    Correct answer:

    • File recovery

    Explaination: Using File Recovery, you will be able to mount the restore point as a drive to your VM and recover files without the need to restore the entire VM.

    33. You want to use allowedValues for one of your parameters. How can you supply values to allowedValues?

    • “allowedValues”: “one”, “two”, “three”
    • “allowedValues”: {“one”, “two”, “three”}
    • “allowedValues”: (“one”, “two”, “three”)
    • “allowedValues”: [“one”, “two”, “three”]

    Correct answer:

    • “allowedValues”: [“one”, “two”, “three”]

    Explaination: The allowed values are provided in an array.

    34. Which of the following bulk operations are available for users in Azure AD? (Select all that apply.)

    • Bulk create
    • Bulk delete
    • Bulk invite
    • Download all users

    Correct answer:

    • Bulk create
    • Bulk delete
    • Bulk invite
    • Download all users

    Explaination: All of the options are considered as bulk operations for users.

    35. You would like to ingest metrics from the VM host and analyze them using Metrics Explorer. What should you do to collect these metrics from the VM?

    • Metrics are collected by default without any additional configuration.
    • During VM deployment, you can enable log collection. By default, this will be enabled.
    • You need to create a Log Analytics workspace to collect these metrics.
    • Data sources.

    Correct answer:

    • During VM deployment, you can enable log collection. By default, this will be enabled.
    • You need to create a Log Analytics workspace to collect these metrics.

    Explaination: The Log Analytics cost is calculated using the amount of data ingested and the number of days the data is retained for (data retention). Thirty-one days of retention is free.

    36. You have been asked to access the table named customers in the storage account axfg03. Which is the right endpoint to access the table?

    • https:// axfg03.table.core.windows.net/Customers
    • https:// axfg03.table.core.windows.net/customers
    • https:// axfg03.table.core.windows.net/CUSTOMERS
    • https:// axfg03.table.core.windows.net/tables/customers

    Correct answer:

    • https:// axfg03.table.core.windows.net/customers

    Explaination: Table names are case sensitive. The right approach is to use the table endpoint followed by the table name.

    37. Which of the following statements is correct?

    • RBAC targets authorization, and a policy targets resource properties.
    • RBAC always supersedes the policy.
    • RBAC and a policy are required to grant access.
    • A policy is not required when you are using RBAC.

    Correct answer:

    • RBAC targets authorization, and a policy targets resource properties.

    Explaination: RBAC targets authorization and access to a specific resource, while a policy targets resource properties such as size, location, type, etc.

    38. Which of the following is an example of manual deployment in App Services?

    • GitHub
    • BitBucket
    • Local Git
    • External Git

    Correct answer:

    • External Git

    Explaination: External Git is an example of manual deployment.

    39. What is the maximum number of nodes that can be added to an AKS cluster with the Standard Load Balancer?

    • 100
    • 1,000
    • 1,500
    • 2,000

    Correct answer:

    • 1,000

    Explaination: Refer to the following: https://docs.microsoft.com/en-us/azure/aks/quotas-skus-regions#service-quotas-and-limits

    40. Your organization has a requirement that all Azure VM backups stored in Azure should be encrypted. What needs to be done to enable encryption at rest?

    • Volume recovery
    • File recovery
    • Folder recovery
    • File system recovery

    Correct answer:

    • File recovery

    Explaination: Using File Recovery, you will be able to mount the restore point as a drive to your VM and recover files without the need to restore the entire VM.

    41. You need to connect to Linux virtual machines using a key pair from the Windows Terminal application. The key name is vm-01, and it is stored in ~/.ssh/key. What is the right syntax for connecting to a VM called vm-01 using the username admin?

    • ssh -k ~/.ssh/key/vm-01 admin@vm-01
    • ssh -p ~/.ssh/key/ -i vm-01 admin@vm-01
    • ssh -i ~/.ssh/key/vm-01 admin@vm-01
    • ssh -c ~/.ssh/key/vm-01 admin@vm-01

    Correct answer:

    • ssh -i ~/.ssh/key/vm-01 admin@vm-01

    Explaination: The -i parameter is used to specify the path to the private key, followed by the username@IP/DNS name format.

    42. To create a hybrid environment, you are planning to deploy a basic VPN gateway. To get zone redundancy, your manager asked you to use a standard SKU public IP address for the VPN gateway. When you were creating a VPN gateway, you were not able to see the option to attach a standard SKU public IP address. What could be the reason?

    • A standard SKU is not supported for VPN gateways.
    • You need to upgrade to VpnGw1 or higher to use a standard SKU.
    • You don’t have permission to attach a standard SKU to the VPN gateway.
    • The public IP is deployed in a different region. You can only select the IP address that is in the same region as the gateway.

    Correct answer:

    • A standard SKU is not supported for VPN gateways.

    Explaination: The standard SKU is supported by VM NICs and public load balancers only. The basic SKU supports VM NICs, VPN gateways, application gateways, and public load balancers.

    43. Select the correct sequence for setting up a virtual network to virtual network connection.

    • Create virtual networks, add gateway subnets, deploy VPN gateways, establish a connection
    • Create a VPN gateway, select the virtual networks to connect, create the connection
    • Create virtual networks, create gateway virtual networks, deploy gateways to gateway virtual network
    • Create a VPN gateway and then create a site-to-site connection

    Correct answer:

    • Create virtual networks, add gateway subnets, deploy VPN gateways, establish a connection

    Explaination: The process is to first create virtual networks, then add gateway subnets, and then deploy VPN gateways. Finally, you establish a connection.

    44. You are setting up Azure Load Balancer, and you would like to implement cookie affinity. However, you are not able to find this while configuring the load balancer. What could be the reason?

    • Cookie affinity is also known as session persistence; use it instead.
    • Cookie affinity requires an L7 load balancer; use an application gateway instead of Azure Load Balancer.
    • Ensure that you are using Azure Load Balancer Standard as cookie affinity is available only on Standard.
    • Set session persistence to a two-tuple hash to enable cookie persistence.

    Correct answer:

    • Cookie affinity requires an L7 load balancer; use an application gateway instead of Azure Load Balancer.

    Explaination: To use cookie affinity, you need to have an L7 load balancer like Azure Application Gateway.

    45. You have an on-premises endpoint that is publicly exposed. You want to check the latency and connectivity from a virtual machine to the FQDN. Which service should you choose?

    • Connection Monitor
    • IP Flow Verify
    • VPN diagnostics
    • Topology

    Correct answer:

    • Connection Monitor

    Explaination: Connection Monitor will verify if the destination is reachable or not. It will also show the hops taken to reach the destination and latency.

    46. What is the maximum throughput offered by a VPN gateway?

    • 1 Gbps
    • 10 Gbps
    • 100 Gbps
    • 1000 Gbps

    Correct answer:

    • 10 Gbps

    Explaination: The bandwidth of the VPN gateway is limited to 10 Gbps.

    47. Which is the cheapest licensing option if you have fewer than 500,000 users and require single sign-on?

    • Azure AD P2
    • Azure AD P1
    • Azure AD Free
    • Azure AD M2

    Correct answer:

    • Azure AD Free

    Explaination: Azure AD Free edition offers 500,000 directory objects, SSO, and B2B collaboration.

    48. Which action will a User Access administrator be able to perform? (Select all that apply.)

    • View resources
    • Modify resources
    • Delegate access
    • Create resources

    Correct answer:

    • View resources
    • Delegate access

    Explaination: A User Access administrator can delegate access to other users; however, this role cannot manage any resources.

    49. You have implemented alerts for all your critical workloads. As of now, you are using ServiceNow for creating internal IT tickets. Which action in action groups offers the easiest way to connect to ServiceNow?

    • Email/SMS/push
    • Email Azure Resource Manager role
    • ITSM
    • ITIL

    Correct answer:

    • ITSM

    Explaination: ITSM connectors can be created in Azure to connect to service management tools like ServiceNow. This connection can be referenced in action groups to create tickets automatically whenever an alert is fired.

    50. Which of the following statements is not true? (Select all that apply.)

    • The Azure Bastion host requires you to create RDP access to the host machine to establish an RDP/SSH connection to other VMs.
    • The Azure Bastion service requires a dedicated subnet.
    • Azure Bastion can be used to establish a connection from the Azure portal over SSL.
    • The Azure Bastion host is charged only when you are connecting to VMs using RDP/SSH.

    Correct answer:

    • The Azure Bastion host requires you to create RDP access to the host machine to establish an RDP/SSH connection to other VMs.
    • The Azure Bastion host is charged only when you are connecting to VMs using RDP/SSH.

    Explaination: Azure Bastion can be used to establish a connection from the Azure portal over SSL; there is no need to download any clients. You will be charged for the entire hour regardless of whether you are using Azure Bastion. The only way to stop being billed is to delete the Azure Bastion service.


    azure-practice-test-2

    1. You created a web app named azwebapp. What will the default URL of the web app be?

    Correct answer:

    Explaination: The default domain will be azurewebsites.net

    2. You are trying to add dynamic devices under M365 groups, and for some reason you are not able to perform that action. What could be the reason?

    • You need to have a Premium P2 license to add dynamic devices under M365 groups.
    • You should have only Windows 10 and Windows Server 2019 devices to add to M365 groups.
    • Dynamic devices are not supported for M365 groups.
    • You need to have the Device Administrator role assigned to group devices in Azure AD.

    Correct answer:

    • You need to have the Device Administrator role assigned to group devices in Azure AD.

    Explaination: Dynamic devices are supported only for security groups.

    3. Which of the following is not mandatory for an ARM template? (Select all that apply.)

    • apiProfile
    • parameters
    • functions
    • variables

    Correct answer:

    • apiProfile
    • parameters
    • functions
    • variables

    Explaination: The only required fields for an ARM template are $schema, contentVersion, and resources.

    4. Which of the following statements about custom domains is true? (Select all that apply.)

    • You need to add a TXT/MX record to validate the domain.
    • You can add multiple domains.
    • You can delete the onmicrosoft.com domain after adding the custom domain.
    • You can remove a domain where users are mapped to the domain.

    Correct answer:

    • You need to add a TXT/MX record to validate the domain.
    • You can add multiple domains.

    Explaination: You can add multiple custom domains to your Azure AD tenant by adding the TXT/MX record to your DNS domain for validation.

    5. Your organization wants to ingest logs from Azure AD to a Log Analytics workspace. Which setting should be configured for this?

    • Ingestion setting
    • Data source setting
    • Diagnostic setting
    • Data collection setting

    Correct answer:

    • Diagnostic setting

    Explaination: Azure AD logs can be streamed to Azure Log Analytics by enabling the diagnostic settings.

    6. Which table should you query to verify if the data collection from the Log Analytics agent is stopped or not?

    • Event
    • Heartbeat
    • Syslog
    • AgentLogs

    Correct answer:

    • Heartbeat

    Explaination: The Heartbeat table will help you identify computers that haven’t had a heartbeat in a specific time frame.

    7. Which one of the following can be used as a persistent storage for Azure Container Instances?

    • Azure Blob Storage
    • Azure Files
    • Azure Data Lake Storage
    • Azure Container Storage plug-in

    Correct answer:

    • Azure Files

    Explaination: Azure Files can be used as a persistent storage for Azure Container Instances.

    8. Which of the following facts are correct? (Select all that apply.)

    • A VM requires a reboot during vertical scaling.
    • There is a size limit to which you can vertically scale; no further scaling will be possible beyond that.
    • Vertical scaling will increase the number of instances without changing the hardware.
    • Vertical scaling can be used to implement true autoscaling.

    Correct answer:

    • A VM requires a reboot during vertical scaling.
    • There is a size limit to which you can vertically scale; no further scaling will be possible beyond that.

    Explaination: A VM requires a reboot during vertical scaling, and there is a size limit to which you can vertically scale; no further scaling will be possible beyond that.

    9. Which classic role is equivalent to the Contributor role?

    • Account administrator
    • Global administrator
    • Co-administrator
    • Service administrator

    Correct answer:

    • Co-administrator

    Explaination: Co-administrators can manage all aspects of resources the same as service administrators; however, co-admins cannot delegate access. For example, if you are co-admin, you cannot add another person as a co-admin. This action can be done only by a service administrator. The co-administrator role is similar to the Contributor role in RBAC.

    10. When you compare the features between Azure Application Gateway and Azure Front Door, you find that most of the features are the same. What is the key difference between Azure Front Door and Azure Application Gateway?

    • Azure Application Gateway is an L7 load balancer, while Azure Front Door is a DNS load balancer.
    • Azure Application Gateway supports path-based and multiple site routing, which is not supported by Azure Front Door.
    • Azure Application Gateway is a regional service, and Azure Front Door is a global service.
    • Application Gateway supports only VMs, and Azure Front Door supports only App Services.

    Correct answer:

    • Azure Application Gateway is a regional service, and Azure Front Door is a global service.

    Explaination: Azure Application Gateway is a regional service, and Azure Front Door is a global service.

    11. MARS takes a backup _____ time(s) per day.

    • 1
    • 2
    • 3
    • 4

    Correct answer:

    • 3

    Explaination: MARS takes a backup three times per day.

    12. You have been asked to access the table named customers in the storage account axfg03. Which is the right endpoint to access the table?

    • https:// axfg03.table.core.windows.net/Customers
    • https:// axfg03.table.core.windows.net/customers
    • https:// axfg03.table.core.windows.net/CUSTOMERS
    • https:// axfg03.table.core.windows.net/tables/customers

    Correct answer:

    • https:// axfg03.table.core.windows.net/customers

    Explaination: Table names are case sensitive. The right approach is to use the table endpoint followed by the table name.

    13. Your organization added a ReadOnly lock to one of your production SQL databases. Which of the following operations cannot be accomplished?

    • Modify queries in the SQL database
    • Create a new table in the SQL database
    • Resize the SQL database
    • Delete the table from the SQL database

    Correct answer:

    • Resize the SQL database

    Explaination: Locks prevent changes to a resource, but they don’t restrict how resources perform their own functions. Any operations done within the SQL database cannot be prevented using locks.

    14. You have deployed an AKS cluster and have downloaded the credentials; however, when using kubectl, you are not able to get the node information from your local computer. As per the terminal, kubectl is not recognized as a known command. What needs to be done to resolve this problem? (Select all that apply.)

    • Download the credentials again and save them to your home directory
    • Install the AKS CLI tools using az aks install-cli
    • SSH to the nodes and verify if the kube-proxy service is running
    • Try accessing the cluster from the cloud shell

    Correct answer:

    • Install the AKS CLI tools using az aks install-cli
    • SSH to the nodes and verify if the kube-proxy service is running

    Explaination: You can install the kubectl binaries to your local computer by executing "az aks install-cli". Kubectl is already installed in the cloud shell, so verify if you can get the node information to rule out any provisioning issues.

    15. Select the correct syntax to declare a variable with the name vmName and a value of webserver-01.

    • variables: ( “vmName”: “webserver-01”)
    • variables: [ “vmName”: “webserver-01”]
    • variables: { “vmName”: “webserver-01”}
    • variables: { “vmName” = “webserver-01”}

    Correct answer:

    • variables: { “vmName”: “webserver-01”}

    Explaination: Variables are declared in the format "variables": { "name": "value"}.

    16. In your organization, administrators created Azure DNS zones, and most of the production zones are hosted on an on-premises Windows DNS server. You want to implement name resolution for your on-premises servers; they should be able to resolve DNS names from both Azure DNS zones and on-premises DNS zones. The on-premises infrastructure is dynamic where VMs are created and deleted dynamically based on the demand. What would be the easiest solution to make the name resolution happen without management overhead?

    • Add Azure DNS servers to all the VMs
    • Create a conditional forwarder on the on-premises domain controller
    • Migrate the on-premises zones to Azure
    • Synchronize Azure DNS zones to on-premises

    Correct answer:

    • Create a conditional forwarder on the on-premises domain controller

    Explaination: Though you can add Azure DNS to all the VMs and make the name resolution happen, as the VMs are dynamically created, it’s not a feasible solution. The easiest way is to add a conditional forwarder to the on-premises DNS server, which will forward all the requests matching the condition to the Azure DNS for name resolution.

    17. Azure Cost Management can generate cost recommendations based on your usage. Which of the following services is responsible for deriving these recommendations?

    • Azure Cost Management Recommendations
    • Azure Cost Advisor
    • Azure Monitor
    • Azure Advisor

    Correct answer:

    • Azure Advisor

    Explaination: Azure Advisor generates the cost recommendations along with Operation Excellence, Performance, Reliability, and Security recommendations.

    18. Your organization wants to use a virtual WAN with an S2S VPN. Which is the cheapest WAN type you can use?

    • Basic
    • Standard
    • Advanced
    • Premium

    Correct answer:

    • Basic

    Explaination: Basic Virtual WAN supports S2S VPN, and this is the cheapest option.

    19. Your security wants to make sure that public access to the storage account from all networks should be denied. All communications should happen via a VPN S2S connection from on-premises. What needs to be done about this requirement?

    • Create a service endpoint
    • Create network rules and add the on-premises network to the storage account
    • Create a private endpoint
    • Create Azure Firewall

    Correct answer:

    • Create a private endpoint

    Explaination: Private endpoints can be created for the storage account that will create an interface for the storage account in the virtual network that can be accessed privately.

    20. How long will the metrics be retained by Microsoft?

    • 90 days
    • 91 days
    • 92 days
    • 93 days

    Correct answer:

    • 93 days

    Explaination: There is no limit to the amount of metric data you can collect, but this data is stored for a maximum of 93 days.

    21. You are trying to connect your Cost Management data to Power BI, and you are not able to do so. Currently, you have five pay-as-you-go subscriptions that run production workloads. What could be the reason for this failure?

    • You need to generate the API key to connect to Power BI.
    • You need to sign in as the administrator to use the Power BI integration.
    • You need to enable Power BI access in Cost Management to download the data.
    • Only the subscription offer doesn’t support the Power BI connector.

    Correct answer:

    • Only the subscription offer doesn’t support the Power BI connector.

    Explaination: The Power BI connector supports only the Enterprise Agreement and Microsoft Customer Agreement subscriptions.

    22. You are using Azure DNS, and one of your colleagues has asked you to add the IPv6 address of a server to the DNS zone. What should you do?

    • Inform the colleague that Azure DNS only supports IPv4 records
    • Create an AAAA record
    • Create a CNAME recording pointing to the IPv6 address
    • Create an A record pointing to the IPv6 address

    Correct answer:

    • Create an AAAA record

    Explaination: Azure DNS supports IPv6 records, and you can create AAAA records to map the name to IPv6 addresses.

    23. Your reliability team wants to distribute the instances of a virtual machine scale set across fault domains. Which option do you need to configure to accomplish this requirement?

    • Scaling policy
    • Uniform distribution
    • Spreading algorithm
    • Availability set

    Correct answer:

    • Spreading algorithm

    Explaination: The spreading algorithm determines how the instances should be spread across fault domains. Microsoft recommends using max spreading to spread the instances across all fault domains.

    24. You need to create a storage account using an ARM template. As per the naming conventions, you should take the name of the resource group and append that with a string that will be provided by the user during runtime. Assume that the string shared by the user will be stored in name. For example, if the name of the resource group is rg-01 and the string provided by the user is storage, then the name should be rg-01-storage. What is the right format to construct the storage account name while writing the resource block?

    • [concat(resourceGroup.name(),’-’, variables(‘name’)]
    • [concat(resourceGroup().name(),’-’, variables(‘name’)]
    • [concat(resourceGroup.name(),’-’, parameters(‘name’)]
    • [concat(resourceGroup().name,’-’, parameters(‘name’)]

    Correct answer:

    • [concat(resourceGroup().name,’-’, parameters(‘name’)]

    Explaination: As the user is providing the value during the runtime, you cannot use variables; you need to use parameters. The resource group name can be captured using resourcegroup().name. The values can be appended using the concat function.

    25. You would like to enable Network Watcher for your subscription to view the topology. What needs to be done to enable Network Watcher?

    • Network Watcher is enabled automatically for every subscription.
    • You need to deploy the Network Watcher service manually in the region where your deployment is.
    • Network Watcher gets enabled when you create a virtual network.
    • Manual deployment is required for only one region as Network Watcher is a global service.

    Correct answer:

    • Network Watcher is enabled automatically for every subscription.

    Explaination: The Network Watcher service is enabled automatically for every subscription.

    26. You are setting up a VPN gateway and would like to add your custom DNS servers. Where will you configure this?

    • Under VPN configuration, you can specify the DNS servers.
    • A VPN gateway inherits the DNS configuration of the virtual network.
    • A private DNS needs to be created to link the VPN gateway to use custom DNS.
    • A VPN uses the DNS servers mentioned in the local network gateway.

    Correct answer:

    • A VPN gateway inherits the DNS configuration of the virtual network.

    Explaination: If you specified a DNS server or servers when you created your virtual network, the VPN gateway will use the DNS servers that you specified.

    27. Which component in AKS managed nodes is responsible for managing requests coming from the master node?

    • kube-proxy
    • kubelet
    • docker
    • api-server

    Correct answer:

    • kubelet

    Explaination: Kubelet is responsible for processing the requests that are coming from the Azure managed node or the master node.

    28. Which parameters are taken into consideration for a three-tuple hash?

    • Source IP address, destination IP address, and protocol
    • Source IP address, source port, and destination IP address
    • Source IP address, destination IP address, and destination port
    • Protocol, destination IP address, and destination port

    Correct answer:

    • Source IP address, destination IP address, and protocol

    Explaination: In a three-tuple hash we are taking the hash of the source IP address, destination IP address, and protocol to map the servers.

    29. You need to use Azure Storage in AKS; what are the storage options available to you via Storage classes? (Select all that apply.)

    • Azure Standard SSD
    • Azure Premium SSD
    • Azure Premium File Storage
    • Azure Tables

    Correct answer:

    • Azure Standard SSD
    • Azure Premium SSD
    • Azure Premium File Storage

    Explaination: Azure Managed SSD Disks (Standard, Premium) and Azure Files (Standard, Premium) are supported for AKS Storage classes.

    30. Azure Hybrid Benefit can be used with which of the following services? (Select all that apply.)

    • Windows VMs
    • SQL servers
    • Linux servers
    • Azure Functions

    Correct answer:

    • Windows VMs
    • SQL servers
    • Linux servers

    Explaination: Azure Hybrid Benefit can be applied to Windows, SQL, and Linux servers. Azure Functions is a serverless service.

    31. You have several Linux virtual machines running in a virtual network. Your management wants to deploy an Azure Firewall for securing the workloads. As soon as you deployed the firewall, the Linux machines are not able to download the updates. What needs to be done to make sure that the updates are allowed? Choose a solution that will have the lowest management overhead.

    • Whitelist IP addresses of update repositories to the firewall
    • Ignore manual updates as Azure automatically updates all virtual machines
    • Add an application rule and whitelist the domains
    • Add a NAT rule to enable updates

    Correct answer:

    • Add an application rule and whitelist the domains

    Explaination: Adding IP addresses is not an efficient solution as chances of these IP addresses getting changed are high. It’s easy to add the FQDNs to an application rule so that requests to these domains are not blocked.

    32. What are the additional cost implications if you are setting up an active-active configuration for a VPN gateway?

    • The VPN gateway cost will be doubled for VPN gateway as your second instance is active.
    • There is no change in the cost as the redundant instances need to be deployed for passive as well.
    • The cost will be comparatively higher as data transfer happens via both tunnels.
    • The cost will be double for data transfer as the data is transferred via both tunnels simultaneously.

    Correct answer:

    • There is no change in the cost as the redundant instances need to be deployed for passive as well.

    Explaination: There won’t be any billing implications or additional cost for switching to active-active. The redundant instances are always running regardless of active-passive or active-active, so the cost of that is always included in the price of the VPN gateway.

    33. What does reclaimPolicy in AKS Storage do?

    • Helps to claim the pod configuration
    • Controls the persistence of the disk
    • Chooses the type of storage used for the cluster
    • Maps the underlying storage to the node pool

    Correct answer:

    • Controls the persistence of the disk

    Explaination: When you delete the pod and the persistent volume is no longer required, reclaimPolicy controls the behavior of the underlying Azure storage resource. The underlying storage resource can be either deleted or kept for use with a future pod.

    34. You would like to have VMs of different configurations in a virtual machine scale set. Which configuration should you select to achieve this?

    • Spreading algorithm
    • Uniform orchestration
    • Flexible orchestration
    • Azure Spot instance

    Correct answer:

    • Flexible orchestration

    Explaination: Flexible orchestration is the option you can use to have VMs of different configurations in a virtual machine scale set

    35. You have linked a virtual network to a private zone with autoregistration enabled. In the virtual network there are 150 VMs, and you accidentally deleted all the DNS records. You need to recover these DNS records as soon as possible to avoid a DNS outage for the virtual network. What needs to be done?

    • The records cannot be recovered.
    • Export the VM and IP addresses to a CSV file and import to the zone.
    • Create a new zone and register the VMs there.
    • No action is required.

    Correct answer:

    • No action is required.

    Explaination: The automatic registration happens again as long as the virtual machine still exists and has a private IP address attached to it. The DNS record is re-created automatically in the zone.

    36. You have implemented a policy-based VPN gateway and set up an S2S connection. Later, you decide to switch to a route-based VPN. What’s the right approach to change from a policy-based VPN to a route-based VPN?

    • Delete the S2S connection and update the VPN gateway; then re-create the connection.
    • Disable the connection, update the gateway, and enable the connection again.
    • Delete the connection, delete the gateway, and create a new route-based VPN.
    • Changing via the portal is not supported; use PowerShell to change the gateway type.

    Correct answer:

    • Delete the connection, delete the gateway, and create a new route-based VPN.

    Explaination: You cannot change a policy-based VPN to route-based VON without redeploying the VPN gateway. Deleting the connection, deleting the gateway, and creating a new route-based VPN is the right approach.

    37. One of the previous administrators of your Azure environment created a General Purpose v1 Hot Standard Storage account in Azure. This account is used to store tables and blobs. Now your management is asking you to implement Lifecycle Management for blobs. However, you are not able to find this option in the Azure portal. What needs to be done?

    • Change the tier to Premium
    • Enable Lifecycle Management from Advanced Properties
    • Change the account to the Cool tier
    • Upgrade to General Purpose v2

    Correct answer:

    • Upgrade to General Purpose v2

    Explaination: Only General Purpose v2 storage accounts support the Lifecycle Management option, so you need to upgrade your storage account.

    38. Your manager has asked you to remove a deployment from the deployment history. How can you achieve this?

    • The deployment history cannot be cleared; Azure stores it for 90 days.
    • Use the az group deployment remove command.
    • Use the az group deployment delete command.
    • Use the az group deployment cancel command.

    Correct answer:

    • Use the az group deployment delete command.

    Explaination: You can use the "az group deployment delete" command to delete a deployment from the deployment history.

    39. What option do you have if the region doesn’t support availability zones?

    • The availability zone is available for all regions.
    • Use an availability set.
    • Flexible orchestration.
    • Azure Spot instance.

    Correct answer:

    • Use an availability set.

    Explaination: Use an availability set in regions where availability zones are not available.

    40. You are planning to implement an Azure VPN gateway, and you would like to direct packets through IPsec tunnels based on the combinations of address prefixes between your on-premises network and the Azure VNet. What configuration should you select to achieve this?

    • Zone-redundant VPN
    • Policy-based VPN
    • Route-based VPN
    • IPsec VPN

    Correct answer:

    • Policy-based VPN

    Explaination: Policy-based gateways implement policy-based VPNs. Policy-based VPNs encrypt and direct packets through IPsec tunnels based on the combinations of address prefixes between your on-premises network and the Azure virtual network. The policy (or traffic selector) is usually defined as an access list in the VPN configuration.

    41. What is the maximum duration of the script that can be run using Custom Script Extension for Linux machines?

    • 9 minutes
    • 90 minutes
    • 95 minutes
    • 20 minutes

    Correct answer:

    • 90 minutes

    Explaination: The script is allowed 90 minutes to run. Anything longer will result in a failed provision of the extension.

    42. What option do you have if the region doesn’t support availability zones?

    • The availability zone is available for all regions.
    • Use an availability set.
    • Flexible orchestration.
    • Azure Spot instance.

    Correct answer:

    • Use an availability set.

    Explaination: Use an availability set in regions where availability zones are not available.

    43. Your organization wants to use Custom Script Extension stored in one of the source controls to be executed on a Linux machine. Which property should be used to specify the command that needs to be executed?

    • fileUris
    • scriptToExecute
    • commandsToExecute
    • commandToExecute

    Correct answer:

    • commandToExecute

    Explaination: The URL to the script can be added using the fileUris property, and then you can execute the script using the commandToExecute option.

    44. Which Azure CLI command is used to validate if the ARM template is syntactically correct?

    • az group template validate
    • az group deployment whatif
    • az group deployment validate
    • az group template whatif

    Correct answer:

    • az group deployment validate

    Explaination: In Azure CLI, you can use "az group deployment validate" to validate whether a template is syntactically correct.

    45. Your security wants to make sure that public access to the storage account from all networks should be denied. All communications should happen via a VPN S2S connection from on-premises. What needs to be done about this requirement?

    • Create a service endpoint
    • Create network rules and add the on-premises network to the storage account
    • Create a private endpoint
    • Use Azure Firewall

    Correct answer:

    • Create a private endpoint

    Explaination: Private endpoints can be created for the storage account that will create an interface for the storage account in the virtual network that can be accessed privately.

    46. Your organization is planning to save VHD files in Azure Blob Storage. Which type of blob should be selected for this?

    • Append blob
    • Block blob
    • General blob
    • Page blob

    Correct answer:

    • Page blob

    Explaination: A page blob is ideal for frequent read/write operations and can be up to 8 TB in size. Azure stores virtual machine OS disks and data disks in page blob format.

    47. Your organization wants to bring your own keys for SSE. Which service should you use to store these keys?

    • Azure Key Vault
    • Key Management Service
    • Recovery Services Vault
    • Windows Key Store

    Correct answer:

    • Azure Key Vault

    Explaination: Azure Key Vault can be used to store SSE and ADE keys.

    48. You have an Azure subscription. You are deploying an Azure Kubernetes Service (AKS) cluster that will contain multiple pods. The pods will use Kubernetes networking; you need to restrict network traffic between the pods. What should you configure on the AKS cluster?

    • Security policy
    • Kubernetes ingress policy
    • Azure network policy
    • Services

    Correct answer:

    • Azure network policy

    Explaination: An Azure network policy needs to be created to restrict the traffic between the pods.

    49. You have an Azure subscription named az-sub01 that contains an Azure Log Analytics workspace named la-workspace-01. You need to view the error events from a table named Event. Which query should you run in la-workspace-01?

    • Get-Event Event | where {$_.EventType == "error"}
    • search in (Event) "error"
    • select * from Event where EventType == "error"
    • search in (Event) * | where EventType -eq "error"

    Correct answer:

    • search in (Event) "error"

    Explaination: You can use search in followed by the table name and keyword for searching in a table. You can also use Event | search "error" or Event | where EventType == "error".

    50. One of your Linux virtual machines has the following NSGs attached to it. question-image
    You are not able to connect to the VM over SSH. How can you fix this?

    • Change the priority of rule 1 of subnet level NSG to 100
    • Delete rule 1 from NIC level NSG
    • Change the source of rule 1 of subnet level NSG
    • Delete the NIC level NSG

    Correct answer:

    • Delete rule 1 from NIC level NSG

    Explaination: Delete rule 1 from the NIC level so NSG will allow SSH traffic.


    consul-architecture

    1. Which of the following is responsible for managing membership and broadcasting messages within the Consul cluster?

    • Serf Protocol
    • Raft Protocol
    • Prepared Queries
    • Proxies

    Correct answer:

    • Serf Protocol

    Explaination: Serf is the gossip protocol that is used across all servers and client members within a Consul cluster for broadcasting messages about server and client membership.

    2. A Consul cluster containing (5) Consul server nodes can tolerate a maximum of how many node failures before the Consul cannot establish a quorum and continue to operate?

    • 1
    • 2
    • 3
    • 4

    Correct answer:

    • 2

    Explaination: The following chart can be used to determine the number of failures a Consul cluster can handle before being unable to establish a quorum and the Consul service becoming unavailable. https://www.consul.io/docs/internals/consensus.html#deployment-table

    3. Which of the following is not true about running Consul in development mode?

    • development mode is not secure
    • development mode is easily scalable
    • development mode allows you to easily experiment with most of the Consul's functionality
    • development mode should never be used in the production environment

    Correct answer:

    • development mode is easily scalable

    Explaination: Dev mode only runs on a single node, such as your desktop or laptop. Therefore, it is not a scalable solution when using it for Consul services

    4. In order to provide high availability and ensure that Consul's state is preserved even if a server fails, HashiCorp suggests that Consul should be configured to run __________.

    • in a cluster made up of three to five servers
    • on as many servers as needed to scale for performance
    • only Kubernetes to provide scheduling for new Consul nodes
    • on a public cloud platform that can provide Hardware redundancy

    Correct answer:

    • in a cluster made up of three to five servers

    Explaination: In order to make sure that Consul's state is preserved even if a server fails, you should always run either three or five servers in production. The odd number of servers (and no more than five of them) strikes a balance between performance and failure tolerance. When scaled beyond (7) servers, the network requirements needed to maintain replication between the clusters may negatively impact the performance of the Consul.

    5. Which nodes in a Consul datacenter do not participate in the LAN gossip pool?

    • Consul server nodes
    • Consul client nodes
    • Consul non-voting server nodes
    • Consul consumers (meaning any client accessing Consul, such as user desktop)

    Correct answer:

    • Consul consumers (meaning any client accessing Consul, such as user desktop)

    Explaination: Consumers of the Consul service do not participate in the gossip pool. However, all members of the Consul do participate in the LAN and possibly a WAN pool, when federated.


    consul-deploy-single-datacenter

    1. What command can be used for new Consul agents to join an existing cluster?

    • consul connect
    • consul join
    • consul cluster -join
    • consul exec -join

    Correct answer:

    • consul join

    Explaination: This is the only valid command for joining the cluster and is the proper way for a Consul agent to join an existing cluster

    2. True or False? When joining a new Consul agent to a cluster, the consul join command must include all the server nodes that make up the cluster.

    • TRUE
    • FALSE

    Correct answer:

    • FALSE

    Explaination: A new Consul agent reference any node in the existing cluster. After joining with one member, the gossip communication will propagate the updated membership state across the cluster.

    3. What command below can be used to display the participating servers and clients within the local Consul cluster?

    • consul members
    • consul monitor
    • consul info
    • consul validate

    Correct answer:

    • consul members

    Explaination: The 'consul members' command outputs the current list of members that a Consul agent knows about, along with their state. The state of a node can only be "alive", "left", or "failed".

    4. Scenario: You are automating the deployment of a new 3-node Consul cluster using Terraform, but not all the nodes are joining the cluster as expected. It seems some nodes are being provisioned faster than others. Because of this, a leader is never elected and the cluster is never established. You are using the Consul configuration that is shown below, but you continue to get the following error on multiple nodes. What can be changed in the configuration file in order to ensure the Consul cluster is bootstrapped and a leader is elected?

    • change join to retry_join
    • update the node name to include numbers instead of letters
    • update node_name to node_names to indicate there is one node in the cluster

    Correct answer:

    • change join to retry_join

    Code: [WARN] raft: EnableSingleNode disabled, and no known peers. Aborting election.

    Configuration file

    { "acl": { "enabled": true, "default_policy": "allow", "down_policy": "extend-cache" }, "bind_addr": "0.0.0.0", "bootstrap_expect": 3, "client_addr": "0.0.0.0", "datacenter": "primary", "data_dir": "/var/consul/data", "join": ["10.0.15.76, 10.0.15.35"], "log_level": "INFO", "node_name": "consul-node-a.example.com", "performance": { "raft_multiplier": 1 },
    "server": true, "ui": true, }

    Explaination: The key to this question is the phrase "It seems some nodes are being provisioned faster than others." Nodes are spinning up faster than others, and since the configuration file only includes a join statement, the nodes being deployed faster cannot communicate with the other nodes, therefore the Consul agent fails. join does not reattempt communication with the listed node(s), therefore the cluster is never bootstrapped

    5. Based on the Consul agent configuration below, what parameter will determine which interface the Consul will use for internal cluster communications?

    • "bind_addr": "10.0.30.186"
    • "client_addr": "0.0.0.0"
    • "node_name": "node-a.example.com"
    • "verify_outgoing": true

    Correct answer:

    • "bind_addr": "10.0.30.186"

    Code: { "log_level": "INFO", "server": true, "node_name": "node-a.example.com", "key_file": "/etc/consul.d/cert.key", "cert_file": "/etc/consul.d/client.pem", "ca_file": "/etc/consul.d/chain.pem", "verify_incoming": true, "verify_outgoing": true, "encrypt": "xxxxxxxxxxxxxxxxxxxxxxxx", "data_dir": "/opt/consul/data", "datacenter": "us-east-1", "bind_addr": "10.0.30.186", "client_addr": "0.0.0.0", "retry_join": ["provider=aws tag_key=Environment-Name tag_value=consul region=us-east-1"], "enable_syslog": true, "acl": { "tokens": { "agent": "xxxxxxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxx" } } }

    Explaination: The parameter bind_addr is used to determine the address that should be bound to for internal cluster communications. This is an IP address that should be reachable by all other nodes in the cluster. By default, this is "0.0.0.0", meaning Consul will bind to all addresses on the local machine and will advertise the private IPv4 address to the rest of the cluster.


    consul-services

    1. Which of the following is NOT a valid type of a Consul health check?

    • Script Health Check
    • Port Health Check
    • TTL Health Check
    • TCP Health Check

    Correct answer:

    • Port Health Check

    Explaination: Port health check is incorrect as only a TCP health check can detect whether or not a connection can be established using an IP address and port

    2. You have registered a new service using the service definition below. What DNS record can you query to get the results of healthy nodes hosting the service?

    • front-end-eCommerce.service.consul
    • web-server-01.service.consul

    Correct answer:

    • front-end-eCommerce.service.consul

    Code: { "service": { "id": "web-server-01", "name": "front-end-eCommerce", "tags": ["v7.05", "production"], "address": "10.3.13.112", "port": 8080, "checks": [ { "args": ["/usr/local/bin/check_mem.py"], "interval": "30s" } ], } }

    Explaination: the service being registered here is named front-end-eCommerce and the default address of a service is .service.consul

    3. A developer named Terry wants to query Consul and only retrieve the hosts providing the "eCommerce-web" service tagged with v7.5. What feature of Consul should Terry use?

    • failover policy
    • prepared query
    • health check
    • service definition

    Correct answer:

    • prepared query

    Explaination: A prepared query allows you to create a more complex service query, including the ability to filter results based on tags

    4. You have deployed a virtual machine that hosts two different web applications named web-01 and web-02. You have multiple health checks configured, including two application (service level) health checks and one host-level health check. When the services are queried, which of the following will be returned as part of the service query?

    • web-01 will be returned but not web-02
    • web-01 and web-02 will both be returned, but web-02 will be returned as failing
    • neither of the services will be returned

    Correct answer:

    • neither of the services will be returned

    Code: The current status of the health checks is as follows:

    Host-Level Health Check: Failing

    Web-01 Health Check: Passing

    Web-02 Health Check: Failing

    Explaination: the host-level health check is failing. Therefore, neither service running on that host will be returned in service query

    5. Which of the following is not a valid method of registering a new service with the Consul?

    • create definition as part of the Consul agent configuration
    • place a file alongside the Consul agent configuration file when using the -config-dir parameter
    • run the consul services register command while referencing a service configuration file
    • register the service in the Consul UI using service definition file

    Correct answer:

    • register the service in the Consul UI using service definition file

    Explaination: The Consul UI doesn't support registering a Consul service directly


    consul-kv-store

    1. You want to set up a watch to invoke an API if a specific value changes in the Consul K/V. What type of watch is the most specific for watching this value?

    • event
    • key prefix
    • key
    • services

    Correct answer:

    • key

    Explaination: a key watch can watch a specific KV pair and alert on changes

    2. Data in the Consul K/V is replicated across what type of node(s)?

    • across all consul server nodes in the cluster
    • across all consul server nodes in all federated datacenters
    • across Consul server and client nodes
    • across Consul client nodes

    Correct answer:

    • across all consul server nodes in the cluster

    Explaination: data is replicated across all server nodes within a cluster

    3. What feature can be used to protect access to the Consul K/V?

    • Consul ACLs
    • encryption
    • mutual TLS
    • consul watch

    Correct answer:

    • Consul ACLs

    Explaination: Consul ACLs provides an RBAC feature in Consul to restrict access to data

    4. Which of the following should NOT be stored in the Consul K/V store?

    • configuration parameters
    • metadata
    • database passwords
    • variables

    Correct answer:

    • database passwords

    Explaination: remember that the Consul K/V is not an encrypted store, so sensitive credentials shouldn't be stored in the K/V. Use something like Vault instead

    5. You are using the Consul HTTP API to retrieve data from the Consul K/V. Instead of getting the expected value, you receive a value such as J2VuYWJsZWQn . Why do you not get the value in plain-text?

    • the data is encrypted on the Consul K/V store
    • Consul K/V values are base64 encoded
    • Consul uses Vault to encrypt any data saved to the Consul K/V

    Correct answer:

    • Consul K/V values are base64 encoded

    Explaination: You can easily decode this value to get the plain-text value


    consul-backup-restore

    1. The Consul Snapshot Agent provides many different features. Which is NOT one of the features provided by the Consul Snapshot Agent?

    • failover
    • high-availability
    • automated snapshots
    • automated recovery

    Correct answer:

    • automated recovery

    Explaination: Automated recovery is not a feature in Consul

    2. True or False? Data can be selectively restored from a Consul snapshot, meaning I can pick and choose what data needs to be restored to my Consul cluster.

    • TRUE
    • FALSE

    Correct answer:

    • FALSE

    Explaination: snapshot restore is an "all or nothing" type of action

    3. Consul operators can take manual snapshots of the cluster by using multiple Consul interfaces. Which Consul interface does not provide the ability to create a snapshot ?

    • API
    • UI
    • CLI

    Correct answer:

    • UI

    Explaination: the User Interface does not offer a way to take a Consul snapshot

    4. A Consul snapshot saves all the information in Consul except which of the following?

    • ACLs
    • Key/Value data
    • Consul agent configuration
    • Prepared Queries

    Correct answer:

    • Consul agent configuration

    Explaination: snapshots do not include the agent configuration

    5. By default, Consul snapshots are taken in ____________ mode, meaning that the leader performs the snapshot.

    • stale
    • consistent
    • encrypted
    • performance

    Correct answer:

    • consistent

    Explaination: a consistent snapshot means that it was indeed taken by the leader node


    consul-service-proxy

    1. Which interface provides the most feature-rich options for creating a Service Intention?

    • API
    • CLI
    • UI

    Correct answer:

    • API

    Explaination: the API at /connect/intentions/exact should be used and provides the most features

    2. The service named eCommerce-FrontEnd relies on a backend database service called customer-db in order to properly service customer orders. Select the correct statement below based on this configuration.

    • the customer-db service is downstream from the eCommerce-FrontEnd
    • the customer-db service is upstream from the eCommerce-FrontEnd

    Correct answer:

    • the customer-db service is upstream from the eCommerce-FrontEnd

    Explaination: the customer-db service is upstream from the eCommerce-FrontEnd service. The eCommerce-FrontEnd is downstream from the customer-db service

    3. True or False? When registering a service proxy, Consul automatically starts a new service proxy if a custom one is not specified.

    • TRUE
    • FALSE

    Correct answer:

    • FALSE

    Explaination: Registration does not start the sidecar proxy - you must do that manually or programmatically

    4. True or False? Intentions follow a top-down ruleset and precedence cannot be overridden.

    • TRUE
    • FALSE

    Correct answer:

    • TRUE

    Explaination: Intentions follow a top-down ruleset using Allow or Deny intentions. More specific rules are evaluated first.

    5. Which of the following statement is NOT true regarding Consul Service Mesh architecture?

    • applications may not be aware of the consul service mesh is present
    • applications can be written for native support of Consul service mesh
    • Service Configuration file often declare the downstream service(s) that the local service relies on
    • intentions define access control for Services

    Correct answer:

    • Service Configuration file often declare the downstream service(s) that the local service relies on

    Explaination: service files would include upstream services, not the downstream


    consul-secure-agent-conf

    1. Which component of the Consul security model uses a pre-shared key to secure communications throughout the Consul cluster?

    • Consul Agent
    • gossip protocol
    • Consul ACL system
    • Consul Certificate Authority

    Correct answer:

    • gossip protocol

    Explaination: You can use consul keygen or consul keyring to manage the gossip encryption key

    2. If you are using your own private certificate authority (CA) to issue certificates for Consul, what additional subject alternative name (SAN) should you add to the certificate to ensure you don't receive errors when configuring the most secure Consul environment?

    • server..
    • add a SAN for the IP Address
    • add a SAN for the DNS friendly name of the Consul cluster
    • add a SAN for each DNS name of all nodes in the cluster

    Correct answer:

    • server..

    Explaination: server.<datacenter>.<domain> ensures a client cannot modify the Consul Agent config and restart as a server

    3. In order to ensure a Consul client cannot modify the agent configuration and restart as a server, what feature should organizations enable in the Consul configuration file?

    • verify_incoming
    • verfiy_server_hostname
    • verify_outgoing
    • encrypt

    Correct answer:

    • verfiy_server_hostname

    Explaination: All outgoing connections will perform hostname verification. It ensures that servers have a certificate valid for server..

    4. True or False? Consul's flexibility allows you to use certificates from multiple internal certificate authorities.

    • TURE
    • FALSE

    Correct answer:

    • FALSE

    Explaination: all certificates must be signed by the same certificate authority

    5. Consul can create multiple types of certificates when it is configured as a certificate authority. Which is NOT one of the types of certificates you can create?

    • server
    • client
    • API
    • CLI

    Correct answer:

    • API

    Explaination: Consul can create certificates types of server, client, and CLI


    consul-acl

    1. True or False? Before the ACL system can be used, it must be enabled in the agent configuration file and bootstrapped.

    • TRUE
    • FALSE

    Correct answer:

    • TRUE

    Explaination: It must be enabled in the configuration file and bootstrapped before policies or tokens can be created

    2. James is making some changes using the Consul CLI and has been provided a token for authentication. Which of the following is NOT a valid way that James can provide the token when executing Consul CLI commands?

    • set up the environment variable CONSUL_HTTP_TOKEN with the value of the token
    • save the token in the local file and reference that file using the -consul-token-file parameter
    • use the -token parameter as the part of the command
    • set environment variable CONSUL_HTTP_TOKEN_FILE to the path of the file where you have saved the token

    Correct answer:

    • save the token in the local file and reference that file using the -consul-token-file parameter

    Explaination: -consul-token-file is not a valid parameter - you could use -token-file instead.

    3. You have completed the configuration of Consul ACLs, the default_policy is set to Deny, and you created a new policy for your end-users to query Consul for a critical service they depend on to perform their job. How can the end-users successfully query Consul using DNS without providing them an ACL token?

    • disable the ACL system for those specific users
    • configure a policy for node_prefix to allow all local nodes to query Consul
    • update the anonymous token with the new policy that you created
    • configure the policy to allow queries from all nodes in the Consul datacenter

    Correct answer:

    • update the anonymous token with the new policy that you created

    Explaination: any request to Consul that does not specifically include a token will try and use the anonymous token for authentication

    4. Julie is working on a Consul cluster with ACLs enabled, but she is able to create new Service Mesh intentions using the command line without providing an ACL token. What could be the reason that her commands are successful?

    • the ACL system has not yet been bootstrapped
    • the default_policy is said to "Allow"
    • the token is being sent using X-Consul-Token header
    • Consul intention creation doesn't require an ACL Token

    Correct answer:

    • the default_policy is said to "Allow"

    Explaination: the ACL system can be enabled and working but if the default_policy is set to allow, any requests to Consul would not require a token

    5. You have created a token for a consultant that should permit access to the Consul cluster until the end of the week. What built-in feature of Consul can you use to automatically ensure that the token is no longer valid at the end of the week?

    • Sign in and manually revoke the token at the end of the week
    • set the optional expiration date when creating the token
    • set up a Cron job that runs at the end of the week and revokes the token
    • restart the consul service at the end of the week

    Correct answer:

    • set the optional expiration date when creating the token

    Explaination: the optional configuration sets the duration on how long the token is valid. After that time, it will be automatically revoked


    consul-gossip-encryption

    1. True or False? By default, Consul automatically encrypts gossip communication/messages using a self-signed certificate.

    • TRUE
    • FALSE

    Correct answer:

    • FALSE

    2. You need to create a gossip encryption key. What Consul built-in tool/command can you use to easily create one or many keys?

    • consul keyring -create
    • consul keygen
    • consul tls cert create -server
    • consul keyrin -install

    Correct answer:

    • consul keygen

    Explaination: consul keygen will quickly create a new encryption key for you

    3. You run a consul keyring -list command and notice that the gossip encryption key being used doesn't match the key displayed in the configuration file. How can this be?

    • the key has been rotated since the initial configuration
    • gossip encryption has been disabled
    • the consul agent was loaded with a different configuration file
    • the key is displayed in the consul keyring command resulting in the creation of the new keys and doesn't show the current keys

    Correct answer:

    • the key has been rotated since the initial configuration

    Explaination: the key being used may not always match the one displayed in the configuration file, since Consul only reads that key one time during the initial configuration of a Consul agent

    4. Gossip uses what type of security method for encryption?

    • mTLS certificate from a trusted CA
    • a self-signed cert minted from the built-in Consul certificate Authority
    • a symmetric key
    • an ACL using the Gossip resource

    Correct answer:

    • a symmetric key

    Explaination: Remember symmetric key also uses a 32-byte, Base64 encoded key.

    5. Which of the following functions/actions can the consul keyring command NOT perform?

    • list the keys installed on the cluster
    • create a new key to be used for the cluster
    • remove a key from the cluster
    • distribute a new key from the cluster

    Correct answer:

    • create a new key to be used for the cluster

    Explaination: the consul keyring command does not have key creation functionality. Use consul keygen instead


    consul-practice-exam

    1. True or False? The Consul UI and the API can only be accessed from a Consul server itself.

    • TRUE
    • FALSE

    Correct answer:

    • FALSE

    Explaination: This is false. The UI and API are intended to be consumed from remote systems, such as a user's desktop or an application looking to discover a remote service in which it needs to establish connectivity. In addition, most consumers of the Consul service wouldn't normally have access to connect (SSH) to a Consul server anyway

    2. In order to provide high availability and ensure that Consul's state is preserved even if a server fails, HashiCorp suggests that Consul should be configured to run __________.

    • in a cluster made up of three to five servers
    • on as many servers as needed to scale for performance
    • only Kubernetes to provide scheduling for new Consul nodes
    • on a public cloud platform that can provide Hardware redundancy

    Correct answer:

    • in a cluster made up of three to five servers

    Explaination: In order to make sure that Consul's state is preserved even if a server fails, you should always run either three or five servers in production. The odd number of servers (and no more than five of them) strikes a balance between performance and failure tolerance. When scaled beyond (7) servers, the network requirements needed to maintain replication between the clusters may negatively impact the performance of the Consul.

    3. Based on the file below, in what directory would you place the consul.hcl configuration file in order to start the Consul service?

    • /etc/consul.d/
    • /usr/local/bin
    • /etc/systemd/system
    • /opt/services/consul

    Correct answer:

    • /etc/consul.d/

    Code: [Unit] Description="HashiCorp Consul - A service mesh solution" Documentation=https://www.consul.io/ Requires=network-online.target After=network-online.target

    [Service] Type=notify User=consul Group=consul ExecStart=/usr/local/bin/consul agent -config-dir=/etc/consul.d/ ExecReload=/usr/local/bin/consul reload ExecStop=/usr/local/bin/consul leave KillMode=process Restart=on-failure LimitNOFILE=65536

    [Install] WantedBy=multi-user.target

    Explaination: Based on the executable statement in the service file, all .hcl configuration files for Consul would be placed in /etc/consul.d/ . You can break up your desired Consul configurations across multiple .hcl files if you wish. It's common to put the actual Consul configuration in a consul.hcl file while putting node_meta data into a node_meta.hcl file, therefore both will be read upon starting or refreshing the Consul service. This is because the executable statement in the service file is using -config-dir rather than pointing to a single file using -config-file

    4. In most organizations, a service will be run on multiple nodes to provide redundancy and high availability. In the following example, what is the name of the Consul service that this service definition will create?

    • web-a
    • web-frontend
    • green
    • web-server-health

    Correct answer:

    • web-frontend

    Code: { "service": { "id": "web-a", "name": "web-frontend", "port": 80, "tags": [ "web", "green" ], "enable_tag_override": false, "checks": [ { "interval": "10s", "name": "web-server-health", "tcp": "localhost:80", "DeregisterCriticalServiceAfter": "60s" } ] } }

    Explaination: The service definition above will create a service named web-frontend, and will register a new node named web-a that will host the web-frontend service. As long as the health check passes, web-a will register as healthy and traffic destined to the web-frontend service will be directed to this node.

    5. Based on the Consul agent configuration below, what parameter will determine which interface the Consul will use for internal cluster communications?

    • "bind_addr": "10.0.30.186"
    • "client_addr": "0.0.0.0"
    • "node_name": "node-a.example.com"
    • "verify_outgoing": true

    Correct answer:

    • "bind_addr": "10.0.30.186"

    Code: { "log_level": "INFO", "server": true, "node_name": "node-a.example.com", "key_file": "/etc/consul.d/cert.key", "cert_file": "/etc/consul.d/client.pem", "ca_file": "/etc/consul.d/chain.pem", "verify_incoming": true, "verify_outgoing": true, "encrypt": "xxxxxxxxxxxxxxxxxxxxxxxx", "data_dir": "/opt/consul/data", "datacenter": "us-east-1", "bind_addr": "10.0.30.186", "client_addr": "0.0.0.0", "retry_join": ["provider=aws tag_key=Environment-Name tag_value=consul region=us-east-1"], "enable_syslog": true, "acl": { "tokens": { "agent": "xxxxxxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxx" } } }

    Explaination: The parameter bind_addr is used to determine the address that should be bound to for internal cluster communications. This is an IP address that should be reachable by all other nodes in the cluster. By default, this is "0.0.0.0", meaning Consul will bind to all addresses on the local machine and will advertise the private IPv4 address to the rest of the cluster.

    6. A Consul cluster containing (5) Consul server nodes can tolerate a maximum of how many node failures before the Consul cannot establish a quorum and continue to operate?

    • 1
    • 2
    • 3
    • 4

    Correct answer:

    • 2

    Explaination: The following chart can be used to determine the number of failures a Consul cluster can handle before being unable to establish a quorum and the Consul service becoming unavailable. https://www.consul.io/docs/internals/consensus.html#deployment-table

    7. Complete the sentence: The main restriction on Consul's K/V store is an object's size, which can be a maximum of _______?

    • 512KB
    • 64KB
    • 8KB
    • 1MB

    Correct answer:

    • 512KB

    Explaination: The main restriction on an object is size - the maximum is 512 KB. Due to the maximum object size and main use cases, you should not need extra storage

    8. Scenario: You are storing configuration settings for your application in Consul's K/V store, and each setting is critical to the successful implementation of the application. A developer recently updated the value for app1, causing the deployment to fail. What Consul feature can be used to monitor the K/V store for updates and automatically take action to remediate the issue?

    • set up health checks to monitor for changes to the K/V store
    • configure a watch and execute the script to update the application
    • set up an ACL to automatically restart the consul service when a value is changed
    • use the raft consensus protocol to replicate the changes from the other nodes when the value is changed

    Correct answer:

    • configure a watch and execute the script to update the application

    Explaination: Watches are a way of specifying a view of data (e.g. list of nodes, KV pairs, health checks) which is monitored for updates. When an update is detected, an external handler is invoked. A handler can be any executable or HTTP endpoint. As an example, you could set up a key watch type that executes a python script when the value of a key changes

    9. True or False? The open-source tools Consul Template and Envconsul require a Consul cluster to operate

    • TRUE
    • FALSE

    Correct answer:

    • FALSE

    Explaination: Despite the name, Consul Template, nor Envconsul, does not require a Consul cluster to operate. Consul Template can retrieve secrets from Vault and manage the acquisition and renewal lifecycle. Envconsul can launch a subprocess that dynamically populates environment variables from secrets read from Vault.

    10. Which of the following Consul features is responsible for securing inter-service communication with mutual TLS by using sidecar proxies?

    • Envoy
    • Consul ACLs
    • Consul Gossip
    • Consul Connect

    Correct answer:

    • Consul Connect

    Explaination: Consul Connect provides service-to-service connection authorization and encryption using mutual Transport Layer Security (TLS). Applications can use sidecar proxies in a service mesh configuration to establish TLS connections for inbound and outbound connections without being aware of Connect at all. Applications may also natively integrate with Connect for optimal performance and security. Connect can help you secure your services and provide data about service-to-service communications.

    11. During leadership election, which members in the local datacenter get a vote to elect a new leader?

    • Consul servers, read-only server nodes, and clients
    • Consul servers and clients
    • Consul Clients
    • Consul server nodes

    Correct answer:

    • Consul server nodes

    Explaination: Consul's consensus protocol (Serf) is responsible for electing a leader during a new cluster creation or if an existing leader fails. The consensus protocol is only used on Consul server nodes, therefore clients do not participate in voting for a new cluster leader. Furthermore, read-only nodes are also known as non-voting nodes and do not participate in voting for a new leader (hence the name).

    12. Complete the following sentence with the proper order of answers:

    • mutual TLS, TLS
    • TLS, mutual TLS
    • SSL, TLS
    • mutual TLS, SSL

    Correct answer:

    • TLS, mutual TLS

    Code: Consul uses two types of certificates for encryption. Consul agent communications are secured by _________ and Consul Connect uses __________ between registered services.

    Explaination: Consul agent communications are done using TLS certificates that can be created by the built-in CA or an external CA if you need more control over certificates. Consul Connect uses mutual TLS for authorization and encryption.

    13. Your colleague has deployed a new Consul cluster, and you want to double-check the encryption key used for gossip communication. You open up an SSH session to a Consul node and type the command consul keyring -list but receive the following error. From the error message below, what is missing from the Consul agent configuration file?

    • the gossip parameter and a value of true
    • the encrypt parameter and the corresponding value
    • the encryption parameter with a valid of true or 1
    • configuration for the TLS certificate, the private key, and the CA bundle

    Correct answer:

    • the encrypt parameter and the corresponding value

    Code: $ consul keyring -list

    ==> Gathering installed encryption keys... error: Unexpected response code: 500 (12 errors occurred: * WAN error: 5/5 nodes reported failure * CONSUL-NODE-D.dc-1: Keyring is empty (encryption not enabled) * CONSUL-NODE-C.dc-1: Keyring is empty (encryption not enabled) * CONSUL-NODE-A.dc-1: Keyring is empty (encryption not enabled) * CONSUL-NODE-E.dc-1: Keyring is empty (encryption not enabled) * CONSUL-NODE-B.dc-1: Keyring is empty (encryption not enabled) * dc-1 (LAN) error: 5/5 nodes reported failure * CONSUL-NODE-E: Keyring is empty (encryption not enabled) * CONSUL-NODE-D: Keyring is empty (encryption not enabled) * CONSUL-NODE-B: Keyring is empty (encryption not enabled) * CONSUL-NODE-A: Keyring is empty (encryption not enabled) * CONSUL-NODE-C: Keyring is empty (encryption not enabled)

    Explaination: In the configuration file, the encrypt parameter must be used to enable gossip encryption and set the gossip encryption key. The provided key is automatically persisted to the data directory and loaded automatically whenever the agent is restarted. The fact that the key is persisted in the data directory means that in order to encrypt Consul's gossip protocol, this option only needs to be provided once on each agent's initial startup sequence.

    14. A user is defining a new prepared query named web-app for an application that includes a failover policy for providing high availability for a service. However, when the user accesses the app using the DNS name web-app.service.consul, access to the application isn't failing to the secondary datacenter as expected. What could be the issue?

    • Consul Federation isn't supported for Web Applications
    • Prepared queries doesn’t support failover policies
    • The user needs to use web-app.query.consul instead
    • Prepared queries are only accessible by API, and not DNS

    Correct answer:

    • The user needs to use web-app.query.consul instead

    Explaination: When defining a prepared query, the default endpoint for using the prepared query is .query.consul. If the user is trying to access it using web-app.service.consul, the user may be hitting the service directly, and not taking advantage of the prepared query at all. Therefore, if the local service were to go down, the failover policy would not be used, since you must hit the DNS name of the prepared query to take advantage of a failover policy.

    15. Which token is always assigned the Accessor ID of 00000000-0000-0000-0000-000000000002, regardless of what cluster you are working on?

    • master token
    • the second token create by the user
    • anonymous token
    • Consul DNS token

    Correct answer:

    • anonymous token

    Explaination: The anonymous token is used when a request is made to Consul without specifying a bearer token. The anonymous token's description and policies may be updated but Consul will prevent this token's deletion. When created, it will be assigned 00000000-0000-0000-0000-000000000002 for its Accessor ID and anonymous for its Secret ID.

    16. Consul uses a gossip protocol that is powered by Serf. How is this communication protected between all participating servers and clients?

    • mutual TLS
    • TLS
    • username and password
    • shared secret

    Correct answer:

    • shared secret

    Explaination: Consul's gossip protocol is protected by a symmetric key, or a shared secret, that is configured as part of the configuration file or in a separate file that is read when the Consul service starts. For example, you can add the parameter "encrypt" to the configuration file with 32-byte, Base64 encoded shared secret. All nodes in the Consul cluster, including WAN joined datacenters, must use the same encryption key. An example of this key would be pUqJrVyVRj5jsiYEkM/tFQYfWyJIv4s3XkvDwy7Cu5s= Furthermore, you can generate this 32-byte, Base64 encoded shared secret by using the built-in command

    17. Using the service configuration below, what service will be registered, and what port will the service run on?

    • watermark_web_a running on port 8080
    • picture_app running on port 8080
    • watermark_web_a running on port 80
    • picture_app running on port 80

    Correct answer:

    • picture_app running on port 8080

    Code: { "service": { "ID": "watermark_web_a", "name": "picture_app", "tags": ["front-end", "watermark"], "port": 8080, "check": { "id": "picture_app_check", "name": "Check Counter health 80", "tcp": "localhost:80", "interval": "10s", "timeout": "1s" } } }

    Explaination: For this service definition, the instance of the service is watermark_web_a but the service itself will be named picture_app. The service definition has a port defined of 8080, so that is the port the service will run on. The health check is checking that a service is running on port 80 on the same host, but that is not the port that the picture_app will be registered on.

    18. Assuming Consul default configurations, which of the following DNS records would be used to access the service referenced by the following configuration:

    • inventory-app.query.service.consul
    • inventory-app.query.consul
    • retail-app.service.consul
    • retail-app.query.consul

    Correct answer:

    • retail-app.query.consul

    Code: { "Name": "retail-app", "Service": { "Service": "inventory-app", "Tags": ["v1.2.3"], "Failover": { "Datacenters": ["dc2", "dc3"] } } }

    Explaination: The configuration provided in the question is a prepared query. The name of the prepared query is retail-app, therefore the DNS record used to query this prepared query is retail-app.query.consul since all prepared queries use the query namespace.

    19. True or False? Using the / character, Consul organizes the data in a directory structure, similar to a file system.

    • TRUE
    • FALSE

    Correct answer:

    • FALSE

    Explaination: The character / will be treated like any other character and is not fixed to the file system. Meaning, including / in a key does not fix it to a directory structure. This model is similar to Amazon S3 buckets. However, / is still useful for organizing data and when recursively searching within the data store.

    20. True or False? You want to restore a Consul from a snapshot. On a five-node Consul cluster, the consul snapshot restore filename.snap command must be run on each individual node before starting the Consul service.

    • TRUE
    • FALSE

    Correct answer:

    • FALSE

    Explaination: Running the restore process should be straightforward. However, there are a couple of actions you can take to ensure the process goes smoothly. First, make sure the datacenter you are restoring is stable and has a leader. You can see this using consul operator raft list-peers and checking server logs and telemetry for signs of leader elections or network issues. You will only need to run the process once, on the leader. The Raft consensus protocol ensures that all servers restore the same state.

    21. After Consul ACLs have been enabled in the configuration file, what is the next step to begin using ACLs in your environment?

    • create new ACL tokens
    • create new ACL policies
    • bootstrap the ACL system
    • disable the anonymous token

    Correct answer:

    • bootstrap the ACL system

    Explaination: Once ACLs have been enabled, you must first bootstrap the ACL system in order to begin using it. To do this, you would run the command consul acl bootstrap and Consul will return the bootstrap token

    22. You need to determine the leader node for the Consul cluster. What command allows you to quickly identify the nodes and their current roles within the cluster?

    • consul members
    • consul nodes-leader
    • consul raft -list
    • consul operator raft list-peers

    Correct answer:

    • consul operator raft list-peers

    Code: Example of the command's output:

    Node           ID                                    Address           State     Voter  RaftProtocol
    CONSUL-NODE-A  121abb4c-16fb-c8ec-2e2b-9595925de4dc  10.0.10.238:8300  follower  true   3
    CONSUL-NODE-C  4bead426-4471-0924-598f-cd6ce0015ebc  10.0.10.48:8300   follower  true   3
    CONSUL-NODE-E  c44e8ab1-1132-1b22-9501-479c690c9e1b  10.0.10.105:8300  leader    true   3
    CONSUL-NODE-D  ba86541f-cd93-6ada-b763-709b0fc6c09f  10.0.11.163:8300  follower  true   3
    CONSUL-NODE-B  2528cba1-06ea-4837-fc7b-13e44af19b0d  10.0.11.141:8300  follower  true   3
    

    Explaination: The Raft operator command is used to interact with Consul's Raft subsystem. Specifically, the list-peers command will display the current Raft peer configuration, which shows the state of each node, being either a leader or a follower.

    23. What is one of the benefits of deploying non-voting servers in a Consul Enterprise cluster environment?

    • they can write data to the cluster to reduce write latency
    • they can expand the number of nodes to take part in quorum election operations
    • they do not receive data from cluster replication, therefore reducing latency
    • they provide enhanced read scalability

    Correct answer:

    • they provide enhanced read scalability

    Explaination: Consul Enterprise provides the ability to scale clustered Consul servers to include voting and non-voting servers. Non-voting servers still receive data from the cluster replication, however, they do not take part in quorum election operations. Expanding your Consul cluster in this way can scale reads without impacting write latency.

    24. Based on the configuration file provided below, how would a new Consul agent discover other Consul datacenter members in order to join the Consul datacenter?

    • using auto-discovery information through DNS
    • discover other members using DC1 name
    • using cloud auto-join
    • using the information provided by a DHCP

    Correct answer:

    • using cloud auto-join

    Code: { "server": false, "node_name": "web-app-01", "datacenter": "DC1", "data_dir": "/opt/consul/data", "bind_addr": "10.0.42.84", "client_addr": "10.0.42.84", "retry_join": ["provider=aws tag_key=consul tag_value=true"], "log_level": "INFO", "enable_syslog": true, }

    Explaination: Consul can join a datacenter by using the cloud auto-join feature, which does automatic cluster joining using cloud metadata. In the configuration file above, the retry_join parameter states that the Consul agent should query AWS and discover instances that have a tag of consul with a value of true

    25. Based on the payload below, what Consul feature is being created with the API?

    • prepared query
    • service
    • Consul agent
    • service mesh intention

    Correct answer:

    • prepared query

    Code: { "Name": "db-service", "Service": { "Service": "redis", "Failover": { "NearestN": 3, "Datacenters": ["dc1", "dc2"] }, "Near": "node1", "OnlyPassing": false, "Tags": ["primary", "!experimental"], "NodeMeta": { "instance_type": "m3.large" }, "ServiceMeta": { "environment": "production" } }, "DNS": { "TTL": "10s" } }

    Explaination: The payload in the question is the configuration of a prepared query. You can immediately tell that it's a prepared query since it includes a failover policy as well. Failover policies are only configured in a prepared query.


    azure-case-studies

    1. You are planning to create a web application which is internet facing. The application should be deployed on Linux Ubuntu VM running Apache webserver. For load balancing the requests, you have created a standard application gateway and added these VMs as backend servers to the application gateway. Your management would like to ensure that the VMs are highly available by deploying VMs in different physical data centers within the same region. Should you deploy VMs across availability sets?

    • Yes
    • No

    Correct answer:

    • No

    2. You are planning to create a web application which is internet facing. The application should be deployed on Linux Ubuntu VM running Apache webserver. For load balancing the requests, you have created a standard application gateway and added these VMs as backend servers to the application gateway. Your management would like to ensure that the VMs are highly available by deploying VMs in different physical data centers within the same region. Should you deploy VMs across availability zones?

    • Yes
    • No

    Correct answer:

    • Yes

    3. You are planning to create a web application which is internet facing. The application should be deployed on Linux Ubuntu VM running Apache webserver. For load balancing the requests, you have created a standard application gateway and added these VMs as backend servers to the application gateway. Your management would like to ensure that the VMs are highly available by deploying VMs in different physical data centers within the same region. Is the following true or false: No need for deployment across datacenters, Application gateway will handle high availability.

    • True
    • False

    Correct answer:

    • False

    4. You are planning to create a web application which is internet facing. The application should be deployed on Linux Ubuntu VM running Apache webserver. For load balancing the requests, you have created a standard application gateway and added these VMs as backend servers to the application gateway. Your management would like to ensure that the VMs are highly available by deploying VMs in different physical data centers within the same region. Should you upgrade to StandardV2 Application Gateway?

    • Yes
    • No

    Correct answer:

    • No

    5. Your web application is currently running on Azure Virtual Machines and you would like to migrate to Azure App Service. Before you move to production, you would like to test the application. Ideally, the testing requires 24 hours. Which tier would you select for testing your application?

    • Use the Free Tier as it is free of cost
    • Use Shared tier
    • Use Basic Tier
    • Use Standard Tier

    Correct answer:

    • Use Basic Tier

    vault associate auth methods

    1. True or False? Vault auth methods are responsible for validating a user's identity and associating policies for authorization?

    • True
    • False

    Correct answer:

    • True

    Explaination: Vault auth methods are used for validating identity and associating policies that are attached to a token.

    2. When using any auth method beyond the token, what is the result of using an auth method?

    • obtaining a Vault token
    • validating your credentials
    • to get access to a Vault policy
    • to generate new dynamic credentials

    Correct answer:

    • obtaining a Vault token

    Explaination: The correct option is the "Obtaining a Vault token" because all subsequent requests to Vault will use the token for authentication.

    3. Which of the following are valid auth methods that can be enabled in Vault?

    • OIDC
    • Azure AD
    • SAML 2.0
    • MySQL

    Correct answer:

    • OIDC

    Explaination: OIDC is the correct auth method. Apart from that, Azure AD is not a valid auth method, although you can use OIDC to configure Vault to use Azure AD for authentication. You might feel this is tricky, but it's important to know what are actual auth methods and what options can be enabled by using the official auth methods, like Azure AD.

    Documentation Link: https://www.vaultproject.io/docs/auth/jwt#oidc-authentication

    4. You are using Terraform in your environment to deploy infrastructure to your public cloud platform. Terraform is being executed on a server running in AWS. The Security team has mandated that any credentials for Terraform must be short-lived and rotated often. What auth method should you use to authenticate to Vault and satisfy these requirements?

    • AWS auth method
    • UserPass
    • AppRole
    • LDAP

    Correct answer:

    • AWS auth method

    Explaination: The credentials are generated only when Terraform needs them and are automatically revoked after the lease. On other hand.  AppRole probably shouldn't be used here since the AWS auth method provides a better alternative, especially since Terraform is being executed from a server running in AWS. AppRole could work, but the AWS auth method is a better choice here. LDAP wouldn't really provide any benefit here, since Terraform needs AWS credentials. UserPass credentials don't have any requirements behind how long they live, so you could have a userpass user that lives forever without having to rotate the password.

    5. Which of the following auth methods are generally associated with machine-to-machine authentication?

    • AppRole
    • OIDC
    • LDAP
    • UserPass

    Correct answer:

    • AppRole

    Explaination: The correct option is the "AppRole". It is frequently the primary auth method used for machine-to-machine authentication. On the other hand.
    LDAP - is generally associated with a human-based authentication method. It generally requires somebody to type in a credential.
    UserPass - is generally associated with a human-based authentication method. It generally requires somebody to type in a credential.
    OIDC - is generally associated with a human-based authentication method, such as Azure AD or Ping Federate. It generally requires somebody to type in a credential.

    Documentation Link: https://www.vaultproject.io/docs/auth/approle


    vault associate policies

    1. You have a new team member on the Vault operations team. Their first task is to rotate the encryption key in Vault as part of the organization's security policy. However, when they log in, they get an access denied error when attempting to rotate the key. The policy being used is below. Why can't the user rotate the encryption key?

    • The policy requires sudo privileges since it is a root-protected path
    • The policy doesn't include create privileges so a new encryption key can't be created
    • The policy should include sys/rotate/<name of key> as part of the path
    • The encryption key has a minimum TTL. Therefore the key cannot be rotated until that time expires

    Correct answer:

    • The policy requires sudo privileges since it is a root-protected path

    Code: path "auth/*" { capabilities = ["create", "read", "update", "delete", "list"] }

    Rotate encryption key

    path "sys/rotate" { capabilities = ["read", "update"] }

    Explaination: Rotating the encryption requires sudo or root access to the path sys/rotate.

    2. Every Vault deployment will have two default policies that are created automatically. What are these two policies?

    • The anonymous policy and the default policy
    • The admin policy and the user policy
    • The primary policy and the secondary policy
    • The root policy and the default policy

    Correct answer:

    • The root policy and the default policy

    Explaination: The default policies are root and default.

    3. Vault policies contain multiple parts, including the path and capabilities. What are the valid capabilities that can be used in a policy?

    • read,write,delete,list,sudo,update
    • read,create,delete,list,sudo,update,deny
    • get,write,remove,list,sudo,update,deny
    • delete,list,update,root,default,deny create,sudo

    Correct answer:

    • read,create,delete,list,sudo,update,deny

    Explaination: Neither get, write, root, or remove is a valid capability. The correct answer is read, create, delete, list, sudo, update, and deny.

    4. You've been provided a Vault token that is attached to the following policy. Select the action below that will be permitted.

    • List secrets stored at kv/data/apps/jenkins
    • Modify an existing Vault policy
    • Store a new secret stored at kv/data/apps/jenkins
    • List the roles for the AWS secrets engine mounted at aws/

    Correct answer:

    • Modify an existing Vault policy

    Code: path "kv/data/apps/jenkins" { capabilities = ["read","update","delete"] } path "sys/policies/*" { capabilities = ["create","update","list","delete"] } path "aws/creds/web-app" { capabilities = ["read"] }

    Explaination: The correct answer is "Modify an existing Vault policy" because the capability update has been permitted for all policies (sys/policies/*). For "List secrets stored at kv/data/apps/jenkins", you could read these secrets, but you won't be able to list the secrets that are stored at this path because that capability doesn't exist on the path. For "Store a new secret stored at kv/data/apps/jenkins", This is wrong because the policy doesn't grant the "create" capability at this path. For "List the roles for the AWS secrets engine mounted at aws/", you have permission to generate credentials against a specific role, but not list the roles at aws/roles.

    5. Given the following policy, select the action that would NOT be permitted.

    • Read a secret at the path kv/data/teams/cloud/database/db2
    • Store a new secret at secret/apps/database/prod-db
    • Read a secret at kv/apps/webapp/ecommerce/production
    • List the secrets stored at kv/data/teams/developers/database/db-001

    Correct answer:

    • Read a secret at the path kv/data/teams/cloud/database/db2

    Code: path "kv/apps/webapp/" { capabilities = ["read"] } path "secret/apps/database/prod-db" { capabilities = ["read", "create", "update", "delete", "list"] } path "kv/data/teams/+/database/db-" { capabilities = ["read", "list"] }

    Explaination: The correct answer is "Read a secret at the path kv/data/teams/cloud/database/db2" because this isn't permitted because the wildcard at the end requires that the ending segment be db-. The path selected does not include the dash ("-") character.

    For "Store a new secret at secret/apps/database/prod-db", this will be permitted by the second policy since it has the create capability, therefore it is the incorrect answer.

    For "Read a secret at kv/apps/webapp/ecommerce/production", this will be permitted by the first policy because there is a wildcard after kv/apps/webapp.

    For "List the secrets stored at kv/data/teams/developers/database/db-001", this will be permitted by the last policy because it follows the correct pattern.


    vault associate tokens

    1. What is the difference between the TTL and the Max TTL?

    • The TTL defines when the token will expire and be revoked.
    • They are essentially the same.
    • The TTL defines when another token will be generated.
    • The max TTL defines the timeframe for which a token cannot be used.

    Correct answer:

    • The TTL defines when the token will expire and be revoked.

    Explaination: TTL defines when the token will expire and Max TTL defines the maximum timeframe for which the token can be renewed.

    2. What of the following feature is true about batch tokens in Vault?

    • Batch tokens are not persisted (written) to storage
    • Batch tokens can create child tokens
    • Batch tokens are written to the storage

    Correct answer:

    • Batch tokens are not persisted (written) to storage

    Explaination: Batch tokens are NOT written to storage.

    3. True or False? To prepare for day-to-day operations, the root token should be safely saved outside of Vault in order to administer Vault.

    • True
    • False

    Correct answer:

    • False

    Explaination: For day-to-day operations, the root token should be deleted after configuring other auth methods which will be used by admins and Vault clients.

    4. Sara uses the Vault command-line interface (CLI) to perform various administrative tasks on the production Vault cluster. However, Sara is receiving permission denied errors when attempting to make changes. She needs to figure out what policies are attached to her token so she can view the policy and determine what permissions need to be added.
    What CLI command can Sara run on the Vault node to determine what policies are attached to the current token?

    • vault token lookup
    • vault operator diagnose
    • vault policy list
    • vault token capabilities

    Correct answer:

    • vault token lookup

    5. Which of the following best describes a token accessor?

    • A value that acts as a reference to a token that can be used to perform limited actions against the token.
    • A token is used for Consul to access Vault auth methods.
    • Describes the value associated with the tokens TTL.
    • A value that describes which clients have access to the attached token.

    Correct answer:

    • A value that acts as a reference to a token that can be used to perform limited actions against the token.

    Quiz 1 - Open Source

    1. Identify some open source software from these

    • MacOS
    • Windows
    • Linux
    • Docker

    Correct answer:

    • Linux
    • Docker

    Explaination: Linux and Docker are open source while MacOS and Windows are closed source software

    2. Early Stellwart of open source, Richard Stallman named his project GNU which is a recursive acronym. Using the internet find out which other works if Richard Stallman popular for.

    • Free Software Foundation
    • GNU GPL License
    • Linux
    • Mozilla

    Correct answer:

    • Free Software Foundation
    • GNU GPL License

    Explaination: Richard stallman created GNU GPL License giving the concept of Copy Left and also started the Free Software Foundation.

    3. For a software to be called, open source software it must ______

    • Have code in clean architecture
    • Have an associated open source license
    • be free of cost
    • be debuggable

    Correct answer:

    • Have an associated open source license

    Explaination: To be called open-source software, there must be a finite set of laid down principles that must be respected. There are called “Open Source Licences”. An open-source licence should regulate each open-source software. A licence defines the conditions of using, modifying and redistributing the source code associated with the open-source software.

    4. In context of open source, "Free" refers to ______

    • Freedom
    • Free of cost
    • Free of bugs
    • Free of governance

    Correct answer:

    • Freedom

    Explaination: "Free" does not necessarily mean without cost/payment, but it tries to define the aspects of freedom to use, modify and redistribute the code.

    5. Facebook’s open source javascript based UI library “React” is an open source project. Use the internet to find out this repository and find which open source license is used for this project?

    • GNU GPL
    • MIT License
    • FreeBSD
    • Apache license 2.0

    Correct answer:

    • MIT License

    Explaination: React is licensed under MIT license. https://github.com/facebook/react/blob/main/LICENSE


    Quiz 2 - Open Source

    1. One of the pioneer organisations in Open source "Open Source Initiative" was founded in 1998. OSI is the steward if Open Source Definition (OSD). Using the official docs (https://opensource.org/docs/osd) choose the original source from which OSD was derived

    • Debian Free Software Guidelines (DFSG)
    • World Wide Web Consortium (W3C)
    • OpenGL
    • The Cathedral and the Bazaar

    Correct answer:

    • Debian Free Software Guidelines (DFSG)

    Explaination: he Open Source Definition was originally derived from the Debian Free Software Guidelines (DFSG). Debian, the producers of the Debian system, have created the Debian Social Contract. The Debian Free Software Guidelines (DFSG) part of the contract, initially designed as a set of commitments that we agree to abide by, has been adopted by the free software community as the basis of the Open Source Definition.

    2. Apart from MIT, Which other organisation among these is associated with MIT License

    • IBM
    • Google
    • Facebook
    • Linux Foundation

    Correct answer:

    • IBM

    Explaination: The Open Source Definition was originally derived from the Debian Free Software Guidelines (DFSG). Debian, the producers of the Debian system, have created the Debian Social Contract. The Debian Free Software Guidelines (DFSG) part of the contract, initially designed as a set of commitments that we agree to abide by, has been adopted by the free software community as the basis of the Open Source Definition.

    3. Any work which is freely available over the internet can be considered open source?

    • True
    • False

    Correct answer:

    • False

    Explaination: The open source licence grants other users permission to access, modify and distribute the work while also defining the boundaries, conditions, and other nuances with it.

    4. Open source software systems offer reliability because of anyone can anytime modify the source code?

    • True
    • False

    Correct answer:

    • False

    Explaination: For any system, reliability is the ability to consistently perform according to its specifications. Open source systems offer reliability because vulnerabilities are fixed and patches and new versions are released a lot faster than a typical closed source system.

    5. Unlike copyleft software licenses, the MIT License also permits reuse within proprietary software

    • True
    • Flase

    Correct answer:

    • True

    Explaination: Unlike copyleft software licenses, the MIT License also permits reuse within proprietary software , provided that all copies of the software or its substantial portions include a copy of the terms of the MIT License and also a copyright notice

    6. Continuous Evolution in open source systems is enabled by

    • Community Support
    • Open Source License
    • Source Code
    • Open Data

    Correct answer:

    • Community Support

    Explaination: The practice of open source involves a community of contributors which helps in the evolution of the idea, project and the scope of the project.

    7. Using Internet, find which of the given are permissions granted by MIT license. You can use the following resource - https://choosealicense.com/licenses/

    • Commercial use
    • modification
    • Liability
    • Warranty

    Correct answer:

    • Commercial use
    • modification

    Explaination: MIT license is a short and simple permissive license allowing Modifications and Commercial use


    Quiz 3 - Getting Started with Open Source

    1. Participating in open source might also include contributing to ______

    • Documentation
    • Design
    • Advocacy
    • Code

    Correct answer:

    • Documentation
    • Design
    • Advocacy
    • Code

    Explaination: Participating in open source has many forms. It is not just limited to contributing to the code base. It also includes design, documentation, content, communities, and advocacy, among several other ways.

    2. Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications. Using the official documentation, select the organisation which maintains Express https://expressjs.com/

    • OpenJS Foundation
    • Open Source Initiative
    • Mozilla Foundation
    • Apple Inc,

    Correct answer:

    • OpenJS Foundation

    Explaination: Express is a project of the OpenJS Foundation.

    3. Contributing to open source means to contribute to the source code of an open source software

    • True
    • False

    Correct answer:

    • False

    Explaination: open-source in its fundamental principle is accepting in nature. In practice, there are more than one ways to be involved in open-source.

    4. A branch is when a new line of development is created that diverges from the main line of development.

    • True
    • False

    Correct answer:

    • True

    Explaination: A branch is when a new line of development is created that diverges from the main line of development. By default, the straight line of development is called “Master”.

    5. In terminology of the version control system Git, a commit refers to

    • Data Snapshots
    • User's Commitment to code
    • Files in Repository
    • Staging Index

    Correct answer:

    • Data Snapshots

    Explaination: Commit Refers to data snapshots. Upon every commit, a snapshot of the look of the file is stored. In general terms, changes made to files inside a repository are made using commits.

    6. Forking a repository means

    • creating a copy of the repository
    • sending files to github
    • initialising a new git repository
    • downloading the repository to local system

    Correct answer:

    • creating a copy of the repository

    Explaination: Forking a repository means creating a copy of the repository. Once a repository has been forked, the repository can be viewed under one’s own account.

    7. On using git add, the changes/files are added to the

    • Git Repository
    • Staging Index
    • VCS Logs
    • Working Directory

    Correct answer:

    • Staging Index

    Explaination: The first step in using git to keep track of changes to these files is to add the change (the file which was changed) to a different area called the “Staging Index”. Before you call these changes permanent (using a commit), this area acts like a bridge between the working directory and the actual git repository. On being sure of the changes made, you would explicitly commit the file moving it to the repository from the staging index.


    Quiz 4 - Open Source Projects

    1. Which is one of the popular system for Internet hosting service and Version control among the following

    • Github
    • Stackoverflow
    • Quora
    • Ansible

    Correct answer:

    • Github

    Explaination: Open source software projects are typically hosted on the internet using platforms that allow version control. Github, Gitlab, BigBucket and are some popular examples where you can find millions of projects

    2. In context of an open source project, the person/s or organization that created the project is typicall the _____

    • Author
    • Coder
    • Contributor
    • Member

    Correct answer:

    • Author

    3. Since there is no boundary whatsoever, open communities promote _____ in technology and innovation.

    • Diversity
    • Business
    • Costs
    • Regulations

    Correct answer:

    • Diversity

    4. The documentation file which typically acts like an instruction manual that welcomes new community members to the project is famously known as -

    • CONTRIBUTING.MD
    • README.MD
    • INTRODUCTION.MD
    • WELCOME.MD

    Correct answer:

    • README.MD

    Explaination: The README is the instruction manual that welcomes new community members to the project. It explains why the project is useful and how to get started.

    5. The ground rules for participants’ behavior are regulated by the

    • Morals
    • Code of conduct
    • Legal policies
    • NDA

    Correct answer:

    • Code of conduct

    Explaination: The code of conduct sets ground rules for participants’ behaviour associated and helps to facilitate a friendly, welcoming environment. While not every project has a CODE_OF_CONDUCT file, its presence signals that this is a welcoming project to contribute to.

    6. Project governance in an open source project typically includes

    • Operations
    • Development Methodology
    • Legality
    • Finances

    Correct answer:

    • Operations
    • Development Methodology

    Quiz 5 - Starting an Open Source Project

    1. Ways to manage interaction and communication in an open community are ?

    • IRCs
    • GitHub Discussions
    • Community Forum
    • VS code

    Correct answer:

    • IRCs
    • GitHub Discussions
    • Community Forum

    2. Open Source Projects could belong to

    • Individuals
    • Organisations
    • Groups
    • Students

    Correct answer:

    • Individuals
    • Organisations
    • Groups
    • Students

    3. People around an open source project make up the

    • Community
    • Project Management Board
    • Advocates
    • Owners

    Correct answer:

    • Community

    4. The purpose of README is to describe the project, serve as an early interaction point for all new users, and provide sufficient knowledge about the usability and working of the project

    • True
    • False

    Correct answer:

    • True

    Explaination: Its purpose is to describe the project, serve as an early interaction point for all new users, and provide sufficient knowledge about the usability and working of the project. For software projects, you might see READMEs containing instructions on how to install and run the project locally.

    5. Which of the following is a critical aspect of documentation in open source projects

    • Describing personal details about author
    • Describing the ways to contribute
    • Describing conversations, threads and discussions
    • Describing the Project

    Correct answer:

    • Describing the ways to contribute
    • Describing conversations, threads and discussions
    • Describing the Project

    Getting Started With OpenShift

    1. If you want an OpenShift environment for dev purposes that you control, which option would you choose?

    • Dev Sandbox
    • OpenShift ReadyContainers (OpenShift Local)
    • Minikube

    Correct answer:

    • OpenShift ReadyContainers (OpenShift Local)

    Explaination: OpenShift Local, previously known as ReadyContainers, is a method that you can use to install OpenShift locally. It looks and feels the same way as any other OpenShift cluster, except it’s free and running on your local computer.

    2. You can install OpenShift in production on both Azure and AWS

    • True
    • False

    Correct answer:

    • True

    Explaination: You can install OpenShift on any cloud, whether it has a specific OpenShift service or not.

    3. If you use the OpenShift Trial, you will still be charged by the cloud provider you run OpenShift on

    • True
    • False

    Correct answer:

    • True

    Explaination: Even though you won’t be charged for OpenShift itself, you’ll be charged for where OpenShift runs. For example, if you run OpenShift on AWS, you’ll be charged for the EC2 instances

    4. Is the Dev Sandbox the same as OpenShift Local?

    • yes
    • no

    Correct answer:

    • no

    Explaination: OpenShift Local is installed locally on a desktop or laptop. Sandbox is run in the cloud.

    5. Under the Developer section of OpenShift, there’s an observability tab where you can see

    • Metrics
    • Prometheus dashboards
    • Cluster information
    • Events

    Correct answer:

    • Metrics
    • Events

    Explaination: The Observability tab allows you to look at metrics, events, alerts, and the dashboard.


    Openshift Concepts – Projects and Users

    1. On the Pod section of the OpenShift UI, there’s a tab called ___ so you can exec into the Pod

    • Exec
    • Terminal
    • Events
    • Logs

    Correct answer:

    • Terminal

    Explaination: The Terminal tab allows you to exec into a Pod, very much like when you’re on the terminal and run kubectl exec -ti

    2. Projects in OpenShift are the same, or very similar, to _____ in Kubernetes

    • RBAC
    • Worker nodes
    • Namespaces
    • User creation

    Correct answer:

    • Namespaces

    Explaination: Projects in OpenShift are an isolation of Pods, Deployments, and other Kubernetes resources. They are almost identical to Namespaces in Kubernetes.

    3. __ is the same as kubectl apply -f

    • test apply -y
    • deploy apply -y
    • oc apply -f
    • openshift apply -f

    Correct answer:

    • oc apply -f

    Explaination: The oc CLI allows you to control and retrieve Kubernetes resources much like the kubectl CLI.

    4. When you deploy a Pod to OpenShift and you don’t specify a Project, it’ll be deployed to the ___ project

    • A new one gets automatically created
    • The Default project
    • The kube-system project
    • The Pod doesn’t get deployed to a Project

    Correct answer:

    • The Default project

    Explaination: Pods, by default, get deployed to the default Project in OpenShift if a Namespace isn’t specified.

    5. You can deploy standard Kubernetes Manifests to OpenShift

    • True
    • False

    Correct answer:

    • True

    Explaination: Kubernetes Manifests work the same way in OpenShift from a deployment and management perspective.


    Concepts – Builds and Deployments

    1. A Build allows you to

    • Automatically deployment workloads
    • Takes code and turns it into a container image
    • Takes a container image and turns it into code
    • Automatically deploys Pods

    Correct answer:

    • Takes code and turns it into a container image

    Explaination: Builds allow you to take code that’s in source control and turn it into a container image to be deployed to Kubernetes

    2. What’s the biggest difference between Deployments and DeploymentConfigs?

    • Pods don’t work on both
    • DeploymentConfigs can’t have Services attached
    • ReplicaSets and ReplicaControllers
    • There are no replicas in DeploymentConfigs

    Correct answer:

    • ReplicaSets and ReplicaControllers

    Explaination: DeploymentConfigs have ReplicaControllers and Deployments have ReplicaSets

    3. S2i allows you to create container images without Dockerfiles

    • True
    • False

    Correct answer:

    • True

    Explaination: S2i allows you to take code and create a docker-compliant container image.

    4. Image streams allow you to

    • Update deployments on the fly with tags
    • Update Pods with tags
    • Delete deployments automatically
    • Automatically deploy DeploymentConfigs

    Correct answer:

    • Update deployments on the fly with tags

    Explaination: Image streams constantly update and create container images for automatic updates of applications and auto-deployments (if configured)

    5. What would you use in OpenShift if you want to have a public-facing app that users can reach via the web browser?

    • Pods with public IPs
    • Deployments with public IPs
    • Routes
    • DaemonSets

    Correct answer:

    • Routes

    Explaination: Routes in OpenShift are very similar to having a Kubernetes Service with a type: LoadBalancer associated with it. Routes look at backend Pods and expose apps via a URL.


    Networks, Services, Routes and Scaling

    1. What command would you use to scale Deployments?

    • oc scale
    • oc deploy
    • oc create -f
    • oc autoscale

    Correct answer:

    • oc autoscale

    Explaination: The oc autoscale command allows you to set minimum Pods and maximum Pods using the --min and --max flags.

    2. Horizontal autoscaling increases CPU/memory on a Pod or a server

    • True
    • False

    Correct answer:

    • False

    Explaination: Horizontal autoscaling increases the amount of Pods or servers that you have. For example, if you have 2 replicas and you want 4 replicas, horizontal autoscaling would take care of that.

    3. Horizontal autoscaling allows you to increase or decrease replicas based on

    • Increased load for an app
    • Decreased load for an app
    • New ingress routes
    • New projects created

    Correct answer:

    • Increased load for an app
    • Decreased load for an app

    Explaination: Autoscaling is all about increased load or decreased load. If there are more users reaching an application, replicas will increase. If there are less users reaching an application, replicas will decrease.

    4. Vertical autoscaling is increasing CPU/memory on a Pod or a server

    • True
    • False

    Correct answer:

    • True

    Explaination: Vertical autoscaling increases hardware resources on a Pod or server

    5. You can set the minimum Pod count by using the following flag:

    • —minus
    • —minusPods
    • —minuz
    • —min

    Correct answer:

    • —min

    Explaination: The --min flags tells Kubernetes that for a specific Deployment, there should be a minimum Pod of X Pods running.


    Storage, Templates and Catalog

    1. Limits do the following

    • Allow for resources to be requested
    • Puts hard limits on CPU (if specified)
    • Puts hard limits on memory (if specified)
    • Increases autoscaling

    Correct answer:

    • Puts hard limits on CPU (if specified)
    • Puts hard limits on memory (if specified)

    Explaination: Limits allow you to specify what resources a Pod can get and what the limit is. For example, if a Pod is limited to 10Mi, even if the Pod needs 15Mi to keep running the app inside of the Pod, it won’t get it

    2. Dynamic storage allows you to:

    • Create your own storage provider
    • Use a StorageClass so you don’t have to create PersisitentVolumes
    • Use PersistentVolumes so you don’t have to create StorageClasses
    • Use local storage as a PersistentVolume

    Correct answer:

    • Use a StorageClass so you don’t have to create PersisitentVolumes

    Explaination: Dynamic storage allows engineers to not have to worry about creating PersistentVolumes and having to manage said volumes across the cluster. Instead, a PersistentVolumeClaim can point to a StorageClass to utilize X amount of storage on demand.

    3. A StorageClass automatically creates a PersistentVolume

    • True
    • False

    Correct answer:

    • False

    Explaination: A StorageClass gives you the necessary tools to utilize storage, but it does not automatically create a PersistentVolume

    4. Requests do the following:

    • Ask for CPU/memory
    • Can keep asking
    • Vertically scales Pods
    • Specify what type of scaling goes into a Pod

    Correct answer:

    • Ask for CPU/memory
    • Can keep asking

    Explaination: Requests give Pods the ability to request CPU and memory to allocate resources for apps running inside of the Pods. They can also keep asking for resources (CPU/memory) if the resources are available.

    5. You can specify limits, requests, and overall quotas per Namespace

    • True
    • False

    Correct answer:

    • True

    Explaination: You can set specific limits and requests per Namespace. That way, you don’t have to manually set them per Pod.


    Openshift Security

    1. You can create a user with the following command

    • oc create user username
    • oc deploy user username
    • oc create person username
    • kubectl create user username

    Correct answer:

    • oc create user username

    Explaination: The oc create user command is used to create a new user in OpenShift

    2. What’s the difference between ClusterRoles and Roles?

    • ClusterRoles are worker-node specific
    • Roles are tied to a worker node
    • ClusterRoles are namespace-scoped
    • Roles are namespace-scoped

    Correct answer:

    • Roles are namespace-scoped

    Explaination: ClusterRoles are cluster-wide and Roles are namespace-scoped.

    3. Security Context Constraints (SCC) allow you to control permissions for Pods

    • True
    • False

    Correct answer:

    • True

    Explaination: Along with the ability to use SELinux, SCC can also control permissions for Pods

    4. Kubernetes secrets allow you to

    • Store sensitive information
    • Create users
    • Delete users
    • Create configmaps

    Correct answer:

    • Store sensitive information

    Explaination: A Kubernetes Secret could be anything from an API key to a password to a username. Whatever you define as sensitive information


    PCAP-ERRORS AND EXCEPTIONS

    1. When does Python throw a ValueError?

    • for errors related to variables in our code
    • for wrong values passed in operations and functions
    • for wrong data types passed in operations and functions

    Correct answer:

    • for wrong values passed in operations and functions

    2. We can build specific exceptions for certain errors.

    • True
    • False

    Correct answer:

    • True

    3. What is the output of the following python code?

    • 5Sally
    • 9
    • Error
    • 5+Sally

    Correct answer:

    • 5Sally

    Code: x = 5 y = "Sally" print(str(x) + y)

    4. What may happen if our Python program does not handle errors?

    • The console returns errors
    • Both of the above
    • None of the above
    • Our program stops running and errors appear in the console

    Correct answer:

    • Both of the above

    5. What is the order of the try/except code blocks?

    • try/except codeblocks are executed one after the other
    • the try codeblock only gets executed if the except codeblock runs without errors
    • the except codeblock only gets executed if the try codeblock fails

    Correct answer:

    • the except codeblock only gets executed if the try codeblock fails

    6. How many exceptions branches may get executed during errors?

    • As many as our exception branches
    • Depends on how many different types of errors we have
    • At most one

    Correct answer:

    • At most one

    7. When does Python throw a TypeError?

    • for errors related to the extension of our python files
    • for wrong data types passed in operations and functions
    • for wrong string and numeric data types

    Correct answer:

    • for wrong data types passed in operations and functions

    8. What mechanisms does Python provide to deal with errors?

    • Built-in error functions
    • Built-in error methods
    • Exception raising
    • The special keywords 'try', 'exception'
    • The special variables try, 'exception'

    Correct answer:

    • Exception raising
    • The special keywords 'try', 'exception'

    9. What is the error thrown by the following code snippet?

    • ValueError
    • IndexError
    • TypeError
    • ZeroDivisionError

    Correct answer:

    • ZeroDivisionError

    Code:

    3 // 0 == 3 % 3

    10. What is the error thrown by the following code snippet?

    • No error
    • ValueError
    • TypeError
    • Index error

    Correct answer:

    • Index error

    Code:

    list1 = [1, 2, 3, 4] list1[4]

    11. What is the output of the following code block?

    • zero error
    • zero error other error
    • index error
    • other error

    Correct answer:

    • zero error

    Code: try: print("my_string"[1/0]) except IndexError: print("index error") except ZeroDivisionError: print("zero error") except: print("other error")

    12. Which of the following code snippet would raise an unhandled exception?

    • C
    • A
    • B

    Correct answer:

    • C

    Code: A.
    try: x = y + 1 except NameError: print("y is not defined")

    B. try: x = 'seasalt'[7] except IndexError: print("No character found in that index")

    C. try: x = 'y' + 1 except ValueError: print("y is not a number value")


    Python Exception Handling

    1. Which of the following code snippet would raise an unhandled exception?

    • B
    • A
    • C

    Correct answer:

    • C

    Code: A.
    try: x = y + 1 except NameError: print("y is not defined") x = y + 1

    B.
    try: x = 'seasalt'[7] except IndexError: print("No character found in that index")

    C. try: x = 'y' + 1 except ValueError: print("y is not a number value")

    2. When does the unnamed exception run?

    • When there is no dedicated named exception
    • After all other named exceptions
    • When it is the only exception branch

    Correct answer:

    • When there is no dedicated named exception
    • When it is the only exception branch

    3. Which of the following code lines is the correct one if we want to break out of the while loop?

    • if i == 4
    • else
    • except IndexError
    • except ValueError

    Correct answer:

    • except IndexError

    Code: flowers = ['roses', 'daisies', 'dahlias', 'camellias'] i = 0 while True: try: print(flowers[i]) i += 1 ... : break

    4. What happens when an exception branch is executed?

    • None of the above
    • Next exception branches shall run if they are related to the error
    • Previous branches shall run if they are related to the error
    • No other branch after or before that is executed

    Correct answer:

    • No other branch after or before that is executed

    PCAP-Hierarchy of Exceptions

    1. When can we use the raise keyword?

    • Inside the try block together with a named exception
    • Inside any try/except block
    • Inside the except block, but unnamed
    • Inside the try or except block with a named exception

    Correct answer:

    • Inside the try block together with a named exception
    • Inside the except block, but unnamed

    2. What is the output of the following code snippet? try:

    • We have a problem!
    • Zero won't work!
    • Zero won't work! We have a problem!

    Correct answer:

    • Zero won't work!

    Code: try: z = 3 // 0 except ZeroDivisionError: print("Zero won't work!") except ArithmeticError: print("We have a problem!")

    3. ZeroDivisionError is a special case of:

    • ValueError
    • ArithmeticError
    • TypeError
    • Exception

    Correct answer:

    • ArithmeticError
    • Exception

    4. What are the abstract exceptions?

    • Exceptions that we call without a specific name
    • General exceptions that they include other exceptions
    • Exception functions that take no arguments

    Correct answer:

    • General exceptions that they include other exceptions

    5. Why shouldn't we put more general exceptions before specific ones?

    • Because we risk having both general and specific exceptions raised
    • Because the tree of exceptions dictate us to do so
    • Because the specific exceptions would never execute and become useless

    Correct answer:

    • Because the specific exceptions would never execute and become useless

    6. What is common between AssertionError and ArithmeticError?

    • Both options
    • None of the options
    • They both stem from Exception
    • They both have more specific error cases

    Correct answer:

    • They both stem from Exception

    Explaination: The statement "They both have more specific error classes" is incorrect. While ArithmeticError does have more specific error classes that inherit from it (e.g., ZeroDivisionError, OverflowError), AssertionError does not have any more specific error classes.

    7. In the following snippet, which exception could replace the existing one? try:

    • ValueError
    • RuntimeError
    • BaseException

    Correct answer:

    • BaseException

    Code: try: y = 5 / 0 except ZeroDivisionError: print("Can't divide with zero.")

    8. What are the specific exceptions included in the LookupError?

    • TypeError
    • KeyError
    • ValueError
    • IndexError

    Correct answer:

    • KeyError
    • IndexError

    9. Which of the below code snippets is correct?

    • A
    • B
    • C

    Correct answer:

    • C

    Code: A. a = input("Enter a number: ") try: float(a) / 0 except Exception: print("Hmm an error occurred.") except TypeError, ZeroDivisionError: print("Please enter valid numbers, besides 0.")

    B.
    a = input("Enter a number: ") try: float(a) / 0 except TypeError, ZeroDivisionError: print("Please enter valid numbers, besides 0.")

    C.
    a = input("Enter a number: ") try: float(a) / 0 except (TypeError, ZeroDivisionError): print("Please enter valid numbers, besides zero.")


    GCP Compute

    1. VM in GCP can run ______?

    • Only public images
    • Only private images
    • Both public and private images
    • Custom images built by organization

    Correct answer:

    • Both public and private images

    2. Default time on all GCP VM is ?

    • GMT
    • UTC
    • Synced with the region your VM is created
    • PST

    Correct answer:

    • UTC

    Explaination: Regardless of the region where you create your VM instance, the default time for your VM instance is Coordinated Universal Time (UTC).

    3. GCP compute instance billing is done ______ ?

    • Monthly
    • Hourly
    • Based on mins
    • Based on seconds

    Correct answer:

    • Based on seconds

    Explaination: Google bills in second-level increments. You pay only for the compute time that you use.

    4. Your organization wants to test a open source database. Can we setup this open soure database on GCP compute?

    • YES
    • NO

    Correct answer:

    • YES

    Explaination: We can setup the database on compute but its not a scalable solution

    5. _______ node is a physical Compute Engine server that is dedicated to hosting only your project's VM instances

    • Solo tenant
    • Multi tenant

    Correct answer:

    • Solo tenant

    GCP Big Data

    1. Big Query pricing is based on ?

    • Number of query you run
    • Amount of data scanned during the query
    • Amount of data stored ?
    • Number of people in the organization

    Correct answer:

    • Amount of data scanned during the query

    2. A client of yours has data in AWS and want to connect to this data from GCP cloud. Such a connection is possible between two clouds ?

    • Yes
    • No

    Correct answer:

    • Yes

    3. Which tool is best to find insights and visualize of the data stored in Big Query?

    • Vertex AI
    • Looker
    • GCP monitoring
    • Big Query Dashboards

    Correct answer:

    • Looker

    4. 4 Vs of Big Data are?

    • Volume, velocity, variety and veracity
    • Velocity, volume, visibility, veracity
    • Veracity, variety, value, volume

    Correct answer:

    • Volume, velocity, variety and veracity

    GCP Compute

    1. Default time on all GCP VM is ?

    • GMT
    • UTC
    • Synced with the region your VM is created
    • PST

    Correct answer:

    • UTC

    Explaination: Regardless of the region where you create your VM instance, the default time for your VM instance is Coordinated Universal Time (UTC).

    2. Your organization wants to test an open source database. Can we setup this open source database on GCP compute?

    • Yes
    • No

    Correct answer:

    • Yes

    Explaination: We can setup the database on compute but its not a scalable solution

    3. GCP compute instance billing is done ______ ?

    • Monthly
    • Hourly
    • Based on mins
    • Based on seconds

    Correct answer:

    • Based on seconds

    Explaination: Google bills in second-level increments. You pay only for the compute time that you use.

    4. VM in GCP can run ______?

    • Only public images
    • Only private images
    • Both public and private images
    • Custom images built by organization

    Correct answer:

    • Both public and private images

    5. _______ node is a physical Compute Engine server that is dedicated to hosting only your project's VM instances

    • Solo tenant
    • Multi tenant

    Correct answer:

    • Solo tenant

    GCP Database

    1. You have been tasked with selecting a database for storing key and value pairs for your application. What kind of DB suits best?

    • SQL
    • NoSQL
    • Both SQL and NoSQL
    • Inmemory DB

    Correct answer:

    • NoSQL

    2. When using Cloud SQL in GCP , Data Replication can only be done within the region and can’t be done outside the region.

    • True
    • False

    Correct answer:

    • False

    Explaination: Database replication can be done outside the region

    3. AlloyDB is a fully managed ______?

    • SQL server
    • Postgres SQL server
    • MysQL server
    • Maria DB

    Correct answer:

    • Postgres SQL server

    GCP Final Quiz

    1. Which GCP services can be used for flat- structured object storage?

    • Cloud Firestore
    • Cloud SQL
    • Cloud Storage

    Correct answer:

    • Cloud Storage

    2. In Cloud Storage, which storage class is ideal for files you access rarely, say, once every five years?

    • Standard
    • Nearline
    • Coldline
    • Archive

    Correct answer:

    • Archive

    3. How many zones are present in a GCP?

    • 1
    • 2
    • 3
    • 4

    Correct answer:

    • 3

    4. What is a managed instance group?

    • Managed instance groups are expensive compared to unmanaged instance groups
    • Managed Instance group can be created using an instance template to create identical instances
    • Managed instance group is a GKE concept that autopilots the nodes
    • Managed instance group is a set of computing engines that can be easily managed

    Correct answer:

    • Managed instance group is a set of computing engines that can be easily managed

    5. We need a NoSQL database to be used for client-side web and mobile apps. Which DB would best suit the use case?

    • Cloud Firestore
    • Cloud Bigtable
    • Cloud Memorystore
    • Firebase Realtime Database

    Correct answer:

    • Cloud Firestore

    6. Which of the following GCP services can be used to securely connect compute instance in GCP to on-premise database service?

    • Cloud VPC
    • Cloud VPN
    • Cloud Interconnect
    • VPC Network Peering

    Correct answer:

    • Cloud Interconnect

    7. What would be the best way to connect to a GCP compute instance?

    • Set up a bastion host; then use this to log in to compute instance
    • Connect via NAT Gateway
    • Connect via serial console
    • Connect via your service account

    Correct answer:

    • Connect via serial console

    8. What type of firewall rule(s) does Google Cloud's networking support?

    • deny
    • allow
    • allow and deny
    • allow, deny, and logical route

    Correct answer:

    • allow and deny

    9. GKE is suitable for ________.

    • Monolith service
    • Microservice design

    Correct answer:

    • Microservice design

    10. A pharma company wants to ensure that its users are notified in real time when its packages are delivered to pharmacies. Which Google Cloud service would you recommend for this?

    • Cloud Pub/Sub
    • Cloud IoT
    • Cloud DataFlow
    • Cloud Firestore

    Correct answer:

    • Cloud Pub/Sub

    11. Which of the following statements is true for “application load testing"?

    • Load testing should be done to sustain 5x the expected traffic to the application.
    • Load testing is to verify if your application and DB connections are working.
    • Load testing can’t really help you determine the scalability of your system.

    Correct answer:

    • Load testing should be done to sustain 5x the expected traffic to the application.

    12. What is data warehouse service in GCP?

    • Cloud Spanner
    • BigQuery
    • Cloud Storage
    • Bigtable

    Correct answer:

    • BigQuery

    13. Your organization is estimating the GCP expenditure for the upcoming quarter. What should they do to control costs?

    • Cloud cost can be a capital expenditure; hence, assign 2x the budget used for the data center.
    • Audit the cost for the previous year and set that as an estimate.
    • Review cloud resource costs frequently because costs depend on usage.
    • Assess and audit organic growth in cloud cost, compare it with expected cloud utilization based on an upcoming project, and share the estimate.

    Correct answer:

    • Assess and audit organic growth in cloud cost, compare it with expected cloud utilization based on an upcoming project, and share the estimate.

    14. What is the biggest factor to consider when building an application for business continuity?

    • Meantime for recovery in case of disaster recovery
    • Latency of the application for end users
    • Cost of the region/zone
    • Business revenue generated from application

    Correct answer:

    • Meantime for recovery in case of disaster recovery

    15. When granting permissions to GCP, what principle should we follow?

    • Basic view access to all resources and content
    • Least access privilege; provide only the required access
    • Share Editor access
    • Replicate team member access directly

    Correct answer:

    • Least access privilege; provide only the required access

    16. What factors must be considered when choosing a region?

    • Region-specific restrictions
    • Where will the developer team work from?
    • Latency requirements of your app
    • Time to deploy changes to your application

    Correct answer:

    • Region-specific restrictions
    • Latency requirements of your app

    17. Your organization decides to move to GCP cloud. How should they start adopting the transformation steps?

    • Adopt changes manually with automation
    • Adopt changes programmatically
    • Adopt changes for applications when problems arise

    Correct answer:

    • Adopt changes programmatically

    18. Our pharmaceutical company wants to observe the behavior of users placing orders and design its application to make it more user-friendly. What might have prompted the company to consider this change?

    • Users/Customers expecting discounts and waiting for orders to be placed
    • Customers expecting a more personalized experience when using the app
    • Company wants to deploy changes immediately
    • Company wants insights on its spending

    Correct answer:

    • Customers expecting a more personalized experience when using the app

    19. You have a billing application that runs only during the month end. This application has a very high SLA, and a failure will delay the commission paid out to sales employees. Which deployment setup would be best for such a use case?

    • Deploy the application on compute engine and choose preemptible instances
    • Develop the application on compute engine with default settings
    • Reserve a compute engine for 3 years and use it to run the billing application
    • Run this application on-premises

    Correct answer:

    • Deploy the application on compute engine and choose preemptible instances

    20. Which databases does Cloud SQL currently support?

    • MySQL, PostgreSQL, SQL Server
    • OracleDB, PostgreSQL, MySQL
    • MariaDB, SQL Server, MySQL
    • MySQL, MongoDB, SQL Server

    Correct answer:

    • MySQL, PostgreSQL, SQL Server

    21. What would the DevOps philosophy recommend to measure first in the modern cloud design?

    • Customer satisfaction
    • Speed of cloud adoption
    • Reliability and health of our production systems
    • Disaster recovery setup

    Correct answer:

    • Reliability and health of our production systems

    30-130-metrics-quiz

    1. How many labels does the following time series have? http_errors_total{instance="1.1.1.1:80", job="api", code="400", endpoint="/user", method="post"} 55234

    • 1
    • 2
    • 3
    • 4
    • 5

    Correct answer:

    • 5

    Explaination: The 5 labels are instance, job, code, endpoint, method

    2. What metric should be used to report the amount of time a process has been running?

    • counter
    • gauge
    • histogram
    • summary

    Correct answer:

    • counter

    Explaination: For this a counter metric would be used as it would count the number of seconds a process has been running for. The uptime of a process can never go down, so a gauge metric shouldn’t be used.

    3. Which of these is not a valid metric?

    • 404_error_count
    • net_conntrack_listener_conn_closed_total
    • http_errors_total
    • node_netstat_Icmp_InErrors

    Correct answer:

    • 404_error_count

    Explaination: Metric names cannot start with a number.

    4. For the metric http_requests_total{path=”/auth”, instance=”node1”, job=”api”} 7782 ; What is the metric name?

    • node1
    • http_requests_total
    • path=”auth”
    • api
    • 7782

    Correct answer:

    • http_requests_total

    5. What are the 4 types of prometheus metrics?

    • counter, float, histogram, summary
    • incrementer, gauge, histogram, summary
    • counter, spatial, linear, summary
    • counter, gauge, histogram, summary

    Correct answer:

    • counter, gauge, histogram, summary

    6. What metric should be used to report the current memory utilization?

    • counter
    • gauge
    • histogram
    • summary

    Correct answer:

    • gauge

    Explaination: Since memory utilization can go up and down, we want to use a gauge metric instead of a counter.

    7. How many total unique time series are there in this output?

    • 9
    • 3
    • 8
    • 5

    Correct answer:

    • 9

    Code: node_arp_entries{instance="node1" job="node"} 200 node_arp_entries{instance="node2" job="node"} 150

    node_cpu_seconds_total{cpu="0", instance="node"1", mode="iowait"} node_cpu_seconds_total{cpu="1", instance="node"1", mode="iowait"} node_cpu_seconds_total{cpu="0", instance="node"1", mode="idle"} node_cpu_seconds_total{cpu="1", instance="node"1", mode="idle"} node_cpu_seconds_total{cpu="1", instance="node"2", mode="idle"}

    node_memory_Active_bytes{instance="node1" job="node"} 419124 node_memory_Active_bytes{instance="node2" job="node"} 55589

    Explaination: Each unique combination of metrics & labels is a separate time series. There are 9 separate instances of that

    8. What are the two labels every metric is assigned by default?

    • node, instance
    • target, job
    • node, job
    • instance, job

    Correct answer:

    • instance, job

    9. What are the two attributes provided by a metric?

    • Category, Detail
    • Type, Detail
    • Help, Type
    • Summary, Type
    • Identity, Help

    Correct answer:

    • Help, Type

    Explaination: HELP - Description of what the metric is TYPE - Specific type of prometheus metric(counter, gauge, histogram, summary)

    10. A web app is being built that allows users to upload pictures, management would like to be able to track the size of uploaded pictures and report back the number of photos that were less than 10Mb, 50Mb, 100MB, 500MB, and 1Gb. What metric would be best for this?

    • counter
    • gauge
    • histogram
    • summary

    Correct answer:

    • histogram

    Explaination: Histograms should be used to calculate how long or how big something is and allows you to group observations into configurable bucket sizes


    PCA mock 1

    1. What are the 3 components of the prometheus server?

    • influxdb, api gateway, retrieval node
    • retrieval node, tsdb, http server
    • retrieval node, alerting, push gateway
    • exporters, tsdb, http server

    Correct answer:

    • retrieval node, tsdb, http server

    Explaination: The 3 main components of the Prometheus instance or retrieval node tsdb, and the HTTP server. The retrieval node is responsible for scraping targets and collecting metrics. After the metrics are scraped, they will be stored in a time series database. To retrieve scraped metrics a query can be sent to the HTTP server.

    2. The metric http_errors_total has 3 labels, path, method, error. Which of the following queries will give the total number of errors for a path of /auth, method of POST, and error code of 401?

    • http_errors_total
    • http_errors_total{path="/auth",method="POST",code="401"}
    • http_errors_total{path="/auth",method="POST"}
    • http_errors_total{path="/auth",method="PUT",code="401"}

    Correct answer:

    • http_errors_total{path="/auth",method="POST",code="401"}

    3. Which component of the Prometheus architecture should be used to collect metrics of short-lived jobs?

    • service discovery
    • exporters
    • push gateway
    • alertmanager

    Correct answer:

    • push gateway

    Explaination: Since Prometheus follows a pull-based model, this makes gathering metrics from short-lived jobs difficult. The push gateway allows short-lived jobs to push metrics to the push gateway, and the Prometheus server can scrape the push gateway.

    4. What is the name of the cli utility that comes with Prometheus?

    • prom-validator
    • prometheus-cli
    • prom-cli
    • promtool

    Correct answer:

    • promtool

    Explaination: The cli utility that ships with Prometheus is called promtool.

    5. What are the 3 components of observability?

    • logging, metrics, traces
    • logging, metrics, alerting
    • traces, exporters, instrumentation
    • metrics, client libraries, traces

    Correct answer:

    • logging, metrics, traces

    6. What metric should be used to track the uptime of a server?

    • counter
    • gauge
    • histogram
    • summary

    Correct answer:

    • counter

    Explaination: For this, a counter metric would be used as it would count the number of seconds a server has been running for. The uptime of a server can never go down, so a gauge metric shouldn’t be used.

    7. What type of metric should be used for measuring internal temperature of a server?

    • counter
    • gauge
    • histogram
    • summary

    Correct answer:

    • gauge

    Explaination: Since temperature readings can go up or down, a gauge metric should be used in this case.

    8. A metric to track requests to an api http_requests_total is created. Which of the following would not be a good choice for a label?

    • path
    • status code
    • email
    • method

    Correct answer:

    • email

    Explaination: Email is a poor choice for a label as there will be a large number of different emails for an application and this will lead to high cardinality

    9. Which of the following is not a valid way to reload Prometheus configuration?

    • restart prometheus server(systemctl restart prometheus)
    • promtool config reload
    • send a POST request to /-/reload with the –web.enable-lifecycle flag
    • send a SIGHUP signal to the prometheus process

    Correct answer:

    • promtool config reload

    Explaination: There are 3 ways to reload Prometheus configurations

    1. Restart prometheus
    2. send a SIGUP signal to the prometheus process
    3. SEND a POST/PUT request to /-/reload with the –web.enable-lifecycle flag

    10. Which query below will give the active bytes on instance 10.1.1.1:9100 45m ago?

    • node_memory_Active_bytes offset 45m
    • node_memory_Active_bytes{instance="10.1.1.1:9100"} offset 45m
    • node_memory_Active_bytes{instance="10.1.1.1:9100"}[45]
    • node_memory_Active_bytes{instance="10.1.1.1:9100"} @45m

    Correct answer:

    • node_memory_Active_bytes{instance="10.1.1.1:9100"} offset 45m

    Explaination: To get the value of a metric 45 minutes ago, use the offset modifier and specify "offset 45m".

    11. Which query below will get all time series for metric node_disk_read_bytes_total for job=web, and job=node?

    • node_disk_read_bytes_total{job=~"web|node"}
    • node_disk_read_bytes_total{job="web|node"}
    • node_disk_read_bytes_total{job=~"web + node"}
    • node_disk_read_bytes_total{job="web", job="node"}

    Correct answer:

    • node_disk_read_bytes_total{job=~"web|node"}

    Explaination: To get all time series for both jobs node, and web, we will need to use a regular expression matcher =~. The regular expression to get both of those jobs is web|node`.

    12. Which query will give sum of all filesystems on the machine? The metric node_filesystem_size_bytes will list out all of the filesystems and their total size.

    • sum(node_filesystem_size_bytes{instance="192.168.1.168:9100"})
    • node_filesystem_size_bytes{instance="192.168.1.168:9100"} + node_filesystem_size_bytes
    • node_filesystem_size_bites(sum)
    • count(node_filesystem_size_bytes{instance="192.168.1.168:9100"})

    Correct answer:

    • sum(node_filesystem_size_bytes{instance="192.168.1.168:9100"})

    Code: node_filesystem_size_bytes{device="/dev/sda2", fstype="vfat", instance="192.168.1.168:9100", mountpoint="/boot/efi"} 536834048 node_filesystem_size_bytes{device="/dev/sda3", fstype="ext4", instance="192.168.1.168:9100", mountpoint="/"} 13268975616 node_filesystem_size_bytes{device="tmpfs", fstype="tmpfs", instance="192.168.1.168:9100", mountpoint="/run"} 727924736 node_filesystem_size_bytes{device="tmpfs", fstype="tmpfs", instance="192.168.1.168:9100", mountpoint="/run/lock"} 5242880 node_filesystem_size_bytes{device="tmpfs", fstype="tmpfs", instance="192.168.1.168:9100", mountpoint="/run/snapd/ns"} 727924736 node_filesystem_size_bytes{device="tmpfs", fstype="tmpfs", instance="192.168.1.168:9100", mountpoint="/run/user/1000"} 727920640

    Explaination: The sum aggregation operator will give the sum of all of the filesystems

    13. What method does Prometheus use to collect metrics from targets?

    • push
    • batch pub
    • pull
    • streams

    Correct answer:

    • pull

    Explaination: Prometheus follows a pull-based model. The prometheus.yml file will have a list of all targets Prometheus will need to scrape, which involves sending an HTTP request to the target.

    14. Which query will return all time series for the metric node_network_transmit_drop_total this is greater than 20 and less than 100?

    • node_network_transmit_drop_total > 20 and < 100
    • node_network_transmit_drop_total > 20 or node_network_transmit_drop_total < 100
    • node_network_transmit_drop_total > 20 and node_network_transmit_drop_total < 100
    • node_network_transmit_drop_total > 20 or < 100

    Correct answer:

    • node_network_transmit_drop_total > 20 and node_network_transmit_drop_total < 100

    Explaination: To get all-time series greater than 20 and less than 10, comparison operators will need to be used >20, <100. Both operators can be combined with the and operator.

    15. Which query will return targets who have more than 50 arp entries?

    • node_arp_entries{job="node"} < 50
    • node_arp_entries{job="node"} > 50
    • node_arp_entries{job="node"} = 50
    • node_arp_entries{job="node" >50}

    Correct answer:

    • node_arp_entries{job="node"} > 50

    Explaination: To return all-time series greater than a specific value(50 in this case), use a comparison operator to find instances with arp entries > 50.

    16. Which query below will return a range vector?

    • node_cpu_seconds_total{cpu="0"}
    • node_boot_time_seconds[5m]
    • http_upload_bytes @1670487164
    • process_virtual_memory_bytes offset 2h

    Correct answer:

    • node_boot_time_seconds[5m]

    Explaination: The range vector selector [5m] will return all values for a metric over the past 5 minutes, so it returns a range vector.

    17. Regarding histogram and summary metrics, which of the following are true?

    • histogram is calculated client side and summary is calculated server side
    • histogram is calculated client side and summary is calculated client side
    • histogram is calculated server side and summary is calculated client side
    • histogram is calculated server side and summary is calculated server side

    Correct answer:

    • histogram is calculated server side and summary is calculated client side

    Explaination: For histograms, quantiles must be calculated server side, thus they are less taxing on client libraries. whereas summary metrics are the opposite, as everything is calculated client side.

    18. What are the different states a Prometheus alert can be in?

    • inactive, triggered, complete
    • ok, pending, firing
    • silenced, firing, triggered
    • inactive, pending, firing

    Correct answer:

    • inactive, pending, firing

    Explaination: Alerts can have 3 states:

    1. inactive - Alert expression has not returned any results
    2. pending - the state of an alert that has been active for less than the configured threshold duration
    3. firing - the state of an alert that has been active for longer than the configured threshold duration

    19. Which of the following would make for a poor SLI?

    • high disk utilization
    • availability
    • error rate
    • Latency

    Correct answer:

    • high disk utilization

    Explaination: For useful SLIs, you want to find metrics that accurately measure a user’s experience. So things like high CPU, memory, and disk utilization would make for poor SLIs, as a user may not experience any degradation of service during these events.

    20. Which query below will give the 99% quantile of the metric http_requests_total?

    • histogram_quantile(0.99, http_requests_total_bucket)
    • http_requests_total(quantile=”0.99”}
    • http_requests_total < 99%
    • quantile(http_requests_total, 0.99)

    Correct answer:

    • histogram_quantile(0.99, http_requests_total_bucket)

    Explaination: For histogram metrics, to calculate a quantile use the histogram_quantile function. The function takes two arguments, the desired percentile, and the histogram metric, make sure to pass in the _bucket sub metric.

    21. What is the purpose of Prometheus scrape_interval?

    • defines what targets to scrape
    • Defines how long to wait for a scrape before timing out
    • Defines how long Prometheus waits before clearing out the TSDB
    • Defines how frequently to scrape a target

    Correct answer:

    • Defines how frequently to scrape a target

    Explaination: scrape_interval configs determine how often to scrape a target. If scrape_interval is set to 30s then each target will get scraped every 30s.

    22. Management has decided to offer a file upload service where the SLO states that 97% of all upload should complete within 30s. A histogram metric is configured to track the upload time, which of the following bucket configurations is recommended for the desired slo?

    • 1, 5, 10, 25, 35, 50
    • 10, 25, 27, 30, 32, 35, 40, 50
    • 35, 45, 55, 65, 75, 100
    • 1, 3, 8, 10, 12, 15, 17

    Correct answer:

    • 10, 25, 27, 30, 32, 35, 40, 50

    Explaination: Since histogram quantiles are approximations, to find out if a slo has been met, make sure that a bucket is specified at the desired slo value.

    23. Which of the following statements are true regarding Alert labels and annotations?

    • Both Alert labels and annotations can be used for routing on Alertmanager
    • Both Alert labels and annotations are used purely for descriptive purposes
    • Alert labels can be used as metadata so alertmanager can match on them and performing routing policies, Annotations should be used for cosmetic descriptions of the alerts
    • Alert annotations can be used as metadata so alertmanager can match on them and performing routing policies, labels should be used for cosmetic description of the alerts

    Correct answer:

    • Alert labels can be used as metadata so alertmanager can match on them and performing routing policies, Annotations should be used for cosmetic descriptions of the alerts

    Code: route: receiver: staff group_by: ['severity'] group_wait: 30s group_interval: 5m repeat_interval: 12h routes: - matchers: job: kubernetes receiver: infra group_by: ['severity']

    Explaination: In the Alertmanager configs, under matchers and group_by, we can match on labels to determine who gets notified for which alerts.

    24. What type of database does Prometheus use?

    • Relational
    • NoSQL
    • Key-Value
    • Time Series
    • Graph

    Correct answer:

    • Time Series

    Explaination: Prometheus uses a time series database.

    25. What is this an example of? `Service provider guaranteed 99.999% uptime each month or else customer will be awarded $10k'

    • SLA
    • SLO
    • SLI
    • SLU

    Correct answer:

    • SLA

    Explaination: An SLA is a contract between a vendor and a user that guarantees a certain SLO and states the consequences for not meeting said SLA.

    26. What configuration will make it so Prometheus doesn’t scrape targets with a label of team: frontend?

    • Option A
    • Option B
    • Option C
    • Option D

    Correct answer:

    • Option A

    Code: Option A:

    relabel_configs:

    • source_labels: [team] regex: frontend action: drop

    Option B:

    relabel_configs:

    • source_labels: [frontend] regex: team action: drop

    Option C:

    metric_relabel_configs:

    • source_labels: [team] regex: frontend action: drop

    Option D:

    relabel_configs:

    • match: [team] regex: frontend action: drop

    Explaination: Option A is the correct answer. The relabel_configs is where you will define which targets Prometheus should scrape. To match on label team: frontend

    1. Set the source_labels to `team
    2. regex field should represent the value of the label `frontend
    3. since we don’t want to scrape the targets, specify action: drop

    27. Analayze the example alertmanager configs and determine when an alert with the following labels arrives on alertmanager, what receiver will it send the alert to team: backend and severity: critical

    • general-email
    • backend-email
    • backend
    • backend-pager
    • frontend-pager

    Correct answer:

    • backend-pager

    Code: route: receiver: general-email routes: - receiver: frontend-email matchers: - team: frontend routes: - matchers: severity: critical receiver: frontend-pager - receiver: backend-email matchers: - team: backend routes: - matchers: severity: critical receiver: backend-pager - receiver: auth-email matchers: - team: auth routes: - matchers: severity: critical receiver: auth-pager receiver: auth-pager

    Explaination: Since the alert has the label team: backend, it will match the second route. By default, it will send an alert to the backend-email receiver. However, there is a subroute. The subroute matches on a label of severity: critical. Since severity: critical has been set on the label, alertmanager will send it to the receiver backend-pager

    28. Analyze the example alertmanager configs and determine when an alert with the following labels arrives on alertmanager, what receiver will it send the alert to team: api and severity: critical?

    • general-email
    • backend-email
    • auth-email
    • backend-pager
    • frontend-pager

    Correct answer:

    • general-email

    Code: route: receiver: general-email routes: - receiver: frontend-email matchers: - team: frontend routes: - matchers: severity: critical receiver: frontend-pager - receiver: backend-email matchers: - team: backend routes: - matchers: severity: critical receiver: backend-pager - receiver: auth-email matchers: - team: auth routes: - matchers: severity: critical receiver: auth-pager receiver: auth-pager

    Explaination: The label team: api does not match with any of the parent routes, so it goes to the default route, which uses the general-email receiver

    29. The following PromQL expression is trying to divide the the node_filesystem_avail_bytes by node_filesystem_size_bytes , and node_filesystem_avail_bytes / node_filesystem_size_bytes. The PromQL expression does not return any results, fix the expression so that it successfully divides the two metric. This is what the two metrics look like before the division operation.

    • SLA
    • node_filesystem_avail_bytes / ignoring(class) node_filesystem_size_bytes
    • node_filesystem_avail_bytes / on(class) node_filesystem_size_bytes
    • node_filesystem_avail_bytes{class!=”SSD”} / on(class) node_filesystem_size_bytes

    Correct answer:

    • node_filesystem_avail_bytes / ignoring(class) node_filesystem_size_bytes

    Code: node_filesystem_avail_bytes{device="/dev/sda2", fstype="vfat", class=”SSD” instance="192.168.1.168:9100", job="test", mountpoint="/boot/efi"}

    node_filesystem_size_bytes{device="/dev/sda2", fstype="vfat", instance="192.168.1.168:9100", job="test", mountpoint="/boot/efi"}
    

    Explaination: The node_filesystem_avail_bytes metric has the following labels:

    • device

    • fstype

    • class

    • instance

    • job

    • mountpoint

      The node_filesystem_size_bytes has the following labels:

    • device

    • fstype

    • instance

    • job

    • mountpoint

      The node_filesystem_size_bytesis missing theclasslabel, so there will never be a match. Use theignoringkeyword and pass in theclass` label so Prometheus will ignore it.

    30. Which type of observability would be used to track a request/transaction as it traverses a system?

    • logs
    • traces
    • metric
    • events

    Correct answer:

    • traces

    Explaination: Traces allow you to follow operations as they traverse through various systems & services, allowing you to follow a request hop by hop through a system.

    31. Which component of the Prometheus architecture should be used to automatically discover all nodes in a Kubernetes cluster?

    • service discovery
    • push gateway
    • alertmanager
    • exporters

    Correct answer:

    • service discovery

    Explaination: Service Discovery allows Prometheus to automatically generate a list of targets to scrape. In highly dynamic environments where nodes/applications are continuously spun and shutdown, like in Kubernetes, Prometheus can automatically update the list of targets.

    32. Analyze the alertmanager configs below. For all the alerts that got generated, how many total notifications will be sent out.?

    • 1
    • 2
    • 3
    • 4
    • 5

    Correct answer:

    • 3

    Code: route: receiver: general-email group_by: [alertname] routes: - receiver: frontend-email group_by: [env] matchers: - team: frontend

    The following alerts get generated by Prometheus with the defined labels.

    alert1 team: frontend env: dev

    alert2 team: frontend env: dev

    alert3 team: frontend env: prod

    alert4 team: frontend env: prod

    alert5 team: frontend env: staging

    Explaination: In the configuration, the group_by configuration is setup to env, which means all alerts will be grouped by the env and a single notification gets sent out. There are 2 alerts with env=dev and another 2 alerts with env=prod and one alert with env=staging. So 3 notifications get generated

    33. What is the default path Prometheus will scrape to collect metrics?

    • /metrics
    • /swagger-stats/metrics
    • /prometheus
    • /stats

    Correct answer:

    • /metrics

    Explaination: The default endpoint Prometheus will scrape is /metrics however, this can be modified with metrics_path

    34. What is the Prometheus client library used for?

    • Instrumenting applications to generate prometheus metrics and to push metrics to the Push Gateway
    • Sending Alerts to Alertmanager
    • Used for Service discovery
    • Generate logs & traces

    Correct answer:

    • Instrumenting applications to generate prometheus metrics and to push metrics to the Push Gateway

    Explaination: Client libraries are to instrument applications so Prometheus can collect metrics from them. In addition, client libraries can also be used to push metrics to a Push Gateway.

    35. The metric http_errors_total{code=”404”} tracks the number of 404 errors a web server has seen. Which query returns what is the average rate of 404s a server has seen for the past 2 hours? Use a 2m sample range and a query interval of 1m

    • avg_over_time(rate(http_errors_total{code=”404”}[2h]))
    • avg_over_time(rate(http_errors_total{code=”404”}[2m])) [2h:1m]
    • avg_over_time(rate(http_errors_total{code=”404”}[2m]) [2h:1m])
    • avg_over_time(rate(http_errors_total{code=”404”}[2m]) [1m:2h])

    Correct answer:

    • avg_over_time(rate(http_errors_total{code=”404”}[2m]) [2h:1m])

    Explaination: Since the question is asking for the what is the average rate of 404 errors over the past 2 hours, rate function will need to be used: rate(http_errors_total{code=”404”}[2m])

    To get the average over the past 2 hours, use the avg_over_time function. The avg_over_time function requires a range vector to be passed in, a subquery will need to be performed on the rate to get the range vector that contains the rate of errors for the past 2 hours. Since we need the average for the past 2 hours, the first value in the subquery will be 2h and the second number is the query interval. Thus the final query looks like this:

    avg_over_time(rate(http_errors_total{code=”404”}[2m]) [2h:1m])

    36. Which of the following is not a valid time value to be used in a range selector?

    • 1h15m
    • 2y
    • 200ms
    • 4w
    • 2mo

    Correct answer:

    • 2mo

    37. Based off the metrics below, which query will return the same result as the query database_write_timeouts / ignoring(error) database_error_total

    • database_write_timeouts / group_left database_error_total
    • database_write_timeouts / on(instance, job, type) database_error_total
    • database_write_timeouts / merge(error) database_error_total
    • database_error_total ignoring(error) / database_write_timeouts

    Correct answer:

    • database_write_timeouts / on(instance, job, type) database_error_total

    Code: database_write_timeouts{instance="db1", job="db", error="212, type="mysql"} 12

    database_error_total{instance="db1", job="db", type="mysql"} 67

    Explaination: To perform division between two vectors, all labels must match for the division to occur; that is why the ignoring keyword is used to filter out the error label, which does not exist on the database_error_total metric. The opposite of the ignoring keyword is the on keyword, which tells Prometheus which labels to match. If we specify the on keyword and pass all labels except for the error label, it will have the same effect as doing ignoring(error)

    38. For a histogram metric, what are the different submetrics?

    • _count, _bucket
    • _bucket
    • _count, _bucket, _sum
    • _total, _sum, _bucket

    Correct answer:

    • _count, _bucket, _sum

    Explaination: Histogram metrics have 3 submetrics: count: total number of observations sum: sum of all observations bucket: number of observations for a specific bucket

    39. Add an annotation to the alert called description that will print out the message that looks like this Instance has low disk space on filesystem , current free space is at %

    • Option A
    • Option B
    • Option C
    • Option D

    Correct answer:

    • Option B

    Code: groups:

    • name: node rules:
      • alert: node_filesystem_free_percent expr: 100 * node_filesystem_free_bytes{job="node"} / node_filesystem_size_bytes{job="node"} < 10

    // Examples of the two metrics used in the alert can be seen below.

    node_filesystem_free_bytes{device="/dev/sda3", fstype="ext4", instance="node1", job="web", mountpoint="/home"}

    node_filesystem_size_bytes{device="/dev/sda3", fstype="ext4", instance="nodde1", job="web", mountpoint="/home"}

    Choose the correct answer: Option A: description: Instance << $Labels.instance >> has low disk space on filesystem << $Labels.mountpoint >>, current free space is at << .Value >>%

    Option B: description: Instance {{ .Labels.instance }} has low disk space on filesystem {{ .Labels.mountpoint }}, current free space is at {{ .Value }}%

    Option C: description: Instance {{ .Labels=instance }} has low disk space on filesystem {{ .Labels=mountpoint }}, current free space is at {{ .Value }}%

    Option D: description: Instance {{ .instance }} has low disk space on filesystem {{ .mountpoint }}, current free space is at {{ .Value }}%

    40. Add an annotation to the alert called description that will print out the message that looks like this Instance has low disk space on filesystem , current free space is at %

    • Option A
    • Option B
    • Option C
    • Option D

    Correct answer:

    • Option B

    Code: groups:

    • name: node rules:
      • alert: node_filesystem_free_percent expr: 100 * node_filesystem_free_bytes{job="node"} / node_filesystem_size_bytes{job="node"} < 10

    Examples of the two metrics used in the alert can be seen below

    node_filesystem_free_bytes{device="/dev/sda3", fstype="ext4", instance="node1", job="web", mountpoint="/home"}

    node_filesystem_size_bytes{device="/dev/sda3", fstype="ext4", instance="nodde1", job="web", mountpoint="/home"}

    Choose the correct option:

    Option A: description: Instance << $Labels.instance >> has low disk space on filesystem << $Labels.mountpoint >>, current free space is at << .Value >>%

    Option B: description: Instance {{ .Labels.instance }} has low disk space on filesystem {{ .Labels.mountpoint }}, current free space is at {{ .Value }}%

    Option C: description: Instance {{ .Labels=instance }} has low disk space on filesystem {{ .Labels=mountpoint }}, current free space is at {{ .Value }}%

    Option D: description: Instance {{ .instance }} has low disk space on filesystem {{ .mountpoint }}, current free space is at {{ .Value }}%

    Explaination: Using the go templating syntax, we can access instance labels with {{ .Labels.instance }} and the mountpoint can be accessed with {{ .Labels.mountpoint }} and the value can be accessed with {{ .Value}}

    41. An engineer forgot to address an alert, based off the alertmanager config below, how long will they need to wait to see the alert again?

    • 10s
    • 4h
    • 5m
    • 15s

    Correct answer:

    • 4h

    Code: route: receiver: pager group_by: [alertname] group_wait: 10s repeat_interval: 4h group_interval: 5m routes: - match: team: api receiver: api-pager - match: team: frontend receiver: frontend-pager

    Explaination: The repeat interval determines how long alertmanager will wait before sending another notification.

    42. You are writing your own exporter for a Redis database. Which of the following would be the correct name for a metric to represent used memory on the by the Redis instance?

    • used_mem_redis_bytes
    • redis_mem_used_kilobytes
    • redis_used_bytes_mem
    • redis_mem_used_bytes

    Correct answer:

    • redis_mem_used_bytes

    Explaination: When naming metrics, the first word should be the application/library, which in this case is redis. The name second part of the metric name should be the metric name. The last part of the name should be the unit which should be unprefixed, so that means we prefer bytes, seconds over kilobytes, and milliseconds.

    43. Which of the following components is responsible for collecting metrics from an instance and exposing them in a format Prometheus expects?

    • exporters
    • alertmanager
    • pushgateway
    • Grafana
    • TSDB

    Correct answer:

    • exporters

    44. The metric node_cpu_temp_celcius reports the current temperature of a nodes CPU in celsius. What query will return the average temperature across all CPUs on a per node basis? The query should return {instance="node1"} 23.5 //average temp across all CPUs on node1 {instance="node2"} 33.5 //average temp across all CPUs on node2

    • avg(node_cpu_temp_celsius)
    • avg on(instance) node_cpu_temp_celsius
    • avg by(instance) (node_cpu_temp_celsius)
    • avg_over_time(node_cpu_temp_celsius)

    Correct answer:

    • avg by(instance) (node_cpu_temp_celsius)

    Code: node_cpu_temp_celsius{instance="node1", cpu="0"} 28

    node_cpu_temp_celsius{instance="node1", cpu="1"} 19

    node_cpu_temp_celsius{instance="node2", cpu="0"} 36

    node_cpu_temp_celsius{instance="node2", cpu="1"} 31

    Explaination: The avg aggregator is used to find the average across multiple time series. To aggregate along each instance to get the average temp across all CPUs on a per-node basis, we will use the by clause and aggregate along the instance label.

    45. In the scrape configs for a pushgateway, what is the purpose of the honor_labels: true

    • Tells prometheus this is a pushgateway
    • Prometheus will drop all labels without this config
    • Allows metrics to specify the instance and job labels instead of pulling it from scrape_configs
    • Used to save disk space when a lot of labels are used

    Correct answer:

    • Allows metrics to specify the instance and job labels instead of pulling it from scrape_configs

    Code: scrape_configs:

    • job_name: pushgateway honor_labels: true static_configs:
      • targets: ["192.168.1.168:9091"]

    46. How can alertmanager prevent certain alerts from generating notification for a temporary period of time?

    • add a new route in alertmanager config and specify silence_period: config
    • Configuring a Silence
    • Configuring a AlertMute
    • Using inhibition rule

    Correct answer:

    • Configuring a Silence

    Explaination: Silences allow you to temporarily pause the generation of notifications for a specific alert(s)

    47. What does the following metric_relabel_config do?

    • renames the metric database_errors_total to database_failures_total
    • drops metric with the name `database_errors_total
    • merges the metrics database_errors_total and database_failures_total
    • tells prometheus to only scrape targets with the metric database_errors_total

    Correct answer:

    • renames the metric database_errors_total to database_failures_total

    Code: scrape_configs:

    • job_name: example metric_relabel_configs:
      • source_labels: [name] regex: database_errors_total action: replace target_label: name replacement: database_failures_total

    48. Where should alerting rules be defined?

    • prometheus configuration file
    • alertmanager configuration file
    • separate rules file
    • export configuration file

    Correct answer:

    • separate rules file

    Code: scrape_configs:

    • job_name: example metric_relabel_configs:
      • source_labels: [name] regex: database_errors_total action: replace target_label: name replacement: database_failures_total

    Explaination: Alerts and recording rules should be defined in a separate rules file. This file then needs to be referenced in the prometheus.yml file as per:

    prometheus.yml
    

    rule_files:

    • rules.yml

    49. What is the default web port of Prometheus?

    • 9090
    • 9001
    • 9100
    • 9003

    Correct answer:

    • 9090

    50. Which statement is true about the rate/irate functions?

    • rate() and irate() operate in the same exact way
    • rate() calculates rate by using the first two datapoints over an interval, irate() calculates the rate only between the last two datapoints in an interval
    • irate() calculates average rate over entire interval, rate() calculates the rate only between the last two datapoints in an interval
    • rate() calculates average rate over entire interval, irate() calculates the rate only between the last two datapoints in an interval

    Correct answer:

    • rate() calculates average rate over entire interval, irate() calculates the rate only between the last two datapoints in an interval

    51. What is the purpose of the for attribute in a Prometheus alert rule?

    • Determines which team team the alert is for
    • Determines how long a rule must be true before firing an alert
    • Tells alertmanager how long to wait before firing a notification
    • Specifies how frequently to fire the alert

    Correct answer:

    • Determines how long a rule must be true before firing an alert

    52. What does the following metric_relabel_config do?

    • Changes the datacenter label to location and prepends the value with dc-
    • removes the datacenter label
    • Drops all metrics that are not from DC-1
    • changes the value of the datacenter label to be prepended with dc-

    Correct answer:

    • Changes the datacenter label to location and prepends the value with dc-

    Code: scrape_configs:

    • job_name: example metric_relabel_configs:
      • source_labels: [datacenter] regex: (.*) action: replace target_label: location replacement: dc-$1

    Explaination: The source_labels specifies the labels to match, which in this case is datacenter. Since the action is replace the label name will be swapped out with the value in target_label, and the value will be swapped out with the replacement.

    53. Which of the following is not something that is tracked in a span within a trace?

    • start time
    • duration
    • complexity
    • parent-id

    Correct answer:

    • complexity

    54. What selector will match on time series whose mountpoint label doesn’t start with /run

    • node_filesystem_avail_bytes{mountpoint!~"/run"}
    • node_filesystem_avail_bytes{mountpoint!="/run.*"}
    • node_filesystem_avail_bytes{mountpoint!~"/run.*"}
    • node_filesystem_avail_bytes{mountpoint!~"/run.^**"}

    Correct answer:

    • node_filesystem_avail_bytes{mountpoint!~"/run.*"}

    Code: node_filesystem_avail_bytes{device="/dev/sda2", fstype="vfat", instance="node1", mountpoint="/boot/efi"}​ node_filesystem_avail_bytes{device="/dev/sda2", fstype="vfat", instance="node2", mountpoint="/boot/efi"}​ node_filesystem_avail_bytes{device="/dev/sda3", fstype="ext4", instance="node1", mountpoint="/"}​ node_filesystem_avail_bytes{device="/dev/sda3", fstype="ext4", instance="node2", mountpoint="/"}​ node_filesystem_avail_bytes{device="tmpfs", fstype="tmpfs", instance="node1", mountpoint="/run"}​ node_filesystem_avail_bytes{device="tmpfs", fstype="tmpfs", instance="node1", mountpoint="/run/lock"}​ node_filesystem_avail_bytes{device="tmpfs", fstype="tmpfs", instance="node1", mountpoint="/run/snapd/ns"}​ node_filesystem_avail_bytes{device="tmpfs", fstype="tmpfs", instance="node1", mountpoint="/run/user/1000"}​ node_filesystem_avail_bytes{device="tmpfs", fstype="tmpfs", instance="node2", mountpoint="/run"}​ node_filesystem_avail_bytes{device="tmpfs", fstype="tmpfs", instance="node2", mountpoint="/run/lock"}​ node_filesystem_avail_bytes{device="tmpfs", fstype="tmpfs", instance="node2", mountpoint="/run/snapd/ns"}​ node_filesystem_avail_bytes{device="tmpfs", fstype="tmpfs", instance="node2", mountpoint="/run/user/1000"}

    Explaination: To match on any mountpoint starting with /run a regular expression /run.* must be used. Since we want to not match on it use a negative regular expression matcher !~

    55. Which of the following is Prometheus’ built in dashboarding/visualization feature?

    • Go Templates
    • Grafana
    • client libraries
    • Console Templates

    Correct answer:

    • Console Templates

    Explaination: Console templates allow you to create custom dashboards to display metrics and graphs.

    56. Which cli command can be used to verify/validate prometheus configurations?

    • prom-util validate config
    • prom-cli check config
    • promtool check config
    • promtool validate config

    Correct answer:

    • promtool check config

    Explaination: promtool is the cli utility for performing config validation. The check config subcommands perform validation of the passed in the configuration

    57. What type of data should Prometheus monitor?

    • Events
    • numeric
    • traces
    • system logs

    Correct answer:

    • numeric

    58. What does the double underscore __ before a label name signify?

    • The label was set by a pushgateway
    • The label is a malformed label
    • The label was set by a client library
    • The label is a reserved label

    Correct answer:

    • The label is a reserved label

    59. What two labels are assigned to every metric by default?

    • target, job
    • target, group
    • instance, group
    • instance, job

    Correct answer:

    • instance, job

    60. Which of the following is not a valid method for reloading alertmanager configuration?

    • restart alertmanager process
    • send a SIGHUP signal to alertmanager process
    • HTTP post to /-/reload endpoint
    • hit the reload config button in alertmanager web-ui

    Correct answer:

    • hit the reload config button in alertmanager web-ui

    LPIC-hardware-settings

    1. A friend is visiting you and brings a portable USB hard drive to share some files with you. You have one SATA drive in your Linux machine. Which name will be given to your friend's portable USB hard drive in the /dev/ directory of your Linux machine?

    • /dev/sata2
    • /dev/sba
    • /dev/sdb
    • /dev/usb1

    Correct answer:

    • /dev/sdb

    Explaination: In Linux, USB drives are treated as SATA drives and follow the same naming conventions. Your initial drive is already identified as /dev/sda, so your friend's USB hard drive will be identified as /dev/sdb.

    2. You have added a new hard drive to a system. You know that the hard drive has no defects, but the system cannot boot. Where would you go to begin troubleshooting this problem?

    • The BIOS setup utility.
    • The manual for the hard drive.
    • The manufacturer's website.
    • An Internet forum.

    Correct answer:

    • The BIOS setup utility.

    Explaination: The BIOS setup utility is the correct place to begin troubleshooting this hardware problem. It could be that the boot device order is incorrect.

    3. You need to know which hardware devices are inside of a Linux system, but you cannot open the system's case. How would you get Linux to produce a list of hardware connected to the PCI bus?

    • cat /proc/hardware
    • ls /dev/
    • lspci
    • modprobe

    Correct answer:

    • lspci

    Explaination: lspci gives information about hardware that is connected to the system's PCI bus.

    4. Which command will list kernel modules in use by hardware?

    • lspci -k
    • lspci -m
    • lspci --modules
    • lspci -l

    Correct answer:

    • lspci -k

    Explaination: The -k option for lspci will list kernel modules in use by hardware.

    5. Which file would you search to determine the CPU features on a Linux machine?

    • /proc/cpuinfo
    • /dev/cpuinfo
    • /proc/cpu
    • /proc/hardware/cpuinfo

    Correct answer:

    • /proc/cpuinfo

    Explaination: Information on the CPU and its features can be found in the cpuinfo file inside the /proc virtual filesystem (/proc/cpuinfo).


    LPIC-boot

    1. You have compiled a custom kernel, and the filesystem type used by your Linux system's root filesystem is compiled as a module. What would you need to include along with the kernel to make sure your system loads the root filesystem correctly?

    • initramfs
    • EFI applications
    • A copy of /etc/modules.conf.d/
    • bootstrap

    Correct answer:

    • initramfs

    Explaination: An initial RAM filesystem (initramfs) should be included if the root filesystem is compiled as a module.

    2. Which option would you pass to journalctl to change the directory it uses to search for log files?

    • --log-directory=
    • -D
    • -d
    • --log-dir

    Correct answer:

    • -D

    Explaination: The -D option allows you to specify a different directory for log files other than the default directory. Example: journalctl -D /mnt/external/var/log/journal.

    3. On a system equipped with BIOS, what should be placed in the MBR of the first storage device in order to boot the system?

    • bootstrap
    • firmware
    • initrd
    • kernel

    Correct answer:

    • bootstrap

    Explaination: The bootstrap binary must be located in the MBR of the first storage device for a system equipped with BIOS to boot correctly.

    4. Which filesystem would you use for the ESP partition?

    • ext2
    • fat32
    • xfs
    • ntfs

    Correct answer:

    • fat32

    Explaination: EFI System Partitions (ESP) should use a FAT filesystem, like FAT12, FAT16, or FAT32.

    5. Which command would you use to view only the last ten lines of the initialization log?

    • dmesg --last
    • dmesg | tail
    • lastlog
    • dmesg -H

    Correct answer:

    • dmesg | tail

    Explaination: Directing the output of dmesg to the tail command will only show the last ten lines of the initialization log.


    LPIC-runlevels

    1. Given a theoretical file located at /etc/rc3.d/S45 ethernet, what would happen to any services listed in this file when the system enters runlevel 3?

    • They will stop.
    • They will start.
    • They will be suspended.
    • They will be restarted.

    Correct answer:

    • They will start.

    Explaination: The letter "S" at the beginning of the file name indicates that services listed in this file will be started.

    2. On SysV systems, which file contains the default init configuration?

    • /etc/init.d/defaults
    • /etc/defaults/inittab
    • /etc/inittab
    • /etc/conf.d/inittab

    Correct answer:

    • /etc/inittab

    Explaination: The default init configuration is stored in /etc/inittab on SysV systems.

    3. Which command would cause the system to shutdown 45 minutes from now?

    • shutdown 00:45
    • shutdown now+45
    • shutdown +45
    • shutdown +45M

    Correct answer:

    • shutdown +45

    Explaination: Specifying +45 after the shutdown command will cause the system to shutdown 45 minutes from the time the command is run.

    4. Using systemctl, how would you determine if a service named myservice.service is configured to start when the system boots?

    • systemctl status myservice.service
    • systemctl is-enabled myservice.service
    • systemctl is-active myservice.service
    • systemctl on-boot myservice.service

    Correct answer:

    • systemctl is-enabled myservice.service

    Explaination: The is-enabled option for systemctl will return "enabled" if a service is enabled to start at boot, or "disabled" if it is not.

    5. If you want to warn other users of a Linux system that the system is going down for maintenance, which command could you use to send a message to all logged-in users?

    • write
    • wall
    • warn
    • wipe

    Correct answer:

    • wall

    Explaination: The wall command is use to send messages to all users logged into a system.


    LPIC-disk-layout

    1. Where are the files for the GRUB bootloader stored?

    • /etc/grub/
    • /boot/
    • /boot/grub/
    • /grub/boot/

    Correct answer:

    • /boot/grub/

    Explaination: The files for the GRUB bootloader are stored in the /boot/grub/ directory.

    2. When a Linux system mounts the EFI partition, where is it usually mounted?

    • /boot/efi/
    • /boot/grub/efi/
    • /mnt/efi/
    • /efi/

    Correct answer:

    • /boot/efi/

    Explaination: Linux usually mounts the EFI partition at /boot/efi/.

    3. Which formula would give the size of a Logical Volume?

    • Size of physical extents divided by number of extents
    • Number of extents divided by size of physical extents
    • Number of extents multiplied by physical extent size
    • Disk sectors multiplied by number of extents

    Correct answer:

    • Number of extents multiplied by physical extent size

    Explaination: The size of a Logical Volume is equal to the number of physical extents multiplied by the total number of extents on the volume.

    4. In addition to swap partitions, Linux can make use of swap files. Where is the swap file typically located?

    • /mnt/swap
    • /swapfile
    • /mnt/swapfile
    • /swap

    Correct answer:

    • /swapfile

    Explaination: If used, a swap file is typically located at /swapfile on Linux systems.

    5. Volume Groups are divided into:

    • Extents
    • Sectors
    • Slices
    • Chunks

    Correct answer:

    • Extents

    Explaination: Volume groups are divided into extents.


    LPIC-boot-manager

    1. When using GRUB Legacy, how is the first partition of the first disk labeled?

    • (hd1,1)
    • (hd0,1)
    • (hd0,0)
    • (hd1,0)

    Correct answer:

    • (hd0,0)

    Explaination: GRUB Legacy begins counting from 0, so the first partition of the first drive would be labeled as (hd0,0).

    2. To change the menu entries for GRUB Legacy, which file would you edit?

    • /boot/grub/menu.lst
    • /etc/grub/grub.cfg
    • /etc/grub/menu.lst
    • /boot/grub/grub.cfg

    Correct answer:

    • /boot/grub/menu.lst

    Explaination: Menu entries for GRUB Legacy are stored in /boot/grub/menu.lst.

    3. When using GRUB 2, which menu entry parameter determines how long GRUB 2 will pause before booting the default menu entry?

    • GRUB_TIMEOUT=
    • GRUB_WAIT=
    • GRUB_PAUSE=
    • GRUB_TIMER=

    Correct answer:

    • GRUB_TIMEOUT=

    Explaination: The menu entry that controls how long GRUB 2 will pause before booting the default menu entry is GRUB_TIMEOUT=.

    4. GRUB 2 stores its configuration file at:

    • /etc/grub/grub.cfg
    • /etc/grub.d/
    • /boot/grub/grub.cfg
    • /boot/grub.d/

    Correct answer:

    • /etc/grub/grub.cfg

    Explaination: The default configuration file for GRUB 2 is /etc/grub/grub.cfg.

    5. If you update the configuration for GRUB 2, which command would you run to write that configuration to the correct directory for GRUB 2 to use the next time you boot the system?

    • grub-config -o /boot/grub/grub.cfg
    • grub-mkconfig -o /boot/grub/grub.cfg
    • grub-mkconfig -o /boot/grub/grub.conf
    • grub-config -o /boot/grub/grub.conf

    Correct answer:

    • grub-mkconfig -o /boot/grub/grub.cfg

    Explaination: After updating the configuration for GRUB 2, you must run grub-mkconfig -o /boot/grub/grub.cfg to make GRUB 2 use the changes on the next system boot.


    LPIC-shared-libraries

    1. The naming format for shared libraries is:

    • libraryname.so.versionnumber
    • libraryname.versionnumber.so
    • libraryname-versionnumber.so
    • libraryname-so.versionnumber

    Correct answer:

    • libraryname.so.versionnumber

    Explaination: The naming format for shared libraries is the library name . so suffix . version number. Example: libpthread.so.1.

    2. You have added a new shared library directory to your system, and you have written a custom configuration file including the full path to to the new shared library location. Which directory would you put the configuration file into?

    • /usr/share/
    • /etc/share
    • /etc/ld.so.conf.d/
    • /usr/ld.so.conf.d/

    Correct answer:

    • /etc/ld.so.conf.d/

    Explaination: Configuration files that define shared library paths go in the /etc/ld.so.conf.d/ directory.

    3. Static libraries have which file extension?

    • .lib
    • .a
    • .out
    • .aout

    Correct answer:

    • .a

    Explaination: Static libraries use the .a file extension.

    4. After adding a new shared library directory to your system, you copied a configuration file with its full path to the correct directory. Which command would you use to notify the system of the change?

    • ldd
    • ldconfig
    • libupdate
    • updatedb

    Correct answer:

    • ldconfig

    Explaination: When making changes to shared libraries on the system, you must run ldconfig to notify the system of the changes.

    5. Which command would you use to list the shared libraries used by the /usr/bin/systemctl program?

    • which /usr/bin/systemctl
    • lib /usr/bin/systemctl
    • ldd /usr/bin/systemctl
    • shared /usr/bin/systemctl

    Correct answer:

    • ldd /usr/bin/systemctl

    Explaination: The ldd command can be used to list all of the shared libraries used by a program.


    LPIC-debian-packages

    1. Which command would you use to install a .deb file located on your local Linux system?

    • dpkg -I
    • dpkg -i
    • dpkg install
    • dpkg -install

    Correct answer:

    • dpkg -i

    Explaination: To install a .deb file located on a local machine, you would you use the dpkg -i command. It is also possible to use dpkg --install (with two dashes).

    2. Which apt-cache command will provide information for a package?

    • apt-cache show
    • apt-cache info
    • apt-cache print
    • apt-cache search

    Correct answer:

    • apt-cache show

    Explaination: The apt-cache show command, followed by a package name, will provide information for a package.

    3. Which apt-file command would show the package that contains the file /usr/bin/systemctl?

    • apt-file search /usr/bin/systemctl
    • apt-file show /usr/bin/systemctl
    • apt-file provides /usr/bin/systemctl
    • apt-file query /usr/bin/systemctl

    Correct answer:

    • apt-file search /usr/bin/systemctl

    Explaination: You can use apt-file search followed by the full path to a file to show which package contains that file.

    4. Which parameter would you add to dpkg-query to show which package contains a particular file?

    • -s
    • -S
    • -l
    • -W

    Correct answer:

    • -S

    Explaination: Using the -S parameter with dpkg-query will show which package contains a particular file.

    5. On a Debian system, which command would remove a package and all of its configuration files?

    • dpkg -r
    • dpkg --remove
    • dkpg --erase
    • dpkg -P

    Correct answer:

    • dpkg -P

    Explaination: Running dpkg with the -P (purge) flag will remove a package and all of its configuration files.


    LPIC-rpm-packages

    1. Using DNF, how would you install the httpd package?

    • dnf install httpd
    • dnf -i httpd
    • dnf httpd
    • dnf provide httpd

    Correct answer:

    • dnf install httpd

    Explaination: When using DNF, the dnf install command, followed by a package name, will install that package. Example: dnf install httpd.

    2. Using YUM or DNF, which option would uninstall a package from the system, along with any packages that depend on that package?

    • remove
    • purge
    • uninstall
    • delete

    Correct answer:

    • remove

    Explaination: Using YUM or DNF, the remove option will uninstall a package from the system, along with all packages that depend on it. Example: dnf remove httpd.

    3. Which yum command will bring repository metadata to the most recent version?

    • yum update
    • yum metadata
    • yum upgrade
    • yum check-metadata

    Correct answer:

    • yum update

    Explaination: The yum update command will update repository metadata.

    4. Using zypper, how would you find out which package provides the file /usr/bin/systemctl?

    • zypper se /usr/bin/systemctl
    • zypper se --provides /usr/bin/systemctl
    • zypper --provides /usr/bin/systemctl
    • zypper se provides /usr/bin/systemctl

    Correct answer:

    • zypper se --provides /usr/bin/systemctl

    Explaination: When using zypper, the se (search) command, followed by --provides and the file path will show which package provides that file. Example: zypper se --provides /usr/bin/systemctl.

    5. Where are repository files stored for DNF and YUM?

    • /etc/repos.d/
    • /etc/yum.repos.d/
    • /etc/yum/repos/
    • /etc/yum/repos.d/

    Correct answer:

    • /etc/yum.repos.d/

    Explaination: Repository files (.repo) are stored in /etc/yum.repos.d/.


    LPIC-virtualization

    1. Intel VT-x and AMD-V are examples of _____ used to provide support for fully virtualized guests?

    • CPU extensions
    • paravirtualized drivers
    • hypervisors
    • virtual machines

    Correct answer:

    • CPU extensions

    Explaination: Intel VT-x and AMD-V are CPU extensions.

    2. Which type of virtualization requires the guest to be capable of running all instructions on virtual hardware?

    • full virtualization
    • paravirtualization
    • hybrid virtualization
    • bare metal

    Correct answer:

    • full virtualization

    Explaination: Fully virtualized machines must be able to run all instructions on the virtual hardware. They are not aware that they are running as virtual machines.

    3. Which program is used to start Linux virtual instances in a cloud environment?

    • upstart
    • kickstart
    • cloud-start
    • cloud-init

    Correct answer:

    • cloud-init

    Explaination: Linux virtual instances for the cloud can be started with cloud-init.

    4. KVM is a _____ hypervisor. Select all that apply.

    • Type-1
    • Type-2
    • Bare metal
    • Hybrid

    Correct answer:

    • Type-2
    • Type-1

    Explaination: Kernel Virtual Machine (KVM) is a Type-1 and Type-2 hypervisor.

    5. Which virtualization method provides the highest performance?

    • Full virtualization
    • Paravirtualization
    • VirtualBox
    • Virsh

    Correct answer:

    • Paravirtualization

    Explaination: Paravirtualization provides the best performance through the use of paravirtualized drivers for networking and storage.


    LPIC-command-line-1

    1. Before the apropos command will work on a new system, it may be necessary to run another command first. Which command would you run to make sure apropos has access to all of the information it needs?

    • apropos -update
    • updatedb
    • dbupdate
    • mandb

    Correct answer:

    • mandb

    Explaination: The mandb command must be run to update the database for apropos. Otherwise, apropos will not have any results to return.

    2. Which command is used to search the short description of man pages for keywords?

    • apropos
    • grep
    • find
    • cat

    Correct answer:

    • apropos

    Explaination: Each manual page has a short description available within it and apropos searches the descriptions for instances of keyword.

    3. If you are unsure of the location of an executable mycommand on a Linux system, how would you find it?

    • whereis mycommand
    • which mycommand
    • find mycommand
    • fetch mycommand

    Correct answer:

    • which mycommand

    Explaination: The which command provides the location of a specified executable. While it is possible to use find to locate the executable, it would require more options than were shown with that answer choice, and is not as straightforward or fast as using which for this task.

    4. To create an empty file named emptyfile in the current working directory, which command would you use?

    • touch emptyfile
    • new emptyfile
    • echo emptyfile
    • blank emptyfile

    Correct answer:

    • touch emptyfile

    Explaination: The touch command can be used to create empty files.

    5. Which command will cause Bash to print the path of the current directory?

    • whereami
    • which directory
    • cwd
    • pwd

    Correct answer:

    • pwd

    Explaination: To print the current working directory, use the pwd command.


    LPIC-command-line-2

    1. You have set a variable called kodekloud using the export command. Which command would print the value of the kodekloud variable?

    • print kodekloud
    • echo kodekloud
    • echo $kodekloud
    • read $kodekloud

    Correct answer:

    • echo $kodekloud

    Explaination: The echo command will print the value of a variable, and the variable name must have a $ before it. Example: echo $kodekloud will return the value assigned to the kodekloud variable.

    2. The _____ command can be used to assign values to environment variables for the current shell session.

    • export
    • env
    • echo
    • import

    Correct answer:

    • export

    Explaination: The export command is used to assign values to environment variables for the current shell session.

    3. The _____ command can be used to clear environment variables for the current shell session.

    • clear
    • unset
    • import
    • echo

    Correct answer:

    • unset

    Explaination: The unset command is used to clear environment variable values for the current shell session.

    4. Which command would return the list of directories used by the shell to find executable commands?

    • echo $PATH
    • print $PATH
    • read $PATH
    • pwd $PATH

    Correct answer:

    • echo $PATH

    Explaination: The command echo $PATH would return a list of directories used by the shell to find executable commands.

    5. The _____ command will print a list of all current environment variables.

    • env
    • path
    • export
    • import

    Correct answer:

    • env

    Explaination: The env command will print a list of all current environment variables.


    LPIC-filters

    1. The _____ command can be used to perform search and replace operations on text files.

    • grep
    • sed
    • find
    • substitute

    Correct answer:

    • sed

    Explaination: The sed command can be used to perform search and replace operations on text files.

    2. Which command can be used to search file content using regular expression patterns?

    • grep
    • find
    • read
    • search

    Correct answer:

    • grep

    Explaination: The grep command can be used to search file content using regular expressions. Grep stands for "get regular expression."

    3. Which command can be used to print only the desired field from text?

    • sed
    • grep
    • cut
    • find

    Correct answer:

    • cut

    Explaination: The cut command can specify which field(s) to print from text.

    4. The _____ command will print the contents of a text file to standard output.

    • cat
    • print
    • grep
    • wc

    Correct answer:

    • cat

    Explaination: The cat command will print the contents of a text file to standard output.

    5. Which command sequence would put the contents of a text file named myfile.txt in alphabetical order and remove all duplicates? Select all that apply.

    • sort myfile.txt | uniq
    • sort myfile.txt | sed -s 'duplicates//g'
    • uniq myfile.txt | sort
    • sed -i -s 'duplicates//g' myfile.txt && sort myfile.txt

    Correct answer:

    • sort myfile.txt | uniq

    Explaination: The sort command will place contents in alphabetical order and the uniq command will print only unique entries (remove duplicates).


    LPIC-file-management-1

    1. Which option(s) would you use with the ls command to print file sizes in human readable format?

    • ls -h
    • ls --human
    • ls -lh
    • ls -l --human

    Correct answer:

    • ls -lh

    Explaination: The -h option for ls lists file sizes in human readable format, and it must always be used with the -l option. Therefore, ls -lh is the correct answer.

    2. To remove a directory called mydir along with all of its files and subdirectories, which command would you use?

    • rm mydir
    • rm -R mydir
    • rm -rf mydir
    • rm mydir/*

    Correct answer:

    • rm -rf mydir

    Explaination: To remove a directory along with its files and subdirectories, we have to specify the -r (recursive) option, and will also need to specify the -f (force) option.

    3. Which command can be used to rename an existing file or directory?

    • mv
    • cp
    • touch
    • ls

    Correct answer:

    • mv

    Explaination: The mv command can be used to rename an existing file or directory by "moving" it from the original name to the new name. Example: mv myfile myfile2.

    4. Which command(s) would list all of the files in the current directory that start with the word "file" followed by one number and .txt?

    • ls file[0-9].txt
    • ls | grep 'file[0-9].txt'
    • ls file*.txt
    • ls | grep 'file*.txt'

    Correct answer:

    • ls file[0-9].txt
    • ls | grep 'file[0-9].txt'

    Explaination: Using the bracketed range [0-9] with either ls or grep as shown above will match exactly one number. Using the * wildcard would match zero or more numbers, and would not produce a list that contained only filenames that started with file followed by one number and .txt. For example, that sequence would also match "file.txt" and "file10.txt".

    5. Which option can be used with ls to show hidden files?

    • -a
    • -h
    • --hidden
    • -?

    Correct answer:

    • -a

    Explaination: The -a option with ls will show "all" including hidden files that begin with a period (.).


    LPIC-file-management-2

    1. Which of the following commands could be used to back up an entire disk, including its filesystem?

    • dd
    • tar
    • cpio
    • gzip

    Correct answer:

    • dd

    Explaination: The dd command can be used to back up an entire disk, including its file system. Example: dd if=/dev/sdb of=/mnt/backups/backup.dd bs=4096.

    2. Which command could be used to create an archive named backup.cpio containing all of the files and directories in the current working directory?

    • cpio -o > backup.cpio
    • ls | cpio -o > backup.cpio
    • cpio * > backup.cpio
    • cpio -o * > backup.cpio

    Correct answer:

    • ls | cpio -o > backup.cpio

    Explaination: Since cpio takes its file list as input from standard input, we would use the output of the ls command to list the files and directories in the current working directory and pass that to cpio as input. The -o option with cpio tells cpio to create an archive, and the > operator is used before the archive's filename to direct cpio to create the archive with that name.

    3. Which option(s) would you use with tar to extract the archive located at /home/kodekloud/archive.tar.gz?

    • cvf
    • xf
    • xfz
    • cfvz

    Correct answer:

    • xf
    • xfz

    Explaination: The options for extract (x) and file (f) would be required. The verbose (v) option is optional, and the option for gzip (z) is only required to create a .gzip compressed archive, not to extract one.

    4. Which of the following find command would find files in the current directory that have an extension of .bak and are larger than 1 gigabyte?

    • find . -name *.bak -size +1G
    • find pwd -name *.bak -size -1G
    • find . -name *.back -size 1G
    • find . -name *.bak -size =1G+

    Correct answer:

    • find . -name *.bak -size +1G

    Explaination: The command find . -name *.bak -size +1G would: search the current directory (.) for files with any name followed by the .bak extension (-name *.bak), with a size that is 1 gigabyte or more (-size +1G).

    5. Which command would take the contents of the /home/kodekloud/ directory and create a gzipped tar archive of the contents in a file called kodekloud.tar.gz?

    • tar -czvf kodekloud.tar.gz /home/kodekloud/
    • tar -czvf /home/kodekloud/ kodekloud.tar.gz
    • tar -cvf kodekloud.tar.gz /home/kodekloud/
    • tar -cvf /home/kodekloud/ kodekloud.tar.gz

    Correct answer:

    • tar -czvf kodekloud.tar.gz /home/kodekloud/

    Explaination: When using tar to create gzipped tar archives, we must use the create (c), gzip (z), and file (f) options, followed by the name of the file we wish to create (kodekloud.tar.gz), and finally, the directory or files we wish to archive and compress (/home/kodekloud/).


    LPIC-streams-1

    1. Which of the following would search the contents of the /etc/ directory for the pattern "kodekloud" and write only the errors to a file a /home/kodekloud/errors.list?

    • grep -r 'kodekloud' /etc/ > /home/kodekloud/errors.list
    • grep -r 'kodekloud' /etc/ 2> /home/kodekloud/errors.list
    • grep -r 'kodekloud' /etc/ 2>&1 /home/kodekloud/errors.list
    • grep -r 'kodekloud' /etc/ 1> /home/kodekloud/errors.list

    Correct answer:

    • grep -r 'kodekloud' /etc/ 2> /home/kodekloud/errors.list

    Explaination: The operator "2>" would cause stderr to be written to the file at "/home/kodekloud/errors.list" while the stdout content would be displayed to the screen.

    2. Which operator would be used to designate a herestring?

    • <
    • <<
    • <<<
    • <<<<

    Correct answer:

    • <<<

    Explaination: The "<<<" operator designates a herestring.

    3. Which symbol(s) would be used to specify a stdout redirect? Select all that apply.

    • 1>
    • 2>
    • 0>
    • >

    Correct answer:

    • 1>
    • >

    Explaination: Stdout is implied by the ">" operator. Stdout is also designated by "1", therefore "1>" also refers to stdout.

    4. Which command would search the /etc/ directory for the pattern "kodekloud" and redirect all output (stdout and stderr) to the file at /home/kodekloud/output.list?

    • grep -r 'kodekloud' /etc/ 2> /home/kodekloud/output.list
    • grep -r 'kodekloud' /etc/ 1> /home/kodekloud/output.list
    • grep -r 'kodekloud' /etc/ > /home/kodekloud/output.list
    • grep -r 'kodekloud' /etc/ &> /home/kodekloud/output.list

    Correct answer:

    • grep -r 'kodekloud' /etc/ &> /home/kodekloud/output.list

    Explaination: The operator "&>" will direct both stderr and stdout to a file. This will cause the file to contain all of the contents that would normally be seen on the screen, including error messages.

    5. Which operator can be used to append text to a file, without overwriting the existing contents?

    • ">"
    • ">>"
    • "<<"
    • "<"

    Correct answer:

    • ">>"

    Explaination: The ">>" operator will append text to a file without overwriting the existing contents.


    LPIC-streams-2

    1. _____ is an intermediary program used to pass the output from one program as arguments to another program.

    • xargs
    • xout
    • xin
    • xinput

    Correct answer:

    • xargs

    Explaination: The xargs program can be used as an intermediary program to pass the output of one program as arguments to another.

    2. Given that the "whoami" command prints the current user's username, what would be the result of the following command: rm -rf /home/$(whoami)

    • It would delete the directory /home/whoami
    • It would delete the user's home directory
    • Nothing; this is not a valid command
    • An endless loop

    Correct answer:

    • It would delete the user's home directory

    Explaination: Since the "whoami" command returns the current user's username, the command would delete the user's home directory (and all subdirectories and files). Example: for the user "kodekloud" this would delete "/home/kodekloud".

    3. The output of _____ is passed as an argument to _____ by xargs in the following command: ps -ef | grep 'httpd' | xargs kill

    • ps to kill
    • grep to kill
    • ps to grep
    • httpd to kill

    Correct answer:

    • grep to kill

    Explaination: The initial output from "ps" is passed to "grep." The output of "grep" is passed to "kill" by xargs. Therefore, the output of "grep" is passed by "xargs" to the "kill" command.

    4. Which operator(s) can be used for command substitution? Select all that apply.

    • ``
    • $()
    • %{}
    • ""

    Correct answer:

    • ``
    • $()

    Explaination: Placing a command inside of backquotes (``) or inside of the parenthesis in $() will cause the shell to use the output of the command in that place. Example: echo "Today is $(date) and this system is uname -a." would produce: Today is Mon Dec 19 02:48:03 PM CST 2022 and this system is Linux kodekloud 5.14.0-210.el9.x86_64 #1 SMP PREEMPT_DYNAMIC Fri Dec 9 20:01:51 UTC 2022 x86_64 x86_64 x86_64 GNU/Linux.

    5. The standard operator used to pass the output of one program to the input of another is:

    • |
    • &
    • @
    • %

    Correct answer:

    • |

    Explaination: The vertical pipe (|) is used to pass the output of one command to the input of another. Example: cat /proc/cpuinfo | grep 'bugs'.


    LPIC-processes

    1. To view processes which have been sent to the background, we can use the _____ command.

    • bg
    • fg
    • jobs
    • cron

    Correct answer:

    • jobs

    Explaination: The jobs command will show a list of processes that have been sent to the background or stopped.

    2. To view dynamically updated information on system processes and resources, we can use the _____ command.

    • top
    • ps
    • jobs
    • uptime

    Correct answer:

    • top

    Explaination: The top command provides dynamically updated information on processes and system resources, such as CPU usage and RAM.

    3. To run a command detached from the current session, we can use the _____ command.

    • nohup
    • SIGTERM
    • jobs
    • bg

    Correct answer:

    • nohup

    Explaination: The "no hangup" (nohup) command runs another command detached from the current session. This is often paired with the & symbol to send the command to the background. Example: nohup ping 8.8.8.8 &.

    4. Which command(s) can we use to view the priority of a process that is already running? Select all that apply.

    • ps
    • top
    • nice
    • renice

    Correct answer:

    • ps
    • top

    Explaination: Both the ps command (with the -el or -Al flags) and the top command can be used to view the priority of a process that is already running.

    5. To modify a the priority of an existing process, we can use the _____ command.

    • renice
    • nice
    • ps
    • top

    Correct answer:

    • renice

    Explaination: The renice command allows us to change the priority ("niceness") of a process that is already running. Example: renice -10 -p 1127.

    6. To get detailed information about a process when we already have the PID (process ID), we can use the _____ command.

    • proc
    • pgrep
    • ps
    • pkill

    Correct answer:

    • ps

    Explaination: The ps command provides detailed information about a process when we already know the PID. Example: ps 1127.

    7. To set the priority for a process when it is run, we can use the _____ command.

    • nice
    • renice
    • top
    • ps

    Correct answer:

    • nice

    Explaination: The nice command allows us to set the process priority ("niceness") when a command is run. Example: nice -n 15 top.

    8. To bring a job with job ID 1 from the background to the foreground, which command could we run?

    • fg %1
    • fg $1
    • bg %1
    • bg $1

    Correct answer:

    • fg %1

    Explaination: We can use the fg command, followed by % and the job number to bring a process from the background to the foreground.

    9. True or false: A regular user can only lower the process niceness one time.

    • True
    • False

    Correct answer:

    • True

    Explaination: A normal user can only lower the niceness of a process one time. The root user can do so multiple times.

    10. Which user account(s) can lower the niceness of a process to a value less than zero? Select all that apply.

    • normal users
    • the root user
    • any user with sudo access
    • only the user who started the process

    Correct answer:

    • the root user
    • any user with sudo access

    Explaination: Only the root user or a user with sudo access using the sudo command can lower the niceness of a process below zero.


    LPIC-screen-tmux

    1. The default configuration file for tmux is located at _____.

    • /etc/tmux.conf.d/tmux.conf
    • /etc/tmux.conf
    • /etc/conf/tmux.conf
    • /etc/tmux/conf/tmux.conf

    Correct answer:

    • /etc/tmux.conf

    Explaination: The default configuration file for tmux is located at /etc/tmux.conf.

    2. The _____ terminal multiplexer uses a client-server model.

    • GNU screen
    • tmux

    Correct answer:

    • tmux

    Explaination: The tmux terminal multiplexer uses a client-server model.

    3. The default configuration file for GNU screen is located at _____.

    • /etc/screenrc
    • /etc/screen/screenrc
    • /etc/screen.conf.d/screenrc
    • /etc/screen/conf/screenrc

    Correct answer:

    • /etc/screenrc

    Explaination: The default configuration file for GNU screen is located at /etc/screenrc.

    4. The default command prefix for GNU screen is:

    • CTRL + a
    • CTRL + b
    • CTRL + v
    • CTRL + s

    Correct answer:

    • CTRL + a

    Explaination: The default command prefix for GNU screen is CTRL + a.

    5. The default command prefix for tmux is:

    • CTRL + a
    • CTRL + b
    • CTRL + v
    • CTRL + s

    Correct answer:

    • CTRL + b

    Explaination: The default command prefix for tmux is CTRL + b.


    LPIC-regular-expressions-1

    1. Which regular expression symbol matches a single instance of a any character?

    • .
    • *
    • $
    • ^

    Correct answer:

    • .

    Explaination: The period (.) matches exactly one instance of any character.

    2. Which regular expression symbol matches any characters from a list provided with that symbol?

    • [ ]
    • ( )
    • *
    • ?

    Correct answer:

    • [ ]

    Explaination: Brackets ([ ]) provide a list of characters, and match any characters provided in the brackets. Example grep 'l[oe]t' would match "lot" and "let."

    3. Which of the following utilities makes use of regular expressions? Select all that apply.

    • grep
    • egrep
    • sed
    • ps

    Correct answer:

    • grep
    • egrep
    • sed

    Explaination: The grep, egrep, and sed utilities make use of regular expressions for pattern matching.

    4. Which regular expression symbol indicates that a line ends with a regular expression pattern?

    • ^
    • $
    • .
    • *

    Correct answer:

    • $

    Explaination: The dollar sign ($) is used to indicate that a line ends with a regular expression pattern.

    5. Which regular expression symbol indicates a line that begins with a regular expression pattern?

    • ^
    • $
    • .
    • *

    Correct answer:

    • ^

    Explaination: The caret (^) is used to indicate that a line begins with a regular expression pattern.


    LPIC-regular-expressions-2

    1. When using grep, we should always enclose our regular expression inside of _____.

    • ' '
    • ( )
    • { }
    • [ ]

    Correct answer:

    • ' '

    Explaination: We should always enclose our regular expressions in single quotes (' ') when using grep.

    2. Which option for sed indicates that every instance of a term should be replaced?

    • g
    • *
    • a
    • ?

    Correct answer:

    • g

    Explaination: The global (g) option with sed indicates that every instance of a term should be replaced. Example: sed 's/day/night/g'.

    3. Which option can be used with sed to edit the file as-is, without specifying a different file name as a target?

    • -i
    • -e
    • --here
    • --same

    Correct answer:

    • -i

    Explaination: The in-place (-i) option with sed can be used to edit a file without specifying a different file name for output.

    4. Which grep option can be used to search an entire directory and its sub directories?

    • -r
    • *
    • -R
    • .

    Correct answer:

    • -r

    Explaination: The recursive (-r) option with grep will cause grep to search an entire directory and its sub directories. Example: grep -r 'kodekloud' /etc/.

    5. Which option can be used with grep when the case (upper or lower) of the term does not matter?

    • -i
    • -e
    • -f
    • -k

    Correct answer:

    • -i

    Explaination: The ignore-case (-i) option can be used when the case of the term does not matter.


    LPIC-file-editing

    1. In command mode, which command will allow us to save changes and exit vi?

    • :wq
    • :q
    • :q!
    • :w

    Correct answer:

    • :wq

    Explaination: The command :wq or "write and quite" will allow us to save changes and exit vi.

    2. When using vi, in normal mode, which key allows us to search the file?

    • /
    • s
    • f
    • t

    Correct answer:

    • /

    Explaination: The / character allows us to specify a search term while in normal mode.

    3. In vi normal mode, the pp command will paste. Which command can be used to copy?

    • cc
    • yy
    • :copy
    • :yank

    Correct answer:

    • yy

    Explaination: The "yy" command will copy (yank) text.

    4. When using vi in normal mode, which command will delete the line at the cursor?

    • d
    • dd
    • yy
    • ZZ

    Correct answer:

    • dd

    Explaination: Pressing "d" twice or "dd" will delete the line at the current cursor position.

    5. In addition to vi, what are some other common editors for Linux?

    • nano
    • Emacs
    • Word
    • notes

    Correct answer:

    • nano
    • Emacs

    Explaination: GNU nano and Emacs are common editors in addition to vi.


    LPIC-filesystems

    1. Which command(s) can be used to work with partitions? Select all that apply.

    • fdisk
    • gdisk
    • parted
    • vdisk

    Correct answer:

    • fdisk
    • gdisk
    • parted

    Explaination: The fdisk, gdisk, and parted commands can all be used to work with partitions.

    2. Which methods can be used on Linux to move memory pages from RAM to the hard disk?

    • swap partition
    • swap file
    • virtual memory
    • disk cache

    Correct answer:

    • swap partition
    • swap file

    Explaination: Swap partitions and swap files can be used to move memory pages from RAM to the hard disk.

    3. Which command is used to create filesystems?

    • mkswap
    • mkfs
    • fdisk
    • parted

    Correct answer:

    • mkfs

    Explaination: The mkfs command can be used to create a variety of filesystems on existing partitions.

    4. Which command can be used to determine how much disk space is available?

    • du
    • df
    • free
    • diskfree

    Correct answer:

    • df

    Explaination: The "disk free" (df) command can be used to see how much free space is left on a disk.

    5. Which command can be used to show how much space is currently taken up on a disk and display that output in human-readable format?

    • du -h
    • df -h
    • free -h
    • diskfree -h

    Correct answer:

    • du -h

    Explaination: The disk usage (du) command with the human-readable (-h) flag can be used to see how much disk space is currently taken up and display it in a human-readable format.

    6. Which command will check a filesystem for errors and repair it if it is offline?

    • fsck
    • fdisk
    • sfc
    • chkdsk

    Correct answer:

    • fsck

    Explaination: The filesystem checker (fsck) will check a filesystem for errors, and can be used to repair the filesystem while it is offline (not mounted).

    7. The two types of partition tables commonly used in Linux are (select two):

    • MBR
    • GPT
    • DVH
    • BSD

    Correct answer:

    • MBR
    • GPT

    Explaination: Linux commonly uses MBR and GPT partition tables (though others are supported).

    8. Which of the following are features of BTRFS? Select all that apply.

    • compression
    • subvolumes
    • snapshots
    • encryption

    Correct answer:

    • compression
    • subvolumes
    • snapshots

    Explaination: BTRFS supports compression, subvolumes, and snapshots.

    9. Before checking a filesystem for errors and repairing any that are found, you should first use the ____ command on the filesystem to get it ready for this process.

    • mount
    • fsck
    • xfs_repair
    • umount

    Correct answer:

    • umount

    Explaination: A filesystem must first be offline for errors to be repaired, so a mounted filesystem must be unmounted before running fsck or xfs_repair.

    10. Which utility can be used to check and repair XFS filesystems?

    • xfs_repair
    • xfs_fsck
    • xfs_check
    • xfs_fix

    Correct answer:

    • xfs_repair

    Explaination: The xfs_repair command can be used to check and repair XFS filesystems.


    LPIC-mount-unmount

    1. A list of filesystems to be mounted when the system boots can be found in _____.

    • /etc/fstab
    • /etc/fs
    • /boot/fstab
    • /boot/fs

    Correct answer:

    • /etc/fstab

    Explaination: The /etc/fstab file contains information about filesystems that should be mounted when the system boots.

    2. Which command will mount every filesystem defined in /etc/fstab?

    • mount -a
    • mount -t
    • mount -e
    • mount -o

    Correct answer:

    • mount -a

    Explaination: The mount -a command will mount all filesystems defined in /etc/fstab.

    3. When trying to unmount a filesystem, you get an error saying the target is busy. Which command can you use to see the program that is keeping the disk busy?

    • lsof
    • lsfiles
    • iowait
    • lsio

    Correct answer:

    • lsof

    Explaination: The "list open files" or "lsof" command can be used to see which program is currently using files on a disk that is busy. Example: lsof /dev/sda1.

    4. In addition to the device's disk identifier and partition number (e.g., /dev/sda1), what else can be used in /etc/fstab to identify a partition? Select all that apply.

    • UUID
    • blkid
    • label
    • FSID

    Correct answer:

    • UUID
    • label

    Explaination: Both the UUID and the filesystem label can be used in /etc/fstab to identify a filesystem.

    5. Which command can be used to show information about all block devices on the system?

    • lsblk
    • mount
    • disks
    • ls /dev/

    Correct answer:

    • lsblk

    Explaination: The lsblk command will show information about all block devices on the system and their filesystems.


    LPIC-permissions-ownership

    1. To add execute permissions for the user-owner of a file to existing permissions, which command would you use?

    • chmod u+x
    • chmod +x
    • chmod u-x
    • chmod -x

    Correct answer:

    • chmod u+x

    Explaination: The command chmod u+x would add execute permissions for the file's user-owner while keeping all other existing permissions.

    2. Which command would change the user owner of a directory named "mydir" to "kodekloud" and also make this change for all files and subdirectories contained in the directory?

    • chown mydir kodekloud
    • chown kodekloud mydir
    • chown -R kodekloud mydir
    • chown -R mydir kodekloud

    Correct answer:

    • chown -R kodekloud mydir

    Explaination: The format for using chown is to specify the owner and then the file or directory, and the -R (recursive) option would apply the changes to all files and subdirectories.

    3. A file named "myfile" has the user owner "kodekloud" and the group owner "users." Which command(s) could be use to change the group owner to "friends"? Select all that apply.

    • chgrp friends myfile
    • chown kodekloud:friends myfile
    • chgrp myfile friends
    • chown myfile kodekloud:friends

    Correct answer:

    • chgrp friends myfile
    • chown kodekloud:friends myfile

    Explaination: The chgrp command can be used to change group ownership, and the chown command can also be used if the group is specified after a user owner and a colon. With both commands, the group comes before the file name.

    4. Which command would change the permissions of the file "myfile" to read, write, and execute for the user owner, read and write for the group owner, and no permissions for all other users? Select all that apply.

    • chmod 760 myfile
    • chmod 660 myfile
    • chmod u=rwx,g=rw,u= myfile
    • chmod u=rw,g=rw=u= myfile

    Correct answer:

    • chmod 760 myfile
    • chmod u=rwx,g=rw,u= myfile

    Explaination: We can use octal, where 7 is "read, write, and execute" for the user owner, 6 is "read and write" for the group owner, and 0 is "nothing" for all other users, or we can use ugo format, were u=rwx gives "read, write, and execute" to the user owner, g=rw gives "read and write" to the group owner, and u= gives nothing to all other users.

    5. How can we set the sticky bit on a file named "myfile"? Other permissions are unimportant. Select all that apply.

    • chmod +t myfile
    • chmod 1777 myfile
    • chmod 0777 myfile
    • chmod 4777 myfile

    Correct answer:

    • chmod +t myfile
    • chmod 1777 myfile

    Explaination: We can add the sticky bit to existing permissions by using chmod +t. We can also specify the sticky bit using the octal value of 1 in a four-digit format.


    LPIC-links

    1. True or false: When a hard link is deleted, the original file is also deleted.

    • True
    • False

    Correct answer:

    • True

    Explaination: A hard link is treated as the original file, but in a different location. If a hard link is deleted, the original file is also deleted.

    2. Which command would create a soft link between myphoto.jpg and /home/kodekloud/photo?

    • ln -s myphoto.jpg /home/kodekloud/photo
    • ln -s /home/kodekloud/photo myphoto.jpg
    • ln myphoto.jpg /home/kodekloud/photo
    • ln /home/kodekloud/photo myphoto.jpg

    Correct answer:

    • ln -s myphoto.jpg /home/kodekloud/photo

    Explaination: The ln -s command creates a soft link, and the format for ln in the specify the file being linked (myphoto.jpg) and then the target (/home/kodekloud/photo).

    3. The command ln myphoto.jpg /home/kodekloud/Pictures/photo would create a _____ link.

    • Symbolic
    • Hard

    Correct answer:

    • Hard

    Explaination: The ln command, when used without other flags, creates a hard link to a file.

    4. You see myphoto.jpg -> photo in the output of the ls command. What type of link does this show?

    • Hard
    • Soft

    Correct answer:

    • Soft

    Explaination: Symbolic or "soft" links are indicated by -> in the output of ls.

    5. True or false: When a soft link is deleted, the original file is also deleted.

    • True
    • False

    Correct answer:

    • False

    Explaination: A soft link points to the original file, but is not considered to be the same as the original file. Therefore, a soft link can be deleted while leaving the original file intact.


    LPIC-file-locations

    1. The standard layout for Linux directories and their contents, as determined by the Linux Foundation, is known as the _____.

    • Filesystem Hierarchy Standard
    • Filesystem Standard Hierarchy
    • Hierarchical Filesystem Standard
    • Standard Hierarchical Filesystem

    Correct answer:

    • Filesystem Hierarchy Standard

    Explaination: The Filesystem Hierarchy Standard (FHS) is a layout determined by the Linux Foundation as an option (but encouraged) standard for Linux directories and their contents.

    2. To locate files, we use the _____ command.

    • find
    • search
    • spotlight
    • cortana

    Correct answer:

    • find

    Explaination: Linux uses the find command to locate files.

    3. Removable storage, such as CD-ROMs and flash drives are mounted to the _____ directory.

    • /mnt
    • /media
    • /home
    • /run

    Correct answer:

    • /media

    Explaination: According to the FHS, user-mountable removable media such as flash drives and CD-ROMS should be mounted to the /media directory.

    4. Temporary files can be located in _____. Select any that apply.

    • /tmp
    • /var/tmp
    • /run
    • /usr/tmp

    Correct answer:

    • /tmp
    • /var/tmp
    • /run

    Explaination: According to the FHS, temporary files that are cleared during system boot are stored in /tmp; temporary files that are not cleared during system boot are stored in /var/tmp; run-time data used by running processes is stored in /run.

    5. Essential programs, available to all users, are found in _____.

    • /bin
    • /sbin
    • /usr/bin
    • /usr/sbin

    Correct answer:

    • /bin

    Explaination: According to the FHS, essential binaries available to everyone are to be placed in the /bin directory.


    LPIC-mock-1

    1. Which option would you pass to journalctl to change the directory it uses to search for log files?

    • --log-directory=
    • -D
    • -d
    • --log-dir

    Correct answer:

    • -D

    Explaination: The -D option allows you to specify a different directory for log files other than the default directory. Example: journalctl -D /mnt/external/var/log/journal.

    2. A friend is visiting you and brings a portable USB hard drive to share some files with you. You have one SATA drive in your Linux machine. Which name will be given to your friend's portable USB hard drive in the /dev/ directory of your Linux machine?

    • /dev/sata2
    • /dev/sba
    • /dev/sdb
    • /dev/usb1

    Correct answer:

    • /dev/sdb

    Explaination: In Linux, USB drives are treated as SATA drives and follow the same naming conventions. Your initial drive is already identified as /dev/sda, so your friend's USB hard drive will be identified as /dev/sdb.

    3. Which command would you use to view only the last ten lines of the initialization log?

    • dmesg --last
    • dmesg | tail
    • lastlog
    • dmesg -H

    Correct answer:

    • dmesg | tail

    Explaination: Directing the output of dmesg to the tail command will only show the last ten lines of the initialization log.

    4. Which command would cause the system to shutdown 45 minutes from now?

    • shutdown 00:45
    • shutdown now+45
    • shutdown +45
    • shutdown +45M

    Correct answer:

    • shutdown +45

    Explaination: Specifying +45 after the shutdown command will cause the system to shutdown 45 minutes from the time the command is run.

    5. If you want to warn other users of a Linux system that the system is going down for maintenance, which command could you use to send a message to all logged-in users?

    • write
    • wall
    • warn
    • wipe

    Correct answer:

    • wall

    Explaination: The wall command is use to send messages to all users logged into a system.

    6. Given a theoretical file located at /etc/rc3.d/S45 ethernet, what would happen to any services listed in this file when the system enters runlevel 3?

    • They will stop.
    • They will start.
    • They will be suspended.
    • They will be restarted.

    Correct answer:

    • They will start.

    Explaination: The letter "S" at the beginning of the file name indicates that services listed in this file will be started.

    7. You need to know which hardware devices are inside of a Linux system, but you cannot open the system's case. How would you get Linux to produce a list of hardware connected to the PCI bus?

    • cat /proc/hardware
    • ls /dev/
    • lspci
    • modprobe

    Correct answer:

    • lspci

    Explaination: lspci gives information about hardware that is connected to the system's PCI bus.

    8. Which filesystem would you use for the ESP partition?

    • ext2
    • fat32
    • xfs
    • ntfs

    Correct answer:

    • fat32

    Explaination: EFI System Partitions (ESP) should use a FAT filesystem, like FAT12, FAT16, or FAT32.

    9. Which formula would give the size of a Logical Volume?

    • Size of physical extents divided by number of extents
    • Number of extents divided by size of physical extents
    • Number of extents multiplied by physical extent size
    • Disk sectors multiplied by number of extents

    Correct answer:

    • Number of extents multiplied by physical extent size

    Explaination: The size of a Logical Volume is equal to the number of physical extents multiplied by the total number of extents on the volume.

    10. When using GRUB Legacy, how is the first partition of the first disk labeled?

    • (hd1,1)
    • (hd0,1)
    • (hd0,0)
    • (hd1,0)

    Correct answer:

    • (hd0,0)

    Explaination: GRUB Legacy begins counting from 0, so the first partition of the first drive would be labeled as (hd0,0).

    11. After adding a new shared library directory to your system, you copied a configuration file with its full path to the correct directory. Which command would you use to notify the system of the change?

    • ldd
    • ldconfig
    • libupdate
    • updatedb

    Correct answer:

    • ldconfig

    Explaination: When making changes to shared libraries on the system, you must run ldconfig to notify the system of the changes.

    12. On a Debian system, which command would remove a package and all of its configuration files?

    • dpkg -r
    • dpkg --remove
    • dkpg --erase
    • dpkg -P

    Correct answer:

    • dpkg -P

    Explaination: Running dpkg with the -P (purge) flag will remove a package and all of its configuration files.

    13. If you update the configuration for GRUB 2, which command would you run to write that configuration to the correct directory for GRUB 2 to use the next time you boot the system?

    • grub-config -o /boot/grub/grub.cfg
    • grub-mkconfig -o /boot/grub/grub.cfg
    • grub-mkconfig -o /boot/grub/grub.conf
    • grub-config -o /boot/grub/grub.conf

    Correct answer:

    • grub-mkconfig -o /boot/grub/grub.cfg

    Explaination: After updating the configuration for GRUB 2, you must run grub-mkconfig -o /boot/grub/grub.cfg to make GRUB 2 use the changes on the next system boot.

    14. Which parameter would you add to dpkg-query to show which package contains a particular file?

    • -s
    • -S
    • -l
    • -W

    Correct answer:

    • -S

    Explaination: Using the -S parameter with dpkg-query will show which package contains a particular file.

    15. Which command would you use to install a .deb file located on your local Linux system?

    • dpkg -I
    • dpkg -i
    • dpkg install
    • dpkg -install

    Correct answer:

    • dpkg -i

    Explaination: To install a .deb file located on a local machine, you would you use the dpkg -i command. It is also possible to use dpkg --install (with two dashes).

    16. Volume Groups are divided into:

    • Extents
    • Sectors
    • Slices
    • Chunks

    Correct answer:

    • Extents

    Explaination: Volume groups are divided into extents.

    17. Where are repository files stored for DNF and YUM?

    • /etc/repos.d/
    • /etc/yum.repos.d/
    • /etc/yum/repos/
    • /etc/yum/repos.d/

    Correct answer:

    • /etc/yum.repos.d/

    Explaination: Repository files (.repo) are stored in /etc/yum.repos.d/.

    18. Using DNF, how would you install the httpd package?

    • dnf install httpd
    • dnf -i httpd
    • dnf httpd
    • dnf provide httpd

    Correct answer:

    • dnf install httpd

    Explaination: When using DNF, the dnf install command, followed by a package name, will install that package. Example: dnf install httpd.

    19. Which virtualization method provides the highest performance?

    • Full virtualization
    • Paravirtualization
    • VirtualBox
    • Virsh

    Correct answer:

    • Paravirtualization

    Explaination: Paravirtualization provides the best performance through the use of paravirtualized drivers for networking and storage.

    20. Using YUM or DNF, which option would uninstall a package from the system, along with any packages that depend on that package?

    • remove
    • purge
    • uninstall
    • delete

    Correct answer:

    • remove

    Explaination: Using YUM or DNF, the remove option will uninstall a package from the system, along with all packages that depend on it. Example: dnf remove httpd.

    21. The _____ command will print a list of all current environment variables.

    • env
    • path
    • export
    • import

    Correct answer:

    • env

    Explaination: The env command will print a list of all current environment variables.

    22. Which command would return the list of directories used by the shell to find executable commands?

    • echo $PATH
    • print $PATH
    • read $PATH
    • pwd $PATH

    Correct answer:

    • echo $PATH

    Explaination: The command echo $PATH would return a list of directories used by the shell to find executable commands.

    23. To create an empty file named emptyfile in the current working directory, which command would you use?

    • touch emptyfile
    • new emptyfile
    • echo emptyfile
    • blank emptyfile

    Correct answer:

    • touch emptyfile

    Explaination: The touch command can be used to create empty files.

    24. Which command is used to search the short description of man pages for keywords?

    • apropos
    • grep
    • find
    • cat

    Correct answer:

    • apropos

    Explaination: Each manual page has a short description available within it and apropos searches the descriptions for instances of keyword.

    25. The _____ command will print the contents of a text file to standard output.

    • cat
    • print
    • grep
    • wc

    Correct answer:

    • cat

    Explaination: The cat command will print the contents of a text file to standard output.

    26. Which command sequence would put the contents of a text file named myfile.txt in alphabetical order and remove all duplicates? Select all that apply.

    • sort myfile.txt | uniq
    • sort myfile.txt | sed -s 'duplicates//g'
    • uniq myfile.txt | sort
    • sed -i -s 'duplicates//g' myfile.txt && sort myfile.txt

    Correct answer:

    • sort myfile.txt | uniq

    Explaination: The sort command will place contents in alphabetical order and the uniq command will print only unique entries (remove duplicates).

    27. Which option can be used with ls to show hidden files?

    • -a
    • -h
    • --hidden
    • -?

    Correct answer:

    • -a

    Explaination: The -a option with ls will show "all" including hidden files that begin with a period (.).

    28. Which option(s) would you use with the ls command to print file sizes in human readable format?

    • ls -h
    • ls --human
    • ls -lh
    • ls -l --human

    Correct answer:

    • ls -lh

    Explaination: The -h option for ls lists file sizes in human readable format, and it must always be used with the -l option. Therefore, ls -lh is the correct answer.

    29. Which command could be used to create an archive named backup.cpio containing all of the files and directories in the current working directory?

    • cpio -o > backup.cpio
    • ls | cpio -o > backup.cpio
    • cpio * > backup.cpio
    • cpio -o * > backup.cpio

    Correct answer:

    • ls | cpio -o > backup.cpio

    Explaination: Since cpio takes its file list as input from standard input, we would use the output of the ls command to list the files and directories in the current working directory and pass that to cpio as input. The -o option with cpio tells cpio to create an archive, and the > operator is used before the archive's filename to direct cpio to create the archive with that name.

    30. Which of the following commands could be used to back up an entire disk, including its filesystem?

    • dd
    • tar
    • cpio
    • gzip

    Correct answer:

    • dd

    Explaination: The dd command can be used to back up an entire disk, including its file system. Example: dd if=/dev/sdb of=/mnt/backups/backup.dd bs=4096.

    31. Which command would take the contents of the /home/kodekloud/ directory and create a gzipped tar archive of the contents in a file called kodekloud.tar.gz?

    • tar -czvf kodekloud.tar.gz /home/kodekloud/
    • tar -czvf /home/kodekloud/ kodekloud.tar.gz
    • tar -cvf kodekloud.tar.gz /home/kodekloud/
    • tar -cvf /home/kodekloud/ kodekloud.tar.gz

    Correct answer:

    • tar -czvf kodekloud.tar.gz /home/kodekloud/

    Explaination: When using tar to create gzipped tar archives, we must use the create (c), gzip (z), and file (f) options, followed by the name of the file we wish to create (kodekloud.tar.gz), and finally, the directory or files we wish to archive and compress (/home/kodekloud/).

    32. Which of the following would search the contents of the /etc/ directory for the pattern "kodekloud" and write only the errors to a file a /home/kodekloud/errors.list?

    • grep -r 'kodekloud' /etc/ > /home/kodekloud/errors.list
    • grep -r 'kodekloud' /etc/ 2> /home/kodekloud/errors.list
    • grep -r 'kodekloud' /etc/ 2>&1 /home/kodekloud/errors.list
    • grep -r 'kodekloud' /etc/ 1> /home/kodekloud/errors.list

    Correct answer:

    • grep -r 'kodekloud' /etc/ 2> /home/kodekloud/errors.list

    Explaination: The operator "2>" would cause stderr to be written to the file at "/home/kodekloud/errors.list" while the stdout content would be displayed to the screen.

    33. _____ is an intermediary program used to pass the output from one program as arguments to another program.

    • xargs
    • xout
    • xin
    • xinput

    Correct answer:

    • xargs

    Explaination: The xargs program can be used as an intermediary program to pass the output of one program as arguments to another.

    34. Given that the "whoami" command prints the current user's username, what would be the result of the following command: rm -rf /home/$(whoami)

    • It would delete the directory /home/whoami
    • It would delete the user's home directory
    • Nothing; this is not a valid command
    • An endless loop

    Correct answer:

    • It would delete the user's home directory

    Explaination: Since the "whoami" command returns the current user's username, the command would delete the user's home directory (and all subdirectories and files). Example: for the user "kodekloud" this would delete "/home/kodekloud".

    35. To bring a job with job ID 1 from the background to the foreground, which command could we run?

    • fg %1
    • fg $1
    • bg %1
    • bg $1

    Correct answer:

    • fg %1

    Explaination: We can use the fg command, followed by % and the job number to bring a process from the background to the foreground.

    36. To view dynamically updated information on system processes and resources, we can use the _____ command.

    • top
    • ps
    • jobs
    • uptime

    Correct answer:

    • top

    Explaination: The top command provides dynamically updated information on processes and system resources, such as CPU usage and RAM.

    37. The default command prefix for tmux is:

    • CTRL + a
    • CTRL + b
    • CTRL + v
    • CTRL + s

    Correct answer:

    • CTRL + b

    Explaination: The default command prefix for tmux is CTRL + b.

    38. To set the priority for a process when it is run, we can use the _____ command.

    • nice
    • renice
    • top
    • ps

    Correct answer:

    • nice

    Explaination: The nice command allows us to set the process priority ("niceness") when a command is run. Example: nice -n 15 top.

    39. The default command prefix for GNU screen is:

    • CTRL + a
    • CTRL + b
    • CTRL + v
    • CTRL + s

    Correct answer:

    • CTRL + a

    Explaination: The default command prefix for GNU screen is CTRL + a.

    40. Which user account(s) can lower the niceness of a process to a value less than zero? Select all that apply.

    • normal users
    • the root user
    • any user with sudo access
    • only the user who started the process

    Correct answer:

    • the root user
    • any user with sudo access

    Explaination: Only the root user or a user with sudo access using the sudo command can lower the niceness of a process below zero.

    41. Which regular expression symbol matches a single instance of a any character?

    • .
    • *
    • $
    • ^

    Correct answer:

    • .

    Explaination: The period (.) matches exactly one instance of any character.

    42. Which regular expression symbol indicates a line that begins with a regular expression pattern?

    • ^
    • $
    • .
    • *

    Correct answer:

    • ^

    Explaination: The caret (^) is used to indicate that a line begins with a regular expression pattern.

    43. Which option can be used with sed to edit the file as-is, without specifying a different file name as a target?

    • -i
    • -e
    • --here
    • --same

    Correct answer:

    • -i

    Explaination: The in-place (-i) option with sed can be used to edit a file without specifying a different file name for output.

    44. Which regular expression symbol indicates that a line ends with a regular expression pattern?

    • ^
    • $
    • .
    • *

    Correct answer:

    • $

    Explaination: The dollar sign ($) is used to indicate that a line ends with a regular expression pattern.

    45. When using vi, in normal mode, which key allows us to search the file?

    • /
    • s
    • f
    • t

    Correct answer:

    • /

    Explaination: The / character allows us to specify a search term while in normal mode.

    46. Which command is used to create filesystems?

    • mkswap
    • mkfs
    • fdisk
    • parted

    Correct answer:

    • mkfs

    Explaination: The mkfs command can be used to create a variety of filesystems on existing partitions.

    47. In command mode, which command will allow us to save changes and exit vi?

    • :wq
    • :q
    • :q!
    • :w

    Correct answer:

    • :wq

    Explaination: The command :wq or "write and quite" will allow us to save changes and exit vi.

    48. Which command(s) can be used to work with partitions? Select all that apply.

    • fdisk
    • gdisk
    • parted
    • vdisk

    Correct answer:

    • fdisk
    • gdisk
    • parted

    Explaination: The fdisk, gdisk, and parted commands can all be used to work with partitions.

    49. Which command can be used to show how much space is currently taken up on a disk and display that output in human-readable format?

    • du -h
    • df -h
    • free -h
    • diskfree -h

    Correct answer:

    • du -h

    Explaination: The disk usage (du) command with the human-readable (-h) flag can be used to see how much disk space is currently taken up and display it in a human-readable format.

    50. Which command will check a filesystem for errors and repair it if it is offline?

    • fsck
    • fdisk
    • sfc
    • chkdsk

    Correct answer:

    • fsck

    Explaination: The filesystem checker (fsck) will check a filesystem for errors, and can be used to repair the filesystem while it is offline (not mounted).

    51. Which command will mount every filesystem defined in /etc/fstab?

    • mount -a
    • mount -t
    • mount -e
    • mount -o

    Correct answer:

    • mount -a

    Explaination: The mount -a command will mount all filesystems defined in /etc/fstab.

    52. A list of filesystems to be mounted when the system boots can be found in _____.

    • /etc/fstab
    • /etc/fs
    • /boot/fstab
    • /boot/fs

    Correct answer:

    • /etc/fstab

    Explaination: The /etc/fstab file contains information about filesystems that should be mounted when the system boots.

    53. In addition to the device's disk identifier and partition number (e.g., /dev/sda1), what else can be used in /etc/fstab to identify a partition? Select all that apply.

    • UUID
    • blkid
    • label
    • FSID

    Correct answer:

    • UUID
    • label

    Explaination: Both the UUID and the filesystem label can be used in /etc/fstab to identify a filesystem.

    54. Which command would change the user owner of a directory named "mydir" to "kodekloud" and also make this change for all files and subdirectories contained in the directory?

    • chown mydir kodekloud
    • chown kodekloud mydir
    • chown -R kodekloud mydir
    • chown -R mydir kodekloud

    Correct answer:

    • chown -R kodekloud mydir

    Explaination: The format for using chown is to specify the owner and then the file or directory, and the -R (recursive) option would apply the changes to all files and subdirectories.

    55. Which command would change the permissions of the file "myfile" to read, write, and execute for the user owner, read and write for the group owner, and no permissions for all other users? Select all that apply.

    • chmod 760 myfile
    • chmod 660 myfile
    • chmod u=rwx,g=rw,u= myfile
    • chmod u=rw,g=rw=u= myfile

    Correct answer:

    • chmod 760 myfile
    • chmod u=rwx,g=rw,u= myfile

    Explaination: We can use octal, where 7 is "read, write, and execute" for the user owner, 6 is "read and write" for the group owner, and 0 is "nothing" for all other users, or we can use ugo format, were u=rwx gives "read, write, and execute" to the user owner, g=rw gives "read and write" to the group owner, and u= gives nothing to all other users.

    56. How can we set the sticky bit on a file named "myfile"? Other permissions are unimportant. Select all that apply.

    • chmod +t myfile
    • chmod 1777 myfile
    • chmod 0777 myfile
    • chmod 4777 myfile

    Correct answer:

    • chmod +t myfile
    • chmod 1777 myfile

    Explaination: We can add the sticky bit to existing permissions by using chmod +t. We can also specify the sticky bit using the octal value of 1 in a four-digit format.

    57. Which command would create a soft link between myphoto.jpg and /home/kodekloud/photo?

    • ln -s myphoto.jpg /home/kodekloud/photo
    • ln -s /home/kodekloud/photo myphoto.jpg
    • ln myphoto.jpg /home/kodekloud/photo
    • ln /home/kodekloud/photo myphoto.jpg

    Correct answer:

    • ln -s myphoto.jpg /home/kodekloud/photo

    Explaination: The ln -s command creates a soft link, and the format for ln in the specify the file being linked (myphoto.jpg) and then the target (/home/kodekloud/photo).

    58. Temporary files can be located in _____. Select any that apply.

    • /tmp
    • /var/tmp
    • /run
    • /usr/tmp

    Correct answer:

    • /tmp
    • /var/tmp
    • /run

    Explaination: According to the FHS, temporary files that are cleared during system boot are stored in /tmp; temporary files that are not cleared during system boot are stored in /var/tmp; run-time data used by running processes is stored in /run.

    59. The command ln myphoto.jpg /home/kodekloud/Pictures/photo would create a _____ link.

    • Symbolic
    • Hard

    Correct answer:

    • Hard

    Explaination: The ln command, when used without other flags, creates a hard link to a file.

    60. Essential programs, available to all users, are found in _____.

    • /bin
    • /sbin
    • /usr/bin
    • /usr/sbin

    Correct answer:

    • /bin

    Explaination: According to the FHS, essential binaries available to everyone are to be placed in the /bin directory.


    LPIC-mock-2

    1. Which command will list kernel modules in use by hardware?

    • lspci -k
    • lspci -m
    • lspci --modules
    • lspci -l

    Correct answer:

    • lspci -k

    Explaination: The -k option for lspci will list kernel modules in use by hardware.

    2. Which file would you search to determine the CPU features on a Linux machine?

    • /proc/cpuinfo
    • /dev/cpuinfo
    • /proc/cpu
    • /proc/hardware/cpuinfo

    Correct answer:

    • /proc/cpuinfo

    Explaination: Information on the CPU and its features can be found in the cpuinfo file inside the /proc virtual filesystem (/proc/cpuinfo).

    3. You have compiled a custom kernel, and the filesystem type used by your Linux system's root filesystem is compiled as a module. What would you need to include along with the kernel to make sure your system loads the root filesystem correctly?

    • initramfs
    • EFI applications
    • A copy of /etc/modules.conf.d/
    • bootstrap

    Correct answer:

    • initramfs

    Explaination: An initial RAM filesystem (initramfs) should be included if the root filesystem is compiled as a module.

    4. Which command would you use to view only the last ten lines of the initialization log?

    • dmesg --last
    • dmesg | tail
    • lastlog
    • dmesg -H

    Correct answer:

    • dmesg | tail

    Explaination: Directing the output of dmesg to the tail command will only show the last ten lines of the initialization log.

    5. Using systemctl, how would you determine if a service named myservice.service is configured to start when the system boots?

    • systemctl status myservice.service
    • systemctl is-enabled myservice.service
    • systemctl is-active myservice.service
    • systemctl on-boot myservice.service

    Correct answer:

    • systemctl is-enabled myservice.service

    Explaination: The is-enabled option for systemctl will return "enabled" if a service is enabled to start at boot, or "disabled" if it is not.

    6. Given a theoretical file located at /etc/rc3.d/S45 ethernet, what would happen to any services listed in this file when the system enters runlevel 3?

    • They will stop.
    • They will start.
    • They will be suspended.
    • They will be restarted.

    Correct answer:

    • They will start.

    Explaination: The letter "S" at the beginning of the file name indicates that services listed in this file will be started.

    7. On a system equipped with BIOS, what should be placed in the MBR of the first storage device in order to boot the system?

    • bootstrap
    • firmware
    • initrd
    • kernel

    Correct answer:

    • bootstrap

    Explaination: The bootstrap binary must be located in the MBR of the first storage device for a system equipped with BIOS to boot correctly.

    8. On SysV systems, which file contains the default init configuration?

    • /etc/init.d/defaults
    • /etc/defaults/inittab
    • /etc/inittab
    • /etc/conf.d/inittab

    Correct answer:

    • /etc/inittab

    Explaination: The default init configuration is stored in /etc/inittab on SysV systems.

    9. When a Linux system mounts the EFI partition, where is it usually mounted?

    • /boot/efi/
    • /boot/grub/efi/
    • /mnt/efi/
    • /efi/

    Correct answer:

    • /boot/efi/

    Explaination: Linux usually mounts the EFI partition at /boot/efi/.

    10. Where are the files for the GRUB bootloader stored?

    • /etc/grub/
    • /boot/
    • /boot/grub/
    • /grub/boot/

    Correct answer:

    • /boot/grub/

    Explaination: The files for the GRUB bootloader are stored in the /boot/grub/ directory.

    11. To change the menu entries for GRUB Legacy, which file would you edit?

    • /boot/grub/menu.lst
    • /etc/grub/grub.cfg
    • /etc/grub/menu.lst
    • /boot/grub/grub.cfg

    Correct answer:

    • /boot/grub/menu.lst

    Explaination: Menu entries for GRUB Legacy are stored in /boot/grub/menu.lst.

    12. Which apt-file command would show the package that contains the file /usr/bin/systemctl?

    • apt-file search /usr/bin/systemctl
    • apt-file show /usr/bin/systemctl
    • apt-file provides /usr/bin/systemctl
    • apt-file query /usr/bin/systemctl

    Correct answer:

    • apt-file search /usr/bin/systemctl

    Explaination: You can use apt-file search followed by the full path to a file to show which package contains that file.

    13. When using GRUB 2, which menu entry parameter determines how long GRUB 2 will pause before booting the default menu entry?

    • GRUB_TIMEOUT=
    • GRUB_WAIT=
    • GRUB_PAUSE=
    • GRUB_TIMER=

    Correct answer:

    • GRUB_TIMEOUT=

    Explaination: The menu entry that controls how long GRUB 2 will pause before booting the default menu entry is GRUB_TIMEOUT=.

    14. Which parameter would you add to dpkg-query to show which package contains a particular file?

    • -s
    • -S
    • -l
    • -W

    Correct answer:

    • -S

    Explaination: Using the -S parameter with dpkg-query will show which package contains a particular file.

    15. You have added a new shared library directory to your system, and you have written a custom configuration file including the full path to to the new shared library location. Which directory would you put the configuration file into?

    • /usr/share/
    • /etc/share
    • /etc/ld.so.conf.d/
    • /usr/ld.so.conf.d/

    Correct answer:

    • /etc/ld.so.conf.d/

    Explaination: Configuration files that define shared library paths go in the /etc/ld.so.conf.d/ directory.

    16. Which apt-cache command will provide information for a package?

    • apt-cache show
    • apt-cache info
    • apt-cache print
    • apt-cache search

    Correct answer:

    • apt-cache show

    Explaination: The apt-cache show command, followed by a package name, will provide information for a package.

    17. Which yum command will bring repository metadata to the most recent version?

    • yum update
    • yum metadata
    • yum upgrade
    • yum check-metadata

    Correct answer:

    • yum update

    Explaination: The yum update command will update repository metadata.

    18. Where are repository files stored for DNF and YUM?

    • /etc/repos.d/
    • /etc/yum.repos.d/
    • /etc/yum/repos/
    • /etc/yum/repos.d/

    Correct answer:

    • /etc/yum.repos.d/

    Explaination: Repository files (.repo) are stored in /etc/yum.repos.d/.

    19. Using zypper, how would you find out which package provides the file /usr/bin/systemctl?

    • zypper se /usr/bin/systemctl
    • zypper se --provides /usr/bin/systemctl
    • zypper --provides /usr/bin/systemctl
    • zypper se provides /usr/bin/systemctl

    Correct answer:

    • zypper se --provides /usr/bin/systemctl

    Explaination: When using zypper, the se (search) command, followed by --provides and the file path will show which package provides that file. Example: zypper se --provides /usr/bin/systemctl.

    20. Which command will cause Bash to print the path of the current directory?

    • whereami
    • which directory
    • cwd
    • pwd

    Correct answer:

    • pwd

    Explaination: To print the current working directory, use the pwd command.

    21. The _____ command can be used to clear environment variables for the current shell session.

    • clear
    • unset
    • import
    • echo

    Correct answer:

    • unset

    Explaination: The unset command is used to clear environment variable values for the current shell session.

    22. Intel VT-x and AMD-V are examples of _____ used to provide support for fully virtualized guests?

    • CPU extensions
    • paravirtualized drivers
    • hypervisors
    • virtual machines

    Correct answer:

    • CPU extensions

    Explaination: Intel VT-x and AMD-V are CPU extensions.

    23. The _____ command can be used to assign values to environment variables for the current shell session.

    • export
    • env
    • echo
    • import

    Correct answer:

    • export

    Explaination: The export command is used to assign values to environment variables for the current shell session.

    24. You have set a variable called kodekloud using the export command. Which command would print the value of the kodekloud variable?

    • print kodekloud
    • echo kodekloud
    • echo $kodekloud
    • read $kodekloud

    Correct answer:

    • echo $kodekloud

    Explaination: The echo command will print the value of a variable, and the variable name must have a $ before it. Example: echo $kodekloud will return the value assigned to the kodekloud variable.

    25. Which command can be used to search file content using regular expression patterns?

    • grep
    • find
    • read
    • search

    Correct answer:

    • grep

    Explaination: The grep command can be used to search file content using regular expressions. Grep stands for "get regular expression."

    26. Which command can be used to print only the desired field from text?

    • sed
    • grep
    • cut
    • find

    Correct answer:

    • cut

    Explaination: The cut command can specify which field(s) to print from text.

    27. Which option can be used with the find command to show only directories?

    • -type d
    • --type -d
    • -type directory
    • --type --directory

    Correct answer:

    • -type d

    Explaination: The option -type d will cause find to limit its output to directories that match the search pattern.

    28. Which command(s) would list all of the files in the current directory that start with the word "file" followed by one number and .txt?

    • ls file[0-9].txt
    • ls | grep 'file[0-9].txt'
    • ls file*.txt
    • ls | grep 'file*.txt'

    Correct answer:

    • ls file[0-9].txt
    • ls | grep 'file[0-9].txt'

    Explaination: Using the bracketed range [0-9] with either ls or grep as shown above will match exactly one number. Using the * wildcard would match zero or more numbers, and would not produce a list that contained only filenames that started with file followed by one number and .txt. For example, that sequence would also match "file.txt" and "file10.txt".

    29. Which of the following find command would find files in the current directory that have an extension of .bak and are larger than 1 gigabyte?

    • find . -name *.bak -size +1G
    • find pwd -name *.bak -size -1G
    • find . -name *.back -size 1G
    • find . -name *.bak -size =1G+

    Correct answer:

    • find . -name *.bak -size +1G

    Explaination: The command find . -name *.bak -size +1G would: search the current directory (.) for files with any name followed by the .bak extension (-name *.bak), with a size that is 1 gigabyte or more (-size +1G).

    30. Which option(s) would you use with tar to extract the archive located at /home/kodekloud/archive.tar.gz?

    • cvf
    • xf
    • xfz
    • cfvz

    Correct answer:

    • xf
    • xfz

    Explaination: The options for extract (x) and file (f) would be required. The verbose (v) option is optional, and the option for gzip (z) is only required to create a .gzip compressed archive, not to extract one.

    31. Which symbol(s) would be used to specify a stdout redirect? Select all that apply.

    • 1>
    • 2>
    • 0>
    • >

    Correct answer:

    • 1>
    • >

    Explaination: Stdout is implied by the ">" operator. Stdout is also designated by "1", therefore "1>" also refers to stdout.

    32. Which operator would be used to designate a herestring?

    • <
    • <<
    • <<<
    • <<<<

    Correct answer:

    • <<<

    Explaination: The "<<<" operator designates a herestring.

    33. Which operator(s) can be used for command substitution? Select all that apply.

    • ``
    • $()
    • %{}
    • ""

    Correct answer:

    • ``
    • $()

    Explaination: Placing a command inside of backquotes (``) or inside of the parenthesis in $() will cause the shell to use the output of the command in that place. Example: echo "Today is $(date) and this system is uname -a." would produce: Today is Mon Dec 19 02:48:03 PM CST 2022 and this system is Linux kodekloud 5.14.0-210.el9.x86_64 #1 SMP PREEMPT_DYNAMIC Fri Dec 9 20:01:51 UTC 2022 x86_64 x86_64 x86_64 GNU/Linux.

    34. The standard operator used to pass the output of one program to the input of another is:

    • |
    • &
    • @
    • %

    Correct answer:

    • |

    Explaination: The vertical pipe (|) is used to pass the output of one command to the input of another. Example: cat /proc/cpuinfo | grep 'bugs'.

    35. To view processes which have been sent to the background, we can use the _____ command.

    • bg
    • fg
    • jobs
    • cron

    Correct answer:

    • jobs

    Explaination: The jobs command will show a list of processes that have been sent to the background or stopped.

    36. The _____ terminal multiplexer uses a client-server model.

    • GNU screen
    • tmux

    Correct answer:

    • tmux

    Explaination: The tmux terminal multiplexer uses a client-server model.

    37. To get detailed information about a process when we already have the PID (process ID), we can use the _____ command.

    • proc
    • pgrep
    • ps
    • pkill

    Correct answer:

    • ps

    Explaination: The ps command provides detailed information about a process when we already know the PID. Example: ps 1127.

    38. To run a command detached from the current session, we can use the _____ command.

    • nohup
    • SIGTERM
    • jobs
    • bg

    Correct answer:

    • nohup

    Explaination: The "no hangup" (nohup) command runs another command detached from the current session. This is often paired with the & symbol to send the command to the background. Example: nohup ping 8.8.8.8 &.

    39. To modify a the priority of an existing process, we can use the _____ command.

    • renice
    • nice
    • ps
    • top

    Correct answer:

    • renice

    Explaination: The renice command allows us to change the priority ("niceness") of a process that is already running. Example: renice -10 -p 1127.

    40. True or false: A regular user can only lower the process niceness one time.

    • True
    • False

    Correct answer:

    • True

    Explaination: A normal user can only lower the niceness of a process one time. The root user can do so multiple times.

    41. Which of the following utilities makes use of regular expressions? Select all that apply.

    • grep
    • egrep
    • sed
    • ps

    Correct answer:

    • grep
    • egrep
    • sed

    Explaination: The grep, egrep, and sed utilities make use of regular expressions for pattern matching.

    42. Which regular expression symbol matches any characters from a list provided with that symbol?

    • [ ]
    • ( )
    • *
    • ?

    Correct answer:

    • [ ]

    Explaination: Brackets ([ ]) provide a list of characters, and match any characters provided in the brackets. Example grep 'l[oe]t' would match "lot" and "let."

    43. Which grep option can be used to search an entire directory and its sub directories?

    • -r
    • *
    • -R
    • .

    Correct answer:

    • -r

    Explaination: The recursive (-r) option with grep will cause grep to search an entire directory and its sub directories. Example: grep -r 'kodekloud' /etc/.

    44. In vi normal mode, the pp command will paste. Which command can be used to copy?

    • cc
    • yy
    • :copy
    • :yank

    Correct answer:

    • yy

    Explaination: The "yy" command will copy (yank) text.

    45. When using vi in normal mode, which command will delete the line at the cursor?

    • d
    • dd
    • yy
    • ZZ

    Correct answer:

    • dd

    Explaination: Pressing "d" twice or "dd" will delete the line at the current cursor position.

    46. The two types of partition tables commonly used in Linux are (select two):

    • MBR
    • GPT
    • DVH
    • BSD

    Correct answer:

    • MBR
    • GPT

    Explaination: Linux commonly uses MBR and GPT partition tables (though others are supported).

    47. Which of the following are features of BTRFS? Select all that apply.

    • compression
    • subvolumes
    • snapshots
    • encryption

    Correct answer:

    • compression
    • subvolumes
    • snapshots

    Explaination: BTRFS supports compression, subvolumes, and snapshots.

    48. In addition to vi, what are some other common editors for Linux?

    • nano
    • Emacs
    • Word
    • notes

    Correct answer:

    • nano
    • Emacs

    Explaination: GNU nano and Emacs are common editors in addition to vi.

    49. Which command can be used to determine how much disk space is available?

    • du
    • df
    • free
    • diskfree

    Correct answer:

    • df

    Explaination: The "disk free" (df) command can be used to see how much free space is left on a disk.

    50. Which utility can be used to check and repair XFS filesystems?

    • xfs_repair
    • xfs_fsck
    • xfs_check
    • xfs_fix

    Correct answer:

    • xfs_repair

    Explaination: The xfs_repair command can be used to check and repair XFS filesystems.

    51. Which command can be used to show information about all block devices on the system?

    • lsblk
    • mount
    • disks
    • ls /dev/

    Correct answer:

    • lsblk

    Explaination: The lsblk command will show information about all block devices on the system and their filesystems.

    52. When trying to unmount a filesystem, you get an error saying the target is busy. Which command can you use to see the program that is keeping the disk busy?

    • lsof
    • lsfiles
    • iowait
    • lsio

    Correct answer:

    • lsof

    Explaination: The "list open files" or "lsof" command can be used to see which program is currently using files on a disk that is busy. Example: lsof /dev/sda1.

    53. A file named "myfile" has the user owner "kodekloud" and the group owner "users." Which command(s) could be use to change the group owner to "friends"? Select all that apply.

    • chgrp friends myfile
    • chown kodekloud:friends myfile
    • chgrp myfile friends
    • chown myfile kodekloud:friends

    Correct answer:

    • chgrp friends myfile
    • chown kodekloud:friends myfile

    Explaination: The chgrp command can be used to change group ownership, and the chown command can also be used if the group is specified after a user owner and a colon. With both commands, the group comes before the file name.

    54. In addition to the device's disk identifier and partition number (e.g., /dev/sda1), what else can be used in /etc/fstab to identify a partition? Select all that apply.

    • UUID
    • blkid
    • label
    • FSID

    Correct answer:

    • UUID
    • label

    Explaination: Both the UUID and the filesystem label can be used in /etc/fstab to identify a filesystem.

    55. Which command would change the permissions of the file "myfile" to read, write, and execute for the user owner, read and write for the group owner, and no permissions for all other users? Select all that apply.

    • chmod 760 myfile
    • chmod 660 myfile
    • chmod u=rwx,g=rw,u= myfile
    • chmod u=rw,g=rw=u= myfile

    Correct answer:

    • chmod 760 myfile
    • chmod u=rwx,g=rw,u= myfile

    Explaination: We can use octal, where 7 is "read, write, and execute" for the user owner, 6 is "read and write" for the group owner, and 0 is "nothing" for all other users, or we can use ugo format, were u=rwx gives "read, write, and execute" to the user owner, g=rw gives "read and write" to the group owner, and u= gives nothing to all other users.

    56. To add execute permissions for the user-owner of a file to existing permissions, which command would you use?

    • chmod u+x
    • chmod +x
    • chmod u-x
    • chmod -x

    Correct answer:

    • chmod u+x

    Explaination: The command chmod u+x would add execute permissions for the file's user-owner while keeping all other existing permissions.

    57. True or false: When a hard link is deleted, the original file is also deleted.

    • True
    • False

    Correct answer:

    • True

    Explaination: A hard link is treated as the original file, but in a different location. If a hard link is deleted, the original file is also deleted.

    58. True or false: When a soft link is deleted, the original file is also deleted.

    • True
    • False

    Correct answer:

    • False

    Explaination: A soft link points to the original file, but is not considered to be the same as the original file. Therefore, a soft link can be deleted while leaving the original file intact.

    59. The standard layout for Linux directories and their contents, as determined by the Linux Foundation, is known as the _____.

    • Filesystem Hierarchy Standard
    • Filesystem Standard Hierarchy
    • Hierarchical Filesystem Standard
    • Standard Hierarchical Filesystem

    Correct answer:

    • Filesystem Hierarchy Standard

    Explaination: The Filesystem Hierarchy Standard (FHS) is a layout determined by the Linux Foundation as an option (but encouraged) standard for Linux directories and their contents.

    60. Removable storage, such as CD-ROMs and flash drives are mounted to the _____ directory.

    • /mnt
    • /media
    • /home
    • /run

    Correct answer:

    • /media

    Explaination: According to the FHS, user-mountable removable media such as flash drives and CD-ROMS should be mounted to the /media directory.


    LPIC-mock-3

    1. Which command would you use to view only the last ten lines of the initialization log?

    • dmesg --last
    • dmesg | tail
    • lastlog
    • dmesg -H

    Correct answer:

    • dmesg | tail

    Explaination: Directing the output of dmesg to the tail command will only show the last ten lines of the initialization log.

    2. On SysV systems, which file contains the default init configuration?

    • /etc/init.d/defaults
    • /etc/defaults/inittab
    • /etc/inittab
    • /etc/conf.d/inittab

    Correct answer:

    • /etc/inittab

    Explaination: The default init configuration is stored in /etc/inittab on SysV systems.

    3. A friend is visiting you and brings a portable USB hard drive to share some files with you. You have one SATA drive in your Linux machine. Which name will be given to your friend's portable USB hard drive in the /dev/ directory of your Linux machine?

    • /dev/sata2
    • /dev/sba
    • /dev/sdb
    • /dev/usb1

    Correct answer:

    • /dev/sdb

    Explaination: In Linux, USB drives are treated as SATA drives and follow the same naming conventions. Your initial drive is already identified as /dev/sda, so your friend's USB hard drive will be identified as /dev/sdb.

    4. Given a theoretical file located at /etc/rc3.d/S45 ethernet, what would happen to any services listed in this file when the system enters runlevel 3?

    • They will stop.
    • They will start.
    • They will be suspended.
    • They will be restarted.

    Correct answer:

    • They will start.

    Explaination: The letter "S" at the beginning of the file name indicates that services listed in this file will be started.

    5. You have added a new hard drive to a system. You know that the hard drive has no defects, but the system cannot boot. Where would you go to begin troubleshooting this problem?

    • The BIOS setup utility.
    • The manual for the hard drive.
    • The manufacturer's website.
    • An Internet forum.

    Correct answer:

    • The BIOS setup utility.

    Explaination: The BIOS setup utility is the correct place to begin troubleshooting this hardware problem. It could be that the boot device order is incorrect.

    6. Which filesystem would you use for the ESP partition?

    • ext2
    • fat32
    • xfs
    • ntfs

    Correct answer:

    • fat32

    Explaination: EFI System Partitions (ESP) should use a FAT filesystem, like FAT12, FAT16, or FAT32.

    7. You have compiled a custom kernel, and the filesystem type used by your Linux system's root filesystem is compiled as a module. What would you need to include along with the kernel to make sure your system loads the root filesystem correctly?

    • initramfs
    • EFI applications
    • A copy of /etc/modules.conf.d/
    • bootstrap

    Correct answer:

    • initramfs

    Explaination: An initial RAM filesystem (initramfs) should be included if the root filesystem is compiled as a module.

    8. Using systemctl, how would you determine if a service named myservice.service is configured to start when the system boots?

    • systemctl status myservice.service
    • systemctl is-enabled myservice.service
    • systemctl is-active myservice.service
    • systemctl on-boot myservice.service

    Correct answer:

    • systemctl is-enabled myservice.service

    Explaination: The is-enabled option for systemctl will return "enabled" if a service is enabled to start at boot, or "disabled" if it is not.

    9. When a Linux system mounts the EFI partition, where is it usually mounted?

    • /boot/efi/
    • /boot/grub/efi/
    • /mnt/efi/
    • /efi/

    Correct answer:

    • /boot/efi/

    Explaination: Linux usually mounts the EFI partition at /boot/efi/.

    10. In addition to swap partitions, Linux can make use of swap files. Where is the swap file typically located?

    • /mnt/swap
    • /swapfile
    • /mnt/swapfile
    • /swap

    Correct answer:

    • /swapfile

    Explaination: If used, a swap file is typically located at /swapfile on Linux systems.

    11. Which apt-cache command will provide information for a package?

    • apt-cache show
    • apt-cache info
    • apt-cache print
    • apt-cache search

    Correct answer:

    • apt-cache show

    Explaination: The apt-cache show command, followed by a package name, will provide information for a package.

    12. On a Debian system, which command would remove a package and all of its configuration files?

    • dpkg -r
    • dpkg --remove
    • dkpg --erase
    • dpkg -P

    Correct answer:

    • dpkg -P

    Explaination: Running dpkg with the -P (purge) flag will remove a package and all of its configuration files.

    13. Which parameter would you add to dpkg-query to show which package contains a particular file?

    • -s
    • -S
    • -l
    • -W

    Correct answer:

    • -S

    Explaination: Using the -S parameter with dpkg-query will show which package contains a particular file.

    14. If you update the configuration for GRUB 2, which command would you run to write that configuration to the correct directory for GRUB 2 to use the next time you boot the system?

    • grub-config -o /boot/grub/grub.cfg
    • grub-mkconfig -o /boot/grub/grub.cfg
    • grub-mkconfig -o /boot/grub/grub.conf
    • grub-config -o /boot/grub/grub.conf

    Correct answer:

    • grub-mkconfig -o /boot/grub/grub.cfg

    Explaination: After updating the configuration for GRUB 2, you must run grub-mkconfig -o /boot/grub/grub.cfg to make GRUB 2 use the changes on the next system boot.

    15. When using GRUB 2, which menu entry parameter determines how long GRUB 2 will pause before booting the default menu entry?

    • GRUB_TIMEOUT=
    • GRUB_WAIT=
    • GRUB_PAUSE=
    • GRUB_TIMER=

    Correct answer:

    • GRUB_TIMEOUT=

    Explaination: The menu entry that controls how long GRUB 2 will pause before booting the default menu entry is GRUB_TIMEOUT=.

    16. The naming format for shared libraries is:

    • libraryname.so.versionnumber
    • libraryname.versionnumber.so
    • libraryname-versionnumber.so
    • libraryname-so.versionnumber

    Correct answer:

    • libraryname.so.versionnumber

    Explaination: The naming format for shared libraries is the library name . so suffix . version number. Example: libpthread.so.1.

    17. Which yum command will bring repository metadata to the most recent version?

    • yum update
    • yum metadata
    • yum upgrade
    • yum check-metadata

    Correct answer:

    • yum update

    Explaination: The yum update command will update repository metadata.

    18. Using YUM or DNF, which option would uninstall a package from the system, along with any packages that depend on that package?

    • remove
    • purge
    • uninstall
    • delete

    Correct answer:

    • remove

    Explaination: Using YUM or DNF, the remove option will uninstall a package from the system, along with all packages that depend on it. Example: dnf remove httpd.

    19. If you are unsure of the location of an executable mycommand on a Linux system, how would you find it?

    • whereis mycommand
    • which mycommand
    • find mycommand
    • fetch mycommand

    Correct answer:

    • which mycommand

    Explaination: The which command provides the location of a specified executable. While it is possible to use find to locate the executable, it would require more options than were shown with that answer choice, and is not as straightforward or fast as using which for this task.

    20. Where are repository files stored for DNF and YUM?

    • /etc/repos.d/
    • /etc/yum.repos.d/
    • /etc/yum/repos/
    • /etc/yum/repos.d/

    Correct answer:

    • /etc/yum.repos.d/

    Explaination: Repository files (.repo) are stored in /etc/yum.repos.d/.

    21. Which type of virtualization requires the guest to be capable of running all instructions on virtual hardware?

    • full virtualization
    • paravirtualization
    • hybrid virtualization
    • bare metal

    Correct answer:

    • full virtualization

    Explaination: Fully virtualized machines must be able to run all instructions on the virtual hardware. They are not aware that they are running as virtual machines.

    22. You have set a variable called kodekloud using the export command. Which command would print the value of the kodekloud variable?

    • print kodekloud
    • echo kodekloud
    • echo $kodekloud
    • read $kodekloud

    Correct answer:

    • echo $kodekloud

    Explaination: The echo command will print the value of a variable, and the variable name must have a $ before it. Example: echo $kodekloud will return the value assigned to the kodekloud variable.

    23. Before the apropos command will work on a new system, it may be necessary to run another command first. Which command would you run to make sure apropos has access to all of the information it needs?

    • apropos -update
    • updatedb
    • dbupdate
    • mandb

    Correct answer:

    • mandb

    Explaination: The mandb command must be run to update the database for apropos. Otherwise, apropos will not have any results to return.

    24. Which command is used to search the short description of man pages for keywords?

    • apropos
    • grep
    • find
    • cat

    Correct answer:

    • apropos

    Explaination: Each manual page has a short description available within it and apropos searches the descriptions for instances of keyword.

    25. The _____ command can be used to perform search and replace operations on text files.

    • grep
    • sed
    • find
    • substitute

    Correct answer:

    • sed

    Explaination: The sed command can be used to perform search and replace operations on text files.

    26. Which command can be used to print only the desired field from text?

    • sed
    • grep
    • cut
    • find

    Correct answer:

    • cut

    Explaination: The cut command can specify which field(s) to print from text.

    27. Which command can be used to rename an existing file or directory?

    • mv
    • cp
    • touch
    • ls

    Correct answer:

    • mv

    Explaination: The mv command can be used to rename an existing file or directory by "moving" it from the original name to the new name. Example: mv myfile myfile2.

    28. To remove a directory called mydir along with all of its files and subdirectories, which command would you use?

    • rm mydir
    • rm -R mydir
    • rm -rf mydir
    • rm mydir/*

    Correct answer:

    • rm -rf mydir

    Explaination: To remove a directory along with its files and subdirectories, we have to specify the -r (recursive) option, and will also need to specify the -f (force) option.

    29. Which command would take the contents of the /home/kodekloud/ directory and create a gzipped tar archive of the contents in a file called kodekloud.tar.gz?

    • tar -czvf kodekloud.tar.gz /home/kodekloud/
    • tar -czvf /home/kodekloud/ kodekloud.tar.gz
    • tar -cvf kodekloud.tar.gz /home/kodekloud/
    • tar -cvf /home/kodekloud/ kodekloud.tar.gz

    Correct answer:

    • tar -czvf kodekloud.tar.gz /home/kodekloud/

    Explaination: When using tar to create gzipped tar archives, we must use the create (c), gzip (z), and file (f) options, followed by the name of the file we wish to create (kodekloud.tar.gz), and finally, the directory or files we wish to archive and compress (/home/kodekloud/).

    30. Which option can be used with ls to show hidden files?

    • -a
    • -h
    • --hidden
    • -?

    Correct answer:

    • -a

    Explaination: The -a option with ls will show "all" including hidden files that begin with a period (.).

    31. Which command could be used to create an archive named backup.cpio containing all of the files and directories in the current working directory?

    • cpio -o > backup.cpio
    • ls | cpio -o > backup.cpio
    • cpio * > backup.cpio
    • cpio -o * > backup.cpio

    Correct answer:

    • ls | cpio -o > backup.cpio

    Explaination: Since cpio takes its file list as input from standard input, we would use the output of the ls command to list the files and directories in the current working directory and pass that to cpio as input. The -o option with cpio tells cpio to create an archive, and the > operator is used before the archive's filename to direct cpio to create the archive with that name.

    32. Which of the following would search the contents of the /etc/ directory for the pattern "kodekloud" and write only the errors to a file a /home/kodekloud/errors.list?

    • grep -r 'kodekloud' /etc/ > /home/kodekloud/errors.list
    • grep -r 'kodekloud' /etc/ 2> /home/kodekloud/errors.list
    • grep -r 'kodekloud' /etc/ 2>&1 /home/kodekloud/errors.list
    • grep -r 'kodekloud' /etc/ 1> /home/kodekloud/errors.list

    Correct answer:

    • grep -r 'kodekloud' /etc/ 2> /home/kodekloud/errors.list

    Explaination: The operator "2>" would cause stderr to be written to the file at "/home/kodekloud/errors.list" while the stdout content would be displayed to the screen.

    33. Which command would search the /etc/ directory for the pattern "kodekloud" and redirect all output (stdout and stderr) to the file at /home/kodekloud/output.list?

    • grep -r 'kodekloud' /etc/ 2> /home/kodekloud/output.list
    • grep -r 'kodekloud' /etc/ 1> /home/kodekloud/output.list
    • grep -r 'kodekloud' /etc/ > /home/kodekloud/output.list
    • grep -r 'kodekloud' /etc/ &> /home/kodekloud/output.list

    Correct answer:

    • grep -r 'kodekloud' /etc/ &> /home/kodekloud/output.list

    Explaination: The operator "&>" will direct both stderr and stdout to a file. This will cause the file to contain all of the contents that would normally be seen on the screen, including error messages.

    34. The default configuration file for tmux is located at _____.

    • /etc/tmux.conf.d/tmux.conf
    • /etc/tmux.conf
    • /etc/conf/tmux.conf
    • /etc/tmux/conf/tmux.conf

    Correct answer:

    • /etc/tmux.conf

    Explaination: The default configuration file for tmux is located at /etc/tmux.conf.

    35. Which operator can be used to append text to a file, without overwriting the existing contents?

    • ">"
    • ">>"
    • "<<"
    • "<"

    Correct answer:

    • ">>"

    Explaination: The ">>" operator will append text to a file without overwriting the existing contents.

    36. To view dynamically updated information on system processes and resources, we can use the _____ command.

    • top
    • ps
    • jobs
    • uptime

    Correct answer:

    • top

    Explaination: The top command provides dynamically updated information on processes and system resources, such as CPU usage and RAM.

    37. To get detailed information about a process when we already have the PID (process ID), we can use the _____ command.

    • proc
    • pgrep
    • ps
    • pkill

    Correct answer:

    • ps

    Explaination: The ps command provides detailed information about a process when we already know the PID. Example: ps 1127.

    38. To set the priority for a process when it is run, we can use the _____ command.

    • nice
    • renice
    • top
    • ps

    Correct answer:

    • nice

    Explaination: The nice command allows us to set the process priority ("niceness") when a command is run. Example: nice -n 15 top.

    39. The default configuration file for GNU screen is located at _____.

    • /etc/screenrc
    • /etc/screen/screenrc
    • /etc/screen.conf.d/screenrc
    • /etc/screen/conf/screenrc

    Correct answer:

    • /etc/screenrc

    Explaination: The default configuration file for GNU screen is located at /etc/screenrc.

    40. Which command(s) can we use to view the priority of a process that is already running? Select all that apply.

    • ps
    • top
    • nice
    • renice

    Correct answer:

    • ps
    • top

    Explaination: Both the ps command (with the -el or -Al flags) and the top command can be used to view the priority of a process that is already running.

    41. Which option can be used with grep when the case (upper or lower) of the term does not matter?

    • -i
    • -e
    • -f
    • -k

    Correct answer:

    • -i

    Explaination: The ignore-case (-i) option can be used when the case of the term does not matter.

    42. When using vi, in normal mode, which key allows us to search the file?

    • /
    • s
    • f
    • t

    Correct answer:

    • /

    Explaination: The / character allows us to specify a search term while in normal mode.

    43. In command mode, which command will allow us to save changes and exit vi?

    • :wq
    • :q
    • :q!
    • :w

    Correct answer:

    • :wq

    Explaination: The command :wq or "write and quite" will allow us to save changes and exit vi.

    44. Which option for sed indicates that every instance of a term should be replaced?

    • g
    • *
    • a
    • ?

    Correct answer:

    • g

    Explaination: The global (g) option with sed indicates that every instance of a term should be replaced. Example: sed 's/day/night/g'.

    45. When using vi in normal mode, which command will delete the line at the cursor?

    • d
    • dd
    • yy
    • ZZ

    Correct answer:

    • dd

    Explaination: Pressing "d" twice or "dd" will delete the line at the current cursor position.

    46. Which of the following are features of BTRFS? Select all that apply.

    • compression
    • subvolumes
    • snapshots
    • encryption

    Correct answer:

    • compression
    • subvolumes
    • snapshots

    Explaination: BTRFS supports compression, subvolumes, and snapshots.

    47. Which grep option can be used to search an entire directory and its sub directories?

    • -r
    • *
    • -R
    • .

    Correct answer:

    • -r

    Explaination: The recursive (-r) option with grep will cause grep to search an entire directory and its sub directories. Example: grep -r 'kodekloud' /etc/.

    48. Which methods can be used on Linux to move memory pages from RAM to the hard disk?

    • swap partition
    • swap file
    • virtual memory
    • disk cache

    Correct answer:

    • swap partition
    • swap file

    Explaination: Swap partitions and swap files can be used to move memory pages from RAM to the hard disk.

    49. Which command can be used to determine how much disk space is available?

    • du
    • df
    • free
    • diskfree

    Correct answer:

    • df

    Explaination: The "disk free" (df) command can be used to see how much free space is left on a disk.

    50. Which command can be used to show information about all block devices on the system?

    • lsblk
    • mount
    • disks
    • ls /dev/

    Correct answer:

    • lsblk

    Explaination: The lsblk command will show information about all block devices on the system and their filesystems.

    51. When trying to unmount a filesystem, you get an error saying the target is busy. Which command can you use to see the program that is keeping the disk busy?

    • lsof
    • lsfiles
    • iowait
    • lsio

    Correct answer:

    • lsof

    Explaination: The "list open files" or "lsof" command can be used to see which program is currently using files on a disk that is busy. Example: lsof /dev/sda1.

    52. Before checking a filesystem for errors and repairing any that are found, you should first use the ____ command on the filesystem to get it ready for this process.

    • mount
    • fsck
    • xfs_repair
    • umount

    Correct answer:

    • umount

    Explaination: A filesystem must first be offline for errors to be repaired, so a mounted filesystem must be unmounted before running fsck or xfs_repair.

    53. In addition to the device's disk identifier and partition number (e.g., /dev/sda1), what else can be used in /etc/fstab to identify a partition? Select all that apply.

    • UUID
    • blkid
    • label
    • FSID

    Correct answer:

    • UUID
    • label

    Explaination: Both the UUID and the filesystem label can be used in /etc/fstab to identify a filesystem.

    54. To add execute permissions for the user-owner of a file to existing permissions, which command would you use?

    • chmod u+x
    • chmod +x
    • chmod u-x
    • chmod -x

    Correct answer:

    • chmod u+x

    Explaination: The command chmod u+x would add execute permissions for the file's user-owner while keeping all other existing permissions.

    55. A file named "myfile" has the user owner "kodekloud" and the group owner "users." Which command(s) could be use to change the group owner to "friends"? Select all that apply.

    • chgrp friends myfile
    • chown kodekloud:friends myfile
    • chgrp myfile friends
    • chown myfile kodekloud:friends

    Correct answer:

    • chgrp friends myfile
    • chown kodekloud:friends myfile

    Explaination: The chgrp command can be used to change group ownership, and the chown command can also be used if the group is specified after a user owner and a colon. With both commands, the group comes before the file name.

    56. Which command would change the permissions of the file "myfile" to read, write, and execute for the user owner, read and write for the group owner, and no permissions for all other users? Select all that apply.

    • chmod 760 myfile
    • chmod 660 myfile
    • chmod u=rwx,g=rw,u= myfile
    • chmod u=rw,g=rw=u= myfile

    Correct answer:

    • chmod 760 myfile
    • chmod u=rwx,g=rw,u= myfile

    Explaination: We can use octal, where 7 is "read, write, and execute" for the user owner, 6 is "read and write" for the group owner, and 0 is "nothing" for all other users, or we can use ugo format, were u=rwx gives "read, write, and execute" to the user owner, g=rw gives "read and write" to the group owner, and u= gives nothing to all other users.

    57. You see myphoto.jpg -> photo in the output of the ls command. What type of link does this show?

    • Hard
    • Soft

    Correct answer:

    • Soft

    Explaination: Symbolic or "soft" links are indicated by -> in the output of ls.

    58. Removable storage, such as CD-ROMs and flash drives are mounted to the _____ directory.

    • /mnt
    • /media
    • /home
    • /run

    Correct answer:

    • /media

    Explaination: According to the FHS, user-mountable removable media such as flash drives and CD-ROMS should be mounted to the /media directory.

    59. Which command would create a soft link between myphoto.jpg and /home/kodekloud/photo?

    • ln -s myphoto.jpg /home/kodekloud/photo
    • ln -s /home/kodekloud/photo myphoto.jpg
    • ln myphoto.jpg /home/kodekloud/photo
    • ln /home/kodekloud/photo myphoto.jpg

    Correct answer:

    • ln -s myphoto.jpg /home/kodekloud/photo

    Explaination: The ln -s command creates a soft link, and the format for ln in the specify the file being linked (myphoto.jpg) and then the target (/home/kodekloud/photo).

    60. Temporary files can be located in _____. Select any that apply.

    • /tmp
    • /var/tmp
    • /run
    • /usr/tmp

    Correct answer:

    • /tmp
    • /var/tmp
    • /run

    Explaination: According to the FHS, temporary files that are cleared during system boot are stored in /tmp; temporary files that are not cleared during system boot are stored in /var/tmp; run-time data used by running processes is stored in /run.


    PCA mock 2

    1. You are writing an exporter for RabbitMQ and are creating a metric to track the size of the message queue. Which of the following would be an appropriate name for the metric.

    • rabbitmq_message_kilobytes
    • message_rabbitmq_bytes
    • rabbitmq_message_bytes
    • bytes_rabbitmq_message

    Correct answer:

    • rabbitmq_message_bytes

    Explaination: When naming metrics, the first word should be the application/library which in this case is rabbitmq. The name second part of the metric name should be the metric name. The last part of the name should be the unit which should be unprefixed so that means we prefer bytes, seconds over kilobytes and milliseconds

    2. Which of the following components is responsible for receiving metrics from short lived jobs?

    • alertmanager
    • prometheus
    • exporter
    • pushgateway

    Correct answer:

    • pushgateway

    Explaination: Short lived jobs should push metrics to pushgateway before exiting. Prometheus can then scrape the pushgateway like any other target

    3. What is the default port that Prometheus listens on?

    • 9100
    • 9200
    • 9090
    • 9001

    Correct answer:

    • 9090

    Explaination: Prometheus listens on port 9090 by default

    4. kafka_topic_partition_replicas metric tracks the number of partitions for a topic/partition. Which query will get the number of partitions for the past 2 hours. Result should return a range vector

    • kafka_topic_partition_replicas[2h]
    • kafka_topic_partition_replicas offset 2h
    • kafka_topic_partition_replicas<2h>
    • kafka_topic_partition_replicas range 2h

    Correct answer:

    • kafka_topic_partition_replicas[2h]

    Explaination: To get value of time series for the past 2hours use a range selector of [2h]. This will return a range vector with the value of the metric for the past 2 hours.

    5. How many labels does the following time series have node_fan_speed{instance="node8", job="server", fan="2"}

    • 3
    • 2
    • 1
    • 4

    Correct answer:

    • 3

    Explaination: There are 3 labels instance, job, fan.

    6. Which of the following is not a component of the Prometheus solution?

    • pushgateway
    • alertmanager
    • exporters
    • influxdb

    Correct answer:

    • influxdb

    7. What type of metric should be used for measuring a users heart rate?

    • counter
    • gauge
    • histogram
    • summary

    Correct answer:

    • gauge

    Explaination: Since heart rate can go up or down, a gauge metric should be used in this case.

    8. What type of database does Prometheus use?

    • Mysql
    • Postgres
    • Time-Series database
    • Mongo
    • dynamoDB
    • AuroraDB

    Correct answer:

    • Time-Series database

    Explaination: Prometheus uses a time series database

    9. What is this an example of? 99% availability with a median latency less than 300ms?

    • SLA
    • SLO
    • SLI
    • SLU

    Correct answer:

    • SLO

    Explaination: This is an example of an SLO. The SLI is the availability and latency, and the SLO is the target value or range for these SLIs, which in this case is 99% availability and 300ms latency. If this was an SLA it would state the consequences for not meeting the SLO.

    10. Which of the following is not a form of observability?

    • metrics
    • streams
    • logs
    • traces

    Correct answer:

    • streams

    Explaination: The three forms of observability are metrics, logs, and traces

    11. Which of the following would make for a good SLI?

    • request failures
    • disk utilization
    • memory utilization
    • Fan Speed
    • Server temperature

    Correct answer:

    • request failures

    Explaination: For good SLIs metrics, use metrics that impact the user's experience. Disk utilization, memory utilization, fan speed, and server temperature are not things that impact the user. Request failures will impact a user’s experience

    12. What are the different states a Prometheus alert can be in?

    • inactive, triggered, complete
    • ok, pending, firing
    • silenced, firing, triggered
    • inactive, pending, firing

    Correct answer:

    • inactive, pending, firing

    Explaination: Alerts can have 3 states: inactive - Alert expression has not returned any results pending - the state of an alert that has been active for less than the configured threshold duration firing - the state of an alert that has been active for longer than the configured threshold duration

    13. Which query below will give the 95% quantile of the metric http_file_upload_bytes?

    • histogram_quantile(0.95, http_file_upload_bytes_bucket)
    • http_file_upload_bytes(quantile=”0.95”}
    • http_file_upload_bytes < 95%
    • quantile(http_file_upload_bytes, 0.95)

    Correct answer:

    • histogram_quantile(0.95, http_file_upload_bytes_bucket)

    Explaination: For histogram metrics, to calculate a quantile use the histogram_quantile function. The function takes two arguments, the desired percentile, and the histogram metric, make sure to pass in the _bucket sub metric.

    14. What method does Prometheus use to collect metrics from targets?

    • push
    • pull
    • batch upload
    • rsync

    Correct answer:

    • pull

    Explaination: Prometheus follows a pull based model. The prometheus.yml file will have a list of all targets prometheus will need to scrape, which involves sending an http request to the target

    15. An application is advertising metrics at the path /monitoring/stats. What property in the scrape configs needs to be modified?

    • targets: [“node1:9100/monitoring/stats”]
    • metrics_path: “/monitoring/stats”
    • http_path: “/monitoring/stats”
    • scrape_path: “/monitoring/stats”

    Correct answer:

    • metrics_path: “/monitoring/stats”

    Explaination: the metrics_path property should be updated with the new path /monitoring/stats

    16. What command should be used to verify that a Prometheus config is valid?

    • prom-util validate config prometheus.yml
    • promcli check config prometheus.yml
    • promtool validate config prometheus.yml
    • promtool check config prometheus.yml

    Correct answer:

    • promtool check config prometheus.yml

    Explaination: Promtool is the cli utility used to verify prometheus configs. The check config subcommand will verify the prometheus config passed to it.

    17. What are the two attributes that metrics can have?

    • TYPE, HELP
    • INFO, CATEGORY
    • INFO, TYPE
    • HELP, INFO
    • TYPE, DESCRIPTION

    Correct answer:

    • TYPE, HELP

    Explaination: The two types of attributes metrics can have are: help - description of what the metric is type - specifies what type of metric(counter, gauge, histogram, summary)

    18. The metric mealplanner_consumed_calories tracks the number of calories that have been consumed by the user. What query will return the amount of calories that had been consumed 4 days ago?

    • mealplanner_consumed_calories[4d]
    • mealplanner_consumed_calories fallback 4d
    • mealplanner_consumed_calories{offset=”4d”}
    • mealplanner_consumed_calories offset 4d

    Correct answer:

    • mealplanner_consumed_calories offset 4d

    Explaination: To get the value of a metric 4 days ago, use the offset modifier and specify 4d

    19. What type of metric should be used to track the number of miles a car has driven?

    • counter
    • gauge
    • histogram
    • summary

    Correct answer:

    • counter

    Explaination: A counter metric should be used as the number of miles a car has been driven cannot go down.

    20. What is the name of the Prometheus query language?

    • PromQuery
    • PromSearch
    • PromQL
    • SQL

    Correct answer:

    • PromQL

    21. The metric node_fan_speed_rpm tracks the current fan speeds. The location label specifies where on the server the fan is located. Which query will return the fan speeds for all fans except the rear fan

    • node_fan_speed_rpm{location!=”rear”}
    • node_fan_speed_rpm<location!=”rear”>
    • node_fan_speed_rpm{location~=”rear”}
    • node_fan_speed_rpm{location!~”rear”}

    Correct answer:

    • node_fan_speed_rpm{location!=”rear”}

    Explaination: To match on all time series where location is not rear use the negative equality matcher !=

    22. Which of the following is not a valid time value to be used in a range selector?

    • 30s
    • 25m
    • 3hr
    • 2w
    • 80ms
    • 4y

    Correct answer:

    • 3hr

    Explaination: the time unit for hours is just h not hr

    23. What query will return all the instances whose active memory bytes is less than 10000?

    • node_memory_Active_bytes{< 10000}
    • node_memory_Active_bytes !< 10000
    • node_memory_Active_bytes < 10000
    • node_memory_Active_bytes > 10000

    Correct answer:

    • node_memory_Active_bytes < 10000

    Explaination: To return all time series less than 10000, use the < operator.

    24. With the following alertmanager configs, after a notification has been sent out, a new alert comes in. How long will alertmanager wait before firing a new notification?

    • 60s
    • 15m
    • 12hr
    • 5m
    • 80ms
    • 4y

    Correct answer:

    • 15m

    Code: route: receiver: staff group_by: ['severity'] group_wait: 60s group_interval: 15m repeat_interval: 12h routes: - matches: job: kubernetes receiver: infra group_by: ['severity']

    Explaination: The group_interval property determines how long alertmanager will wait after sending a notification, before it sends a new notification for a group.

    25. For metric_relabel_configs and relabel_configs, when matching on multiple source labels, what is the default delimiter

    • ;
    • :
    • -
    • =
    • /
    • ?

    Correct answer:

    • ;

    Explaination: The default delimiter is ;

    26. What does the following config do?

    • drops all targets with env, and team labels
    • scrapes all targets with env and team labels
    • drops all targets whose env label is set to dev and team label is set to marketing
    • sets the env and team` label on all targets for this job

    Correct answer:

    • drops all targets whose env label is set to dev and team label is set to marketing

    Code: scrape_configs:

    • job_name: example relabel_configs:
      • source_labels: [env, team] regex: dev;marketing action: drop

    Explaination: The source labels match on labels env and team. The regex field determines what values to match on for the labels. In this case it will match on env=dev and team=marketing. Since the action is drop, it means all targets with env=dev and team=marketing labels will be dropped. All other targets will get scraped

    27. Which of the following components is responsible for collecting metrics from an instance and exposing them in a format Prometheus expects?

    • exporters
    • alertmanager
    • pushgateway
    • Grafana
    • TSDB

    Correct answer:

    • exporters

    28. The metric node_filesystem_avail_bytes reports the available bytes for each filesystem on a node. Which query will return all filesystems that has either less than 1000 available bytes or greater than 50000 bytes

    • node_filesystem_avail_bytes < 1000 || node_filesystem_avail_bytes > 50000
    • node_filesystem_avail_bytes < 1000 or > 50000
    • node_filesystem_avail_bytes < 1000 || > 50000
    • node_filesystem_avail_bytes < 1000 or node_filesystem_avail_bytes > 50000

    Correct answer:

    • node_filesystem_avail_bytes < 1000 or node_filesystem_avail_bytes > 50000

    Explaination: To return all filesystems less than 1000 or greater than 50000, use the or operator.

    29. Which of the following is Prometheus’ built in dashboarding/visualization feature?

    • Go Templates
    • Grafana
    • client libraries
    • Console Templates

    Correct answer:

    • Console Templates

    30. What does the following config do?

    • The label fstype will be dropped for all metrics
    • All targets with the fstype label will not get scraped
    • The metric fstype will have all of its labels dropped
    • the metric fstype will get dropped

    Correct answer:

    • The label fstype will be dropped for all metrics

    Code: scrape_configs:

    • job_name: "demo" metric_relabel_configs:
      • regex: fstype action: labeldrop

    Explaination: metric_relabel_configs runs after metrics are scraped. The labeldrop action will drop the label matched from the regex field.

    31. The following time series return values with a lot of decimal values. What query will return values rounded down to the closest integer node_cpu_seconds_total {cpu="0", mode="idle"} 115.12​ {cpu="0", mode="irq"} 87.4482​ {cpu="0", mode="steal"} 44.245

    • ceil(node_cpu_seconds_total)
    • floor(node_cpu_seconds_total)
    • abs(node_cpu_seconds_total)
    • node_cpu_seconds_total @floor

    Correct answer:

    • floor(node_cpu_seconds_total)

    Explaination: To round the values down to nearest integer use the floor function

    32. The metric http_requests tracks the total number of requests across each endpoint and method. What query will return the total number of requests for each path

    • http_requests{path}
    • http_requests on path
    • sum by(path) (http_requests)
    • sum(http_requests{by=path}

    Correct answer:

    • sum by(path) (http_requests)

    Code: http_requests{method="get", path="/auth"} 3​

    http_requests{method="post", path="/auth"} 1​

    http_requests{method="get", path="/user"} 4​

    http_requests{method="post", path="/user"} 8​

    http_requests{method="post", path="/upload"} 2​

    http_requests{method="get", path="/tasks"} 4​

    http_requests{method="put", path="/tasks"} 6​

    http_requests{method="post", path="/tasks"} 1​

    http_requests{method="get", path="/admin"} 3​

    http_requests{method="post", path="/admin"} 9

    Explaination: To get the total number of requests for each path, a sum aggregator must be performed and since we want to group it by path a by clause on path should by used

    33. Which of the following is not a valid method for reloading alertmanager configuration?

    • restart alertmanager process
    • send a SIGHUP signal to alertmanager proces
    • HTTP post to /-/reload endpoint
    • hit the reload config button in alertmanager web-ui

    Correct answer:

    • hit the reload config button in alertmanager web-ui

    34. Which statement is true regarding Prometheus rules?

    • Groups are run sequentially and rules within a group are run in parallel
    • Groups are run in parallel and rules within a group are run sequentially
    • Groups and rules within a group are run in parallel
    • Groups and rules within a group are run sequentially

    Correct answer:

    • Groups are run in parallel and rules within a group are run sequentially

    35. Groups and rules within a group are run sequentially

    • Both Alert labels and annotations can be used for routing on Alertmanager
    • Both Alert labels and annotations are used purely for descriptive purposes
    • Alert labels can be used as metadata so alertmanager can match on them and performing routing policies, Annotations should be used for cosmetic descriptions of the alerts
    • Alert annotations can be used as metadata so alertmanager can match on them and performing routing policies, labels should be used for cosmetic description of the alerts

    Correct answer:

    • Alert labels can be used as metadata so alertmanager can match on them and performing routing policies, Annotations should be used for cosmetic descriptions of the alerts

    36. Where are alert rules defined?

    • In the Alertmanager.yml file
    • In the PushGateway
    • In the Prometheus.yml file
    • In a separate rules file on the Prometheus server

    Correct answer:

    • In a separate rules file on the Prometheus server

    Explaination: Alert rules are defined on the prometheus server in a separate rules file

    37. What update needs to occur to add an annotation called description that prints out the message redis server <insert instance name> is down!

    • description: "redis server <.Labels.instance> is down!"
    • description: "redis server $$.Labels.instance$$ is down!"
    • description: "redis server {{up{job=”redis”}}} is down!"
    • description: "redis server {{.Labels.instance}} is down!"

    Correct answer:

    • description: "redis server {{.Labels.instance}} is down!"

    Code:

    • name: redis-alerts rules: - alert: redis_down expr: up{job="redis"} == 0 labels: org: kodekloud

    Explaination: To create an annotation that will insert the instance name, the go templating language needs to be used. To access the instance label use {{.Labels.instance}}

    38. Analyze the alertmanager configs below : Based off the alert below, which receiver will send the notification for the alert alert labels: team: frontend

    • kodekloud
    • apple
    • general
    • kodekloud-pager

    Correct answer:

    • general

    Code: route: group_wait: 20s receiver: general group_by: ['alertname'] routes: - match: org: kodekloud receiver: kodekloud-pager - match: org: apple receiver: apple

    Explaination: The alert has only one label team: frontend which does not match any of the routes, so it fallsback to the default receiver which is general

    39. What data type do Prometheus metric values use?

    • Decimals
    • integers
    • strings
    • 64 bit floats

    Correct answer:

    • 64 bit floats

    Explaination: The alert has only one label team: frontend which does not match any of the routes, so it fallsback to the default receiver which is general

    40. The metric health_consumed_calories tracks how many calories a user has eaten and health_burned_calories tracks the number of calories burned while exercising. To calculate net calories for the day subtract health_burned_calories from health_consumed_calories. Based on the time series below, which expression successfully calculates net calories. health_consumed_calories{job="health", meal="dinner"} 800 health_burned_calories{job="health", activity="cardio"} 200

    • health_consumed_calories - health_burned_calories
    • health_consumed_calories - ignoring(meal, activity) health_burned_calories
    • health_consumed_calories - ignoring(meal) health_burned_calories
    • health_consumed_calories - ignoring(actvity) health_burned_calories

    Correct answer:

    • health_consumed_calories - ignoring(meal, activity) health_burned_calories

    Explaination: The health_consumed_calories has label meal that health_burned_calories does not have and health_burned_calories has the label activity that health_consumed_calories doesn’t have. To perform subtraction operation between the two, both labels will need to be ignored using the ignoring keyword

    41. Which component of the Prometheus architecture should be used to automatically discover all nodes in a Kubernetes cluster?

    • service discovery
    • exporters
    • push gateway
    • alertmanager

    Correct answer:

    • service discovery

    42. What is the purpose of Prometheus scrape_interval?

    • defines what targets to scrape
    • Defines how long to wait for a scrape before timing out
    • Defines how long Prometheus waits before clearing out the TSDB
    • Defines how frequently to scrape a target

    Correct answer:

    • Defines how frequently to scrape a target

    Explaination: scrape_interval configs determine how often to scrape a target. If scrape_interval is set to 30s then each target will get scraped every 30s

    43. A car reports the number of miles it has been driven with the metric car_total_miles Which query returns what is the average rate of miles the car has driven the past 2 hours. Use a 4m sample range and a query interval of 1m.

    • avg_over_time(rate(car_total_miles[4h]))
    • avg_over_time(rate(car_total_miles[4m])) [2h:1m]
    • avg_over_time(rate(car_total_miles[4m]) [2h:1m])
    • avg_over_time(rate(car_total_miles[4m]) [1m:2h])

    Correct answer:

    • avg_over_time(rate(car_total_miles[4m]) [2h:1m])

    Explaination: Since the question is asking for the what is the average rate of miles over the past 2 hours, rate function will need to be used: rate(car_total_miles[4m])

    To get the average over the past 2 hours use the avg_over_time function. The avg_over_time function requeries a range vector to be passed in, a subquery will need to be performed on the rate to get the range vector that contains the rate of errors for the past 2 hours. Since we need the average for the past 2hours, the first value in the subquery is going to be 2h and the second number is the query interval. Thus the final query looks like:

    avg_over_time(rate(car_total_miles[4m]) [2h:1m])

    44. Which query will return whether or not a target is currently able to be scraped?

    • status
    • up
    • scrape
    • reachability

    Correct answer:

    • up

    Explaination: the up query will return a 1 if a target is able to be successfully scraped and a 0 if it is not

    45. Which statement is true about the rate/irate functions?

    • rate() calculates average rate over entire interval, irate() calculates the rate only between the last two datapoints in an interval
    • rate() and irate() operate in the same exact way
    • rate() calculates rate by using the first two datapoints over an interval, irate() calculates the rate only between the last two datapoints in an interval
    • irate() calculates average rate over entire interval, rate() calculates the rate only between the last two datapoints in an interval

    Correct answer:

    • rate() calculates average rate over entire interval, irate() calculates the rate only between the last two datapoints in an interval

    46. Which configuration in alertmanager will wait 2 minutes before firing off an alert to prevent unnecessary notifications getting sent?

    • group_wait: 2m
    • group_interval: 2m
    • repeat_interval: 2m
    • group_cache: 2m

    Correct answer:

    • group_wait: 2m

    Explaination: When an alert arrives on alertmanager, alertmanager will wait the amount of time specified on group_wait, to wait for other alerts to arrive before firing off a notification.

    47. What does the following config do?

    • Targets with label team will get scraped, all other targets will be dropped
    • renames the organization label to team and the value of the label will get prepended with org-
    • the team label will get dropped
    • renames the team label to orginization and the value of the label will get prepended with org-

    Correct answer:

    • renames the team label to orginization and the value of the label will get prepended with org-

    Code: scrape_configs:

    • job_name: "example" metric_relabel_configs:
      • source_labels: [team] regex: (.*) action: replace target_label: organization replacement: org-$1

    Explaination: The metric_relabel_configs takes place after scraping metrics. The source_labels matches team and the action is set to replace. Which will replace the label name of teamwith thetarget_labelthat is specified. The value of the label will be changed to what is specified in the replacement field, which prependsorg-` to the value.

    48. The node_cpu_seconds_total metric tracks the number of seconds cpu has spent in a specific mode. The metric will break it down per cpu using the cpu label. Which query will return the total time all cpus on an instance spent in a mode that is not idle. Make sure to group the result on a per instance basis

    • sum by(instance) (node_cpu_seconds{mode!="idle"}
    • sum(node_cpu_seconds{mode!="idle"}
    • sum by(instance) (node_cpu_seconds{mode=~"idle"}

    Correct answer:

    • sum by(instance) (node_cpu_seconds{mode!="idle"}

    Code: node_cpu_seconds_total{cpu="0", instance="192.168.1.168:9100", job="test", mode="idle"} node_cpu_seconds_total{cpu="0", instance="192.168.1.168:9100", job="test", mode="iowait"} node_cpu_seconds_total{cpu="0", instance="192.168.1.168:9100", job="test", mode="irq"} node_cpu_seconds_total{cpu="0", instance="192.168.1.168:9100", job="test", mode="nice"} node_cpu_seconds_total{cpu="0", instance="192.168.1.168:9100", job="test", mode="softirq"} node_cpu_seconds_total{cpu="0", instance="192.168.1.168:9100", job="test", mode="steal"} node_cpu_seconds_total{cpu="0", instance="192.168.1.168:9100", job="test", mode="system"} node_cpu_seconds_total{cpu="1", instance="192.168.1.168:9100", job="test", mode="idle"} node_cpu_seconds_total{cpu="1", instance="192.168.1.168:9100", job="test", mode="iowait"} node_cpu_seconds_total{cpu="1", instance="192.168.1.168:9100", job="test", mode="irq"} node_cpu_seconds_total{cpu="1", instance="192.168.1.168:9100", job="test", mode="nice"} node_cpu_seconds_total{cpu="1", instance="192.168.1.168:9100", job="test", mode="softirq"} node_cpu_seconds_total{cpu="1", instance="192.168.1.168:9100", job="test", mode="steal"} node_cpu_seconds_total{cpu="1", instance="192.168.1.168:9100", job="test", mode="system"}

    Explaination: To sum up all modes except idle use the negative equality matcher mode!="idle" and use the sum aggregator. To group by instance use the by keyword and pass the instance label

    49. A database backup service has an slo that states that 97% of all backup jobs will be completed within 60s. A histogram metric is configured to track the backup process time, which of the following bucket configurations is recommended for the desired slo

    • 1, 5, 10, 25, 35, 50, 80, 90
    • 10, 25, 27, 30, 32, 35, 40, 50
    • 35, 45, 55, 60, 65, 75, 100
    • 1, 3, 8, 10, 12, 15, 17, 30, 40, 55, 65, 70

    Correct answer:

    • 35, 45, 55, 60, 65, 75, 100

    Explaination: Since histogram quantiles are approximations, to find out if a slo has been met, make sure that a bucket is specified at the desired slo value of 60s.

    50. What type of data should prometheus monitor?

    • Events
    • numeric
    • traces
    • system logs

    Correct answer:

    • numeric

    51. How is application instrumentation achieved?

    • pushgateway
    • alertmanager
    • Service discovery
    • Client libraries
    • grafana

    Correct answer:

    • Client libraries

    Explaination: Prometheus client libraries allow you to instrument applications.

    52. What is the purpose of repeat_interval in alertmanager?

    • how long to initially wait to send a group of alerts
    • How often to fire alerts to alertmanager
    • How long to wait before sending a notification again if it has already been sent successfully for an alert
    • How often to space out notifications for each group of alerts

    Correct answer:

    • How long to wait before sending a notification again if it has already been sent successfully for an alert

    Explaination: Prometheus client libraries allow you to instrument applications.

    53. Analayze alertmanager configs below. Based off the following alert which receiver will receive the notification alertname: node_filesystem_full labels: team: frontend notification: pager

    • frontend-email
    • frontend-pager
    • backend-email
    • general-email

    Correct answer:

    • frontend-pager

    Code: route: receiver: general-email group_by: [alertname] routes: - receiver: frontend-email matchers: - team: frontend routes: - matchers: notification: pager receiver: frontend-pager - receiver: backend-email matchers: - team: backend - receiver: auth-email matchers: - team: auth

    Explaination: Since the alert has the label team: frontend it will match the first route. The second label notification: pager will cause the alert to match the subroute and send it to frontend-pager

    54. What does the double underscore __ before a label name signify?

    • The label was set by a pushgateway
    • The label is a reserved label
    • The label is a malformed label
    • The label was set by a client library

    Correct answer:

    • The label is a reserved label

    55. What type of data does Prometheus collect?

    • events
    • logs
    • traces
    • numeric

    Correct answer:

    • numeric

    56. For a histogram metric, what are the different submetrics?

    • _count, _bucket
    • _bucket
    • _count, _bucket, _sum
    • _total, _sum, _bucket

    Correct answer:

    • _count, _bucket, _sum

    Explaination: Histogram metrics have 3 submetrics: count: total number of observations sum: sum of all observations bucket: number of observations for a specific bucket

    57. What is the default path Prometheus will scrape to collect metrics?

    • /metrics
    • /swagger-stats/metrics
    • /prometheus
    • /stats

    Correct answer:

    • /metrics

    58. The metric http_errors_total has 3 labels, path, method, error. Which of the following queries will give the total number of errors for a path of /auth, method of POST, and error code of 401?

    • http_errors_total
    • http_errors_total{path="/auth",method="POST",code="401"}
    • http_errors_total{path="/auth",method="POST"}
    • http_errors_total{path="/auth",method="PUT",code="401"}

    Correct answer:

    • http_errors_total{path="/auth",method="POST",code="401"}

    59. In the prometheus configuration, what is the purpose of the scheme field?

    • Determines if prometheus uses push or pull based model
    • Determines if prometheus will collect metrics or logs
    • Determines if prometheus will use http or https
    • Determines the format metrics are stored in the database

    Correct answer:

    • Determines if prometheus will use http or https

    60. What does the following config do?

    • Drops all targets with the docker_container_crash_total metric
    • renames the metric docker_container_crash_total to docker_container_restart_total
    • Drops the docker_container_crash_total metric
    • Replaces all labels fro docker_container_crash_total

    Correct answer:

    • renames the metric docker_container_crash_total to docker_container_restart_total

    Code: scrape_configs:

    • job_name: "demo" metric_relabel_configs:
      • source_labels: [name] regex: docker_container_crash_total action: replace target_label: name replacement: docker_container_restart_total

    Explaination: when the source_label matches on the label __name__ this represents the metrics name. In this case the field regex represents the name of the metric you want to match on. The action is set to replace, and the value of replacement will be the new name of the metric.


    Docker Engine Architecture

    1. By default, data stored inside the container is always persistent

    • True
    • False

    Correct answer:

    • False

    2. What are the components of the Docker Engine?

    • REST API, Docker Daemon
    • Images, Containers, Volumes
    • Docker Cli, Docker Daemon, REST API

    Correct answer:

    • Docker Cli, Docker Daemon, REST API

    3. What component of the docker engine manages the images, containers, volumes and networks on a host?

    • REST API
    • Docker Daemon
    • Docker CLI

    Correct answer:

    • Docker Daemon

    4. Which component is responsible for keeping the containers alive when the Docker Daemon goes down?

    • LibContainer
    • Runc
    • Containerd
    • Containerd-Shim

    Correct answer:

    • Containerd-Shim

    5. We can run containers without installing Docker.

    • True
    • False

    Correct answer:

    • True

    6. By default, Docker is configured to look for images on Google Cloud Registry

    • True
    • False

    Correct answer:

    • False

    7. What are the primary objects that Docker engine manages?

    • RunC
    • LibContainer
    • Containerd
    • Images, Containers, Volumes, Networks

    Correct answer:

    • Images, Containers, Volumes, Networks

    8. What component of the docker architecture is responsible for managing containers on Linux on version 1.15 of Docker Engine?

    • LibContainer
    • Docker API
    • LXC

    Correct answer:

    • LibContainer

    9. What does OCI stand for?

    • Open Communication Initiative
    • Open Container Initiative
    • Open Command Interface
    • Open Container Interface

    Correct answer:

    • Open Container Initiative

    10. Which component is a read-only template used for creating a Docker container?

    • Docker Network
    • Docker images
    • Container
    • Docker volume

    Correct answer:

    • Docker images

    11. Which is the default data directory for Docker?

    • /var/lib/docker
    • /var/log/docker
    • /etc/docker
    • /home/docker

    Correct answer:

    • /var/lib/docker

    12. What are the 2 specifications from OCI?

    • container-spec
    • runtime-spec
    • image-spec
    • oci-spec
    • libcontainer-spec

    Correct answer:

    • runtime-spec
    • image-spec

    13. What is the command to view the version of docker engine installed?

    • docker --version
    • docker version
    • docker engine info
    • docker info engine

    Correct answer:

    • docker version

    Docker Service Configuration

    1. What is the port conventionally used to configure un-encrypted traffic on TCP?

    • 2345
    • 2346
    • 2375
    • 2376

    Correct answer:

    • 2375

    2. What is the command used to list the running containers on the Docker Host?

    • docker container ls
    • docker container start
    • docker container stop
    • None of the above

    Correct answer:

    • docker container ls

    3. What file is used to configure the docker daemon?

    • /var/lib/docker/docker.conf
    • /var/lib/docker/daemon.json
    • /etc/docker/daemon.json
    • /etc/docker/daemon.conf

    Correct answer:

    • /etc/docker/daemon.json

    4. What flags are used to configure encryption on docker daemon?

    • tlsverify, tlscert, tlskey
    • tlsverify, key, cert
    • key, cert, tls
    • host, key, cert, tls

    Correct answer:

    • tlsverify, tlscert, tlskey

    5. On what interfaces are the docker daemon made available by default?

    • TCP socket
    • UDP socket
    • Unix Socket
    • 192.168.1.10

    Correct answer:

    • Unix Socket

    6. What is the default network driver used when a container is created?

    • overlay
    • bridge
    • none
    • host

    Correct answer:

    • bridge

    7. Which of the below commands create a container with nginx image and name nginx?

    • docker container create nginx --name nginx
    • docker container --name nginx nginx
    • docker container run nginx
    • docker container create --name nginx nginx

    Correct answer:

    • docker container create --name nginx nginx

    8. What is the command to start docker daemon manually?

    • docker
    • dockerd
    • docker-engine
    • docker --start-engine

    Correct answer:

    • dockerd

    9. How to list all running and stopped containers and their status?

    • docker container ls
    • docker container ls -a
    • docker container ls -aq
    • docker container ls -q

    Correct answer:

    • docker container ls -a

    10. How to start a stopped Container?

    • docker container rm nginx
    • docker container start nginx
    • docker container create nginx
    • docker container run nginx

    Correct answer:

    • docker container start nginx

    11. What is the option used in docker run command to attach to the terminal of the container in an interactive mode?

    • -f
    • -it
    • -i
    • -t

    Correct answer:

    • -it

    12. How do I get only the IDs of running containers?

    • docker container ls
    • docker container ls -a
    • docker container ls -aq
    • docker container ls -q

    Correct answer:

    • docker container ls -q

    13. You cannot start a killed container.

    • True
    • False

    Correct answer:

    • False

    14. What is the command to change the container name “httpd” to “webapp”?

    • docker container rename httpd webapp
    • docker container rename webapp httpd
    • docker container replace --name httpd webapp
    • docker container create --name webapp httpd

    Correct answer:

    • docker container rename httpd webapp

    15. What is the command to run a “nginx” container in a detached mode with name “webapp”?

    • docker container run -it --name webapp nginx
    • docker container run -it --name nginx webapp
    • docker container run -d --name webapp nginx
    • docker container run -d --name nginx webapp

    Correct answer:

    • docker container run -d --name webapp nginx

    16. Delete the stopped container named “webapp”.

    • docker container delete webapp
    • docker container remove webapp
    • docker container kill webapp
    • docker container rm webapp

    Correct answer:

    • docker container rm webapp

    Interacting with a Running Container

    1. Which combination of keys are used to escape from the shell and keep the container webapp running?

    • Ctrl+c
    • Ctrl+p+q
    • exit, Ctrl+p+q
    • Ctrl+c, exit

    Correct answer:

    • Ctrl+p+q

    2. You have a running container and want to execute a command inside it. Which command will you use?

    • execute
    • run
    • start
    • exec

    Correct answer:

    • exec

    3. How to display the running processes inside the container?

    • docker container top container-name
    • docker container stats container-name
    • docker ps container-name
    • docker container logs container-name

    Correct answer:

    • docker container top container-name

    4. You have a webapp container and image httpd. Inspect the logs of the webapp container. Which command is used to get the stream logs of the webapp container so that you can view the logs live?

    • docker container log webapp
    • docker container log -f webapp
    • docker container logs webapp
    • docker container logs -f webapp

    Correct answer:

    • docker container logs -f webapp

    5. Which combination of keys are used to exit from the shell and stop the container webapp?

    • Ctrl+c
    • Ctrl+p+q
    • Ctrl+p
    • Ctrl+z

    Correct answer:

    • Ctrl+c

    6. We deployed a container called webapp. Inspect this container to get the IPPrefixLen.

    • docker container inspect webapp | grep IPPrefixLen
    • docker container top webapp | grep IPPrefixLen
    • docker container run webapp | grep IPPrefixLen
    • docker container logs webapp | grep IPPrefixLen

    Correct answer:

    • docker container inspect webapp | grep IPPrefixLen

    7. We have deployed some containers. What command is used to get the container with the highest memory?

    • docker container stats
    • docker container status
    • docker container top
    • docker container ls

    Correct answer:

    • docker container stats

    8. Run a container called webapp with image nginx, and in an interactive mode.

    • docker container run -it nginx
    • docker container run -it nginx --name webapp
    • docker container run nginx
    • docker container run -it --name webapp nginx

    Correct answer:

    • docker container run -it --name webapp nginx

    9. Which command returns only new and/or live events?

    • docker system info
    • docker container events
    • docker container events -f
    • docker system events

    Correct answer:

    • docker system events

    10. Which command returns events since the past 30 minutes?

    • docker system events since 30m
    • docker system events --since 30m
    • docker container events --since 30m
    • docker container events since 30m

    Correct answer:

    • docker system events --since 30m

    11. Run a container named webapp with nginx image in detached mode. Select the right answer.

    • docker container run --detach --name=webapp nginx
    • docker container run --detach --name=nginx webapp
    • docker container create -d --name=nginx webapp
    • docker container create -d nginx

    Correct answer:

    • docker container run --detach --name=webapp nginx

    12. Delete the “webapp” Container. Select the right answer.

    • docker container delete webapp
    • docker container remove webapp
    • docker container kill webapp
    • docker container rm webapp

    Correct answer:

    • docker container rm webapp

    13. Stop the container named "nginx".

    • docker container halt nginx
    • docker container stop nginx
    • docker container rm nginx
    • docker container pause nginx

    Correct answer:

    • docker container stop nginx

    14. Which command is used to get the events of the container named "webapp"? (This one is for you to read the documentation)

    • docker system events since 10m
    • docker system events --filter 'container=webapp'
    • docker system events --filter 'image=webapp'

    Correct answer:

    • docker system events --filter 'container=webapp'

    15. How do you list running & stopped containers?

    • docker container ls -a
    • docker container ls -q
    • docker container ls
    • docker container ls -q, docker container ls

    Correct answer:

    • docker container ls -a

    16. Stop all running containers on the host. Select the right answer.

    • docker container stop $(docker container ls -a)
    • docker container rm $(docker container ls -q)
    • docker container stop $(docker container ls -q)
    • docker container stop --all

    Correct answer:

    • docker container stop $(docker container ls -q)

    17. Delete all running and stopped containers on the host. (Explore the documentation to identify an option to force remove running containers)

    • docker container stop $(docker container ls -q)
    • docker container rm $(docker container ls -q)
    • docker container stop $(docker container ps -q)
    • docker container rm -f $(docker container ls -aq)

    Correct answer:

    • docker container rm -f $(docker container ls -aq)

    18. What is the command to pause a running container?

    • docker container pause
    • docker container --pause
    • docker container halt
    • docker container SIGSTOP

    Correct answer:

    • docker container pause

    19. Which command is used to delete the stopped containers?

    • docker container remove $(docker container ls -aq)
    • docker container rm $(docker container ls -aq)
    • docker container prune
    • docker container rm --all

    Correct answer:

    • docker container prune

    20. What are the signals sent to a running container when the docker container stop command is executed?

    • SIGSTOP followed by SIGKILL
    • SIGTERM followed by SIGKILL
    • SIGKILL followed by SIGTERM
    • SIGKILL followed by SIGSTOP

    Correct answer:

    • SIGTERM followed by SIGKILL

    Restart Policies

    1. Run a container with image nginx, name nginx and hostname webapp.

    • docker container run -d --name webapp --hostname=webapp nginx
    • docker container run -d --name nginx webapp
    • docker container run -d --name nginx --hostname=webapp nginx
    • docker container run -d --name webapp nginx

    Correct answer:

    • docker container run -d --name nginx --hostname=webapp nginx

    2. Which policy would restart the containers even after the docker daemon is restarted?

    • unless-stopped
    • on-failure
    • always
    • always, unless-stopped

    Correct answer:

    • always

    3. What is the default restart policy?

    • unless-stopped
    • on-failure
    • no
    • always

    Correct answer:

    • no

    4. Which policy is used to restart a container unless it is explicitly stopped or Docker is restarted.

    • unless-stopped
    • on-failure
    • no
    • always

    Correct answer:

    • unless-stopped

    5. Which command can be used to check the restart policy of webapp container?

    • docker container inspect webapp
    • docker container info webapp
    • docker container check webapp
    • None of the above

    Correct answer:

    • docker container inspect webapp

    6. Restart container unless it is explicitly stopped or Docker is restarted.

    • unless-stopped
    • on-failure
    • no
    • always

    Correct answer:

    • unless-stopped

    7. Which command should be used to update the httpd container with the always policy?

    • docker container update --restart always httpd
    • docker container unpause --restart always httpd
    • docker container upgrade --restart always httpd

    Correct answer:

    • docker container update --restart always httpd

    8. What is the hostname set on the container when the following command is run : docker container run -d --name webapp httpd

    • webapp
    • apache
    • httpd
    • containers unique id

    Correct answer:

    • containers unique id

    9. Which command should be used to update all the running containers with unless-stopped policy?

    • docker container upgrade --restart unless-stopped $(docker container ls -q)
    • docker container update --restart unless-stopped $(docker container ls -q)
    • docker container upgrade --restart unless-stopped $(docker container ls -aq)
    • docker container update --restart unless-stopped $(docker container ls -aq)

    Correct answer:

    • docker container update --restart unless-stopped $(docker container ls -q)

    10. Which option is used to reduce container downtime due to daemon crashes, planned outages, or upgrades?

    • Restart Policy
    • Swarm
    • Live Restore
    • Restart Policy, Live Restore

    Correct answer:

    • Live Restore

    11. How to enable the live restore setting to keep containers alive when the daemon becomes unavailable?

    • echo '{"live-restore": true}' >> /etc/docker/daemon.json
    • echo '{"live-restore": true}' >> /var/lib/docker/daemon.json
    • echo '{true: "live-restore"}' >> /etc/docker/daemon.json
    • echo '{true: "live-restore"}' >> /var/lib/docker/daemon.json

    Correct answer:

    • echo '{"live-restore": true}' >> /etc/docker/daemon.json

    12. What is the path file which is used to add the live restore?

    • /etc/docker/daemon.json
    • /var/lib/docker/daemon.json
    • /var/log/docker/daemon.json
    • /var/lib/docker

    Correct answer:

    • /etc/docker/daemon.json

    13. Which of the below commands may be used to copy a file /web.conf from a container named webapp with id 89683681 to the /tmp directory on the host?

    • docker container cp /tmp/web.conf webapp:/etc/web.conf
    • docker container cp webapp:/web.conf /webapp
    • docker container cp 89683681:/web.conf /tmp/
    • docker container cp webapp:/web.conf /tmp/

    Correct answer:

    • docker container cp 89683681:/web.conf /tmp/
    • docker container cp webapp:/web.conf /tmp/

    14. Copy the /etc/nginx directory from the webapp container to the docker host under /tmp/.

    • docker container copy webapp:/etc/nginx /tmp/
    • docker container cp webapp:/etc/nginx /tmp/
    • docker container copy /tmp/ webapp:/etc/nginx
    • docker container cp /tmp/ webapp:/etc/nginx

    Correct answer:

    • docker container cp webapp:/etc/nginx /tmp/

    15. What is the command to copy the file /root/myfile.txt from the host to /root/ of the webapp container?

    • docker container copy /root/myfile.txt webapp:/root/
    • docker container cp /root/myfile.txt webapp:/root/
    • docker container copy webapp:/root/ /root/myfile.txt
    • docker container cp webapp:/root/ /root/myfile.txt

    Correct answer:

    • docker container cp /root/myfile.txt webapp:/root/

    16. We can copy a file from a stopped container.

    • True
    • False

    Correct answer:

    • True

    17. Data inside the container is persistent.

    • True
    • False

    Correct answer:

    • False

    18. You can run multiple instances of the same application on the docker host.

    • True
    • False

    Correct answer:

    • True

    19. You can map to the same port on the Docker host more than once.

    • True
    • False

    Correct answer:

    • False

    20. Which option could be used to expose a webapp container to the outside world?

    • -p
    • -P
    • –publish
    • –expose

    Correct answer:

    • -p
    • -P
    • –publish

    21. Unless specified otherwise, docker publishes the exposed port on all network interfaces.

    • True
    • False

    Correct answer:

    • True

    22. Map UDP port 80 in the container to port 8080 on the Docker host.

    • -p 8080:80/udp
    • -p 80:8080/udp
    • -P 8080:80/udp
    • None of the above

    Correct answer:

    • -p 8080:80/udp

    23. Map TCP port 80 in the container to port 8080 on the Docker host for connections to host IP 192.168.1.10 . Select the all right answers

    • -p 192.168.1.10:8080:80
    • -p 192.168.1.10:80:8080
    • -p 192.168.1.10:8080:80/tcp
    • -p 192.168.1.10:8080:8080

    Correct answer:

    • -p 192.168.1.10:8080:80
    • -p 192.168.1.10:8080:80/tcp

    24. How does the -P option in the docker container run command know what ports to publish on the container?

    • It identifies the ports listening inside the container using netstat command
    • It uses the ExposedPorts field set on the container or the EXPOSE instruction in the Dockerfile
    • It requires the –expose command line argument
    • It assigns random ports between 32768 and 61000

    Correct answer:

    • It uses the ExposedPorts field set on the container or the EXPOSE instruction in the Dockerfile

    25. How does docker map a port on a container to a port on the host?

    • Using an internal load balancer
    • FirewallD Rules
    • Using an external load balancer
    • IPTables Rules

    Correct answer:

    • IPTables Rules

    26. What IPTables chains does Docker modify to configure port mapping on a host?

    • INPUT
    • FORWARD
    • DOCKER
    • OUTPUT

    Correct answer:

    • DOCKER

    Troubleshooting Docker Daemon

    1. Enable the debugging mode. Select the right answer

    • echo '{"debug": true}' > /etc/docker/daemon.json
    • echo '{"debug"}' > /etc/docker/daemon.json
    • echo '{"debug": true}' > /var/lib/docker/daemon.json
    • echo '{"debug"}' > /var/lib/docker/daemon.json

    Correct answer:

    • echo '{"debug": true}' > /etc/docker/daemon.json

    2. Which environment variable will be used to connect a remote docker server?

    • DOCKER_REMOTE
    • DOCKER_HOST
    • DOCKER_CONFIG
    • None of the above

    Correct answer:

    • DOCKER_HOST

    3. How to check the logs of the docker daemon?

    • journalctl -u docker.service
    • less /var/log/messages
    • less /var/log/daemon.log
    • /var/log/docker.log

    Correct answer:

    • journalctl -u docker.service
    • less /var/log/messages
    • less /var/log/daemon.log
    • /var/log/docker.log

    4. What may be the cause of this error: “unable to configure the Docker daemon with file /etc/docker/daemon.json: the following directives are specified both as a flag and in the configuration file: tls: (from flag: true, from file: false)”?

    • The tls flag is set to true in daemon.json file and false in the command line
    • The tls flag is set to false in daemon.json file and true in the command line
    • The tls flag is not set on the command line
    • The tls flag is not set in the daemon.json file

    Correct answer:

    • The tls flag is set to false in daemon.json file and true in the command line

    5. How to check if the docker service is running or not?

    • docker status
    • sudo systemctl status docker
    • sudo systemctl docker status
    • sudo service status docker

    Correct answer:

    • sudo systemctl status docker

    6. Which command is used to check the default logging driver?

    • docker system df
    • docker system events
    • docker system prune
    • docker system info

    Correct answer:

    • docker system info

    7. Where is the log of the webapp container with id 78373635 on the Docker Host?

    • /var/lib/docker/containers/78373635/78373635.json
    • /var/log/docker/78373635.json
    • /etc/docker/78373635.json
    • /var/lib/docker/tmp/78373635/78373635.json

    Correct answer:

    • /var/lib/docker/containers/78373635/78373635.json

    8. What is the default logging driver?

    • json-file
    • syslog
    • journald
    • splunk

    Correct answer:

    • json-file

    9. Run a webapp container, and make sure that no logs are configured for this container.

    • docker run -it --log-driver none webapp
    • docker run -it --logging-driver none webapp
    • docker run -it webapp
    • docker run -it --log none webapp

    Correct answer:

    • docker run -it --log-driver none webapp

    10. How to change the default logging driver to syslog?

    • echo '{"log-driver": "syslog"}' > /etc/docker/daemon.json
    • echo '{"syslog": "log-driver"}' > /etc/docker/daemon.json
    • echo '{"log-driver": "syslog"}' > /var/lib/docker/daemon.json
    • echo '{"syslog": "log-driver"}' > /var/lib/docker/daemon.json

    Correct answer:

    • echo '{"log-driver": "syslog"}' > /etc/docker/daemon.json

    Docker Images

    1. What is the default tag if not specified when building an image with the name webapp?

    • none
    • default
    • latest
    • v1

    Correct answer:

    • latest

    2. Run ubuntu container with the trusty tag.

    • docker run ubuntu
    • docker run ubuntu:latest
    • docker run ubuntu:trusty
    • docker run ubuntu -t trusty

    Correct answer:

    • docker run ubuntu:trusty

    3. What is the default public registry for docker?

    • Docker Hub
    • Amazon Container Registry
    • Google Container Registry
    • Docker Trusted Registry

    Correct answer:

    • Docker Hub

    4. List the full length image IDs. (Please explore documentation)

    • docker image ls --digests
    • docker images --digests
    • docker images --no-trunc
    • None of the above

    Correct answer:

    • docker images --no-trunc

    5. What is the purpose of a private registry?

    • tightly control where your images are being stored
    • fully own your images distribution pipeline
    • integrate image storage and distribution tightly into your in-house development workflow
    • All of the above

    Correct answer:

    • All of the above

    6. Select the right answer. Which command is used to list the local images?

    • docker image ls
    • docker images ls
    • docker container image ls
    • docker container images ls

    Correct answer:

    • docker image ls

    7. Display images with a name containing postgres, at least 12 stars.

    • docker find --filter=stars=12 postgres
    • docker search --filter=stars=12 postgres
    • docker find --limit=12 postgres
    • docker search --limit=12 postgres

    Correct answer:

    • docker search --filter=stars=12 postgres

    8. Download nginx image from the Google Container Registry hub registry.

    • docker image pull nginx
    • docker image build nginx
    • docker image load nginx
    • docker pull gcr.io/kodekloud/nginx

    Correct answer:

    • docker pull gcr.io/kodekloud/nginx

    9. You have an nginx:v1 image with size 100M. You’ve now created your own version of the image – nginx:v2 by retagging the first image, what is the total size of both?

    • 50M
    • 100M
    • 150M
    • 200M

    Correct answer:

    • 100M

    10. What is the command to inspect the "httpd:latest" image?

    • docker inspect image httpd:latest
    • docker run inspect httpd:latest
    • docker container inspect httpd:latest
    • docker analysis image httpd:latest

    Correct answer:

    • docker inspect image httpd:latest

    11. Display images with a name containing busybox, at least 3 stars and are official builds.

    • docker find --filter is-official=true --filter stars=3 busybox
    • docker search --filter is-official=true --filter stars=3 busybox
    • docker find --filter is-official=true --limit=3 busybox
    • docker search --filter is-official=true --limit=3 busybox

    Correct answer:

    • docker search --filter is-official=true --filter stars=3 busybox

    12. Which command should be used to get the total size consumed by all images on a host?

    • docker image list
    • docker image df
    • docker system df
    • docker system list

    Correct answer:

    • docker system df

    13. In the output of the "docker system df" command what does the ACTIVE field indicate on the images row?

    • Number of Images currently available on the system
    • Number of Images built on the system
    • Number of Images with containers
    • Number of containers running on the system

    Correct answer:

    • Number of Images with containers

    Image Addressing Convention Add-on

    1. What is the total space consumed by images on this system?

    • 355 MB
    • 505 MB
    • 405 MB
    • 455 MB

    Correct answer:

    • 355 MB

    2. What command might have generated the above output?

    • docker container ps
    • docker ps
    • docker image ps
    • docker image list

    Correct answer:

    • docker image list

    3. What image might the webapp image be made of?

    • redis
    • ubuntu
    • alpine
    • nginx

    Correct answer:

    • nginx

    4. When you run the docker image inspect ubuntu command it gives the error “No such image”. Why is that?

    • Must run the command docker inspect ubuntu/ubuntu
    • Image Ubuntu does not have the latest tag
    • Must authenticate to docker hub first before running this command
    • Must run the command docker image history ubuntu

    Correct answer:

    • Image Ubuntu does not have the latest tag

    Authenticating to Registry

    1. Which command is used to remove webapp:v1 image locally?

    • docker image rm webapp
    • docker image rm webapp:v1
    • docker image remove webapp:v1
    • docker image del webapp:v1

    Correct answer:

    • docker image rm webapp:v1
    • docker image remove webapp:v1

    2. While trying to delete image postgres, you got an error “conflict: unable to remove repository reference “postgres” (must force) – container 1a56b95e073c is using its referenced image adf2b126dda8″. What may be the cause of this error?

    • A container is using this image
    • Must use force option to delete an image
    • Another image is using layers from this image
    • The image was built locally on this host

    Correct answer:

    • A container is using this image

    3. When you log in to a registry, the command stores credentials in … (Please explore the documentation pages for this)

    • $HOME/.docker/config.json
    • /etc/docker/.docker/config.json
    • /var/lib/docker/.docker/config.json
    • /var/lib/docker/containers/.docker/config.json

    Correct answer:

    • $HOME/.docker/config.json

    4. What is the user/account and image/repository name for the image company/nginx?

    • image=company, user=nginx
    • image=company, user=company
    • image=nginx, user=nginx
    • image=nginx, user=company

    Correct answer:

    • image=nginx, user=company

    5. You are required to store a copy of the official alpine image in your company’s internal docker registry. What would be your approach?

    • Create a Dockerfile similar to the official image and build an image
    • Pull the official image, tag it with the address of the internal docker registry and push to the internal docker registry

    Correct answer:

    • Pull the official image, tag it with the address of the internal docker registry and push to the internal docker registry

    6. Choose the right command to pull ubuntu image from a private registry at gcr.io

    • docker pull ubuntu
    • docker pull kk/ubuntu
    • docker pull gcr.io/kk/ubuntu
    • All of the above

    Correct answer:

    • docker pull gcr.io/kk/ubuntu

    7. Remove all unused images on the Docker host

    • docker image prune -a
    • docker image rm -a
    • docker image delete -a
    • None of the above

    Correct answer:

    • docker image prune -a

    8. Which command is used to authenticate with azr.com registry which listens on port 5000?

    • docker auth azr.com:5000
    • docker login azr.com:5000

    Correct answer:

    • docker login azr.com:5000

    9. Which subcommand will be used to get more info about images?

    • inspect
    • load
    • import
    • ls

    Correct answer:

    • inspect

    10. Which command can be used to get the ExposedPorts of a webapp image?

    • docker container ls
    • docker image inspect webapp
    • docker container inspect webapp
    • docker image ls

    Correct answer:

    • docker image inspect webapp

    11. Display all layers of httpd image along with the size on each layer.

    • docker image layers httpd
    • docker image history httpd
    • docker image inspect httpd
    • docker images history httpd

    Correct answer:

    • docker image history httpd

    12. How to get the Os field alone of the httpd image?

    • docker image inspect httpd -f '{{.Os}}'
    • docker image ls | grep Os
    • docker image history | grep Os
    • docker image inspect httpd -f '{{.OperatingSystem}}'

    Correct answer:

    • docker image inspect httpd -f '{{.Os}}'

    13. A government facility runs a secure data center with no internet connectivity. A new application requires access to docker images hosted on docker hub. What is the best approach to solve this?

    • Get the Dockerfile of the image and build a local version from within the restricted environment.
    • Establish a secure link between the host in the restricted environment and docker hub
    • Pull docker images from a host with access to docker hub, convert to a tarball using docker image save command, and copy to the restricted environment and extract the tarball
    • Pull docker images from a host with access to docker hub, then push to a registry hosted within the restricted environment.

    Correct answer:

    • Pull docker images from a host with access to docker hub, convert to a tarball using docker image save command, and copy to the restricted environment and extract the tarball

    14. Print the value of ‘Architecture’ and ‘Os’ for a 'webapp' image.

    • docker image inspect webapp -f '{{.Os}}' -f '{{.Architecture}}'
    • docker image inspect webapp -f '{{.Os}} {{.Architecture}}'
    • docker image inspect webapp -f '{{.Os}}', -f '{{.Architecture}}'
    • docker image inspect webapp -f '{{.Os .Architecture}}'

    Correct answer:

    • docker image inspect webapp -f '{{.Os}} {{.Architecture}}'

    15. Which command can be used to get a backup of image webapp?

    • docker image backup webapp -o webapp.tar
    • docker image save webapp -o webapp.tar
    • docker container save webapp -o webapp.tar
    • docker container backup webapp -o webapp.tar

    Correct answer:

    • docker image save webapp -o webapp.tar

    16. A tarfile – nginx.tar – has been created using the docker image save command. Which command can be used to extract it into your docker host.

    • docker image import -i nginx.tar
    • docker image restore -i nginx.tar
    • docker container restore -i nginx.tar
    • docker image load -i nginx.tar

    Correct answer:

    • docker image load -i nginx.tar

    17. You have created a nginx container and customized it to create your own webpage. How can you create an image out of it to share with others?

    • docker image save
    • docker image export
    • docker export
    • You can only create an image using a Dockerfile

    Correct answer:

    • docker export

    18. How do you restore an image created from the docker export command?

    • docker container import
    • docker image import
    • docker image load
    • docker image restore

    Correct answer:

    • docker image import

    19. The “export” command works with Docker images.

    • True
    • False

    Correct answer:

    • False

    20. Export webapp container’s filesystem as a tar archive. Select the right answer

    • docker export webapp mywebapp.tar
    • docker image export --output="mywebapp.tar" webapp
    • docker image save -i mywebapp.tar
    • docker container export webapp > mywebapp.tar

    Correct answer:

    • docker container export webapp > mywebapp.tar

    Building a Custom Image

    1. Which method can be used to build an image using existing containers?

    • docker commit
    • docker export
    • docker save
    • docker load

    Correct answer:

    • docker commit
    • docker export

    2. The container being committed and its processes will be paused while the image is committed.

    • True
    • False

    Correct answer:

    • True

    3. The … is a text document that contains all the commands a user could call on the command line to assemble an image.

    • Docker Compose
    • .dockerignore
    • build context
    • Dockerfile

    Correct answer:

    • Dockerfile

    4. Which of the following is not an instruction supported in the Dockerfile? Select the all right answers.

    • EXPOSE
    • ADD
    • WORKDIR
    • EXEC

    Correct answer:

    • EXEC

    5. The docker container commit is the recommended approach for building a custom image.

    • True
    • False

    Correct answer:

    • False

    6. Which of the following commands is used to list the docker images on the Docker Host?

    • docker images
    • docker image ls
    • docker image get
    • docker ls image

    Correct answer:

    • docker images
    • docker image ls

    7. We have a running container named webapp with the nginx image. We added a custom html file to this container. How do we create an image named mynginx from this container?

    • docker container commit webapp mynginx
    • docker container commit mynginx webapp
    • docker container update webapp mynginx
    • None of the above

    Correct answer:

    • docker container commit webapp mynginx

    8. Which of the following commands used to match all images with the com.example.version label?

    • docker images --label="com.example.version"
    • docker images --filter "com.example.version"
    • docker images --filter "label=com.example.version"
    • docker images --format "label=com.example.version"

    Correct answer:

    • docker images --filter "label=com.example.version"

    9. You are required to create an image from an existing image. What is the recommended approach?

    • Use docker image export and docker image import command
    • Use docker container export and docker container import command
    • Use docker image save and docker image load command
    • Use docker container commit command

    Correct answer:

    • Use docker image save and docker image load command

    10. You are required to create an image from an existing container. What is the recommended approach?

    • Use docker image export and docker image import command
    • Use docker container export and docker container import command
    • Use docker container commit command
    • Use docker container export and docker image import command

    Correct answer:

    • Use docker container export and docker image import command

    Building a Custom Image

    1. What is the port of the web application configured for the service to listen within the container?

    • 8080
    • 5000
    • 80
    • 0.0.0.0

    Correct answer:

    • 8080

    Code: FROM python:3.6 RUN pip install flask COPY . /opt/ EXPOSE 8080 WORKDIR /opt ENTRYPOINT ["python", "app.py"]

    2. When a container is created using the image built with the following Dockerfile, what is the command used to RUN the application inside it.

    • pip install flask
    • docker run app.py
    • app.py
    • python app.py

    Correct answer:

    • python app.py

    Code: FROM python:3.6 RUN pip install flask COPY . /opt/ EXPOSE 8080 WORKDIR /opt ENTRYPOINT ["python", "app.py"]

    3. To what location within the container is the application code copied to?

    • /opt
    • /app
    • /root
    • /var

    Correct answer:

    • /opt

    Code: FROM python:3.6 RUN pip install flask COPY . /opt/ EXPOSE 8080 WORKDIR /opt ENTRYPOINT ["python", "app.py"]

    4. Refer to the below Dockerfile and answer the following questions: What is the parent image from which this application is created?

    • ubuntu:latest
    • python
    • centos:7
    • python:3.6

    Correct answer:

    • python:3.6

    Code:

    FROM python:3.6 RUN pip install flask COPY . /opt/ EXPOSE 8080 WORKDIR /opt ENTRYPOINT ["python", "app.py"]


    Build Contexts

    1. Whenever a build is initiated by running the Docker build command, the files under the build context are transferred to the Docker daemon, at a temporary directory under the docker’s filesystem. Which directory are these files stored in?

    • /var/lib/docker/tmp
    • /var/lib/docker/image
    • /var/lib/docker/volumes
    • /var/lib/docker/plugins

    Correct answer:

    • /var/lib/docker/tmp

    2. While building a docker image from code stored in a remote URL, which command will be used to build from a directory called docker in the branch dev?

    Correct answer:

    3. Which of the below commands may be used to build an image with the Dockerfile filename?

    • docker build .
    • docker build -f Dockerfile .
    • docker build -t Dockerfile2 .
    • docker build -t .

    Correct answer:

    • docker build .
    • docker build -f Dockerfile .

    4. Choose the correct flag that is used to apply a tag to an image.

    • -i
    • -p
    • -f
    • -t

    Correct answer:

    • -t

    5. Build an image using a context build under path /tmp/docker and name it webapp.

    • docker build /tmp/docker
    • docker build /tmp/docker -t webapp
    • docker build webapp -t /tmp/docker
    • docker pull -it /tmp/docker bash

    Correct answer:

    • docker build /tmp/docker -t webapp

    6. If you do not specify a tag name, you can’t build the image.

    • True
    • False

    Correct answer:

    • False

    7. What is the default tag if not specified when building an image with the name webapp?

    • none
    • default
    • latest
    • v1

    Correct answer:

    • latest

    8. A build’s context is the set of files located in the specified PATH or URL, Which kind of resources can the URL parameter refer to ?

    • Git repositories
    • pre-packaged tarball contexts
    • Path to a local directory

    Correct answer:

    • Git repositories
    • pre-packaged tarball contexts
    • Path to a local directory

    9. What is the command to build an image using a Dockerfile.dev file under path /opt/myapp with the name webapp. The current directory you are in is /tmp.

    • docker build Dockerfile.dev -t webapp /opt/myapp
    • docker build -f /opt/myapp/Dockerfile.dev /opt/myapp -t webapp
    • docker build -f Dockerfile.dev /opt/myapp -t webapp
    • docker build -t Dockerfile.dev -name webapp -f /opt/myapp

    Correct answer:

    • docker build -f /opt/myapp/Dockerfile.dev /opt/myapp -t webapp

    10. What is a recommended approach for installing packages and libraries while building an image?

    • Download packages on the host and use ADD instructions to add them to the image.
    • Use the ADD instruction to provide a URL to the package on the remote host.
    • Use the RUN instruction and have the apt-get update and apt-get install commands on the same instruction.
    • Use the RUN instruction and have the apt-get update and apt-get install commands as separate instructions.

    Correct answer:

    • Use the RUN instruction and have the apt-get update and apt-get install commands on the same instruction.

    11. What is the file used to exclude temporary files such as log files or builds from the context during a build?

    • .git
    • .gitignore
    • .dockerignore
    • None of the above

    Correct answer:

    • .dockerignore

    12. Using RUN apt-get update && apt-get install -y ensures your Dockerfile installs the latest package versions with no further coding or manual intervention. This technique is known as …..

    • Docker-stack
    • Cache busting
    • Version pinning
    • Build-context

    Correct answer:

    • Cache busting

    13. If the build fails at a particular stage, it repurposes the previous layers from the cache and does not really rebuild them.

    • True
    • False

    Correct answer:

    • True

    14. What is a best practice while installing multiple packages as part of the install instruction?

    • Add them on the same line
    • Add them on separate lines separated by a slash in alphanumeric order
    • Add a separate instruction for each package
    • Add them on separate lines separated by a slash

    Correct answer:

    • Add them on separate lines separated by a slash in alphanumeric order

    15. Which among the following scenarios will lead to docker invalidating cache on a given layer?

    • Change in instruction
    • Change in a file used with the ADD instruction
    • Addition of a new instruction at the end of the file
    • Release of a new version of a package installed with the RUN instruction

    Correct answer:

    • Change in instruction
    • Change in a file used with the ADD instruction

    16. …… forces the build to install a particular version of package regardless of what’s in the cache. This technique can also reduce failures due to unanticipated changes in required packages.

    • Docker-stack
    • Cache busting
    • Version pinning
    • Build-context

    Correct answer:

    • Version pinning

    17. Which option can be used to disable the cache while building a docker image?

    • --no-cache
    • --force-rm=true
    • --disable-cache
    • --cache-from false

    Correct answer:

    • --no-cache

    Documentation Link: https://docs.docker.com/engine/reference/commandline/build/#:~:text=%2D%2Dno%2Dcache,building%20the%20image

    18. What is a recommended approach to reduce build time while building docker images?

    • Instructions likely to change more often must be at the top of the Dockerfile
    • Instructions likely to change more often must be at the bottom of the Dockerfile
    • Instructions likely to change more often must be in the middle of the Dockerfile
    • The order of the instructions within the Dockerfile doesn’t matter.

    Correct answer:

    • Instructions likely to change more often must be at the bottom of the Dockerfile

    19. A Dockerfile is built from the Ubuntu image as the base image. What would happen to the cache when a new version of the Ubuntu image is made available at Dockerhub?

    • Cache is invalidated and docker pulls the new image and recreates from scratch.
    • Cache is not invalidated and docker continues to use existing cache.

    Correct answer:

    • Cache is not invalidated and docker continues to use existing cache.

    20. COPY instruction has some features like local-only tar extraction and remote URL support.

    • True
    • False

    Correct answer:

    • False

    21. COPY instruction only supports the basic copying of local files into the container.

    • True
    • False

    Correct answer:

    • True

    22. Which instruction(s) can be used in the Dockerfile to copy content from the local filesystem into the containers?

    • ADD
    • COPY
    • MOVE
    • RUN

    Correct answer:

    • ADD
    • COPY

    23. What is the right instruction to download a file from "https://file.tar.xz" and copy to "/testdir" in the image?

    Correct answer:


    CMD-vs-Entrypoint

    1. Which of the following is the correct format for CMD instruction?

    • CMD ["executable","param1","param2"]
    • CMD ["param1","param2"]
    • CMD command param1 param2
    • CMD command,param1,param2

    Correct answer:

    • CMD ["executable","param1","param2"]
    • CMD ["param1","param2"]
    • CMD command param1 param2

    2. What is the output of the following Dockerfile snippet when container runs as docker run -it <image> kk?

    • Hello kk
    • Hello
    • World kk
    • kk Hello

    Correct answer:

    • Hello kk

    Code: ENTRYPOINT ["/bin/echo", "Hello"] CMD ["World"]

    3. If you list more than one CMD instruction in the Dockerfile then only the last CMD will take effect.

    • True
    • False

    Correct answer:

    • True

    4. What is the output of the following Dockerfile snippet when container runs as docker run -it <image>?

    • Hello world
    • Hello
    • world
    • world Hello

    Correct answer:

    • Hello world

    Code: ENTRYPOINT ["/bin/echo", "Hello"] CMD ["world"]

    5. Choose the correct instruction to add the echo "Hello World" command in the Dockerfile.

    • CMD [echo "Hello World"]
    • CMD ["echo", "Hello World"]
    • CMD ["Hello World"]
    • None of the above

    Correct answer:

    • CMD ["echo", "Hello World"]

    6. If CMD is used to provide default arguments for the ENTRYPOINT instruction, both the CMD and ENTRYPOINT instructions should be specified.

    • True
    • False

    Correct answer:

    • True

    7. A parent image is the image that your image is based on. It refers to the contents of the FROM directive in the Dockerfile.

    • True
    • False

    Correct answer:

    • True

    8. When a user runs the command docker run my-custom-image sleep 1000.

    • docker overrides the ENTRYPOINT instruction with "sleep 1000"
    • docker overrides the CMD instruction with "sleep 1000"
    • docker override ENTRYPOINT instruction with "sleep" and CMD instruction with "1000"

    Correct answer:

    • docker overrides the CMD instruction with "sleep 1000"

    9. A parent image has FROM scratch in its Dockerfile.

    • True
    • False

    Correct answer:

    • False

    10. While building an image, You have one base image, but there could be multiple parent images.

    • True
    • False

    Correct answer:

    • True

    11. How do you identify if a Docker file is configured to use multi-stage builds?

    • The Dockerfile has the tag multi-stage at the top
    • The Dockerfile has multiple FROM instructions
    • The Dockerfile has multiple RUN instructions
    • The Dockerfile is built from the scratch image

    Correct answer:

    • The Dockerfile has multiple FROM instructions

    12. You are developing an e-commerce application. The application must store cart details of users temporarily as long as the user’s session is active. What is the recommended approach to storing the cart details with the application deployed as a docker container?

    • Store the cart details in the /tmp directory of the container
    • Store the cart details in the memory of the container
    • Store the cart details in a volume backed by a in-memory cache service like redis

    Correct answer:

    • Store the cart details in a volume backed by a in-memory cache service like redis

    13. By default, the stages are not named, and you refer to them by their integer number, starting with 1 for the first FROM instruction in the multi-stage build.

    • True
    • False

    Correct answer:

    • False

    14. The "--from=0" in the following Dockerfile instruction line refers to:

    • The base image specified in the FROM instruction of the first set of instructions.
    • The base image specified in the FROM instruction of the second set of instructions.
    • The image built using the first set of instructions in the Dockerfile.
    • The image built using the last set of instructions in the Dockerfile

    Correct answer:

    • The image built using the first set of instructions in the Dockerfile.

    Code: "COPY --from=0 /go/src/github.com/alexellis/href-counter/app ."

    15. Name the stage which uses nginx as a base image to builder in the Dockerfile.

    • FROM nginx
    • FROM nginx AS builder
    • The last image build
    • FROM node AS builder

    Correct answer:

    • FROM nginx AS builder

    16. What instruction is used to copy a file from an external image named redis not part of any stage in the multi-stage build process?

    • –from=redis
    • –from=0
    • –copy-from=redis
    • –copy-from=0

    Correct answer:

    • –from=redis

    17. It’s recommended to avoid sending unwanted files to the build context by using .gitignore file to exclude those files.

    • True
    • False

    Correct answer:

    • False

    18. Which is the recommended approach to install packages following the best practices in Dockerfile?

    • RUN apt-get update && apt-get install -y git httpd
    • RUN apt-get update && apt-get install -y \        git \        httpd
    • RUN apt-get update \ RUN apt-get install -y git \ RUN apt-get install -y httpd

    Correct answer:

    • RUN apt-get update && apt-get install -y \        git \        httpd

    19. An application you are developing requires an httpd server as frontend, a python application as the backend API server, a MongoDB database and a worker developed in Python. What is the recommended approach in building images for these containers?

    • Build httpd, python API server, MongoDB database and Python worker into a single image to allow ease of deployment
    • Build httpd into an image, MongoDB database to another and Python API and worker together into a single image
    • Build separate images for each component of the application

    Correct answer:

    • Build separate images for each component of the application

    20. Which of the below steps can help minimize the build time of images?

    • Only install necessary packages within the image
    • Avoid sending unwanted files to the build context using .dockerignore
    • Combine multiple dependent instructions into a single one and cleanup temporary files
    • Move the instructions that are likely to change most frequently to the bottom of the Dockerfile
    • Use multi-stage builds

    Correct answer:

    • Avoid sending unwanted files to the build context using .dockerignore
    • Move the instructions that are likely to change most frequently to the bottom of the Dockerfile

    21. Which of the below can help minimize the image size?

    • Only install necessary packages within the image
    • Avoid sending unwanted files to the build context using .dockerignore
    • Combine multiple dependent instructions into a single one and cleanup temporary files
    • Move the instructions that are likely to change most frequently to the bottom of the Dockerfile
    • Use multi-stage builds

    Correct answer:

    • Only install necessary packages within the image
    • Combine multiple dependent instructions into a single one and cleanup temporary files
    • Use multi-stage builds

    Docker Networking

    1. What is the command to connect a running container with name myapp to the existing bridge network my-net?

    • docker container connect myapp my-net
    • docker container attach myapp my-net
    • docker network connect my-net myapp
    • docker network connect myapp my-net

    Correct answer:

    • docker network connect my-net myapp

    2. Which command is used to see the network settings and IP address assigned to a container with id c164825bb3d3 that uses the myapp image?

    • docker inspect myapp
    • docker container ls myapp
    • docker container ls c164825bb3d3
    • docker inspect c164825bb3d3

    Correct answer:

    • docker inspect c164825bb3d3

    3. Which command is used to list the default available networks?

    • docker network --filter
    • docker network get
    • docker network ls
    • None of the above

    Correct answer:

    • docker network ls

    4. Overlay networks connect multiple Docker daemons together and enable swarm services to communicate with each other.

    • True
    • False

    Correct answer:

    • True

    5. Which of the following commands would create a user-defined bridge network called my-net?

    • docker network create my-net
    • docker create network my-net
    • docker network create -d bridge my-net
    • docker network create --type bridge my-net
    • docker network create --driver bridge my-net

    Correct answer:

    • docker network create my-net
    • docker network create -d bridge my-net
    • docker network create --driver bridge my-net

    6. What is the default network driver used on a container if you haven’t specified one?

    • host
    • bridge
    • overlay
    • Macvlan

    Correct answer:

    • bridge

    7. How to get the subnet, gateway of the network c0a0b59a3807?

    • docker info c0a0b59a3807
    • docker container inspect c0a0b59a3807
    • docker network inspect c0a0b59a3807
    • docker inspect c0a0b59a3807

    Correct answer:

    • docker network inspect c0a0b59a3807

    8. If you use the …… network mode for a container, that container’s network stack is not isolated from the Docker host (the container shares the host’s networking namespace), and the container does not get its own IP-address allocated.

    • host
    • bridge
    • overlay
    • Macvlan

    Correct answer:

    • host

    9. What is the command to remove the my-net network?

    • docker network create my-net
    • docker network rm my-net
    • docker network connect my-net
    • None of the above

    Correct answer:

    • docker network rm my-net

    10. What is the command to remove all unused networks?

    • docker network create my-net
    • docker network rm my-net
    • docker network prune
    • docker network rm --all

    Correct answer:

    • docker network prune

    Docker Storage

    1. The volumes are mounted as “readonly” by default inside the container if no options are specified.

    • True
    • False

    Correct answer:

    • False

    2. What is the command to remove unused volumes?

    • docker container rm my-vol
    • docker volume rm my-vol
    • docker volume prune
    • docker volume rm --all

    Correct answer:

    • docker volume prune

    3. By default, all files created inside a container are stored on a writable container layer.

    • True
    • False

    Correct answer:

    • True

    4. Volumes are the preferred mechanism for persisting data generated by and used by Docker containers.

    • True
    • False

    Correct answer:

    • True

    5. Which command is used to remove the my-vol volume?

    • docker volume del my-vol
    • docker volume remove my-vol
    • docker volume prune my-vol
    • docker volume rm my-vol

    Correct answer:

    • docker volume remove my-vol
    • docker volume rm my-vol

    6. What is the command to create a volume with the name my-vol?

    • docker volume create my-vol
    • docker create volume my-vol
    • docker volume prune
    • docker volume rm all

    Correct answer:

    • docker volume create my-vol

    7. What is the command to list volumes?

    • docker volume ls
    • docker volume prune
    • docker volume get
    • None of the above

    Correct answer:

    • docker volume ls

    8. What is the command to get details of the volume my-vol such as the driver, mountpoint, volumename, ..etc?

    • docker volume inspect my-vol
    • docker volume fetch my-vol
    • docker volume get my-vol
    • docker volume ls my-vol

    Correct answer:

    • docker volume inspect my-vol

    9. Which option is used to mount a volume ?

    • -v
    • –volume-mount
    • --mount
    • --volume

    Correct answer:

    • -v
    • --volume
    • --mount

    10. You can remove a vol1 which is in use by a container using the command docker volume rm --force vol1.

    • True
    • False

    Correct answer:

    • False

    11. Which among the below is a correct command to start a webapp container with the volume vol2, mounted to the destination directory /app?

    • docker run -d --name webapp --mount source=vol2,target=/app httpd
    • docker run -d --name webapp -v vol2:/app httpd
    • docker run -d --name webapp --volume vol2:/app httpd

    Correct answer:

    • docker run -d --name webapp --mount source=vol2,target=/app httpd
    • docker run -d --name webapp -v vol2:/app httpd
    • docker run -d --name webapp --volume vol2:/app httpd

    12. By default, all files inside an image are in a writable layer.

    • True
    • False

    Correct answer:

    • False

    13. Which among the below is a correct command to start a webapp container with the volume vol3, mounted to the destination directory /opt in readonly mode?

    • docker run -d --name webapp --mount source=vol3,target=/opt,readonly httpd
    • docker run -d --name webapp -v vol3:/opt:ro httpd
    • docker run -d --name webapp -v vol3:/opt:readonly httpd
    • docker run -d --name webapp --volume vol3:/opt:ro httpd
    • docker run -d --name webapp --mount source=vol3,target=/opt,ro httpd

    Correct answer:

    • docker run -d --name webapp --mount source=vol3,target=/opt,readonly httpd
    • docker run -d --name webapp -v vol3:/opt:ro httpd
    • docker run -d --name webapp --volume vol3:/opt:ro httpd
    • docker run -d --name webapp --mount source=vol3,target=/opt,ro httpd

    Docker Compose

    1. …….. is a YAML file which contains details about the services, networks, and volumes for setting up a Docker application.

    • Dockerfile
    • Docker Compose
    • .dockerignore
    • .env

    Correct answer:

    • Docker Compose

    2. Which command can be used to create and start containers in foreground using the existing docker-compose.yml?

    • docker-compose up
    • docker-compose ps
    • docker-compose logs
    • docker-compose stop

    Correct answer:

    • docker-compose up

    3. Using …… we can configure containers and communication between them in a declarative way.

    • Docker Compose
    • Dockerfile
    • Device Mapper
    • Build-context

    Correct answer:

    • Docker Compose

    4. …… is the command to list the containers created by compose file.

    • docker-compose ls
    • docker-compose ps
    • docker-compose list

    Correct answer:

    • docker-compose ps

    5. …… is the command to check the logs for the whole stack defined inside compose file.

    • docker-compose up
    • docker-compose ps
    • docker-compose logs
    • docker-compose up -d

    Correct answer:

    • docker-compose logs

    6. Which command can be used to create and start containers in background or in detached mode in compose using the existing docker-compose.yml?

    • docker-compose up
    • docker-compose up --background
    • docker-compose up --detach
    • docker-compose up -d

    Correct answer:

    • docker-compose up --detach
    • docker-compose up -d

    7. Which command can be used to stop (only and not delete) the whole stack of containers created by compose file?

    • docker-compose down
    • docker-compose stop
    • docker-compose destroy
    • docker-compose halt

    Correct answer:

    • docker-compose stop

    8. docker-compose stop command stops and removes the whole stack of container created by compose file.

    • True
    • False

    Correct answer:

    • False

    9. Select the right answer. Which command can be used to delete the application stack created using compose file?

    • docker-compose rm
    • docker-compose stop
    • docker-compose down
    • docker-compose destroy

    Correct answer:

    • docker-compose down

    10. Compose files that doesn’t declare a version are considered “version 0”.

    • True
    • False

    Correct answer:

    • False

    11. With the docker-compose up command, we can run containers on multiple docker hosts.

    • True
    • False

    Correct answer:

    • False

    12. Compose files using the version 2 and version 3 syntax must indicate the version number at the root of the document.

    • True
    • False

    Correct answer:

    • True

    Docker Compose-Add On

    1. What is the host port on which the web application will be exposed on?

    • 80
    • 8080
    • Version 1
    • foobar.com

    Correct answer:

    • 8080

    2. What kind of volume mount is configured on the web application for the /var/log directory inside the container?

    • Volume mount
    • Bind mount

    Correct answer:

    • Volume mount

    3. What kind of volume mount is configured on the web application for the /code directory inside the container?

    • Volume Mount
    • Bind Mount

    Correct answer:

    • Bind Mount

    4. How can the web application address redis?

    • Using the container ID generated by redis
    • Using the name redis
    • Using the internal IP address of the redis container
    • By exposing port 6379 of redis container on the host and then using hosts IP

    Correct answer:

    • Using the name redis

    5. Which of the following statements are true?

    • All of the web, redis and db images will be built before deploying containers.
    • The redis image will be built and the web image will be pulled from Dockerhub if it doesn’t already exist on the host.
    • The web image will be built and the redis image will be pulled from Dockerhub if it doesn’t already exist on the host.
    • All images will be pulled from Dockerhub.

    Correct answer:

    • The web image will be built and the redis image will be pulled from Dockerhub if it doesn’t already exist on the host.

    6. Which is the correct statement referring to the following Compose file?

    • The depends_on configuration is not supported in Compose version 3
    • db and redis services will be started before web service
    • web service will be started before db and redis services
    • None of the above

    Correct answer:

    • db and redis services will be started before web service

    Swarm Architecture and Setup

    1. Swarm nodes can be physical or virtual, on the cloud or on prem that have Docker engine installed on it.

    • True
    • False

    Correct answer:

    • True

    2. A swarm cluster consists of at least one manager node and one or more worker nodes.

    • True
    • False

    Correct answer:

    • True

    3. What are the advantages of container orchestration?

    • High availability
    • Auto Scaling
    • Self healing
    • Declarative

    Correct answer:

    • High availability
    • Auto Scaling
    • Self healing
    • Declarative

    4. What technologies can be used to group multiple machines together into a single cluster to run applications in the form of containers?

    • Swarm
    • Kubernetes
    • Mesos
    • Openshift

    Correct answer:

    • Swarm
    • Kubernetes
    • Mesos
    • Openshift

    5. Who is responsible for maintaining the desired state of the swarm cluster and taking necessary actions if a node was to fail or a new node was added to the cluster?

    • manager node
    • worker node
    • slave node
    • worker, slave nodes

    Correct answer:

    • manager node

    6. You can promote a worker node to a manager node.

    • True
    • False

    Correct answer:

    • True

    7. Manager nodes are dedicated to management tasks only and cannot run workloads.

    • True
    • False

    Correct answer:

    • False

    8. The manager in the swarm cluster receives instructions or tasks from the worker node and runs containers.

    • True
    • False

    Correct answer:

    • False

    9. The communication between the nodes in the swarm cluster are not secured by default.

    • True
    • Flase

    Correct answer:

    • Flase

    10. The command docker node promote can be executed on any node “manager or worker”.

    • True
    • False

    Correct answer:

    • False

    11. Is it possible to promote a worker node to manager in swarm?

    • Yes
    • No

    Correct answer:

    • Yes

    12. What does the Reachable status of a node indicate in docker swarm?

    • The node is a worker node and is reachable
    • The node is a manager node and is reachable
    • The node is a manager node and is reachable and is not the leader
    • The node is a manager node and is the leader

    Correct answer:

    • The node is a manager node and is reachable and is not the leader

    13. If you have one manager in your swarm cluster, is it possible to demote it to a worker node?

    • True
    • False

    Correct answer:

    • False

    14. What feature of swarm closely relates to this use case – “If an instance of an application crashes, it is immediately replaced by a new one”?

    • Rolling updates
    • Self healing
    • Scaling
    • Load Balancing

    Correct answer:

    • Self healing

    15. Promote worker1 to a manager node . Select the right answer.

    • docker promote node worker1
    • docker node promote worker1
    • docker swarm node promote worker1
    • docker swarm promote node worker1

    Correct answer:

    • docker node promote worker1

    16. Change manager1 to a worker node . Select the right answer.

    • docker swarm node demote manager1 docker swarm node demote manager1
    • docker demote node manager1
    • docker node demote manager1
    • docker node demote manager1 worker

    Correct answer:

    • docker node demote manager1

    17. Which command is used to check the status of manager/worker nodes?

    • docker swarm ls
    • docker node ps
    • docker node ls
    • docker swarm show nodes

    Correct answer:

    • docker node ls

    18. We want to perform maintenance tasks on node – worker1 – for performing patching and updates. Select the best way to achieve this.

    • docker node update --availability drain worker1
    • docker node update --availability active worker1
    • docker node rm worker1
    • None of the above

    Correct answer:

    • docker node update --availability drain worker1

    19. We have a single manager 2 worker node swarm cluster. All three nodes are hosting workload. What is the sequence of activities to remove the manager node from the swarm cluster?

    • Drain the node, and run docker swarm leave.
    • Demote to a worker node, drain the node and run docker swarm leave.
    • Promote a worker node to manager, demote manager to worker, drain the node and run docker swarm leave.
    • Add a new worker node, drain the manager node, and run docker swarm leave.

    Correct answer:

    • Promote a worker node to manager, demote manager to worker, drain the node and run docker swarm leave.

    20. When a worker node becomes active again after draining, the old containers will go back to this node.

    • True
    • False

    Correct answer:

    • False

    21. It is recommended to have one manager in your cluster?

    • True
    • False

    Correct answer:

    • False

    22. …. is responsible for making sure that all the manager nodes that are in charge of managing and scheduling tasks in the cluster, are storing the same consistent state.

    • CFS
    • Scheduler
    • Raft consensus
    • Leader

    Correct answer:

    • Raft consensus

    23. The manager node is responsible for maintaining the cluster state, distributing and ensuring the state of containers and services across all workers.

    • True
    • False

    Correct answer:

    • True

    24. Which of the below statements are true when you have more than 1 manager nodes?

    • All decisions are made by all the managers at once.
    • All decisions are made by each manager turn by turn in a round robin fashion.
    • All decisions are made by 1 manager who is the leader.

    Correct answer:

    • All decisions are made by 1 manager who is the leader.

    25. Out of a total of 3 masters if one node was to fail or was not responding at that moment and only two nodes were available,the decision to add the new worker can still be made with an agreement between the two available nodes.

    • True
    • False

    Correct answer:

    • True

    26. …. is defined as the minimum number of managers required to be present for carrying out cluster management tasks.

    • Majority
    • Fault tolerance
    • Quorum
    • Single failure

    Correct answer:

    • Quorum

    27. What is the maximum number of managers recommended by Docker in a swarm cluster?

    • 3
    • 5
    • 7
    • No limit

    Correct answer:

    • 7

    28. Which formula can be used to calculate the Quorum of N nodes?

    • N + 1
    • N+1 / 2
    • N-1/2
    • (N /2) +1

    Correct answer:

    • (N /2) +1

    29. Which formula can be used to calculate the fault tolerance of N nodes?

    • N + 1
    • N+1 / 2
    • N / 2 +1
    • (N-1)/2

    Correct answer:

    • (N-1)/2

    30. What is the maximum number of managers possible in a swarm cluster?

    • 3
    • 5
    • 7
    • No limit

    Correct answer:

    • No limit

    31. It is recommended to have an even number of master nodes.

    • True
    • False

    Correct answer:

    • False

    32. Assume that you have 3 managers in your cluster, what will happen if 2 managers fail at the same time? Select the all right answers.

    • The services hosted on the available worker nodes will continue to run.
    • The services hosted on the available worker nodes will stop running.
    • New services/workers can be created or added.
    • New services/workers can’t be created or added.

    Correct answer:

    • The services hosted on the available worker nodes will continue to run.
    • New services/workers can’t be created or added.

    33. How many manager nodes must be online in a cluster with 7 manager nodes for the swarm cluster to continue to operate?

    • 3
    • 1
    • 4
    • 5

    Correct answer:

    • 4

    34. How many manager nodes must be online in a cluster with 13 manager nodes for the swarm cluster to continue to operate?

    • 3
    • 1
    • 6
    • 7

    Correct answer:

    • 7

    35. Among the below what is the recommended number of manager nodes as per best practices?

    • 9
    • 7
    • 1
    • 4

    Correct answer:

    • 7

    36. You have 3 data centers and 13 managers. How best should you distribute the managers between them to withstand site wide disruptions?

    • 5-5-3
    • 6-6-1
    • 7-5-1
    • 7-3-3

    Correct answer:

    • 5-5-3

    37. You have 3 data centers and 7 managers. How best should you distribute the managers between them to withstand site wide disruptions?

    • 4-2-1
    • 3-2-3
    • 3-2-2
    • 3-1-3

    Correct answer:

    • 3-2-2

    38. You have 3 data centers and 11 managers. How best should you distribute the managers between them to withstand site wide disruptions?

    • 4-3-3
    • 4-4-3
    • 4-5-2
    • 9-0-2

    Correct answer:

    • 4-4-3

    39. You have 3 data centers and 9 managers. How best should you distribute the managers between them to withstand site wide disruptions?

    • 3-3-3
    • 9-0-0
    • 4-4-1
    • 4-3-2

    Correct answer:

    • 3-3-3

    40. Which of the below statements are true?

    • By default, manager nodes host workloads. You must explicitly configure it not to.
    • By default, manager nodes do not host workloads. You must explicitly configure it to host workloads.

    Correct answer:

    • By default, manager nodes host workloads. You must explicitly configure it not to.

    Auto Lock

    1. After restarting the docker service and trying to run docker service ls, you get an error “Error response from daemon: Swarm is encrypted and needs to be unlocked before it can be used. How can you solve this error?

    • docker swarm leave
    • docker swarm update
    • docker swarm lock
    • docker swarm unlock

    Correct answer:

    • docker swarm unlock

    2. Which command can be used to return the current key which is used inside the cluster ?

    • docker swarm lock-key
    • docker swarm lock --autolock=true
    • docker swarm unlock --autolock=true
    • docker swarm unlock-key

    Correct answer:

    • docker swarm unlock-key

    **3. …. are one or more instances of a single application that runs across the Swarm Cluster

    Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment