Offset explorer как пользоваться
Перейти к содержимому

Offset explorer как пользоваться

  • автор:

Apache Kafka. Безопасность, мониторинг и управление кластером

Мы расскажем, как настроить безопасность кластеров Kafka и Zookeeper, какие инструменты можно использовать для мониторинга и управления кластером, а также про особенности продукта, с которыми мы столкнулись.

Почему Apache Kafka?

Apache Kafka — это унификация. Десятки поставщиков и потребителей, миллионы сообщений в день и огромные массивы данных — для этого нужна надежная, отказоустойчивая и высокопроизводительная шина данных. Существует множество версий дистрибутивов Apache Kafka, например vanilla kafka, oбразы от confluent, bitnami, wurstmeister и т.д. Мы расскажем про решение на базе сборок от Confluent в виде Docker-образов. Оно самое надежное в плане информационной безопасности. Конфигурирование и запуск контейнеров с Kafka в данном случае происходит с помощью docker-compose.

За время работы с Kafka мы прошли путь от «коробочного» решения до тонкой настройки безопасности кластера, применения TLS шифрования и разворачивания по рекомендациям вендора по построению геораспределенного кластера. В конфигурации «из коробки» нет первоначальных настроек безопасности. Для контроля доступов, вносимых изменений и безопасного взаимодействия перед нами встала задача настройки на кластере Apache Kafka TLS шифрования, аутентификации и авторизации средствами встроенного ACL.

TLS шифрование

Обеспечивает шифрование соединения между брокерами Kafka, серверами Zookeeper, клиентами и брокерами. Вся ключевая информация помещается в хранилища — keystore, которые разделяют на два вида:

  • keystore, где хранятся ключи и сертификаты стороны, в отношении которой пройдет процедура аутентификации и установления защищенного соединения, например, приватный ключ и ассоциированный с ним и подписанный со стороны центра сертификации (ЦC) сертификат.
  • truststore, куда помещаются сертификаты, которым доверяет носитель хранилища.

Общий процесс настройки TLS выглядит так:

  1. Для каждого сервера брокера и Zookeeper создаем keystore (настройки конфигурации см. в следующей главе):
    • Создаем keystore + генерируем ключевую пару — закрытый ключ и соответствующую цепь сертификатов (certificate chain), в которой после выполнения команды будет самоподписанный сертификат, содержащий его открытый ключ.
    • Создаем запрос на подпись для ЦC.
    • Подписываем запрос закрытым ключом ЦC. В нашем случае есть промежуточный ЦC и корневой ЦC.
    • Подписанный запрос импортируем в созданный ранее keystore, в цепочку сертификатов закрытого ключа. Сначала импортируем сертификаты всех ЦС, подписавших наш запрос, и только потом сам подписанный запрос. Это необходимо для точного установления цепи сертификатов, которая производится утилитой keytool, иначе получим ошибку.
    • Производим настройки конфигурации брокеров, серверов Zookeeper и клиентов.

В итоге на брокере и серверах Zookeeper мы получим keystore с 3 ключевыми объектами:

  • сертификат промежуточного ЦC, подписанный корневым ЦC;
  • самоподписанный сертификат корневого ЦC;
  • приватный ключ сервера со связанной цепью сертификатов: серверный сертификат, подписанный промежуточным ЦC;
  • сертификат промежуточного ЦC, подписанный корневым ЦC и самоподписанный сертификат корневого ЦC.
  1. Создаем truststore для клиентов и брокеров (для взаимодействия в качестве клиента с хостами Zookeeper) и в него импортируем сертификаты ЦC, чьим подписям клиент должен доверять. Здесь односторонняя аутентификация, т.е. клиент проверяет брокера и Zookeeper серверы брокера. Если нужно настроить двухстороннюю аутентификацию, проверку клиента или Zookeeper серверы на брокере, проделываем те же операции, что и на брокере, по созданию keystore на клиенте, а на Zookeeper создаем соответствующий truststore.

Важно отметить, что при создании клиентов и при использовании библиотеки librdkafka сертификаты доверенных ЦС могут браться клиентом непосредственно из операционной системы (ОС). К примеру, для машин на Windows необходимо на клиенте задавать настройку:

По умолчанию предполагается только Root и если сертификат сервера подписан еще и промежуточным ЦС, клиент не сможет установить цепь доверия и получит ошибку, поэтому нужно указывать CA.

В дистрибутиве Apache Kafka от Confluent предусмотрена директория для размещения файлов, необходимых для настройки TLS. Внутри контейнера это /etc/kafka/secrets . Для размещения файлов необходимо в конфигурационном файле деплоя образов прописать признак монтирования данной директории.

Далее рассмотрим настройку брокера и сервера Apache Zookeeper в составе кластера Apache Kafka. На остальных представителях кластера конфигурация аналогичная.

Настройка keystore

Создание Keystore на стороне серверов кластера

На сервере должна быть установлена Java, также можно выполнить команды внутри Docker контейнера с дистрибутивом Apache Kafka от Confluent:

keytool -genkeypair -validity days -keyalg RSA -keystore server1.keystore.p12 -storetype pkcs12 -alias server1 -dname «CN=fqdn,OU=x,O=x,L=Moscow,ST=Moscow,C=RU» -ext SAN=DNS:fqdn

Где days – срок действия сертификата в днях, fqdn – доменное имя хоста.

Таким образом, создан keystore с названием «server1.keystore.p12» с типом pkcs12, псевдонимом server1 пары приватный\публичный ключ сервера.

Если установлена версия Java 9 и выше, тип -storetype pkcs12 можно не указывать, т.к. он задан по умолчанию. Далее нужно подписать сертификат сервера в данном keystore.

Создание запроса на подпись сертификата

keytool -certreq -keystore server1.keystore.p12 -alias server1 -file server1.csr

Запрос необходимо подписать на стороне ЦС.

В keystore добавляем сертификаты ЦС (как промежуточного, так и корневого) и импортируем цепь сертификатов, полученную ранее. Тем самым мы замещаем самоподписанный сертификат сервера, указывая при этом alias, заданный при создании keystore.

keytool -importcert -file root-ca.crt -keystore server1.keystore.p12 -alias RootCA

keytool -importcert -file subroot-ca.crt -keystore server1.keystore.p12 -alias SubCA

keytool -importcert -file server1.pem -keystore server1.keystore.p12 -alias server1

Для проверки успешности импорта выводим содержимое keystore командой:

keytool -list -v -keystore server1.keystore.p12

Keystore готов к работе.

Создание truststore

В truststore помещаем сертификаты ЦС, подписавших сертификат сервера, чтобы сторона взаимодействия могла удостовериться, что представленный сертификат подписан доверенным ЦС.

keytool -importcert -file root-ca.crt -keystore client.truststore.p12 -alias RootCA

keytool -importcert -file subroot-ca.crt -keystore client.truststore.p12 -alias SubCA

keytool -list -v -keystore client.truststore.p12

Как уже упоминалось ранее, при построении клиента с помощью библиотеки librdkafka будут использоваться доверенные сертификаты ОС.

Настройки конфигурации сервера

Kafka поддерживает протокол SASL для аутентификации. При этом он может использоваться наряду с шифрованием – SASL_SSL, либо без него – SASL_PLAINTEXT. SASL позволяет применять разные механизмы аутентификации: PLAIN, SCRAM, OAUTHBEARER, Kerberos. С ними можно ознакомиться по ссылке.

Конфигурация брокера

Рассмотрены необходимые корректировки в конфигурацию и параметры для запуска кластера Apache Kafka в виде контейнеризированного решения от Сonfluent с использованием docker-compose. Особенности преобразования конфигурационных параметров Kafka для docker-compose файлов деплоя — на официальном сайте Confluent. Параметры для брокеров предваряются — « KAFKA_ », для Zookeeper — « ZOOKEEPER_ ».

Задаем параметр взаимодействия между брокерами через протокол SASL_SSL:

Параметр взаимодействия с клиентами через протокол SASL_SSL:

Необходимо добавить порт, к примеру, 9096 для приема подключений от клиентов с использованием TLS: SASL_SSL

TLS шифрование Zookeeper предполагает настройку клиентских портов для подключения, о чем расскажем далее, поэтому указываем на брокерах эти порты, к примеру, 2281. Для кластера Zookeeper из 3 хостов.

KAFKA_ZOOKEEPER_CONNECT: zookeeper_server1.domain.ru:2281, zookeeper_server2.domain.ru:2281, zookeeper_server3.domain.ru:2281

Задаем относительный путь до файла keystore (как уже упоминалось ранее, для confluent стандартный рабочий каталог для настроек TLS — /etc/kafka/secrets), файла с паролем (server1.creds) от keystore и пароля закрытого ключа, который совпадает с паролем от keystore. И аналогичные настройки для файла truststore.

KAFKA_SSL_TRUSTSTORE_PASSWORD:pass
Активация TLS шифрования для взаимодействия брокеров с кластером Zookeeper:

TLS не поддерживается фрэймворком Zookeeper NIO (используется по умолчанию), поэтому переопределяем его на Netty:

Нужно задать расположение паролей keystore и truststore для взаимодействия с Zookeeper. Примечательно, для данных параметров нужно указать абсолютный путь внутри контейнера, т.к. стандартное расположение «/etc/kafka/secrets» автоматически не учитывается:

Конфигурация Zookeeper сервера

Взаимодействие между серверами кластера Zookeeper предлагается осуществлять с использованием TLS:

Как отметили ранее, для активации TLS необходимо переопределить используемый Zookeeper серверами фрэймворк, а также задать keystore, truststore для взаимодействия кворума:

Поднимаем порт, принимающий подключения с использованием TLS:

Задаем keystore и truststore для взаимодействия с клиентами:

Для настройки TLS использовалась утилита keytool .

При настройке keystore, файлов и директорий, необходимых внутри контейнера, нужно учитывать, что в версиях дистрибутива от 5.5.х Kafka и Zookeeper от Confluent работа внутри контейнера происходит от пользователя “appuser”, а не от “root”, как это было раньше, и необходимо выдавать соответствующие права на файлы на уровне системы хоста. Для хостовой системы пользователь appuser представлен UID 1000 и GID 1000.

В сборке Kafka и Zookeeper от Confluent версии 5.0.x установлена Java 8, начиная с версии 6.0.x и в текущей 7.0.x — Java 11. Соответствие версий дистрибутивов Apache Kafka и Confluent приведены на сайте. Данный аспект обуславливает использование ключей утилиты keytool.

К примеру, в официальной документации для создания keystore используется ключ “ –genkey ”. Как гласит документация, данный ключ устарел и переименован в “ –genkeypair ”, начиная с версии Java 6, а « –import » переименован в « –importcert ». При использовании “ –genkey ” без указания « -storetype pkcs12 » в версиях до Java 9 созданный keystore будет использовать признанный устаревшим формат JKS. Исходя из этого, лучше использовать новые ключи для формирования keystore.

Т.к. для подписи сертификата использовался промежуточный ЦС, то помимо сертификата корневого ЦС нужно добавить в keystore еще и сертификат промежуточного ЦС.

В зависимости от политики и правил подписания сертификатов в вашей компании могут накладываться ограничения, к примеру, на область действия сертификата или полей расширения. Мы столкнулись с тем, что у сертификатов после подписания была только возможность проверки подлинности сервера (serverAuth), а поле SAN необходимо было дополнительно задавать. При попытке запустить кластер на сертификатах с данным ограничением возникает ошибка.

javax.net.ssl|ERROR|19|/0.0.0.0:3888|2021-10-27 11:18:22.090 GMT|TransportContext.java:341|Fatal (CERTIFICATE_UNKNOWN): Extended key usage does not permit use for
TLS client authentication (
«throwable» : sun.security.validator.ValidatorException: Extended key usage does not permit use for TLS client authentication

В виду того, что сервер может выступать клиентом при взаимодействиях в кластере, нужно еще добавить возможность проверки подлинности клиента (clientAuth). Данный аспект появился в официальной документации Apache Kafka, начиная с версии 2.6.

Иногда стоит увеличить уровень логирования для более полного понимания картины при настройке и запуске, поэтому для получения более детальных логов в конфигурационном файле деплоя требуемого контейнера в параметр « KAFKA_OPTS » прописываем:

Аутентификация

Основные механизмы, поддерживаемые Kafka и предусмотренные протоколом SASL, для аутентификации по имени пользователя и паролю – PLAIN и SCRAM. PLAIN подразумевает передачу паролей в открытом виде, поэтому требует организации шифрования канала при реализации в промышленном контуре. В SCRAM пароли без криптографического преобразования не передаются, что повышает уровень защищенности, необходимость использования шифрования остается. В отличие от PLAIN, где пароли всех подключающихся пользователей хранятся в файлах JAAS на брокере, в SCRAM они записываются в хэшированном виде на серверы Zookeeper. Таким образом использование SCRAM добавляет бОльшие чем в PLAIN временные издержки на установление соединения, но в ходе дальнейшей передачи данных они нивелируются.

Рассмотрим настройку SASL PLAIN. Напомним, что при использовании SASL аутентификация клиента на уровне TLS не производится. В процессе настройки для каждого сервера конфигурируется JAAS файл с учетными данными и указанием способа аутентификации. При использовании SASL поверх SSL на брокерах мы указываем расположение JAAS файла внутри контейнера:

Внутри файла указываются учетные данные и механизм аутентификации внутри обособленных блоков. Блок описывает взаимодействие: к примеру, блок «KafkaServer» отражает данные для взаимодействия клиентов с брокерами. Блок «Client» описывает, под каким пользователем брокер обращается к кластеру Zookeeper. Пример JAAS файла:

KafkaServer org.apache.kafka.common.security.plain.PlainLoginModule required
username=»KafkAdmin»
password=»»
user_KafkaAdmin =»password»
user_User1=»password»;
>;

Client org.apache.kafka.common.security.plain.PlainLoginModule required
username=»ZooKafka»
password=»password»;
>;

На стороне Zookeeper при активации SASL задаются следующие параметры:

KAFKA_OPTS: «-Djava.security.auth.login.config=/etc/kafka/zookeeper_server_jaas.conf -Dzookeeper.authProvider.1=org.apache.zookeeper.server.auth.SASLAuthenticationProvider -Dzookeeper.requireClientAuthScheme=sasl

В файле jaas указывается блок «Server», где описываются: пользователь, под которым взаимодействуют сами хосты Zookeeper, и пользователь, под которым брокеры обращаются к Zookeeper:

Server org.apache.kafka.common.security.plain.PlainLoginModule required
username=»ZooAdmin»
password=»pass»
user_ZooKafka=»pass»;
>;

При включении SASL на Zookeeper на созданные до этого Znode не распространяются применяемые правила, поэтому нужно выполнять zookeeper-security-migration.sh.

Авторизация

Для целей авторизации настроен ACL.

На стороне брокеров нужно выполнить ряд настроек:

Для ограничения возможности записи метаданных в Zookeeper задаем следующий параметр:

Настраивается суперпользователь, от которого брокеры будут работать в кластере:

JAAS файлы уже были представлены ранее как для брокеров, так и для Zookeeper — пользователям в них и задаются права ACL.

Всем приложениям, осуществляющим запись (producer) и чтение (consumer), заданы отдельные пользователи с разграничением минимально необходимых прав на манипуляции в кластере. Сonsumer в рамках приложений выделяются в группы (consumer group), пользователям выдаются права на чтение из своих групп.

Основные команды приведены по ссылке.

Инструменты

Здесь мы расскажем об инструментах для мониторинга и управления кластером Apache Kafka, которыми мы пользовались.

Prometheus JMX exporter

Это стандарт для мониторинга систем. Он использует полностью открытый исходный код, содержит десятки разных экспортеров, с помощью которых быстро настраивается мониторинг инфраструктуры. Более подробно об этом можно почитать тут.

Для установки Prometheus JMX exporter нужно создать директорию для хранения его исполняемых и конфиг файлов:

Prometheus получает метрики с серверов Kafka за счет JMX exporter агента устанавливаемого на узлы кластера.

Скачиваем последнюю версию JMX exporter и настраиваем конфигурацию для работы на каждом брокере Kafka, например:

Загружаем конфигурационный файл последней версии для брокеров kafka:

Добавляем в .yml файл развертывания кластера kafka настройки для каждого брокера:

1) KAFKA_OPTS: «-javaagent:/etc/kafka/prometheus/jmx_prometheus_javaagent-0.16.1.jar=8088:/etc/kafka/prometheus/kafka-2_0_0.yml»

/etc/kafka/prometheus/jmx_prometheus_javaagent-0.16.1.jar –путь внутри контейнера до jar файла

8088 – порт, на котором будет слушаться JMXexporter (если кластер развернут на одном сервере, необходимо указывать разные порты для каждого брокера!)

/etc/kafka/prometheus/kafka-2_0_0.yml – путь внутри контейнера до конфигурационного файла.

Возможные ошибки, возникающие при использовании параметра -javaagent в блоке KAFKA_OPTS :

При использовании CLI kafka внутри контейнера возможно возникновение ошибок вида:

Exception in thread «main» java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at sun.instrument.InstrumentationImpl.loadClassAndStartAgent(InstrumentationImpl.java:386)
at sun.instrument.InstrumentationImpl.loadClassAndCallPremain(InstrumentationImpl.java:401)
Caused by: java.net.BindException: Address already in use
at sun.nio.ch.Net.bind0(Native Method)
at sun.nio.ch.Net.bind(Net.java:433)
at sun.nio.ch.Net.bind(Net.java:425)
at sun.nio.ch.ServerSocketChannelImpl.bind(ServerSocketChannelImpl.java:223)
at sun.nio.ch.ServerSocketAdaptor.bind(ServerSocketAdaptor.java:74)
at sun.net.httpserver.ServerImpl.(ServerImpl.java:100)
at sun.net.httpserver.HttpServerImpl.(HttpServerImpl.java:50)
at sun.net.httpserver.DefaultHttpServerProvider.createHttpServer(DefaultHttpServerProvider.java:35)
at com.sun.net.httpserver.HttpServer.create(HttpServer.java:130)
at io.prometheus.jmx.shaded.io.prometheus.client.exporter.HTTPServer.(HTTPServer.java:190)
at io.prometheus.jmx.shaded.io.prometheus.jmx.JavaAgent.premain(JavaAgent.java:31)
. 6 more
FATAL ERROR in native method: processing of -javaagent failed
Aborted (core dumped)

Чтобы ошибка не возникала, нужно перед выполнением команд в CLI Kafka единоразово на всю сессию выполнить команду:

/app/docker/docker-images/prometheus – реальный путь на сервере

/etc/kafka/prometheus — путь внутри контейнера

Выполняем передеплой контейнеров kafka, используя команду:

sudo docker-compose -f /путь/к/файлу.yml up –d

Выполнить проверку генерации метрик JMXexporter-ом на хостах и портах указанных в настройках:

В конфиг – файле prometheus.yml на сервере с prometheus в блоке « scrape_configs » необходимо добавить строки вида:

Grafana

Для визуализации получаемых метрик можно использовать Grafana, в ней удобно настроить свои dashboards или скачать готовые решения. Для сбора метрик нужно установить и настроить сборщик Prometheus. В качестве альтернативы можно использовать Zabbix, он прекрасно работает с JMX метриками и может брать их напрямую с хоста экспортера без Prometheus.

Instana

Для мониторинга кластеров Kafka можно использовать систему Instana с автодискаверингом. При работе с ней были выявлены некоторые ньюасы, о которых мы расскажем ниже.

Помимо штатных показателей производительности кластера kafka и встроенных детекторов аномального состояния кластера, у Instana есть очень полезная функция — отображение Consumer Groups Lag Per Topic. Она подсчитывает лаги Consumer групп в разрезе топиков, визуализирует данные в графическом виде, позволяет взглянуть на них в реальном времени или во временных интервалах. В качестве альтернативы отображения Consumer Groups Lag можно использовать решение от linkedin — Burrow, он имеет встроенный Prometheus exporter (начиная с версии 1.3.4) и хорошо визуализирует лаги работая вкупе со стеком Prometheus + Grafana.

Техподдержка Instana утверждает следующее: «We use the Kafka broker API in order to calculate lag as a diff between last committed and last consumed offset for specific consumer group and topic».

Для отображения Consumer Groups Lag Per Topic агентом Instana используется следующая команда вида:

kafka-consumer-groups —describe —all-groups —bootstrap-server localhost:9092

Внимательные читатели могли заметить, что в кластере kafka с настроенными ACL листами выполнение CLI команды (на примере кластера на основе дистрибутива от confluent) docker exec -it container_name kafka-consumer-groups —describe —all-groups —bootstrap-server kafka1.test:9092 совершенно справедливо будет возвращать пустой результат или выдавать ошибку, причин такому поведению несколько:

  1. команда по умолчанию обращается к кластеру Kafka по протоколу PLAINTEXT, соответственно, она работает исключительно при настройке кластера на работу с данным протоколом (параметр KAFKA_ADVERTISED_LISTENERS );
  2. при настроенном параметре KAFKA_ADVERTISED_LISTENERS PLAINTEXT:// при запросе будет выдаваться пустой результат, т.к. на кластере включен ACL, а по протоколу PLAINTEXT, как мы рассматривали выше, осуществляется анонимный доступ, без указания учетных данных;
  3. при отсутствии настроенного параметра KAFKA_ADVERTISED_LISTENERS PLAINTEXT:// возникнет ошибка Error: Executing consumer group command failed due to org.apache.kafka.common.KafkaException: Failed to find brokers to send ListGroups ;
  4. для обращения по другим протоколам нужно использовать команду вида:
    docker exec -it container_name kafka-consumer-groups —describe —all-groups —bootstrap-server kafka1.test:9096 —command-config /путь/до/jaas-конфиг.conf ;

где jaas-конфиг.conf это файл со строками подключения по протоколу SASL_PLAINTEXT или SASL_SSL и логином/паролем с необходимыми правами.

Примеры таких конфигов:

Конфиг для работы по протоколу SASL_PLAINTEXT:

security.protocol=SASL_PLAINTEXT
sasl.mechanism=PLAIN
sasl.jaas.config=org.apache.kafka.common.security.plain.PlainLoginModule required
username=»user»
password=»password»;

Конфиг для работы по протоколу SASL_SSL:

security.protocol=SASL_SSL
sasl.mechanism=PLAIN
ssl.truststore.location=/etc/kafka/secrets/kafka.truststore.jks
ssl.truststore.password=password
sasl.jaas.config=org.apache.kafka.common.security.plain.PlainLoginModule required
username=»user»
password=»password»;

Нужно обратить внимание на использование отличных от задаваемых по умолчанию (9092) портов, если путь до server.properties брокеров не прописан в конфигурации агента Instana, он будет искать конфиг файлы в следующих путях:

  • Аргументы процесса брокера Kafka.
  • Переменная окружения KAFKA_SERVER_PROPERTIES

Агент Instana использует путь /opt/kafka/config/server.properties по умолчанию, если путь к server.properties не удалось найти ни одним из вышеупомянутых способов.

Не найдя конфиг файлы по данным путям, агент Instana будет стучаться до кластера Kafka по порту по умолчанию – 9092, что приведет к многочисленным ошибкам подключения к кластеру Kafka и отсутствию некоторых данных в вэб консоли Instana.

Немного о возникших проблемах при использовании Instana. Механизм подсчета Consumer Groups Lag Per Topic иногда сбоит и начинает показывать значение, кратное количеству брокеров, т.е. при реальном лаге в 300 сообщений, на 3х брокерной конфигурации возможно отображение лага в 1500 сообщений. Также данную фичу сейчас нельзя использовать на кластерах с настроенными ACL, т.к. отдельной настройки под механизм Consumer Groups Lag Per Topic в Instana нет. Мы завели в компании Instana Feature Request для добавления функционала тонкой настройки механизма Consumer Groups Lag Per Topic и ожидаем его добавления в ближайшем будущем.

Kafka Cruise Control + Cruise Control UI
  • мониторинг состояния брокеров, топиков и партиций;
  • мониторинг нагрузки и утилизации ресурсов кластера;
  • продвинутую балансировку нагрузки;
  • детектирование аномалий и автохилинг;
  • автоматизацию добавления/удаления брокеров.
Kafka GitOps

Еще один незаменимый инструмент — Kafka GitOps. Позволяет автоматизировать управление топиками и списками управления доступом (ACL) Apache Kafka.

Топики и ACL определяются и ведутся в файле YAML формата. Идея проекта — управление топиками и ACL Kafka через версионные файлы конфигурации. При запуске Kafka GitOps сравнивает желаемое состояние кластера Kafka с фактическим и создает план для выполнения в кластере. После выполнения топики и ACL будут соответствовать желаемому состоянию.

Kafka GitOps также создает необходимые ACL для каждого типа приложений. Нет необходимости вручную создавать кучу списков ACL для Kafka Connect, Kafka Streams и т. д.

Работа с консолью:

По дефолту приложение ищет файл state.yaml в текущей директории. Если конфиг лежит в той же директории, что и jar-файл, то параметр -f при вызове указывать не нужно.

Примеры стандартных команд запуска приложения из консоли:

java -jar kafka-gitops-all.jar -f /kafka/statefile/topics.yaml

java -jar kafka-gitops-all.jar

Ниже приведены аргументы (доступны по параметру -h )

-f, —file= расположение файла с конфигом
—no-delete только изменять и добавлять, не удалять топики\ACL-листы
—skip-acls не анализировать ACL-листы из конфига, настраивать только топики Kafka
-v, —verbose детальный вывод в консоль
-o расположение, куда записать получившийся план (если мы хотим только сформировать план, не применяя изменения к кластеру Kafka)

Команды:

apply применить конфиг к Kafka
plan только построить план изменений, не применяя к Kafka
validate валидировать конфиг на предмет наличия\отсутствия ошибок в state.yaml файле

Пример вызова приложения:

java -jar kafka-gitops-all.jar -f /kafka/statefile/topics.yaml —skip-acls —no-delete —verbose plan

тут мы запускаем программу, говорим ей не анализировать ACL-листы (—skip-acls );
не пытаться удалить, а только изменить и добавить топики\ACl-листы ( —no-delete );
выводить все промежуточные шаги в консоль (—verbose ), только формировать план изменений ( plan ), так как мы не добавляли флаг -o , то план изменений будет только выведен в консоль и не будет сохранен в файл).

Конфиг (файл state.yaml)

Блок общих настроек:

settings:
topics:
defaults:
replication: 1 # (ко всем топикам из конфига по умолчанию применять фактор репликации = 1, если не указано иного)
blacklist:
prefixed:
— _confluent # (игнорировать уже имеющиеся в Kafka топики, название которых начинается на _confluent)

Блок настроек топиков:

topics:
msg: # (название топика)
partitions: 3 # (кол-во партиций)
replication: 1 # (фактор репликации)
configs:
cleanup.policy: compact # (любые параметры настройки топиков)
segment.bytes: 1000000 # (любые параметры настройки топиков)
test-msg:
partitions: 2
replication: 1
configs:
cleanup.policy: compact
segment.bytes: 1000000

Переменные окружения:

Параметры подключения к кафке настраиваются через параметры окружения:

KAFKA_BOOTSTRAP_SERVERS=localhost:9092
KAFKA_SASL_JAAS_PASSWORD=kafka
KAFKA_SASL_JAAS_USERNAME=kafka
KAFKA_SECURITY_PROTOCOL=SASL_PLAINTEXT
KAFKA_CLIENT_ID=gitops-user
KAFKA_SASL_MECHANISM=PLAIN

Если на кластере Apache Kafka нет никакой авторизации, то достаточно будет прописать параметр KAFKA_BOOTSTRAP_SERVERS

AKHQ

Удобный и функциональный GUI менеджер для Apache Kafka — AKHQ.

Его ключевые особенности:

  • позволяет организовать мультикластерную конфигурацию из единого интерфейса;
  • поддержка протоколов и механизмов аутентификации и шифрования для Apache Kafka;
  • управление топиками, consumer группами, конфигурациями кластера, пользователями, ACL и т.д.;
  • интеграция с LDAP, RBAC, Schema Registry, Kafka Connect и многими другими продуктами и технологиями;
  • тонкая настройка прав доступа к web-интерфейсу системы.

Пример .yml конфиг файла для быстрого старта с использованием docker контейнера:

version: ‘3.6’
services:
akhq:
image: tchiotludo/akhq
environment:
AKHQ_CONFIGURATION: |
akhq:
connections:
cluster-1:
properties:
bootstrap.servers: «server1:19092, server2:29092, server3:39092»
cluster-2:
properties:
bootstrap.servers: » server1:19092, server2:29092, server3:39092″
cluster-3:
properties:
bootstrap.servers: » server1:19092, server2:29092, server3:39092″
security.protocol: SASL_PLAINTEXT
sasl.mechanism: PLAIN
sasl.jaas.config: org.apache.kafka.common.security.plain.PlainLoginModule required username=»user» password=»password»;
network_mode: host

Offset explorer

Offset Explorer (ранее Kafka Tool) — толстый клиент для управления и использования кластеров Apache Kafka с поддежкой мультикластерности. Он позволяет быстро просматривать объекты в кластере Kafka, а также сообщения, хранящиеся в топиках кластера. Offset Explorer содержит функционал, ориентированный как на разработчиков, так и на администраторов.

Некоторые из ключевых особенностей:

  • быстрый просмотр кластеров Kafka, включая их брокеров, топики и consumer’ов;
  • просмотр содержимого и добавление новых сообщений в партициях;
  • просмотр и выставление offset у consumer;
  • вывод сообщений в JSON, XML и Avro формате с возможностью их локального сохранения;
  • управление топиками, их конфигурациями и ACL листами;
  • поддержка протоколов и механизмов аутентификации и шифрования для Apache Kafka;
  • возможность написания своих собственных плагинов для вывода кастомных форматов данных.

Вывод

Apache Kafka позволяет пропускать через единую централизованную среду огромное количество сообщений, а затем хранить их, не беспокоясь о производительности и потере данных. Продукт собрал вокруг себя множество проектов, утилит, средств для комфортной работы, мониторинга, управления. В статье представлен наш опыт использования некоторых из них, которые показались нам интересными. Важную часть работы современных информационных систем составляет организация безопасности их работы и взаимодействия. В данной статье мы также рассмотрели ньюансы настройки безопасности кластеров Apache Kafka и Zookeeper, авторизации ACL, SASL аутентификации. Надеемся, наш опыт будет вам полезен.

  • Блог компании Национальный расчетный депозитарий
  • Системное администрирование
  • IT-инфраструктура
  • Apache

Documentation

If your cluster is configured for plaintext security (typically in test environments only) you do not need to configure any additional security attributes. You can just click on Test to test that your connection is working properly or Add to add the server connection without testing it first.

SASL

If your cluster is configured for SASL (plaintext or SSL) you must either specify the JAAS config in the UI or pass in your JAAS config file to Offset Explorer when you start it. The exact contents of the JAAS file depend on the configuration of your cluster, please refer to the Kafka documentation.

  • offsetexplorer.exe -J-Djava.security.auth.login.config=c:/client_jaas.conf
  • offsetexplorer -J-Djava.security.auth.login.config=/client_jaas.conf
  • /Applications/Offset Explorer.app/Contents/java/app

If you do not pass the JAAS config file at the startup of Offset Explorer, you must specify it under the JAAS Config tab for each connection.

If you are using SASL Plaintext you typically must change the sasl.mechanism client property to PLAIN. This property can be entered in the ‘SASL Mechanism’ text field under the ‘Advanced’ section.

SSL

If your Kafka cluster is configured to use SSL you may need to set various SSL configuration parameters. Unless your Kafka brokers are using a server certificate issued by a public CA, you need to point to a local truststore that contains the self signed root certificate that signed your brokers certificate. You also need to enter the password for this truststore.

If the SAN(s) in your server certificate do not match the actual hostname of the brokers you are connecting to, you will receive an SSL error (No subject alternative DNS name matching xxx found) when you try to connect. You can avoid this by unchecking the ‘Validate SSL endpoint hostname’ checkbox in the ‘Broker security’ section. This will set the ssl.endpoint.identification.algorithm client property to null.

If your Kafka cluster requires a client certificate (two-way authentication) you also need to configure your keystore attributes. The keystore contains the private key that you use to authenticate to your Kafka brokers. You also need to configure a password for the keystore as well as password for the private key in the keystore.

Azure Event Hubs

In order to connect Offset Explorer to an Azure Event Hub, you must first make sure that «Kafka Surfaces» is enabled. This can be confirmed by navigating to the Event Hubs namespace page and seeing if it is enabled.

Once this has been confirmed, navigate to the «Shared access policies» menu item in the Event Hubs namespace. You can either use the RootManageSharedAccessKey, or make your own policy. Once you have chosen the policy, click on it and copy the connection string–primary key value.

Once the link has been copied, you can open Offset Explorer and add a new connection. In the properties tab, choose a name and version for the cluster. Note that Azure Event Hubs do not support access to Zookeeper so you must leave the Zookeeper host field empty.

In the security tab, change the security type from plaintext to SASL SSL.

In the advanced tab, make sure to use port number 9093, as it differs from the standard port for Kafka (9092). You will also need to insert PLAIN into the SASL mechanism field.

For the JAAS Config tab, you will need to enter the following information (note that the password is equal to the connection string–primary key link that you copied earlier):

Once all this information has been entered, you can click «Add» to add the connection.

Amazon MSK

The easiest method to connect to your Amazon MSK cluster is to configure your MSK security settings to allow SASL/SCRAM authentication. In order to connect Offset Explorer to your Amazon MSK environment using SASL/SCRAM authentication, you will need to add the following settings when creating your cluster in Offset Explorer:

Properties tab: Confirm that zookeeper host is left blank. Pick the version number that matches your Amazon MSK cluster.

Security tab: Confirm that the broker security type is SASL SSL.

Advanced tab: Confirm the bootstrap servers input is correctly given. Also, enter the following into the SASL Mechanism box: SCRAM-SHA-512

JAAS Config tab: Copy the following, switching out «myuser» for correct username and «mypassword» for correct password. These credentials are stored in the AWS Secrets Manager secret that is associated with your MSK SASL/SCRAM authentication.

Once these settings for the cluster have been given, you can add the server connection by clicking «Add» and connect.

Confluent Cloud

In order to connect Offset Explorer to a Confluent Cloud environment, you will need to add the following settings when creating your cluster in Offset Explorer:

Properties tab: Confirm that zookeeper host is left blank.

Security tab: Confirm that the broker security type is SASL SSL.

Advanced tab: Confirm the bootstrap servers input is correctly given. Also, enter the following into the SASL Mechanism box: PLAIN

JAAS Config tab: Copy the following, switching out «myapikey» and «myapisecret» for correct values.

Once these settings for the cluster have been given, you can add the cluster by clicking «Add» and connect.

Offset Explorer | UI Tool for Apache Kafka

© 2015-2023 DB Solo, LLC. All rights reserved.

Offset explorer как пользоваться

Watch videos, read documentation, and hear Chocolatey success stories from companies you trust. View Resources

Events

Find past and upcoming webinars, workshops, and conferences. New events have recently been added! View Events

Courses

Step-by-step guides for all things Chocolatey! Earn badges as you learn through interactive digital courses. View Courses

Chocolatey Community Coffee Break

Join the Chocolatey Team on our regular monthly stream where we discuss all things Community, what we do, how you can get involved and answer your Chocolatey questions.

Chocolatey Product Spotlight

Join the Chocolatey Team on our regular monthly stream where we put a spotlight on the most recent Chocolatey product releases. You’ll have a chance to have your questions answered in a live Ask Me Anything format.

Announcing Chocolatey Central Management 0.10.0

Livestream from
Thursday, 06 October 2022
We recently released our largest update to Chocolatey Central Management so far. Join Gary and Steph to find out more about Chocolatey Central Management and the new features and fixes we’ve added to this release. Watch On-Demand

Chocolatey and Intune Overview

Webinar Replay from
Wednesday, 30 March 2022
At Chocolatey Software we strive for simple, and teaching others. Let us teach you just how simple it could be to keep your 3rd party applications updated across your devices, all with Intune! Watch On-Demand

Chocolatey For Business. In Azure. In One Click.

Livestream from
Thursday, 9 June 2022
Join James and Josh to show you how you can get the Chocolatey For Business recommended infrastructure and workflow, created, in Azure, in around 20 minutes. Watch On-Demand

The Future of Chocolatey CLI

Livestream from
Thursday, 04 August 2022
Join Paul and Gary to hear more about the plans for the Chocolatey CLI in the not so distant future. We’ll talk about some cool new features, long term asks from Customers and Community and how you can get involved! Watch On-Demand

Hacktoberfest Tuesdays 2022

Livestreams from
October 2022
For Hacktoberfest, Chocolatey ran a livestream every Tuesday! Re-watch Cory, James, Gary, and Rain as they share knowledge on how to contribute to open-source projects such as Chocolatey CLI. Watch On-Demand

Chocolatey Product Spotlight: Chocolatey 1.2.0 and Chocolatey Licensed Extension 5.0.0

Livestream from
Thursday, 03 November 2022
Join Paul and Gary for this months Chocolatey product livestream where we look at the latest release of Chocolatey 1.2.0, Chocolatey Licensed Extension 5.0.0 and shine a spotlight on the new hook scripts functionality. This opens up so many possibilities for Chocolatey CLI users! Watch On-Demand

Chocolatey Coding Livestream

Livestream from
Tuesday, 29 November 2022
Join Josh as he adds the ability to manage Chocolatey GUI config and features with the Chocolatey Ansible Collection. Watch On-Demand

Introduction into Chocolatey with Veeam

Webinar from
Tuesday, 13 December 2022
Join Gary, Paul, and Maurice as they introduce and demonstrate how to use Chocolatey! Questions will be answered live in an Ask Me Anything format. Watch On-Demand

Welcome to the Chocolatey Community Package Repository! The packages found in this section of the site are provided, maintained, and moderated by the community.

Moderation

Every version of each package undergoes a rigorous moderation process before it goes live that typically includes:

  • Security, consistency, and quality checking
  • Installation testing
  • Virus checking through VirusTotal
  • Human moderators who give final review and sign off

Organizational Use

If you are an organization using Chocolatey, we want your experience to be fully reliable. Due to the nature of this publicly offered repository, reliability cannot be guaranteed. Packages offered here are subject to distribution rights, which means they may need to reach out further to the internet to the official locations to download files at runtime.

Fortunately, distribution rights do not apply for internal use. With any edition of Chocolatey (including the free open source edition), you can host your own packages and cache or internalize existing community packages.

Disclaimer

Your use of the packages on this site means you understand they are not supported or guaranteed in any way. Learn more.

I Understand
Generate Script
B U I L D E R

Step 1: Review Your Packages

Step 2: Choose Your Integration Method

Step 3: Enter Your Internal Repository Url

Step 3: Copy Your Script or Download Config

Option 1: Copy Script
Option 2: Download Config

Save as .config File

Step 4: Setup Your Environment

1. Ensure you are set for organizational deployment
2. Get the package into your environment
  • Open Source or Commercial:
    • Proxy Repository — Create a proxy nuget repository on Nexus, Artifactory Pro, or a proxy Chocolatey repository on ProGet. Point your upstream to https://community.chocolatey.org/api/v2/. Packages cache on first access automatically. Make sure your choco clients are using your proxy repository as a source and NOT the default community repository. See source command for more information.
    • You can also just download the packages and push them to a repository Download Packages
    • Open Source
      • Download the packages: Download Packages
      • Follow manual internalization instructions

      Step 5: Copy Your Script

      Add this to a PowerShell script or use a Batch script with tools and in places where you are calling directly to Chocolatey. If you are integrating, keep in mind enhanced exit codes.

      If you do use a PowerShell script, use the following to ensure bad exit codes are shown as failures:

       ## 1. REQUIREMENTS ## ### Here are the requirements necessary to ensure this is successful. ### a. Internal/Private Cloud Repository Set Up ### #### You'll need an internal/private cloud repository you can use. These are #### generally really quick to set up and there are quite a few options. #### Chocolatey Software recommends Nexus, Artifactory Pro, or ProGet as they #### are repository servers and will give you the ability to manage multiple #### repositories and types from one server installation. ### b. Download Chocolatey Package and Put on Internal Repository ### #### You need to have downloaded the Chocolatey package as well. #### Please see https://chocolatey.org/install#organization ### c. Other Requirements ### #### We initialize a few things that are needed by this script - there are no other requirements. $ErrorActionPreference = "Stop" #### Set TLS 1.2 (3072) as that is the minimum required by various up-to-date repositories. #### Use integers because the enumeration value for TLS 1.2 won't exist #### in .NET 4.0, even though they are addressable if .NET 4.5+ is #### installed (.NET 4.5 is an in-place upgrade). [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072 #### We use this variable for future REST calls. $RequestArguments = @ < UseBasicParsing = $true >## 2. TOP LEVEL VARIABLES ## ### a. Your internal repository url (the main one). ### #### Should be similar to what you see when you browse #### to https://community.chocolatey.org/api/v2/ $NugetRepositoryUrl = "INTERNAL REPO URL" ### b. Internal Repository Credential ### #### If required, add the repository access credential here # $NugetRepositoryCredential = [PSCredential]::new( # "username", # ("password" | ConvertTo-SecureString -AsPlainText -Force) # ) # $RequestArguments.Credential = $NugetRepositoryCredential ### c. Chocolatey nupkg download url ### #### This url should result in an immediate download when you navigate to it $ChocolateyDownloadUrl = "$($NugetRepositoryUrl.TrimEnd('/'))/package/chocolatey.2.2.2.nupkg" ### d. Chocolatey Central Management (CCM) ### #### If using CCM to manage Chocolatey, add the following: #### i. Endpoint URL for CCM # $ChocolateyCentralManagementUrl = "https://chocolatey-central-management:24020/ChocolateyManagementService" #### ii. If using a Client Salt, add it here # $ChocolateyCentralManagementClientSalt = "clientsalt" #### iii. If using a Service Salt, add it here # $ChocolateyCentralManagementServiceSalt = "servicesalt" ## 3. ENSURE CHOCOLATEY IS INSTALLED ## ### Ensure Chocolatey is installed from your internal repository #### Download the Nupkg, appending .zip to the filename to handle archive cmdlet limitations if (-not (Get-Command choco.exe -ErrorAction SilentlyContinue)) < $TempDirectory = Join-Path $env:Temp "chocolateyInstall" if (-not (Test-Path $TempDirectory -PathType Container)) < $null = New-Item -Path $TempDirectory -ItemType Directory >$DownloadedNupkg = Join-Path $TempDirectory "$(Split-Path $ChocolateyDownloadUrl -Leaf).zip" Invoke-WebRequest -Uri $ChocolateyDownloadUrl -OutFile $DownloadedNupkg @RequestArguments #### Extract the Nupkg, and run the chocolateyInstall script if (Get-Command Microsoft.PowerShell.Archive\Expand-Archive -ErrorAction SilentlyContinue) < Microsoft.PowerShell.Archive\Expand-Archive -Path $DownloadedNupkg -DestinationPath $TempDirectory -Force >else < # PowerShell versions catch < Write-Warning "Unable to unzip package using built-in compression." throw $_ >> & $(Join-Path $TempDirectory "tools\chocolateyInstall.ps1") > if (-not (Get-Command choco.exe -ErrorAction SilentlyContinue)) < refreshenv >## 4. CONFIGURE CHOCOLATEY BASELINE ## ### a. FIPS Feature ### #### If you need FIPS compliance - make this the first thing you configure #### before you do any additional configuration or package installations # choco feature enable -n useFipsCompliantChecksums ### b. Apply Recommended Configuration ### #### Move cache location so Chocolatey is very deterministic about #### cleaning up temporary data and the location is secured to admins choco config set --name cacheLocation --value C:\ProgramData\chocolatey\cache #### Increase timeout to at least 4 hours choco config set --name commandExecutionTimeoutSeconds --value 14400 #### Turn off download progress when running choco through integrations choco feature disable --name showDownloadProgress ### c. Sources ### #### Remove the default community package repository source choco source list --limitoutput | ConvertFrom-Csv -Header 'Name', 'Location' -Delimiter '|' | ForEach-Object < if ($_.Location -eq 'https://community.chocolatey.org/api/v2/') < choco source remove -n $_.Name >> #### Add internal default sources #### You could have multiple sources here, so we will provide an example #### of one using the remote repo variable here #### NOTE: This EXAMPLE may require changes if ($NugetRepositoryCredential) < choco source add --name ChocolateyInternal --source $NugetRepositoryUrl --user $NugetRepositoryCredential.UserName --password $NugetRepositoryCredential.GetNetworkCredential().Password --priority 1 >else < choco source add --name ChocolateyInternal --source $NugetRepositoryUrl --priority 1 >### b. Keep Chocolatey Up To Date ### #### Keep chocolatey up to date based on your internal source #### You control the upgrades based on when you push an updated version #### to your internal repository. #### Note the source here is to the OData feed, similar to what you see #### when you browse to https://community.chocolatey.org/api/v2/ choco upgrade chocolatey --confirm ## 5. ENSURE CHOCOLATEY FOR BUSINESS ## ### If you don't have Chocolatey for Business (C4B), you'll want to remove from here down. ### a. Ensure The License File Is Installed ### #### Create a license package using script from https://docs.chocolatey.org/en-us/how-tos/setup-offline-installation#exercise-4-create-a-package-for-the-license choco install chocolatey-license --source $NugetRepositoryUrl --confirm ### b. Disable The Licensed Source ### #### The licensed source cannot be removed, so it must be disabled. #### This must occur after the license has been set by the license package. if ("chocolatey-license" -in (choco list --localonly --limitoutput | ConvertFrom-Csv -Header "Name" -Delimiter "|").Name) < choco source disable --name chocolatey.licensed >else < Write-Warning "Not disabling 'chocolatey.licensed' feed, as Chocolatey-License has not been installed." >### c. Ensure Chocolatey Licensed Extension ### #### You will have downloaded the licensed extension to your internal repository #### as you have disabled the licensed repository in step 5b. #### Ensure the chocolatey.extension package (aka Chocolatey Licensed Extension) if ("chocolatey-license" -in (choco list --localonly --limitoutput | ConvertFrom-Csv -Header "Name" -Delimiter "|").Name) < choco install chocolatey.extension --source $NugetRepositoryUrl --confirm >else < Write-Warning "Not installing 'chocolatey.extension', as Chocolatey-License has not been installed." >#### The Chocolatey Licensed Extension unlocks all of the following, which also have configuration/feature items available with them. You may want to visit the feature pages to see what you might want to also enable: #### - Package Builder - https://docs.chocolatey.org/en-us/features/paid/package-builder #### - Package Internalizer - https://docs.chocolatey.org/en-us/features/paid/package-internalizer #### - Package Synchronization (3 components) - https://docs.chocolatey.org/en-us/features/paid/package-synchronization #### - Package Reducer - https://docs.chocolatey.org/en-us/features/paid/package-reducer #### - Package Audit - https://docs.chocolatey.org/en-us/features/paid/package-audit #### - Package Throttle - https://docs.chocolatey.org/en-us/features/paid/package-throttle #### - CDN Cache Access - https://docs.chocolatey.org/en-us/features/paid/private-cdn #### - Branding - https://docs.chocolatey.org/en-us/features/paid/branding #### - Self-Service Anywhere (more components will need to be installed and additional configuration will need to be set) - https://docs.chocolatey.org/en-us/features/paid/self-service-anywhere #### - Chocolatey Central Management (more components will need to be installed and additional configuration will need to be set) - https://docs.chocolatey.org/en-us/features/paid/chocolatey-central-management #### - Other - https://docs.chocolatey.org/en-us/features/paid/ ### d. Ensure Self-Service Anywhere ### #### If you have desktop clients where users are not administrators, you may #### to take advantage of deploying and configuring Self-Service anywhere choco feature disable --name showNonElevatedWarnings choco feature enable --name useBackgroundService choco feature enable --name useBackgroundServiceWithNonAdministratorsOnly choco feature enable --name allowBackgroundServiceUninstallsFromUserInstallsOnly choco config set --name allowedBackgroundServiceCommands --value "install,upgrade,uninstall" ### e. Ensure Chocolatey Central Management ### #### If you want to manage and report on endpoints, you can set up and configure ### Central Management. There are multiple portions to manage, so you'll see ### a section on agents here along with notes on how to configure the server ### side components. if ($ChocolateyCentralManagementUrl) < choco install chocolatey-agent --source $NugetRepositoryUrl --confirm choco config set --name CentralManagementServiceUrl --value $ChocolateyCentralManagementUrl if ($ChocolateyCentralManagementClientSalt) < choco config set --name centralManagementClientCommunicationSaltAdditivePassword --value $ChocolateyCentralManagementClientSalt >if ($ChocolateyCentralManagementServiceSalt) < choco config set --name centralManagementServiceCommunicationSaltAdditivePassword --value $ChocolateyCentralManagementServiceSalt >choco feature enable --name useChocolateyCentralManagement choco feature enable --name useChocolateyCentralManagementDeployments > 
       ## 1. REQUIREMENTS ## ### Here are the requirements necessary to ensure this is successful. ### a. Internal/Private Cloud Repository Set Up ### #### You'll need an internal/private cloud repository you can use. These are #### generally really quick to set up and there are quite a few options. #### Chocolatey Software recommends Nexus, Artifactory Pro, or ProGet as they #### are repository servers and will give you the ability to manage multiple #### repositories and types from one server installation. ### b. Download Chocolatey Package and Put on Internal Repository ### #### You need to have downloaded the Chocolatey package as well. #### Please see https://chocolatey.org/install#organization ### c. Other Requirements ### #### i. chocolatey.chocolatey ##### You will require the chocolatey.chocolatey collection to be installed ##### on all machines using this playbook. ##### Please see https://github.com/chocolatey/chocolatey-ansible/#installing-the-collection-from-ansible-galaxy - name: Install and Configure Chocolatey hosts: all ## 2. TOP LEVEL VARIABLES ## vars: ### a. Your internal repository url (the main one). ### #### Should be similar to what you see when you browse #### to https://community.chocolatey.org/api/v2/ nuget_repository_url: INTERNAL REPO URL ### b. Internal Repository Credential ### #### If required, add the repository access credential here and #### uncomment lines with source_username and source_password below # nuget_repository_username: username # nuget_repository_password: password ### c. Chocolatey Central Management (CCM) ### #### If using CCM to manage Chocolatey, add the following: #### i. Endpoint URL for CCM # chocolatey_central_management_url: https://chocolatey-central-management:24020/ChocolateyManagementService #### ii. If using a Client Salt, add it here # chocolatey_central_management_client_salt: clientsalt #### iii. If using a Service Salt, add it here # chocolatey_central_management_service_salt: servicesalt ## 3. ENSURE CHOCOLATEY IS INSTALLED ## ### Ensure Chocolatey is installed from your internal repository tasks: - name: Install chocolatey win_chocolatey: name: chocolatey source: "">"" # source_username: "">"" # source_password: "">"" ## 4. CONFIGURE CHOCOLATEY BASELINE ## ### a. FIPS Feature ### #### If you need FIPS compliance - make this the first thing you configure #### before you do any additional configuration or package installations # - name: Enable FIPS compliance # win_chocolatey_feature: # name: useFipsCompliantChecksums # state: enabled ### b. Apply Recommended Configuration ### #### Move cache location so Chocolatey is very deterministic about #### cleaning up temporary data and the location is secured to admins - name: Set the cache location win_chocolatey_config: name: cacheLocation state: present value: C:\ProgramData\chocolatey\cache #### Increase timeout to at least 4 hours - name: Set the command execution timeout win_chocolatey_config: name: commandExecutionTimeoutSeconds state: present value: 14400 #### Turn off download progress when running choco through integrations - name: Disable showing download progress win_chocolatey_feature: name: showDownloadProgress state: disabled ### c. Sources ### #### Remove the default community package repository source - name: Remove Chocolatey Community Repository win_chocolatey_source: name: chocolatey state: absent #### Add internal default sources #### You could have multiple sources here, so we will provide an example #### of one using the remote repo variable here #### NOTE: This EXAMPLE may require changes - name: Add Internal Repository win_chocolatey_source: name: ChocolateyInternal state: present source: > # source_username: > # source_password: > priority: 1 ### b. Keep Chocolatey Up To Date ### #### Keep chocolatey up to date based on your internal source #### You control the upgrades based on when you push an updated version #### to your internal repository. #### Note the source here is to the OData feed, similar to what you see #### when you browse to https://community.chocolatey.org/api/v2/ - name: Upgrade Chocolatey win_chocolatey: name: chocolatey state: latest ## 5. ENSURE CHOCOLATEY FOR BUSINESS ## ### If you don't have Chocolatey for Business (C4B), you'll want to remove from here down. ### a. Ensure The License File Is Installed ### #### Create a license package using script from https://docs.chocolatey.org/en-us/how-tos/setup-offline-installation#exercise-4-create-a-package-for-the-license - name: Install Chocolatey License win_chocolatey: name: chocolatey-license source: ChocolateyInternal state: latest ### b. Disable The Licensed Source ### #### The licensed source cannot be removed, so it must be disabled. #### This must occur after the license has been set by the license package. - name: Disable Chocolatey Community Repository win_chocolatey_source: name: chocolatey.licensed state: disabled ### c. Ensure Chocolatey Licensed Extension ### #### You will have downloaded the licensed extension to your internal repository #### as you have disabled the licensed repository in step 5b. #### Ensure the chocolatey.extension package (aka Chocolatey Licensed Extension) - name: Install Chocolatey Extension win_chocolatey: name: chocolatey.extension source: ChocolateyInternal state: latest #### The Chocolatey Licensed Extension unlocks all of the following, which also have configuration/feature items available with them. You may want to visit the feature pages to see what you might want to also enable: #### - Package Builder - https://docs.chocolatey.org/en-us/features/paid/package-builder #### - Package Internalizer - https://docs.chocolatey.org/en-us/features/paid/package-internalizer #### - Package Synchronization (3 components) - https://docs.chocolatey.org/en-us/features/paid/package-synchronization #### - Package Reducer - https://docs.chocolatey.org/en-us/features/paid/package-reducer #### - Package Audit - https://docs.chocolatey.org/en-us/features/paid/package-audit #### - Package Throttle - https://docs.chocolatey.org/en-us/features/paid/package-throttle #### - CDN Cache Access - https://docs.chocolatey.org/en-us/features/paid/private-cdn #### - Branding - https://docs.chocolatey.org/en-us/features/paid/branding #### - Self-Service Anywhere (more components will need to be installed and additional configuration will need to be set) - https://docs.chocolatey.org/en-us/features/paid/self-service-anywhere #### - Chocolatey Central Management (more components will need to be installed and additional configuration will need to be set) - https://docs.chocolatey.org/en-us/features/paid/chocolatey-central-management #### - Other - https://docs.chocolatey.org/en-us/features/paid/ ### d. Ensure Self-Service Anywhere ### #### If you have desktop clients where users are not administrators, you may #### to take advantage of deploying and configuring Self-Service anywhere - name: Hide not-elevated warnings win_chocolatey_feature: name: showNonElevatedWarnings state: disabled - name: Use background mode for self-service win_chocolatey_feature: name: useBackgroundService state: enabled - name: Use background service for non-admins win_chocolatey_feature: name: useBackgroundServiceWithNonAdministratorsOnly state: enabled - name: Allow background uninstallation for user installs win_chocolatey_feature: name: allowBackgroundServiceUninstallsFromUserInstallsOnly state: enabled - name: Set allowed background service commands win_chocolatey_config: name: backgroundServiceAllowedCommands state: present value: install,upgrade,uninstall ### e. Ensure Chocolatey Central Management ### #### If you want to manage and report on endpoints, you can set up and configure ### Central Management. There are multiple portions to manage, so you'll see ### a section on agents here along with notes on how to configure the server ### side components. - name: Install Chocolatey Agent when: chocolatey_central_management_url is defined win_chocolatey: name: chocolatey-agent source: ChocolateyInternal state: latest - name: Set the Central Management Service URL when: chocolatey_central_management_url is defined win_chocolatey_config: name: CentralManagementServiceUrl state: present value: > - name: Set the Central Management Client Salt when: chocolatey_central_management_client_salt is defined win_chocolatey_config: name: centralManagementClientCommunicationSaltAdditivePassword state: present value: > - name: Set the Central Management Service Salt when: chocolatey_central_management_service_salt is defined win_chocolatey_config: name: centralManagementServiceCommunicationSaltAdditivePassword state: present value: > - name: Use Central Management when: chocolatey_central_management_url is defined win_chocolatey_feature: name: useChocolateyCentralManagement state: enabled - name: Use Central Management Deployments when: chocolatey_central_management_url is defined win_chocolatey_feature: name: useChocolateyCentralManagementDeployments state: enabled 
       ## 1. REQUIREMENTS ## ### Here are the requirements necessary to ensure this is successful. ### a. Internal/Private Cloud Repository Set Up ### #### You'll need an internal/private cloud repository you can use. These are #### generally really quick to set up and there are quite a few options. #### Chocolatey Software recommends Nexus, Artifactory Pro, or ProGet as they #### are repository servers and will give you the ability to manage multiple #### repositories and types from one server installation. ### b. Download Chocolatey Package and Put on Internal Repository ### #### You need to have downloaded the Chocolatey package as well. #### Please see https://chocolatey.org/install#organization ### c. Other Requirements ### #### The Chocolatey resources are available with any recent version of Chef. #### We utilise the Chocolatey recipe to install the Chocolatey binaries. include_recipe "chocolatey" ## 2. TOP LEVEL VARIABLES ## ### a. Your internal repository url (the main one). ### #### Should be similar to what you see when you browse #### to https://community.chocolatey.org/api/v2/ NugetRepositoryUrl = "INTERNAL REPO URL" ### b. Internal Repository Credential ### #### If required, add the repository access credential here # NugetRepositoryUsername = "username" # NugetRepositoryPassword = "password" ### c. Chocolatey nupkg download url ### #### This url should result in an immediate download when you navigate to it in #### a web browser ChocolateyNupkgUrl = "INTERNAL REPO URL/package/chocolatey.2.2.2.nupkg", ### d. Chocolatey Central Management (CCM) ### #### If using CCM to manage Chocolatey, add the following: #### i. Endpoint URL for CCM # ChocolateyCentralManagementUrl = "https://chocolatey-central-management:24020/ChocolateyManagementService" #### ii. If using a Client Salt, add it here # ChocolateyCentralManagementClientSalt = "clientsalt" #### iii. If using a Service Salt, add it here # ChocolateyCentralManagementServiceSalt = "servicesalt" ## 3. ENSURE CHOCOLATEY IS INSTALLED ## ### Ensure Chocolatey is installed from your internal repository node['chocolatey']['install vars'] = < 'chocolateyDownloadUrl' =>"#", > ## 4. CONFIGURE CHOCOLATEY BASELINE ## ### a. FIPS Feature ### #### If you need FIPS compliance - make this the first thing you configure #### before you do any additional configuration or package installations # chocolatey_feature 'useFipsCompliantChecksums' do # action :enable # end ### b. Apply Recommended Configuration ### #### Move cache location so Chocolatey is very deterministic about #### cleaning up temporary data and the location is secured to admins chocolatey_config 'cacheLocation' do value 'C:\ProgramData\chocolatey\cache' end #### Increase timeout to at least 4 hours chocolatey_config 'commandExecutionTimeoutSeconds' do value '14400' end #### Turn off download progress when running choco through integrations chocolatey_feature 'showDownloadProgress' do action :disable end ### c. Sources ### #### Remove the default community package repository source chocolatey_source 'chocolatey' do action :remove end #### Add internal default sources #### You could have multiple sources here, so we will provide an example #### of one using the remote repo variable here #### NOTE: This EXAMPLE may require changes chocolatey_source 'ChocolateyInternal' do source "#" priority 1 action :add end execute 'ChocolateyInternal' do command "choco source add --name ChocolateyInternal -s # -u=# -p=# --priority=1" only_if < NugetRepositoryUsername != nil || NugetRepositoryPassword != nil >end ### b. Keep Chocolatey Up To Date ### #### Keep chocolatey up to date based on your internal source #### You control the upgrades based on when you push an updated version #### to your internal repository. #### Note the source here is to the OData feed, similar to what you see #### when you browse to https://community.chocolatey.org/api/v2/ chocolatey_package 'chocolatey' do action :upgrade source "#" end ## 5. ENSURE CHOCOLATEY FOR BUSINESS ## ### If you don't have Chocolatey for Business (C4B), you'll want to remove from here down. ### a. Ensure The License File Is Installed ### #### Create a license package using script from https://docs.chocolatey.org/en-us/how-tos/setup-offline-installation#exercise-4-create-a-package-for-the-license chocolatey_package 'chocolatey-license' do action :install source "#" end ### b. Disable The Licensed Source ### #### The licensed source cannot be removed, so it must be disabled. #### This must occur after the license has been set by the license package. chocolatey_source 'chocolatey.licensed' do action :disable end ### c. Ensure Chocolatey Licensed Extension ### #### You will have downloaded the licensed extension to your internal repository #### as you have disabled the licensed repository in step 5b. #### Ensure the chocolatey.extension package (aka Chocolatey Licensed Extension) chocolatey_package 'chocolatey.extention' do action install source "#" end #### The Chocolatey Licensed Extension unlocks all of the following, which also have configuration/feature items available with them. You may want to visit the feature pages to see what you might want to also enable: #### - Package Builder - https://docs.chocolatey.org/en-us/features/paid/package-builder #### - Package Internalizer - https://docs.chocolatey.org/en-us/features/paid/package-internalizer #### - Package Synchronization (3 components) - https://docs.chocolatey.org/en-us/features/paid/package-synchronization #### - Package Reducer - https://docs.chocolatey.org/en-us/features/paid/package-reducer #### - Package Audit - https://docs.chocolatey.org/en-us/features/paid/package-audit #### - Package Throttle - https://docs.chocolatey.org/en-us/features/paid/package-throttle #### - CDN Cache Access - https://docs.chocolatey.org/en-us/features/paid/private-cdn #### - Branding - https://docs.chocolatey.org/en-us/features/paid/branding #### - Self-Service Anywhere (more components will need to be installed and additional configuration will need to be set) - https://docs.chocolatey.org/en-us/features/paid/self-service-anywhere #### - Chocolatey Central Management (more components will need to be installed and additional configuration will need to be set) - https://docs.chocolatey.org/en-us/features/paid/chocolatey-central-management #### - Other - https://docs.chocolatey.org/en-us/features/paid/ ### d. Ensure Self-Service Anywhere ### #### If you have desktop clients where users are not administrators, you may #### to take advantage of deploying and configuring Self-Service anywhere chocolatey_feature 'showNonElevatedWarnings' do action :disable end chocolatey_feature 'useBackgroundService' do action :enable end chocolatey_feature 'useBackgroundServiceWithNonAdministratorsOnly' do action :enable end chocolatey_feature 'allowBackgroundServiceUninstallsFromUserInstallsOnly' do action :enable end chocolatey_config 'backgroundServiceAllowedCommands' do value 'install,upgrade,uninstall' end ### e. Ensure Chocolatey Central Management ### #### If you want to manage and report on endpoints, you can set up and configure ### Central Management. There are multiple portions to manage, so you'll see ### a section on agents here along with notes on how to configure the server ### side components. chocolatey_package 'chocolatey-agent' do action install source "#" # user "#" # password "#" only_if < ChocolateyCentralManagementUrl != nil >end chocolatey_config 'CentralManagementServiceUrl' do value "#" only_if < ChocolateyCentralManagementUrl != nil >end chocolatey_config 'centralManagementClientCommunicationSaltAdditivePassword' do value "#" only_if < ChocolateyCentralManagementClientSalt != nil >end chocolatey_config 'centralManagementServiceCommunicationSaltAdditivePassword' do value "#" only_if < ChocolateyCentralManagementServiceSalt != nil >end chocolatey_feature 'useChocolateyCentralManagement' do action :enable only_if < ChocolateyCentralManagementUrl != nil >end chocolatey_feature 'useChocolateyCentralManagementDeployments' do action :enable only_if < ChocolateyCentralManagementUrl != nil >end 

      Requires cChoco DSC Resource. See docs at https://github.com/chocolatey/cChoco.

       #requires -Modules cChoco ## 1. REQUIREMENTS ## ### Here are the requirements necessary to ensure this is successful. ### a. Internal/Private Cloud Repository Set Up ### #### You'll need an internal/private cloud repository you can use. These are #### generally really quick to set up and there are quite a few options. #### Chocolatey Software recommends Nexus, Artifactory Pro, or ProGet as they #### are repository servers and will give you the ability to manage multiple #### repositories and types from one server installation. ### b. Download Chocolatey Package and Put on Internal Repository ### #### You need to have downloaded the Chocolatey package as well. #### Please see https://chocolatey.org/install#organization ### c. Other Requirements ### #### i. Requires chocolatey\cChoco DSC module to be installed on the machine compiling the DSC manifest #### NOTE: This will need to be installed before running the DSC portion of this script if (-not (Get-Module cChoco -ListAvailable)) < $null = Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -Force if (($PSGallery = Get-PSRepository -Name PSGallery).InstallationPolicy -ne "Trusted") < Set-PSRepository -Name PSGallery -InstallationPolicy Trusted >Install-Module -Name cChoco if ($PSGallery.InstallationPolicy -ne "Trusted") < Set-PSRepository -Name PSGallery -InstallationPolicy $PSGallery.InstallationPolicy >> #### ii. Requires a hosted copy of the install.ps1 script ##### This should be available to download without authentication. ##### The original script can be found here: https://community.chocolatey.org/install.ps1 Configuration ChocolateyConfig < ## 2. TOP LEVEL VARIABLES ## param( ### a. Your internal repository url (the main one). ### #### Should be similar to what you see when you browse #### to https://community.chocolatey.org/api/v2/ $NugetRepositoryUrl = "INTERNAL REPO URL", ### b. Chocolatey nupkg download url ### #### This url should result in an immediate download when you navigate to it in #### a web browser $ChocolateyNupkgUrl = "INTERNAL REPO URL/package/chocolatey.2.2.2.nupkg", ### c. Internal Repository Credential ### #### If required, add the repository access credential here # $NugetRepositoryCredential = [PSCredential]::new( # "username", # ("password" | ConvertTo-SecureString -AsPlainText -Force) # ), ### d. Install.ps1 URL #### The path to the hosted install script: $ChocolateyInstallPs1Url = "https://community.chocolatey.org/install.ps1" ### e. Chocolatey Central Management (CCM) ### #### If using CCM to manage Chocolatey, add the following: #### i. Endpoint URL for CCM # $ChocolateyCentralManagementUrl = "https://chocolatey-central-management:24020/ChocolateyManagementService", #### ii. If using a Client Salt, add it here # $ChocolateyCentralManagementClientSalt = "clientsalt", #### iii. If using a Service Salt, add it here # $ChocolateyCentralManagementServiceSalt = "servicesalt" ) Import-DscResource -ModuleName PSDesiredStateConfiguration Import-DscResource -ModuleName cChoco Node 'localhost' < ## 3. ENSURE CHOCOLATEY IS INSTALLED ## ### Ensure Chocolatey is installed from your internal repository Environment chocoDownloadUrl < Name = "chocolateyDownloadUrl" Value = $ChocolateyNupkgUrl >cChocoInstaller installChocolatey < DependsOn = "[Environment]chocoDownloadUrl" InstallDir = Join-Path $env:ProgramData "chocolatey" ChocoInstallScriptUrl = $ChocolateyInstallPs1Url >## 4. CONFIGURE CHOCOLATEY BASELINE ## ### a. FIPS Feature ### #### If you need FIPS compliance - make this the first thing you configure #### before you do any additional configuration or package installations # cChocoFeature featureFipsCompliance < # FeatureName = "useFipsCompliantChecksums" # >### b. Apply Recommended Configuration ### #### Move cache location so Chocolatey is very deterministic about #### cleaning up temporary data and the location is secured to admins cChocoConfig cacheLocation < DependsOn = "[cChocoInstaller]installChocolatey" ConfigName = "cacheLocation" Value = "C:\ProgramData\chocolatey\cache" >#### Increase timeout to at least 4 hours cChocoConfig commandExecutionTimeoutSeconds < DependsOn = "[cChocoInstaller]installChocolatey" ConfigName = "commandExecutionTimeoutSeconds" Value = 14400 >#### Turn off download progress when running choco through integrations cChocoFeature showDownloadProgress < DependsOn = "[cChocoInstaller]installChocolatey" FeatureName = "showDownloadProgress" Ensure = "Absent" >### c. Sources ### #### Remove the default community package repository source cChocoSource removeCommunityRepository < DependsOn = "[cChocoInstaller]installChocolatey" Name = "chocolatey" Ensure = "Absent" >#### Add internal default sources #### You could have multiple sources here, so we will provide an example #### of one using the remote repo variable here. #### NOTE: This EXAMPLE may require changes cChocoSource addInternalSource < DependsOn = "[cChocoInstaller]installChocolatey" Name = "ChocolateyInternal" Source = $NugetRepositoryUrl Credentials = $NugetRepositoryCredential Priority = 1 >### b. Keep Chocolatey Up To Date ### #### Keep chocolatey up to date based on your internal source #### You control the upgrades based on when you push an updated version #### to your internal repository. #### Note the source here is to the OData feed, similar to what you see #### when you browse to https://community.chocolatey.org/api/v2/ cChocoPackageInstaller updateChocolatey < DependsOn = "[cChocoSource]addInternalSource", "[cChocoSource]removeCommunityRepository" Name = "chocolatey" AutoUpgrade = $true >## 5. ENSURE CHOCOLATEY FOR BUSINESS ## ### If you don't have Chocolatey for Business (C4B), you'll want to remove from here down. ### a. Ensure The License File Is Installed ### #### Create a license package using script from https://docs.chocolatey.org/en-us/how-tos/setup-offline-installation#exercise-4-create-a-package-for-the-license cChocoPackageInstaller chocolateyLicense < DependsOn = "[cChocoPackageInstaller]updateChocolatey" Name = "chocolatey-license" >### b. Disable The Licensed Source ### #### The licensed source cannot be removed, so it must be disabled. #### This must occur after the license has been set by the license package. Script disableLicensedSource < DependsOn = "[cChocoPackageInstaller]chocolateyLicense" GetScript = < $Source = choco source list --limitoutput | ` ConvertFrom-Csv -Delimiter '|' -Header Name, Source, Disabled | ` Where-Object Name -eq "chocolatey.licensed" return @< Result = if ($Source) < [bool]::Parse($Source.Disabled) >else < Write-Warning "Source 'chocolatey.licensed' was not present." $true # Source does not need disabling >> > SetScript = < $null = choco source disable --name "chocolatey.licensed" >TestScript = < $State = [ScriptBlock]::Create($GetScript).Invoke() return $State.Result >> ### c. Ensure Chocolatey Licensed Extension ### #### You will have downloaded the licensed extension to your internal repository #### as you have disabled the licensed repository in step 5b. #### Ensure the chocolatey.extension package (aka Chocolatey Licensed Extension) cChocoPackageInstaller chocolateyLicensedExtension < DependsOn = "[Script]disableLicensedSource" Name = "chocolatey.extension" >#### The Chocolatey Licensed Extension unlocks all of the following, which also have configuration/feature items available with them. You may want to visit the feature pages to see what you might want to also enable: #### - Package Builder - https://docs.chocolatey.org/en-us/features/paid/package-builder #### - Package Internalizer - https://docs.chocolatey.org/en-us/features/paid/package-internalizer #### - Package Synchronization (3 components) - https://docs.chocolatey.org/en-us/features/paid/package-synchronization #### - Package Reducer - https://docs.chocolatey.org/en-us/features/paid/package-reducer #### - Package Audit - https://docs.chocolatey.org/en-us/features/paid/package-audit #### - Package Throttle - https://docs.chocolatey.org/en-us/features/paid/package-throttle #### - CDN Cache Access - https://docs.chocolatey.org/en-us/features/paid/private-cdn #### - Branding - https://docs.chocolatey.org/en-us/features/paid/branding #### - Self-Service Anywhere (more components will need to be installed and additional configuration will need to be set) - https://docs.chocolatey.org/en-us/features/paid/self-service-anywhere #### - Chocolatey Central Management (more components will need to be installed and additional configuration will need to be set) - https://docs.chocolatey.org/en-us/features/paid/chocolatey-central-management #### - Other - https://docs.chocolatey.org/en-us/features/paid/ ### d. Ensure Self-Service Anywhere ### #### If you have desktop clients where users are not administrators, you may #### to take advantage of deploying and configuring Self-Service anywhere cChocoFeature hideElevatedWarnings < DependsOn = "[cChocoPackageInstaller]chocolateyLicensedExtension" FeatureName = "showNonElevatedWarnings" Ensure = "Absent" >cChocoFeature useBackgroundService < DependsOn = "[cChocoPackageInstaller]chocolateyLicensedExtension" FeatureName = "useBackgroundService" Ensure = "Present" >cChocoFeature useBackgroundServiceWithNonAdmins < DependsOn = "[cChocoPackageInstaller]chocolateyLicensedExtension" FeatureName = "useBackgroundServiceWithNonAdministratorsOnly" Ensure = "Present" >cChocoFeature useBackgroundServiceUninstallsForUserInstalls < DependsOn = "[cChocoPackageInstaller]chocolateyLicensedExtension" FeatureName = "allowBackgroundServiceUninstallsFromUserInstallsOnly" Ensure = "Present" >cChocoConfig allowedBackgroundServiceCommands < DependsOn = "[cChocoFeature]useBackgroundService" ConfigName = "backgroundServiceAllowedCommands" Value = "install,upgrade,uninstall" >### e. Ensure Chocolatey Central Management ### #### If you want to manage and report on endpoints, you can set up and configure ### Central Management. There are multiple portions to manage, so you'll see ### a section on agents here along with notes on how to configure the server ### side components. if ($ChocolateyCentralManagementUrl) < cChocoPackageInstaller chocolateyAgent < DependsOn = "[cChocoPackageInstaller]chocolateyLicensedExtension" Name = "chocolatey-agent" >cChocoConfig centralManagementServiceUrl < DependsOn = "[cChocoPackageInstaller]chocolateyAgent" ConfigName = "CentralManagementServiceUrl" Value = $ChocolateyCentralManagementUrl >if ($ChocolateyCentralManagementClientSalt) < cChocoConfig centralManagementClientSalt < DependsOn = "[cChocoPackageInstaller]chocolateyAgent" ConfigName = "centralManagementClientCommunicationSaltAdditivePassword" Value = $ChocolateyCentralManagementClientSalt >> if ($ChocolateyCentralManagementServiceSalt) < cChocoConfig centralManagementServiceSalt < DependsOn = "[cChocoPackageInstaller]chocolateyAgent" ConfigName = "centralManagementServiceCommunicationSaltAdditivePassword" Value = $ChocolateyCentralManagementServiceSalt >> cChocoFeature useCentralManagement < DependsOn = "[cChocoPackageInstaller]chocolateyAgent" FeatureName = "useChocolateyCentralManagement" Ensure = "Present" >cChocoFeature useCentralManagementDeployments < DependsOn = "[cChocoPackageInstaller]chocolateyAgent" FeatureName = "useChocolateyCentralManagementDeployments" Ensure = "Present" >> > > # If working this into an existing configuration with a good method for $ConfigData = @ < AllNodes = @( @< NodeName = "localhost" PSDscAllowPlainTextPassword = $true >) > try < Push-Location $env:Temp $Config = ChocolateyConfig -ConfigurationData $ConfigData Start-DscConfiguration -Path $Config.PSParentPath -Wait -Verbose -Force >finally

      Requires Puppet Chocolatey Provider module. See docs at https://forge.puppet.com/puppetlabs/chocolatey.

       ## 1. REQUIREMENTS ## ### Here are the requirements necessary to ensure this is successful. ### a. Internal/Private Cloud Repository Set Up ### #### You'll need an internal/private cloud repository you can use. These are #### generally really quick to set up and there are quite a few options. #### Chocolatey Software recommends Nexus, Artifactory Pro, or ProGet as they #### are repository servers and will give you the ability to manage multiple #### repositories and types from one server installation. ### b. Download Chocolatey Package and Put on Internal Repository ### #### You need to have downloaded the Chocolatey package as well. #### Please see https://chocolatey.org/install#organization ### c. Other Requirements ### #### i. Requires puppetlabs/chocolatey module #### See https://forge.puppet.com/puppetlabs/chocolatey ## 2. TOP LEVEL VARIABLES ## ### a. Your internal repository url (the main one). ### #### Should be similar to what you see when you browse #### to https://community.chocolatey.org/api/v2/ $_repository_url = 'INTERNAL REPO URL' ### b. Chocolatey nupkg download url ### #### This url should result in an immediate download when you navigate to it in #### a web browser $_choco_download_url = 'INTERNAL REPO URL/package/chocolatey.2.2.2.nupkg' ### c. Chocolatey Central Management (CCM) ### #### If using CCM to manage Chocolatey, add the following: #### i. Endpoint URL for CCM # $_chocolatey_central_management_url = 'https://chocolatey-central-management:24020/ChocolateyManagementService' #### ii. If using a Client Salt, add it here # $_chocolatey_central_management_client_salt = "clientsalt" #### iii. If using a Service Salt, add it here # $_chocolatey_central_management_service_salt = 'servicesalt' ## 3. ENSURE CHOCOLATEY IS INSTALLED ## ### Ensure Chocolatey is installed from your internal repository ### Note: `chocolatey_download_url is completely different than normal ### source locations. This is directly to the bare download url for the ### chocolatey.nupkg, similar to what you see when you browse to ### https://community.chocolatey.org/api/v2/package/chocolatey class $_choco_download_url, use_7zip => false, > ## 4. CONFIGURE CHOCOLATEY BASELINE ## ### a. FIPS Feature ### #### If you need FIPS compliance - make this the first thing you configure #### before you do any additional configuration or package installations #chocolateyfeature enabled, #> ### b. Apply Recommended Configuration ### #### Move cache location so Chocolatey is very deterministic about #### cleaning up temporary data and the location is secured to admins chocolateyconfig 'C:\ProgramData\chocolatey\cache', > #### Increase timeout to at least 4 hours chocolateyconfig '14400', > #### Turn off download progress when running choco through integrations chocolateyfeature disabled, > ### c. Sources ### #### Remove the default community package repository source chocolateysource absent, location => 'https://community.chocolatey.org/api/v2/', > #### Add internal default sources #### You could have multiple sources here, so we will provide an example #### of one using the remote repo variable here #### NOTE: This EXAMPLE requires changes chocolateysource present, location => $_repository_url, priority => 1, username => 'optional', password => 'optional,not ensured', bypass_proxy => true, admin_only => false, allow_self_service => false, > ### b. Keep Chocolatey Up To Date ### #### Keep chocolatey up to date based on your internal source #### You control the upgrades based on when you push an updated version #### to your internal repository. #### Note the source here is to the OData feed, similar to what you see #### when you browse to https://community.chocolatey.org/api/v2/ package latest, provider => chocolatey, source => $_repository_url, > ## 5. ENSURE CHOCOLATEY FOR BUSINESS ## ### If you don't have Chocolatey for Business (C4B), you'll want to remove from here down. ### a. Ensure The License File Is Installed ### #### Create a license package using script from https://docs.chocolatey.org/en-us/guides/organizations/organizational-deployment-guide#exercise-4-create-a-package-for-the-license # TODO: Add resource for installing/ensuring the chocolatey-license package package latest, provider => chocolatey, source => $_repository_url, > ### b. Disable The Licensed Source ### #### The licensed source cannot be removed, so it must be disabled. #### This must occur after the license has been set by the license package. ## Disabled sources still need all other attributes until ## https://tickets.puppetlabs.com/browse/MODULES-4449 is resolved. ## Password is necessary with user, but not ensurable, so it should not ## matter what it is set to here. If you ever do get into trouble here, ## the password is your license GUID. chocolateysource disabled, priority => '10', user => 'customer', password => '1234', require => Package['chocolatey-license'], > ### c. Ensure Chocolatey Licensed Extension ### #### You will have downloaded the licensed extension to your internal repository #### as you have disabled the licensed repository in step 5b. #### Ensure the chocolatey.extension package (aka Chocolatey Licensed Extension) package latest, provider => chocolatey, source => $_repository_url, require => Package['chocolatey-license'], > #### The Chocolatey Licensed Extension unlocks all of the following, which also have configuration/feature items available with them. You may want to visit the feature pages to see what you might want to also enable: #### - Package Builder - https://docs.chocolatey.org/en-us/features/paid/package-builder #### - Package Internalizer - https://docs.chocolatey.org/en-us/features/paid/package-internalizer #### - Package Synchronization (3 components) - https://docs.chocolatey.org/en-us/features/paid/package-synchronization #### - Package Reducer - https://docs.chocolatey.org/en-us/features/paid/package-reducer #### - Package Audit - https://docs.chocolatey.org/en-us/features/paid/package-audit #### - Package Throttle - https://docs.chocolatey.org/en-us/features/paid/package-throttle #### - CDN Cache Access - https://docs.chocolatey.org/en-us/features/paid/private-cdn #### - Branding - https://docs.chocolatey.org/en-us/features/paid/branding #### - Self-Service Anywhere (more components will need to be installed and additional configuration will need to be set) - https://docs.chocolatey.org/en-us/features/paid/self-service-anywhere #### - Chocolatey Central Management (more components will need to be installed and additional configuration will need to be set) - https://docs.chocolatey.org/en-us/features/paid/chocolatey-central-management #### - Other - https://docs.chocolatey.org/en-us/features/paid/ ### d. Ensure Self-Service Anywhere ### #### If you have desktop clients where users are not administrators, you may #### to take advantage of deploying and configuring Self-Service anywhere chocolateyfeature disabled, > chocolateyfeature enabled, > chocolateyfeature enabled, > chocolateyfeature enabled, > chocolateyconfig 'install,upgrade,uninstall', > ### e. Ensure Chocolatey Central Management ### #### If you want to manage and report on endpoints, you can set up and configure ### Central Management. There are multiple portions to manage, so you'll see ### a section on agents here along with notes on how to configure the server ### side components. if $_chocolatey_central_management_url < package latest, provider => chocolatey, source => $_repository_url, require => Package['chocolatey-license'], > chocolateyconfig $_chocolatey_central_management_url, > if $_chocolatey_central_management_client_salt < chocolateyconfig $_chocolatey_central_management_client_salt, > > if $_chocolatey_central_management_service_salt < chocolateyconfig $_chocolatey_central_management_client_salt, > > chocolateyfeature enabled, require => Package['chocolatey-agent'], > chocolateyfeature enabled, require => Package['chocolatey-agent'], > > 

      KafkaTool Offset Explorer: Unable to open the keystore using the given password

      I am calling a remote kafka broker from offset explorer using SSL without zookeeper. The configuration requires only setting a chroot path, bootstrapservers, and truststore/keystore locations and passwords. For some reason, it says that the keystore password is invalid. Offset Explorer says that it is unable to open the keystore using the given password. I can successfully access the broker and view topics using the keystore and truststore from a different application that is already deployed, however when I generate a new keystore from my local machine I get the password error shown below. I have confirmed that the certificate and private key can access the broker via KCat CLI tool, skipping the keystore/truststore step. Additionally, when accessing the keystore via keytool command in CLI, the password works as expected. Why would this password not work in OffsetExplorer? (Below bash script creates they keystore, $1 is the path to my signed certificate and $2 is the path to my private key)

      # Converts the pem certificate/key to p12 format # outputs certificate.p12 with the password set by -passout openssl pkcs12 -export -in $1 \ -inkey $2 -out certificate.p12 \ -passin pass:helloworld -passout pass:helloworld # Create the jks file using the p12 generated above keytool -importkeystore -srckeystore certificate.p12 -srcstoretype PKCS12 \ -srcstorepass helloworld -deststorepass helloworld \ -destkeypass helloworld -destkeystore $1-client.keystore.jks 

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *