Introduction and use of common ansible modules

Posted by itpvision on Wed, 09 Feb 2022 08:33:18 +0100

Install ansible

apt update
apt install -y software-properties-common
apt-add-repository --yes --update ppa:ansible/ansible
apt install -y ansible

Generate key unclassified connection

ssh-keygen -f ~/.ssh/id_rsa -P '' -q
#Copy the ssh key to the remote host. You don't need to enter the password when ssh
ssh-copy-id root@192.168.0.74

ansible manage those hosts

Host Inventory configuration file:
The default file is:
/etc/ansible/hosts

Introduction and use of Ansible common modules

ping module

The ping module is mainly used to test whether the target server can be connected

ansible test -m ping

command module

Command module is a pure command execution module, which is used to execute commands on the managed machine. It can also expand functions with many secondary parameters and instructions. Pipeline function is not supported
It should be noted that when the - m parameter of ansible is not specifically specified, the Module called by default is command. The following are some common secondary parameters of command:
creates
Judge that when the file exists, the command will not be executed
free_form
Linux instructions to be executed
chdir
Switch to the specified directory before executing the command
removes
Judge that when the file does not exist, this option will not be executed

ansible test -m command -a "hostname"
#Determine whether there is AA Txt file. If it exists, skip and do not create it
ansible test -m command  -a "creates=aa.txt mkdir -p /opt/aa"
ansible test -m command -a "echo aa"
ansible test -m command -a "chdir=/opt mkdir aa"
#Determine whether there is AA Txt file, if not, it will not be executed
ansible test -m command  -a "creates=aa.txt mkdir -p /opt/aa"

shell module

The main feature of this module is that it includes all command functions and secondary parameter support, and supports pipeline.

ansible test -m shell -a "ps -ef | grep ansible | grep -v grep"

file module

The file module is mainly for some simple operations of files, mainly creating or permission setting, judging the existence of existing files, etc.
group
Define the group of files / directories
mode
Define permissions for files / directories
owner
Define the owner of the file / directory
path
Required to define the path of the file / directory
recurse
Recursively set the attributes of the file, which is only valid for the directory
src
The path to be linked only applies when state=link
dest
The linked path only applies to the case where state=link
state
Directory: if the directory does not exist, create a directory
File: even if the file does not exist, it will not be created
Link: create a soft link
Hard: create a hard link
touch: if the file does not exist, a new file will be created. If the file or directory already exists, its last modification time will be updated
absent: delete directories, files, or unlink files

#Change file ownership, group, and mode. When the mode is specified using octal numbers, the first number should always be 0
ansible test -m file -a "path=/root/su.yaml  owner=test group=test mode=0644"
#Make soft connection
ansible test -m file -a "src=/root/su.yaml dest=/opt/aa.yaml state=link"
# touch creates files and sets permissions using symbol mode (equivalent to 0644)
ansible test -m file -a "path=/root/aa.txt state=touch mode='u=rw,g=r,o=r'"
# touch create files, add / delete some permissions
ansible test -m file -a "path=/root/aa.txt state=touch mode='u+rw,g-wx,o-rwx'"
# Create a directory if it does not exist
ansible test -m file -a "path=/opt/aa state=directory mode=0755"

copy module

Perform a copy operation on a remote host.
src
The local address of the file to be copied to the remote host can be an absolute path or a relative path. If the path is a directory, it will be copied recursively. In this case, if the path ends with "/", only the contents in the directory will be copied. If "/" is not used, the entire contents including the directory will be copied, similar to rsync.
content
The override value of src file can be set directly
dest
Required. The absolute path of the remote host to which the source file is to be copied. If the source file is a directory, the path must also be a directory
directory_mode
Recursively set the permission of the directory. It is the default permission of the system by default
force
If the target host contains the file but the contents are different, if set to yes, it will be forced to overwrite. If set to no, it will be copied only when the file does not exist in the target location of the target host. The default is yes
others
All options in the file module can be used here

#copy local files to remote server and add permissions
ansible test -m copy -a "src=/srv/myfiles/foo.conf dest=/etc/foo.conf owner=foo group=foo mode=0644"
ansible test -m copy -a "src=/srv/myfiles/foo.conf dest=/etc/foo.conf owner=foo group=foo mode='u=rw,g=r,o=r'"
#Copy all files in aa directory
ansible test -m copy -a "src=/root/aa/ dest=/opt"

service module

For managing services, remember not to use this module for Centos7.
arguments
Provide some options to the command line
enabled
Whether to start the machine? yes|no requires at least one of state and enabled.
name
Required, service name
runlevel
Run level
sleep
If restarted is executed, then sleep for a few seconds between stop and start
state
Start, stop, restart and reload the current service

# Start service httpd, if not running
ansible test -m service -a "name=httpd state=started"
# Stop service httpd, if running
ansible test -m service -a "name=httpd state=stopped"
# Enable sample actions for service httpd without using running state
ansible test -m service -a "name=httpd enabled=yes"

cron module

Ansible cron module is mainly used to add, delete and update crontab task plans of the operating system
name
Task plan name
cron_file
Replace the client with the file of the user's task plan
minute
Minutes (0-59, *, / 2)
hour
When (0-23, *, / 2)
day
Day (1-31, *, * / 2)
month
Month (1-12, *, * / 2)
weekday
Weeks (0-6 or 1-7, *)
job
For any planned command, state should be equal to present
backup
Do you want to back up the previous task schedule
user
User who created a new task schedule
state
Specify task plan present, absent

#Based on the cron module, create a crontab task plan. For example, let all back-end servers synchronize with ntpdate from the 192.168.0.250 host at 00:00 every day. The task name is Ntpdate server for sync time. Be sure to pay attention to this timing service and configure the ntp server at 192.168.0.250 
ansible test -m cron -a "minute=0 hour=0 day=* month=* weekday=* name='Ntpdate server for sync time' job='ntpdate 192.168.0.250'"
#backup=yes, which means that backup is enabled, and the backup files will be stored under the client / tmp / directory 
ansible test -m cron -a "minute=0 hour=0 day=* month=* weekday=* name='Ntpdate server for sync time' backup=yes job='ntpdate time.ntp.org'"
#Delete crontab task schedule 
ansible test -m cron -a "name='Ntpdate server for sync time' state=absent"

File system module

The file system module is used to configure the file system of the managed machine. Please be careful when changing the module involves high-level operation. The common parameters are:
dev
Target block device
force
Force creation on a device with an existing file system
fstype
Type of file system
opts
Options passed to mkfs command

#Format call disk
ansible test -m filesystem -a "dev=/dev/sdb fstype=ext4"

mount module

Remote host partition mount
dump
Storage (see column 5 of fstab file). Note that if it is set to null and the status is set to present, it will stop working and duplicate entries will be made in subsequent runs. No impact on Solaris System.
fstype
Required, file system type. The required status is present or mounted
name
Required, mount point
opts
Parameters passed to mount command
src
Required, the path of the device to mount. The required status is present or mounted
state
Required. The options are as follows:
present only handles the configuration in fstab
absent delete mount point
mounted automatically creates and mounts mount points
unmounted uninstall

ansible test -m mount -a "name=/mnt/data src=/dev/sdb1 fstype=ext4 opts=ro state=present"

sysctl module

sysctl configuration module of remote linux host
name
Variable name
value
value
reload
Whether to use sysctl -p reload file when the file is updated
state
Is it to remove (absent) or set (present) from the file
sysctl_file
If it is not the default file, specify another file
sysctl_set
Using sysctl command to set, reload file is not necessary

Ansible doc sysctl can see the following example

#The following is an example defined in the yml format file:
# Set vm.swappiness to 5 in /etc/sysctl.conf
- sysctl:
    name: vm.swappiness
    value: 5
    state: present
# Remove kernel.panic entry from /etc/sysctl.conf
- sysctl:
    name: kernel.panic
    state: absent
    sysctl_file: /etc/sysctl.conf
# Set kernel.panic to 3 in /tmp/test_sysctl.conf
- sysctl:
    name: kernel.panic
    value: 3
    sysctl_file: /tmp/test_sysctl.conf
    reload: no
# Set ip forwarding on in /proc and do not reload the sysctl file
- sysctl:
    name: net.ipv4.ip_forward
    value: 1
    sysctl_set: yes
# Set ip forwarding on in /proc and in the sysctl file and reload if necessary
- sysctl:
    name: net.ipv4.ip_forward
    value: 1
    sysctl_set: yes
    state: present
    reload: yes

yum module

This module is most used when RedHat / CentOS is the OS of the remote node. I won't say more about what Yum is. RedHat / CentOS package management tool
Use yum package manager to manage packages. The options are:
config_file
yum's profile (optional)
disable_gpg_check
Turn off gpg_check (optional)
disablerepo
Do not enable a source (optional)
enablerepo
Enable a source (optional)
name
The name of the software package to be operated. It defaults to the latest package and indicates the package to be installed. It can carry the version number or pass a url or the path of a local rpm package
state
Status (present, absent, latest), indicating whether it is installed or uninstalled
   present: default, indicating installation
  latest: install as the latest version
   absent: indicates deletion

#Install the latest version of http
ansible test -m yum -a 'name=httpd state=latest' 
##Install rpm package
ansible test -m yum -a 'name=http://nginx.org/packages/centos/6/noarch/RPMS/nginx-release-centos-6-0.el6.ngx.noarch.rpm state=present'

apt module

This module is most often used as the remote node of Tu. I won't say much about Apt, the package management tool of Ubuntu/Debian.
deb
For installing on remote machines Package with suffix deb (optional)
install_recommends
This parameter can control whether the software package is only downloaded or installed after downloading on the remote computer. The default parameter is true. When set to false, only the software package is downloaded and not installed
update_cache
When this parameter is yes, it is equal to apt get update (optional)
name
The name of the software package to be downloaded by apt supports the version making mode of name=git=1.6
state
Status (present, absent, latest), indicating whether it is installed or uninstalled
   present: default, indicating installation
  lastest: install the latest version
   absent: indicates deletion

# Update and install foo before installing foo package
ansible test -m apt -a "name=foo update_cache=yes"
# Remove foo package
ansible test -m apt -a "name=foo state=absent"
# Install foo package
ansible test -m apt -a "name=foo state=present"
# Install foo 1.0 package
ansible test -m apt -a "name=foo=1.00 state=present"
# Install nginx's latest release package named squeeze backport, and perform the update before installation
ansible test -m apt -a "name=nginx state=latest default_release=squeeze-backports update_cache=yes"
# Only download the latest package of openjdk-6-jdk without installing it
ansible test -m apt -a "name=openjdk-6-jdk state=latest install_recommends=no"
# Install all software packages to the latest version
ansible test -m apt -a "upgrade=dist"
# Update apt get's list
ansible test -m apt -a "update_cache=yes"
# Stop update after 3600 seconds_ cache
ansible test -m apt -a "update_cache=yes cache_valid_time=3600"
# Install / TMP / mypackage. On the remote node Deb software package
ansible test -m apt -a "deb=/tmp/mypackage.deb"

pip module

Used to manage Python library dependencies. In order to use the pip module, you must provide the parameter name or requirements
chdir
Directory entered by cd before executing pip command
name
The name of the Python library to install or the URL of the remote package.
requirements
A PIP requirements Txt file, which should be the local file of the remote system. If you use the chdir option, you can specify the file as a relative path.
version
The installed version of the specified Python library.
extra_args
Additional parameters are passed to pip.
executable
The path name of an explicit executable or executable that is used to run PIP for a particular version of Python installed on the system. For example, pip-3.3, if Python 2.7 and 3.3 are installed on the system and you want to run PIP for Python 3.3 installation. It cannot be specified with the "virtualenv" parameter (added in 2.1). By default, it will use the version that is applicable to the Python interpreter. pip3 on python 3, pip2 or pip on python 2.
virtualenv
Optional path to the virtualenv directory to install to. It cannot be specified with the 'executable' parameter (added in 2.1). If virtualenv does not exist, it will be created before installing the package. Optional virtualenv_site_packages,virtualenv_command and virtualenv_ The python option affects the creation of virtualenv.
virtualenv_command
The command or pathname used to create the virtual environment. For example, pyvenv, virtualenv, virtualenv2, ~ / bin /virtualenv, / usr/local/bin/virtualenv.
virtualenv_python
Python executable for creating a virtual environment. For example, python 3 5,python2.7. When not specified, the python version used to run the ansible module is used. When virtualenv_command should not use this parameter when using pyvenv or - m venv modules.
state
Status (present, absent, latest, forceinstall), indicating whether to install or uninstall
   present: default, indicating installation
  lastest: install the latest version
   absent: indicates deletion
   forceinstall: the "forceinstall" option is only applicable to ansible version 2.1 and later.

# Install the bottle python package.
ansible test -m pip -a "name=bottle"
# Install the bottle python package in version 0.11.
ansible test -m pip -a "name=bottle version=0.11"
# Install MyApp using remote protocols (bzr +, hg +, git +, svn +). You don't have to be in extra_ The '- e' option is provided in args.
ansible test -m pip -a "name=svn+http://myrepo/svn/MyApp#egg=MyApp"
# Install MyApp using remote protocols (bzr +, hg +, git +).
ansible test -m pip -a "name=git+http://myrepo/app/MyApp"
# Install MyApp from a local package
ansible test -m pip -a "name=file:///path/to/MyApp.tar.gz"
# Install the bottle into the specified virtualenv and inherit the globally installed modules
ansible test -m pip -a "name=bottle virtualenv=/my_app/venv virtualenv_site_packages=yes"
# Install the bottle into the specified virtualenv using Python 2.7
ansible test -m pip -a "name=bottle virtualenv=/my_app/venv virtualenv_command=virtualenv-2.7"
# Install the bottle in the user's home directory.
ansible test -m pip -a "name=bottle extra_args=--user"
# Install the specified python requirements
ansible test -m pip -a "requirements=/my_app/requirements.txt"
# Install the specified python requirements in the specified virtualenv.
ansible test -m pip -a "requirements=/my_app/requirements.txt virtualenv=/my_app/venv"
# Install the specified python requirements and custom pip source URL
ansible test -m pip -a "requirements=/my_app/requirements.txt extra_args=-i https://example.com/pypi/simple"
# bottle is specially installed for Python 3.3, using the 'pip-3.3' executable.
ansible test -m pip -a "name=bottle executable=pip-3.3"
# Install the bottle. If it is already installed, force it to be reinstalled
ansible test -m pip -a "name=bottle state=forcereinstall"

user module

The user module requests three instructions: useradd, userdel and usermod
home
Specify the user's home directory, which needs to be used with createhome.
groups
Specify the user's group.
uid
Specifies the uid to use.
password
Specify the password of the user.
Note that when specifying the password parameter, the plaintext password cannot be used, because the following string of passwords will be directly transmitted to the / etc/shadow file of the managed host, so the password string needs to be encrypted first. Then put the obtained string into password.
name
Specify the user name.
createhome
Whether to create home directory yes|no.
system
Whether it is a system user.
remove
When state=absent, remove=yes means to delete it together with the home directory, which is equivalent to userdel -r.
state
Create or delete. (present,absent)
shell
Specifies the user's shell environment.
generate_ssh_key
Whether to generate SSH key for relevant users. This will not overwrite the existing SSH key.
ssh_key_bits
Optionally, specify the number of digits in the SSH key to be created.
ssh_key_passphrase
Set the password for the SSH key. If no password is provided, the SSH key will default to no password.
ssh_key_file
Specify the SSH key file name (optional). If this is a relative file name, it will be relative to the user's home directory.
ssh_key_type
Specify the type of SSH key to generate (optional). Depends on the type of key that will be available on the target.

# Use the bash shell to add the user "test" and attach the group "Administrator" and "developer" to the user group
ansible test -m user -a "name=test shell=/bin/bash groups=admins,developers append=yes"
# Delete user 'test'
ansible test -m user -a "name=test state=absent remove=yes"
# At ~ / ssh/id_ Create a 2048 bit SSH key for user test in RSA
ansible test -m user -a "name=test generate_ssh_key=yes ssh_key_bits=2048 ssh_key_file=.ssh/id_rsa"

group module

The goup module requests three instructions: groupadd, groupdel and groupmod.
gid
Specifies the gid to use.
name
Specify the user name.
state
Create or delete. (present,absent)
system
If yes, the created group is a system group.

#Sample group commands from Ansible Playbooks
ansible test -m group -a "name=somegroup state=present"

get_url module

This module is mainly used to download files from http, ftp and https servers (similar to wget). It mainly has the following options:
sha256sum
Conduct sha256 check after downloading;
timeout
Download timeout, 10s by default
url
Download URL
url_password,url_username
It is mainly used when the user name and password are required for authentication
dest
The absolute path to where to download the file. If dest is a directory, the file name provided by the server is used, or if not provided, the base name of the URL on the remote server is used.
headers
Add a custom HTTP header for the request in the format "key:value, key:value".

# Demo example of playbook
- name: Download foo.conf
  get_url:
    url: http://example.com/path/file.conf
    dest: /etc/foo.conf
    mode: '0440'

- name: Download file and force basic auth
  get_url:
    url: http://example.com/path/file.conf
    dest: /etc/foo.conf
    force_basic_auth: yes

- name: Download file with custom HTTP headers
  get_url:
    url: http://example.com/path/file.conf
    dest: /etc/foo.conf
    headers:
      key1: one
      key2: two

- name: Download file with check (sha256)
  get_url:
    url: http://example.com/path/file.conf
    dest: /etc/foo.conf
    checksum: sha256:b5bb9d8014a0f9b1d61e21e796d78dccdf1352f23cd32812f4850b878ae4944c

stat module

Obtain remote file status information, including atime, ctime, mtime, md5, uid, gid and other information

ansible test -m stat -a "path=/etc/sysctl.conf"
#Displays information about all ansible default variables
ansible test -m setup

script module

This module is used to execute sh script on the managed machine.

#A simple example of creating a directory is to create the / usr/local/src/data/log directory, as follows:
# cat test1.sh 
#---------------------------------------------------
#!/bin/bash
if [ -z $1 ] || [ -z $2 ];then echo "Wrong,Please input two args" echo "Usage `basename $0` arguments arguments" exit 6
fi
mkdir -pv /usr/local/src/$1/$2
# cat createdir.yml 
---
- hosts: test
  user: root
  gather_facts: True
  tasks:
    - name: Create Dir in client server 
    script: /etc/ansible/test1.sh data log
#Execution:
ansible-playbook createdir.yml

unarchive module

Used to extract files. The module contains the following options:
copy
Whether to copy the file from the local 'master' to the remote host before decompressing the file. The default is yes. If it is no, the compressed package on the target host must exist. This option is similar to remote_src is mutually exclusive.
creates(path)
If the specified absolute path (file or directory) already exists, this step will not be run.
dest
A path on the remote host, that is, the absolute path of file decompression.
keep_newer( yes | no)
Do not replace an existing file that is newer than the file in the archive.
group
The group of unzipped directories or files
owner
The owner of the extracted file or directory
remote_src
Setting to yes indicates that the archived file is already on the remote system, not local to the Ansible controller. This option is mutually exclusive with copy.
list_files
If yes, the files in the compressed package will be listed. The default is no, which is a new option in version 2.0
mode
Permissions of extracted files
src (path / required)
If remote_src=no (default), it is the local path of the archive file to be copied to the target server; It can be absolute or relative.
If it is remote_src=yes, the path of the existing archive file to be decompressed on the target server.
If remote_src=yes and src contain: / /, the remote computer will first download the file from the URL. (version 2.0). In simple cases only, to fully download support, use get_url module.

#name: set foo Extract tgz into / var/lib/foo
ansible test -m unarchive -a "src=foo.tgz dest=/var/lib/foo"
#name: unzip the existing files on the remote computer
ansible test -m unarchive -a "src=/tmp/foo.zip dest=/usr/local/bin remote_src=yes"
#name: files to be downloaded for decompressing documents (added in 2.0)
ansible test -m unarchive -a "src=https://example.com/example.zip dest=/usr/local/bin remote_src=yes"

debug module

This module is used to output information during debugging. It is very useful for debugging variables or expressions without stopping playing this. Debugging with the 'when:' instruction is useful. The Windows target also supports this module.
msg
Debug output messages
var
Pass the output of a task as a variable to the debug module, and debug will print it directly
verbosity
debug level (level 0 by default, all displayed)

Example:

---
- hosts: test
  gather_facts: F   #Open debug
  vars:
    war: "ps -ef | grep tomcat | grep -v grep | awk '{print $2}'"
  tasks:
    - name: stop tomcat 
      shell: nohup /bin/bash /tmp/stop_tomcat.sh& 
      ignore_errors: True 
      register: tomcat_out  #Define variables to store the returned results
    - name: show result #Define the task of the output result 
      debug: 
        var: tomcat_out 
        verbosity: 0 #In this way, not only the command results are output, but also the relevant debugging information is returned. If only the execution results are output, Tomcat is used_ out. stdout. 
    - name: back war 
      shell: cp /home/admin/taobao-tomcat-production-7.0.59.3/deploy/ROOT.war /tmp/
    - name: remove romate dir 
      file: 
        path: /home/admin/taobao-tomcat-production-7.0.59.3/deploy/ROOT 
        state: absent
    - name: remove romate war 
      file: 
        path: /home/admin/taobao-tomcat-production-7.0.59.3/deploy/ROOT.war 
        state: absent
    - name: copy war 
      copy: 
        src: /home/admin/.jenkins/jobs/NET-hangfa/workspace/aecc_purchase_portal_web/xx.war  
        dest: /home/admin/taobao-tomcat-production-7.0.59.3/deploy/ROOT.war 
        owner: admin 
        group: wheel 
        mode: 0644
    - name: start tomcat 
      shell: nohup sh /home/admin/taobao-tomcat-production-7.0.59.3/bin/startup.sh &
    - name: tomcatalive 
      shell: "{{war}}" 
      register: check
    - name: show 
      debug: 
        var: check.stdout 
        verbosity: 0 #check. The information displayed by stdout will be clearer

wait_for module

During the execution of playbook, wait for some operations to complete before subsequent operations

connect_timeout

Timeout to wait for a connection before the next task is executed
delay
When waiting for a port or file or connecting to the specified state, the default timeout is 300 seconds. In the waiting time of 300 seconds, wait_ The for module will always poll whether the specified object reaches the specified state. delay is how often to poll the state.
host
wait_ The address of the host that the for module waits for. The default is 127.0.0.1
port
wait_ The port of the host to which the for module is to be
path
Path. The next task starts only when the file exists, that is, wait for the file to be created
state
The waiting state, that is, when the waiting file or port or connection state reaches the specified state, the next task starts to execute. When the object of waiting is a port, the status has started and stopped, that is, the port has been monitored or the port has been closed; When the waiting object is a file, the status is present or started, except, that is, the file has been created or deleted; When the waiting object is a connection, the status is drained, that is, the connection has been established. The default is started
timeout
wait_ The timeout for waiting for. The default is 300 seconds

Example:

---
- hosts: test
  user: root
  tasks:
    - wait_for: 
        port: 8080 
        state: started #Wait for port 8080 to listen normally before starting the next task until it times out
    - wait_for: 
        port: 8000 
        delay: 10 #Wait for port 8000 to listen normally, and check every 10s until the wait times out
    - wait_for: 
        host: 0.0.0.0 
        port: 8000 
        delay: 10 
        state: drained #Wait for port 8000 until a connection is established
    - wait_for: 
        host: 0.0.0.0 
        port: 8000 
        state: drained 
        exclude_hosts: 10.2.1.2,10.2.1.3 #Wait until a connection is established on port 8000. If the connection comes from 10.2.1.2 or 10.2.1.3, ignore it.
    - wait_for: 
        path: /tmp/foo #Wait for the / tmp/foo file to be created
    - wait_for: 
        path: /tmp/foo 
        search_regex: completed #Wait until the / tmp/foo file has been created and the file needs to contain the completed string
    - wait_for: 
        path: /var/lock/file.lock 
        state: absent #Wait for / var / lock / file Lock deleted
    - wait_for: 
        path: /proc/3466/status 
        state: absent #Wait for the specified process to be destroyed
    - local_action: 
        wait_for port: 22 
        host: "{{ ansible_ssh_host | default(inventory_hostname) }}" 
        search_regex: OpenSSH 
        delay: 10 #Wait for openssh to start and check every 10s

template module

Generate a file based on the template method and copy it to the remote host (template is a module that uses Jinjia2 format as the file template to replace variables in the document. Every time it is used, it will be marked as "changed" by ansible.)
backup
If the original target file exists, back up the target file first. Default: no
src
The path to the Jinja2 format template on the ansible controller. This can be a relative or absolute path.
dest
Render the template to a location on a remote machine.
force
Whether to force overwrite. The default value is yes
owner
Target file owner
group
Target file group
mode
The permission mode of the target file, which can be specified as symbol mode (for example, u + rwx or u = rw, g = r, o = r).

- name: File template to/etc/files.conf
  template:
    src: /mytemplates/foo.j2
    dest: /etc/file.conf
    owner: bin
    group: wheel
    mode: '0644'

- name: Use symbol mode (equivalent to 0644) to template the file
  template:
    src: /mytemplates/foo.j2
    dest: /etc/file.conf
    owner: bin
    group: wheel
    mode: u=rw,g=r,o=r

- name: Replication is operating system dependent named.conf edition. By executing on the original file ls -Z /etc/named.conf Acquired setype
  template:
    src: named.conf_{{ ansible_os_family }}.j2
    dest: /etc/named.conf
    group: named
    setype: named_conf_t
    mode: 0640

- name: Create from template DOS Style text file
  template:
    src: config.ini.j2
    dest: /share/windows/config.ini
    newline_sequence: '\r\n'

- name: adopt visudo After verification, the new sudoers Copy files in place
  template:
    src: /mine/sudoers
    dest: /etc/sudoers
    validate: /usr/sbin/visudo -cf %s

- name: Security update sshd Configuration to avoid locking yourself
  template:
    src: etc/ssh/sshd_config.j2
    dest: /etc/ssh/sshd_config
    owner: root
    group: root
    mode: '0600'
    validate: /usr/sbin/sshd -t -f %s
    backup: yes

Topics: ansible