Thank you for reading this post, don't forget to subscribe!
создаём структуру директорий:
mkdir -p /etc/ansible/{playbooks/roles_play,roles/new_server/{defaults,handlers,meta,tasks,templates}}
Описание структуры:
/etc/ansible/playbooks/ - тут хранятся плейбуки
/etc/ansible/playbooks/roles_play/ - тут хранятся плейбуки с которых будем запускать роль
/etc/ansible/roles/ - тут хранятся роли
/etc/ansible/roles/new_server - тут хранится роль для первичной установки. (в которой содержаться следующие директории defaults handlers meta tasks templates)
перейдём к содержимому директории
/etc/ansible/roles/new_server/tasks
Плейбук для добавления epel репозитория:
/etc/ansible/roles/new_server/tasks/installepelrepo.yml
1 |
[codesyntax lang="bash"] |
1 2 3 4 5 6 7 8 9 10 |
- name: Install EPEL repo. yum: name: https://dl.fedoraproject.org/pub/epel/epel-release-latest-{{ ansible_distribution_major_version }}.noarch.rpm state: present - name: Import EPEL GPG key. rpm_key: key: /etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-{{ ansible_distribution_major_version }} state: present |
1 2 3 4 |
[/codesyntax] Плейбук для установки стандартных пакетов: |
/etc/ansible/roles/new_server/tasks/defaultpackages.yml
[codesyntax lang="bash"]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
- name: Install default packages yum: name: "{{item}}" state: present with_items: - telnet - htop - bind-utils - net-tools - vim - nano - tcpdump - ntp - libselinux-python - wget - name: Install additional packages in Centos/Rhel 7 yum: name: "{{ item }}" state: present with_items: - iptables - iptables-services when: (ansible_distribution_major_version == "7") - name: Delete firewalld service yum: name: firewalld state: absent when: (ansible_distribution_major_version == "7") |
[/codesyntax]
Плейбук для обновления пакетов и системы:
/etc/ansible/roles/new_server/tasks/upgradesystem.yml
[codesyntax lang="bash"]
1 2 3 4 5 |
- name: upgrade all packages yum: name: '*' state: latest |
[/codesyntax]
Плейбук для с настроенным конфигурационным файлом sshd
/etc/ansible/roles/new_server/tasks/ssh.yml
в зависимости от версии операционной системы (ansible_distribution_major_version ) будет скопирован соответствующий конфигурационный файл:
[root@ansible tasks]# ll /etc/ansible/roles/new_server/templates/sshd_config*
-rw-r--r--. 1 root root 3875 Jan 5 2018 /etc/ansible/roles/new_server/templates/sshd_config6
-rw-r--r--. 1 root root 4359 Jun 9 18:37 /etc/ansible/roles/new_server/templates/sshd_config7
[codesyntax lang="bash"]
1 2 3 4 5 |
- name: Copy sshd_config to remote host template: src=/etc/ansible/roles/new_server/templates/sshd_config{{ ansible_distribution_major_version }} dest=/etc/ssh/sshd_config mode='600' notify: - restart sshd |
[/codesyntax]
Плейбук для ntp сервера:
/etc/ansible/roles/new_server/tasks/ntp.yml
[codesyntax lang="bash"]
1 2 3 4 5 |
- name: Copy NTP config to remote host template: src=/etc/ansible/roles/new_server/templates/ntp.conf dest=/etc/ntp.conf notify: - restart ntpd |
[/codesyntax]
Плейбук для копирования sudo в котором нашим пользователям можно будет авторизовываться под root
/etc/ansible/roles/new_server/tasks/sudoers.yml
[codesyntax lang="bash"]
1 2 |
- name: Copy sudoers to remote host template: src=/etc/ansible/roles/new_server/templates/sudoers dest=/etc/sudoers mode='440' |
[/codesyntax]
Плейбук для добавления пользователей
/etc/ansible/roles/new_server/tasks/addusers.yml
[codesyntax lang="bash"]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
- name: add users user: name: "{{ item }}" group: wheel shell: /bin/bash append: yes with_items: - ansible - mid - user1 - name: Set authorized key took from file for users authorized_key: user: "{{ item }}" state: present key: "{{ lookup('file', '/home/ansible/.ssh/{{ item }}.id_rsa.pub') }}" with_items: - mid - user1 - name: Set authorized key took from file for ansible authorized_key: user: ansible state: present key: "{{ lookup('file', '/home/ansible/.ssh/id_rsa.pub') }}" |
[/codesyntax]
Плейбук для отключения Selinux
/etc/ansible/roles/new_server/tasks/selinuxDisable.yaml
[codesyntax lang="bash"]
1 2 3 |
- name: DISABLE SELINUX selinux: state=disabled |
[/codesyntax]
Основной файл который будет подтягивать данные плейбуки:
/etc/ansible/roles/new_server/tasks/main.yml
[codesyntax lang="bash"]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
--- - import_tasks: installepelrepo.yml tags: epel - import_tasks: defaultpackages.yml tags: default - import_tasks: upgradesystem.yml tags: upgrade - import_tasks: ssh.yml tags: sshd - import_tasks: ntp.yml tags: ntp - import_tasks: sudoers.yml tags: sudo - import_tasks: addusers.yml tags: adduser - import_tasks: selinuxDisable.yaml tags: disable Selinux |
[/codesyntax]
Плейбук с которого будет запускаться данная роль:
/etc/ansible/playbooks/roles_play/new_server.yml
[codesyntax lang="bash"]
1 2 3 4 5 6 7 8 9 |
--- - hosts: test become: true ignore_errors: yes become_method: sudo gather_facts: yes roles: - new_server |
[/codesyntax]
Handler для нашей установки:
/etc/ansible/roles/new_server/handlers/main.yml
[codesyntax lang="bash"]
1 2 3 4 5 6 |
--- - name: restart ntpd service: name=ntpd state=restarted enabled=yes - name: restart sshd service: name=sshd state=restarted enabled=yes |
[/codesyntax]
Темплейты которые копируется в процессе установки:
cat /etc/ansible/roles/new_server/templates/ntp.conf
# ntp.conf(5), ntp_acc(5), ntp_auth(5), ntp_clock(5), ntp_misc(5), ntp_mon(5).driftfile /var/lib/ntp/drift# Permit time synchronization with our time source, but do not
# permit the source to query or modify the service on this system.
restrict default nomodify notrap nopeer noquery# Permit all access over the loopback interface. This could
# be tightened as well, but to do so would effect some of
# the administrative functions.
restrict 127.0.0.1
restrict ::1# Hosts on local network are less restricted.
#restrict 192.168.1.0 mask 255.255.255.0 nomodify notrap# Use public servers from the pool.ntp.org project.
# Please consider joining the pool (http://www.pool.ntp.org/join.html).server 0.us.pool.ntp.org iburst
server 1.us.pool.ntp.org iburst
server 2.us.pool.ntp.org iburst
server 3.us.pool.ntp.org iburst
#broadcast 192.168.1.255 autokey # broadcast server
#broadcastclient # broadcast client
#broadcast 224.0.1.1 autokey # multicast server
#multicastclient 224.0.1.1 # multicast client
#manycastserver 239.255.254.254 # manycast server
#manycastclient 239.255.254.254 autokey # manycast client
# Enable public key cryptography.
#crypto
includefile /etc/ntp/crypto/pw
# Key file containing the keys and key identifiers used when operating
# with symmetric key cryptography.
keys /etc/ntp/keys
# Specify the key identifiers which are trusted.
#trustedkey 4 8 42
# Specify the key identifier to use with the ntpdc utility.
#requestkey 8
# Specify the key identifier to use with the ntpq utility.
#controlkey 8
# Enable writing of statistics records.
#statistics clockstats cryptostats loopstats peerstats
# Disable the monitoring facility to prevent amplification attacks using ntpdc
# monlist command when default restrict does not include the noquery flag. See
# CVE-2013-5211 for more details.
# Note: Monitoring will not be disabled with the limited restriction flag.
disable monitor
[/spoiler]
cat /etc/ansible/roles/new_server/templates/sudoers
## Sudoers allows particular users to run various commands as
## the root user, without needing the root password.
##
## Examples are provided at the bottom of the file for collections
## of related commands, which can then be delegated out to particular
## users or groups.
##
## This file must be edited with the 'visudo' command.## Host Aliases
## Groups of machines. You may prefer to use hostnames (perhaps using
## wildcards for entire domains) or IP addresses instead.
# Host_Alias FILESERVERS = fs1, fs2
# Host_Alias MAILSERVERS = smtp, smtp2## User Aliases
## These aren't often necessary, as you can use regular groups
## (ie, from files, LDAP, NIS, etc) in this file - just use %groupname
## rather than USERALIAS
# User_Alias ADMINS = jsmith, mikem## Command Aliases
## These are groups of related commands…## Networking
# Cmnd_Alias NETWORKING = /sbin/route, /sbin/ifconfig, /bin/ping, /sbin/dhclient, /usr/bin/net, /sbin/iptables, /usr/bin/rfcomm, /usr/bin/wvdial, /sbin/iwconfig, /sbin/mii-tool## Installation and management of software
# Cmnd_Alias SOFTWARE = /bin/rpm, /usr/bin/up2date, /usr/bin/yum## Services
# Cmnd_Alias SERVICES = /sbin/service, /sbin/chkconfig
## Updating the locate database
# Cmnd_Alias LOCATE = /usr/bin/updatedb
## Storage
# Cmnd_Alias STORAGE = /sbin/fdisk, /sbin/sfdisk, /sbin/parted, /sbin/partprobe, /bin/mount, /bin/umount
## Delegating permissions
# Cmnd_Alias DELEGATING = /usr/sbin/visudo, /bin/chown, /bin/chmod, /bin/chgrp
## Processes
# Cmnd_Alias PROCESSES = /bin/nice, /bin/kill, /usr/bin/kill, /usr/bin/killall
## Drivers
# Cmnd_Alias DRIVERS = /sbin/modprobe
# Defaults specification
#
# Refuse to run if unable to disable echo on the tty.
#
Defaults !visiblepw
#
# Preserving HOME has security implications since many programs
# use it when searching for configuration files. Note that HOME
# is already set when the the env_reset option is enabled, so
# this option is only effective for configurations where either
# env_reset is disabled or HOME is present in the env_keep list.
#
Defaults always_set_home
Defaults env_reset
Defaults env_keep = "COLORS DISPLAY HOSTNAME HISTSIZE KDEDIR LS_COLORS"
Defaults env_keep += "MAIL PS1 PS2 QTDIR USERNAME LANG LC_ADDRESS LC_CTYPE"
Defaults env_keep += "LC_COLLATE LC_IDENTIFICATION LC_MEASUREMENT LC_MESSAGES"
Defaults env_keep += "LC_MONETARY LC_NAME LC_NUMERIC LC_PAPER LC_TELEPHONE"
Defaults env_keep += "LC_TIME LC_ALL LANGUAGE LINGUAS _XKB_CHARSET XAUTHORITY"
#
# Adding HOME to env_keep may enable a user to run unrestricted
# commands via sudo.
#
# Defaults env_keep += "HOME"
Defaults secure_path = /sbin:/bin:/usr/sbin:/usr/bin
## Next comes the main part: which users can run what software on
## which machines (the sudoers file can be shared between multiple
## systems).
## Syntax:
##
## user MACHINE=COMMANDS
##
## The COMMANDS section may have other options added to it.
##
## Allow root to run any commands anywhere
root ALL=(ALL) ALL
## Allows members of the 'sys' group to run networking, software,
## service management apps and more.
# %sys ALL = NETWORKING, SOFTWARE, SERVICES, STORAGE, DELEGATING, PROCESSES, LOCATE, DRIVERS
## Allows people in group wheel to run all commands
# %wheel ALL=(ALL) ALL
## Same thing without a password
%wheel ALL=(ALL) NOPASSWD: ALL
## Allows members of the users group to mount and unmount the
## cdrom as root
# %users ALL=/sbin/mount /mnt/cdrom, /sbin/umount /mnt/cdrom
## Allows members of the users group to shutdown this system
# %users localhost=/sbin/shutdown -h now
## Read drop-in files from /etc/sudoers.d (the # here does not mean a comment)
#includedir /etc/sudoers.d
[/spoiler]
# $OpenBSD: sshd_config,v 1.80 2008/07/02 02:24:18 djm Exp $# This is the sshd server system-wide configuration file. See
# sshd_config(5) for more information.# This sshd was compiled with PATH=/usr/local/bin:/bin:/usr/bin# The strategy used for options in the default sshd_config shipped with
# OpenSSH is to specify options with their default value where
# possible, but leave them commented. Uncommented options change a
# default value.#Port 22
#AddressFamily any
#ListenAddress 0.0.0.0
#ListenAddress ::# Disable legacy (protocol version 1) support in the server for new
# installations. In future the default will change to require explicit
# activation of protocol 1
Protocol 2# HostKey for protocol version 1
#HostKey /etc/ssh/ssh_host_key
# HostKeys for protocol version 2
#HostKey /etc/ssh/ssh_host_rsa_key
#HostKey /etc/ssh/ssh_host_dsa_key
# Lifetime and size of ephemeral version 1 server key
#KeyRegenerationInterval 1h
#ServerKeyBits 1024
# Logging
# obsoletes QuietMode and FascistLogging
#SyslogFacility AUTH
SyslogFacility AUTHPRIV
#LogLevel INFO
# Authentication:
#LoginGraceTime 2m
PermitRootLogin no
#StrictModes yes
#MaxAuthTries 6
#MaxSessions 10
#RSAAuthentication yes
PubkeyAuthentication yes
AuthorizedKeysFile .ssh/authorized_keys
#AuthorizedKeysCommand none
#AuthorizedKeysCommandRunAs nobody
# For this to work you will also need host keys in /etc/ssh/ssh_known_hosts
#RhostsRSAAuthentication no
# similar for protocol version 2
#HostbasedAuthentication no
# Change to yes if you don't trust ~/.ssh/known_hosts for
# RhostsRSAAuthentication and HostbasedAuthentication
#IgnoreUserKnownHosts no
# Don't read the user's ~/.rhosts and ~/.shosts files
#IgnoreRhosts yes
# To disable tunneled clear text passwords, change to no here!
#PasswordAuthentication yes
#PermitEmptyPasswords no
PasswordAuthentication yes
# Change to no to disable s/key passwords
#ChallengeResponseAuthentication yes
ChallengeResponseAuthentication no
# Kerberos options
#KerberosAuthentication no
#KerberosOrLocalPasswd yes
#KerberosTicketCleanup yes
#KerberosGetAFSToken no
#KerberosUseKuserok yes
# GSSAPI options
#GSSAPIAuthentication no
GSSAPIAuthentication yes
#GSSAPICleanupCredentials yes
GSSAPICleanupCredentials yes
#GSSAPIStrictAcceptorCheck yes
#GSSAPIKeyExchange no
# Set this to 'yes' to enable PAM authentication, account processing,
# and session processing. If this is enabled, PAM authentication will
# be allowed through the ChallengeResponseAuthentication and
# PasswordAuthentication. Depending on your PAM configuration,
# PAM authentication via ChallengeResponseAuthentication may bypass
# the setting of "PermitRootLogin without-password".
# If you just want the PAM account and session checks to run without
# PAM authentication, then enable this but set PasswordAuthentication
# and ChallengeResponseAuthentication to 'no'.
#UsePAM no
UsePAM yes
# Accept locale-related environment variables
AcceptEnv LANG LC_CTYPE LC_NUMERIC LC_TIME LC_COLLATE LC_MONETARY LC_MESSAGES
AcceptEnv LC_PAPER LC_NAME LC_ADDRESS LC_TELEPHONE LC_MEASUREMENT
AcceptEnv LC_IDENTIFICATION LC_ALL LANGUAGE
AcceptEnv XMODIFIERS
#AllowAgentForwarding yes
#AllowTcpForwarding yes
#GatewayPorts no
#X11Forwarding no
X11Forwarding yes
#X11DisplayOffset 10
#X11UseLocalhost yes
#PrintMotd yes
#PrintLastLog yes
#TCPKeepAlive yes
#UseLogin no
#UsePrivilegeSeparation yes
#PermitUserEnvironment no
#Compression delayed
#ClientAliveInterval 0
#ClientAliveCountMax 3
#ShowPatchLevel no
#UseDNS yes
#PidFile /var/run/sshd.pid
#MaxStartups 10:30:100
#PermitTunnel no
#ChrootDirectory none
# no default banner path
#Banner none
# override default of no subsystems
Subsystem sftp /usr/libexec/openssh/sftp-server
# Example of overriding settings on a per-user basis
#Match User anoncvs
# X11Forwarding no
# AllowTcpForwarding no
# ForceCommand cvs server
[/spoiler]
[spoiler]
# This is the sshd server system-wide configuration file. See
# sshd_config(5) for more information.
# This sshd was compiled with PATH=/usr/local/bin:/usr/bin
# The strategy used for options in the default sshd_config shipped with
# OpenSSH is to specify options with their default value where
# possible, but leave them commented. Uncommented options override the
# default value.
# If you want to change the port on a SELinux system, you have to tell
# SELinux about this change.
# semanage port -a -t ssh_port_t -p tcp #PORTNUMBER
#
#Port 22
#AddressFamily any
#ListenAddress 0.0.0.0
#ListenAddress ::
# The default requires explicit activation of protocol 1
#Protocol 2
# HostKey for protocol version 1
#HostKey /etc/ssh/ssh_host_key
# HostKeys for protocol version 2
HostKey /etc/ssh/ssh_host_rsa_key
#HostKey /etc/ssh/ssh_host_dsa_key
HostKey /etc/ssh/ssh_host_ecdsa_key
HostKey /etc/ssh/ssh_host_ed25519_key
# Lifetime and size of ephemeral version 1 server key
#KeyRegenerationInterval 1h
#ServerKeyBits 1024
# Ciphers and keying
#RekeyLimit default none
# Logging
# obsoletes QuietMode and FascistLogging
#SyslogFacility AUTH
SyslogFacility AUTHPRIV
#LogLevel INFO
# Authentication:
#LoginGraceTime 2m
PermitRootLogin no
#StrictModes yes
#MaxAuthTries 6
#MaxSessions 10
#RSAAuthentication yes
PubkeyAuthentication yes
# The default is to check both .ssh/authorized_keys and .ssh/authorized_keys2
# but this is overridden so installations will only check .ssh/authorized_keys
AuthorizedKeysFile .ssh/authorized_keys
#AuthorizedPrincipalsFile none
#AuthorizedKeysCommand none
#AuthorizedKeysCommandUser nobody
# For this to work you will also need host keys in /etc/ssh/ssh_known_hosts
#RhostsRSAAuthentication no
# similar for protocol version 2
#HostbasedAuthentication no
# Change to yes if you don't trust ~/.ssh/known_hosts for
# RhostsRSAAuthentication and HostbasedAuthentication
#IgnoreUserKnownHosts no
# Don't read the user's ~/.rhosts and ~/.shosts files
#IgnoreRhosts yes
# To disable tunneled clear text passwords, change to no here!
#PasswordAuthentication yes
#PermitEmptyPasswords no
PasswordAuthentication yes
# Change to no to disable s/key passwords
#ChallengeResponseAuthentication yes
ChallengeResponseAuthentication no
# Kerberos options
#KerberosAuthentication no
#KerberosOrLocalPasswd yes
#KerberosTicketCleanup yes
#KerberosGetAFSToken no
#KerberosUseKuserok yes
# GSSAPI options
GSSAPIAuthentication yes
GSSAPICleanupCredentials no
#GSSAPIStrictAcceptorCheck yes
#GSSAPIKeyExchange no
#GSSAPIEnablek5users no
# Set this to 'yes' to enable PAM authentication, account processing,
# and session processing. If this is enabled, PAM authentication will
# be allowed through the ChallengeResponseAuthentication and
# PasswordAuthentication. Depending on your PAM configuration,
# PAM authentication via ChallengeResponseAuthentication may bypass
# the setting of "PermitRootLogin without-password".
# If you just want the PAM account and session checks to run without
# PAM authentication, then enable this but set PasswordAuthentication
# and ChallengeResponseAuthentication to 'no'.
# WARNING: 'UsePAM no' is not supported in Red Hat Enterprise Linux and may cause several
# problems.
UsePAM yes
#AllowAgentForwarding yes
#AllowTcpForwarding yes
#GatewayPorts no
X11Forwarding yes
#X11DisplayOffset 10
#X11UseLocalhost yes
#PermitTTY yes
#PrintMotd yes
#PrintLastLog yes
#TCPKeepAlive yes
#UseLogin no
UsePrivilegeSeparation sandbox # Default for new installations.
#PermitUserEnvironment no
#Compression delayed
#ClientAliveInterval 0
#ClientAliveCountMax 3
#ShowPatchLevel no
#UseDNS yes
#PidFile /var/run/sshd.pid
#MaxStartups 10:30:100
#PermitTunnel no
#ChrootDirectory none
#VersionAddendum none
# no default banner path
#Banner none
# Accept locale-related environment variables
AcceptEnv LANG LC_CTYPE LC_NUMERIC LC_TIME LC_COLLATE LC_MONETARY LC_MESSAGES
AcceptEnv LC_PAPER LC_NAME LC_ADDRESS LC_TELEPHONE LC_MEASUREMENT
AcceptEnv LC_IDENTIFICATION LC_ALL LANGUAGE
AcceptEnv XMODIFIERS
# override default of no subsystems
Subsystem sftp /usr/libexec/openssh/sftp-server
# Example of overriding settings on a per-user basis
#Match User anoncvs
# X11Forwarding no
# AllowTcpForwarding no
# PermitTTY no
# ForceCommand cvs server
[/spoiler]
/etc/ansible/hosts
добавляем группу и ip адрес серверов на которые будет производиться установка:[root@ansible ~]# cat /etc/ansible/hosts | grep -v ^# | grep -v ^$
[test]
192.168.1.170
Теперь создаём пользователей и ключи
su - ansible
ssh-keygen
su - mid
ssh-keygen
su - user1
ssh-keygen
cp /home/mid/.ssh/id_rsa.pub /home/ansible/.ssh/mid.id_rsa.pub
cp /home/user1/.ssh/id_rsa.pub /home/ansible/.ssh/user1.id_rsa.pub
chown -R ansible:ansible /home/ansible/
Запускаем установку:
Для начала правим файл:
/etc/ansible/playbooks/roles_play/new_server.yml
в нём меняем строку
- hosts: test
на
- hosts: 192.168.1.170
если оставить test то установка пройдёт для всех серверов данной группы
1 2 3 4 5 6 |
Для тестового прогона(<strong>-C</strong>), можем использовать следующую команду: <strong>ansible-playbook -C -u root /etc/ansible/playbooks/roles_play/new_server.yml --ask-pass </strong>запускаем её от рута и используем опцию <strong>--ask-pass </strong>которая запросит пароль. в дальнейших запусках будем использовать пользователя ansible и <strong>--ask-pass </strong>будет не нужен так как ключи для ssh будут уже добавлены. Запускаем теперь в обычном режиме, вывод будет примерно такой: <strong>ansible-playbook -u root /etc/ansible/playbooks/roles_play/new_server.yml --ask-pass</strong> |
[spoiler]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 |
[root@ansible ~]# ansible-playbook -u root /etc/ansible/playbooks/roles_play/new_server.yml --ask-pass SSH password: PLAY [192.168.1.170] ******************************************************************************************************************************************************* TASK [Gathering Facts] ***************************************************************************************************************************************************** ok: [192.168.1.170] TASK [new_server : Install EPEL repo.] ************************************************************************************************************************************* changed: [192.168.1.170] TASK [new_server : Import EPEL GPG key.] *********************************************************************************************************************************** changed: [192.168.1.170] TASK [new_server : Install default packages] ******************************************************************************************************************************* [DEPRECATION WARNING]: Invoking "yum" only once while using a loop via squash_actions is deprecated. Instead of using a loop to supply multiple items and specifying `name: "{{item}}"`, please use `name: ['telnet', 'htop', 'bind-utils', 'net-tools', 'vim', 'nano', 'tcpdump', 'ntp', 'libselinux-python', 'wget']` and remove the loop. This feature will be removed in version 2.11. Deprecation warnings can be disabled by setting deprecation_warnings=False in ansible.cfg. changed: [192.168.1.170] => (item=[u'telnet', u'htop', u'bind-utils', u'net-tools', u'vim', u'nano', u'tcpdump', u'ntp', u'libselinux-python', u'wget']) TASK [new_server : Install additional packages in Centos/Rhel 7] *********************************************************************************************************** [DEPRECATION WARNING]: Invoking "yum" only once while using a loop via squash_actions is deprecated. Instead of using a loop to supply multiple items and specifying `name: "{{ item }}"`, please use `name: ['iptables', 'iptables-services']` and remove the loop. This feature will be removed in version 2.11. Deprecation warnings can be disabled by setting deprecation_warnings=False in ansible.cfg. changed: [192.168.1.170] => (item=[u'iptables', u'iptables-services']) TASK [new_server : Delete firewalld service] ******************************************************************************************************************************* ok: [192.168.1.170] TASK [new_server : upgrade all packages] *********************************************************************************************************************************** changed: [192.168.1.170] TASK [new_server : Copy sshd_config to remote host] ************************************************************************************************************************ changed: [192.168.1.170] TASK [new_server : Copy NTP config to remote host] ************************************************************************************************************************* changed: [192.168.1.170] TASK [new_server : Copy sudoers to remote host] **************************************************************************************************************************** changed: [192.168.1.170] TASK [new_server : add users] ********************************************************************************************************************************************** changed: [192.168.1.170] => (item=ansible) changed: [192.168.1.170] => (item=mid) changed: [192.168.1.170] => (item=user1) TASK [new_server : Set authorized key took from file for users] ************************************************************************************************************ changed: [192.168.1.170] => (item=mid) changed: [192.168.1.170] => (item=user1) TASK [new_server : Set authorized key took from file for ansible] ********************************************************************************************************** changed: [192.168.1.170] RUNNING HANDLER [new_server : restart ntpd] ******************************************************************************************************************************** changed: [192.168.1.170] RUNNING HANDLER [new_server : restart sshd] ******************************************************************************************************************************** changed: [192.168.1.170] PLAY RECAP ***************************************************************************************************************************************************************** 192.168.1.170 : ok=15 changed=13 unreachable=0 failed=0 |
[/spoiler]
вывод будет примерно таким:[root@ansible ~]# ansible-playbook -u ansible /etc/ansible/playbooks/roles_play/new_server.yml
[spoiler]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
PLAY [192.168.1.170] ******************************************************************************************************************************************************* TASK [Gathering Facts] ***************************************************************************************************************************************************** ok: [192.168.1.170] TASK [new_server : Install EPEL repo.] ************************************************************************************************************************************* ok: [192.168.1.170] TASK [new_server : Import EPEL GPG key.] *********************************************************************************************************************************** ok: [192.168.1.170] TASK [new_server : Install default packages] ******************************************************************************************************************************* [DEPRECATION WARNING]: Invoking "yum" only once while using a loop via squash_actions is deprecated. Instead of using a loop to supply multiple items and specifying `name: "{{item}}"`, please use `name: ['telnet', 'htop', 'bind-utils', 'net-tools', 'vim', 'nano', 'tcpdump', 'ntp', 'libselinux-python', 'wget']` and remove the loop. This feature will be removed in version 2.11. Deprecation warnings can be disabled by setting deprecation_warnings=False in ansible.cfg. ok: [192.168.1.170] => (item=[u'telnet', u'htop', u'bind-utils', u'net-tools', u'vim', u'nano', u'tcpdump', u'ntp', u'libselinux-python', u'wget']) TASK [new_server : Install additional packages in Centos/Rhel 7] *********************************************************************************************************** [DEPRECATION WARNING]: Invoking "yum" only once while using a loop via squash_actions is deprecated. Instead of using a loop to supply multiple items and specifying `name: "{{ item }}"`, please use `name: ['iptables', 'iptables-services']` and remove the loop. This feature will be removed in version 2.11. Deprecation warnings can be disabled by setting deprecation_warnings=False in ansible.cfg. ok: [192.168.1.170] => (item=[u'iptables', u'iptables-services']) TASK [new_server : Delete firewalld service] ******************************************************************************************************************************* ok: [192.168.1.170] TASK [new_server : upgrade all packages] *********************************************************************************************************************************** ok: [192.168.1.170] TASK [new_server : Copy sshd_config to remote host] ************************************************************************************************************************ ok: [192.168.1.170] TASK [new_server : Copy NTP config to remote host] ************************************************************************************************************************* ok: [192.168.1.170] TASK [new_server : Copy sudoers to remote host] **************************************************************************************************************************** ok: [192.168.1.170] TASK [new_server : add users] ********************************************************************************************************************************************** ok: [192.168.1.170] => (item=ansible) ok: [192.168.1.170] => (item=mid) ok: [192.168.1.170] => (item=user1) TASK [new_server : Set authorized key took from file for users] ************************************************************************************************************ ok: [192.168.1.170] => (item=mid) ok: [192.168.1.170] => (item=user1) TASK [new_server : Set authorized key took from file for ansible] ********************************************************************************************************** ok: [192.168.1.170] TASK [new_server : DISABLE SELINUX] **************************************************************************************************************************************** [WARNING]: SELinux state temporarily changed from 'enforcing' to 'permissive'. State change will take effect next reboot. changed: [192.168.1.170] PLAY RECAP ***************************************************************************************************************************************************************** 192.168.1.170 : ok=14 changed=1 unreachable=0 failed=0 |
[/spoiler]