# Ansible module and some advance options
Modules:
Command: This module help you to execute commands to the target host, it may be command or script
===> chdir:
Following is simple playboot that will display contents of /etc/hosts of webserers.
and you can use chdir sub-module that tells ansible servers to change dir to /etc before doing cat to hosts file
[root@ansimaster playbooks]# cat date.yml
-
name: Play 1
hosts: webservers
tasks:
- name: Execute a date command
command: cat hosts chdir=/etc
[root@ansimaster playbooks]#
===> creates
[root@ansimaster playbooks]# cat date.yml
-
name: Play 1
hosts: webservers
tasks:
- name: Execute a date command
command: cat hosts chdir=/etc
- name: create folder if not exists
command: mkdir /test_dir creates=true
[root@ansimaster playbooks]#
[root@ansimaster ~]# ansible --version
ansible 2.7.10
config file = /etc/ansible/ansible.cfg
configured module search path = [u'/root/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
ansible python module location = /usr/lib/python2.7/site-packages/ansible
executable location = /usr/bin/ansible
python version = 2.7.5 (default, Nov 6 2016, 00:28:07) [GCC 4.8.5 20150623 (Red Hat 4.8.5-11)]
[root@ansimaster ~]#
[root@ansimaster home]# ansible webservers:dbservers -m shell -a "echo "=======";hostname;echo "========";\n;ip a| grep ens34"
192.168.159.153 | CHANGED | rc=0 >>
=======
db1
========
3: ens34: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP qlen 1000
inet 192.168.159.153/24 brd 192.168.159.255 scope global ens34
inet 192.168.159.156/24 brd 192.168.159.255 scope global secondary dynamic ens34/bin/sh: n: command not found
192.168.159.142 | CHANGED | rc=0 >>
=======
web1
========
3: ens34: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP qlen 1000
inet 192.168.159.142/24 brd 192.168.159.255 scope global ens34
inet 192.168.159.155/24 brd 192.168.159.255 scope global secondary dynamic ens34/bin/sh: n: command not found
[root@ansimaster home]#
================= adhoc commands =======
[root@ansimaster ~]# ansible dbservers -m command -a /usr/bin/hostname
192.168.159.153 | CHANGED | rc=0 >>
db1
[root@ansimaster ~]# ansible webservers -m command -a /usr/bin/hostname
192.168.159.142 | CHANGED | rc=0 >>
web1
[root@ansimaster ~]# ansible localhost -m command -a /usr/bin/hostname
localhost | CHANGED | rc=0 >>
ansimaster
[root@ansimaster ~]#
======================================================================
Use -o optio to display ansible adhoc command outout in single line
======================================================================
[root@ansimaster ~]# ansible webservers -m command -a /usr/bin/hostname -o
192.168.159.142 | CHANGED | rc=0 | (stdout) web1
[root@ansimaster ~]#
[root@ansimaster ~]#
[root@ansimaster ~]# ansible dbservers -m command -a /usr/bin/hostname -o
192.168.159.153 | CHANGED | rc=0 | (stdout) db1
[root@ansimaster ~]#
[root@ansimaster ~]# ansible webservers -m command -a 'cat /etc/motd' -o
192.168.159.142 | CHANGED | rc=0 | (stdout) this is managed by ansible
[root@ansimaster ~]# ansible webservers -m copy -a 'content="etc/motd is managed by ansibale\n" dest=/etc/motd' -o
192.168.159.142 | CHANGED => {"changed": true, "checksum": "d34ee6cd1004e828c6241cd9bb873555a6ac10c2", "dest": "/etc/motd", "gid": 0, "group": "root", "md5sum": "b0d0234efbedea7222af15bb134a40d4", "mode": "0644", "owner": "root", "secontext": "system_u:object_r:etc_t:s0", "size": 32, "src": "/root/.ansible/tmp/ansible-tmp-1562164775.78-137644172963725/source", "state": "file", "uid": 0}
[root@ansimaster ~]#
[root@ansimaster ~]# ansible dbservers -m copy -a 'content="etc/motd is managed by ansibale\n" dest=/etc/motd' -o
192.168.159.153 | CHANGED => {"changed": true, "checksum": "d34ee6cd1004e828c6241cd9bb873555a6ac10c2", "dest": "/etc/motd", "gid": 0, "group": "root", "md5sum": "b0d0234efbedea7222af15bb134a40d4", "mode": "0644", "owner": "root", "secontext": "system_u:object_r:etc_t:s0", "size": 32, "src": "/root/.ansible/tmp/ansible-tmp-1562164789.3-108260834981552/source", "state": "file", "uid": 0}
[root@ansimaster ~]#
[root@ansimaster ~]# ansible webservers -m command -a 'cat /etc/motd' -o
192.168.159.142 | CHANGED | rc=0 | (stdout) etc/motd is managed by ansibale
[root@ansimaster ~]# ansible dbservers -m copy -a 'content="/etc/motd is managed by ansibale\n" dest=/etc/motd' -o
192.168.159.153 | CHANGED => {"changed": true, "checksum": "95ab7b16d1a7d8dafbd55b57ffae5627d4b88b66", "dest": "/etc/motd", "gid": 0, "group": "root", "md5sum": "01f3b61cfe0086feca8a24208a7892b2", "mode": "0644", "owner": "root", "secontext": "system_u:object_r:etc_t:s0", "size": 33, "src": "/root/.ansible/tmp/ansible-tmp-1562164811.49-99926344171678/source", "state": "file", "uid": 0}
[root@ansimaster ~]#
[root@ansimaster ~]#
[root@ansimaster ~]# ansible webservers -m command -a 'cat /etc/motd' -o
192.168.159.142 | CHANGED | rc=0 | (stdout) etc/motd is managed by ansibale
[root@ansimaster ~]#
[root@ansimaster ~]#
[root@ansimaster ~]#
===================================================
Ad-hoc command to list httpd and firewalld installed on remote server
===================================================
root@ansimaster:/etc/ansible]#ansible webservers -a 'yum list installed firewalld'
[WARNING]: Consider using yum module rather than running yum
192.168.122.50 | SUCCESS | rc=0 >>
Loaded plugins: fastestmirror, langpacks
Installed Packages
firewalld.noarch 0.5.3-5.el7 @base
[root@ansimaster:/etc/ansible]#
======================================================
ansible-doc is used to list available modules
======================================================
[root@ansimaster ~]# ansible-doc -l
a10_server Manage A10 Networks AX/SoftAX/Thunder/vThunder devices' server object.
a10_server_axapi3 Manage A10 Networks AX/SoftAX/Thunder/vThunder devices
a10_service_group Manage A10 Networks AX/SoftAX/Thunder/vThunder devices' service groups.
a10_virtual_server Manage A10 Networks AX/SoftAX/Thunder/vThunder devices' virtual servers.
aci_aaa_user Manage AAA users (aaa:User)
aci_aaa_user_certificate Manage AAA user certificates (aaa:UserCert)
aci_access_port_to_interface_policy_leaf_profile Manage Fabric interface policy leaf profile interface selectors (infra:HPortS,...
aci_aep Manage attachable Access Entity Profile (AEP) objects (infra:AttEntityP, infra...
aci_aep_to_domain Bind AEPs to Physical or Virtual Domains (infra:RsDomP)
aci_ap Manage top level Application Profile (AP) objects (fv:Ap)
aci_bd Manage Bridge Domains (BD) objects (fv:BD)
aci_bd_subnet Manage Subnets (fv:Subnet)
aci_bd_to_l3out Bind Bridge Domain to L3 Out (fv:RsBDToOut)
aci_config_rollback Provides rollback and rollback preview functionality (config:ImportP)
aci_config_snapshot Manage Config Snapshots (config:Snapshot, config:ExportP)
aci_contract Manage contract resources (vz:BrCP)
aci_contract_subject Manage initial Contract Subjects (vz:Subj)
aci_contract_subject_to_filter Bind Contract Subjects to Filters (vz:RsSubjFiltAtt)
aci_domain Manage physical, virtual, bridged, routed or FC domain profiles (phys:DomP, vm...
aci_domain_to_encap_pool Bind Domain to Encap Pools (infra:RsVlanNs)
aci_domain_to_vlan_pool Bind Domain to VLAN Pools (infra:RsVlanNs)
aci_encap_pool Manage encap pools (fvns:VlanInstP, fvns:VxlanInstP, fvns:VsanInstP)
aci_encap_pool_range Manage encap ranges assigned to pools (fvns:EncapBlk, fvns:VsanEncapBlk)
aci_epg Manage End Point Groups (EPG) objects (fv:AEPg)
aci_epg_monitoring_policy Manage monitoring policies (mon:EPGPol)
aci_epg_to_contract Bind EPGs to Contracts (fv:RsCons, fv:RsProv)
aci_epg_to_domain Bind EPGs to Domains (fv:RsDomAtt)
aci_fabric_node Manage Fabric Node Members (fabric:NodeIdentP)
aci_filter Manages top level filter objects (vz:Filter)
aci_filter_entry Manage filter entries (vz:Entry)
aci_firmware_source Manage firmware image sources (firmware:OSource)
aci_interface_policy_fc Manage Fibre Channel interface policies (fc:IfPol)
aci_interface_policy_l2 Manage Layer 2 interface policies (l2:IfPol)
aci_interface_policy_leaf_policy_group Manage fabric interface policy leaf policy groups (infra:AccBndlGrp, infra:Acc...
aci_interface_policy_leaf_profile Manage fabric interface policy leaf profiles (infra:AccPortP)
aci_interface_policy_lldp Manage LLDP interface policies (lldp:IfPol)
aci_interface_policy_mcp Manage MCP interface policies (mcp:IfPol)
aci_interface_policy_ospf Manage OSPF interface policies (ospf:IfPol)
[root@ansimaster ~]#
[root@ansimaster ~]# ansible-doc yum
> YUM (/usr/lib/python2.7/site-packages/ansible/modules/packaging/os/yum.py)
Installs, upgrade, downgrades, removes, and lists packages and groups with the `yum' package
manager. This module only works on Python 2. If you require Python 3 support see the [dnf] module.
* note: This module has a corresponding action plugin.
OPTIONS (= is mandatory):
- allow_downgrade
Specify if the named package and version is allowed to downgrade a maybe already installed higher
version of that package. Note that setting allow_downgrade=True can make this module behave in a
non-idempotent way. The task could end up with a set of packages that does not match the complete
list of specified packages to install (because dependencies between the downgraded package and
others can cause changes to the packages which were in the earlier transaction).
[Default: no]
type: bool
version_added: 2.4
- autoremove
If `yes', removes all "leaf" packages from the system that were originally installed as dependencies
of user-installed packages but which are no longer required by any such package. Should be used
alone or when state is `absent'
NOTE: This feature requires yum >= 3.4.3 (RHEL/CentOS 7+)
[Default: False]
type: bool
version_added: 2.7
------------- Snip --------------
------------- Snip --------------
EXAMPLES:
- name: install the latest version of Apache
yum:
name: httpd
state: latest
- name: ensure a list of packages installed
yum:
name: "{{ packages }}"
vars:
packages:
- httpd
- httpd-tools
- name: remove the Apache package
yum:
name: httpd
state: absent
- name: install the latest version of Apache from the testing repo
yum:
name: httpd
enablerepo: testing
state: present
- name: install one specific version of Apache
yum:
name: httpd-2.2.29-1.4.amzn1
state: present
- name: upgrade all packages
yum:
name: '*'
state: latest
- name: upgrade all packages, excluding kernel & foo related packages
yum:
name: '*'
state: latest
exclude: kernel*,foo*
- name: install the nginx rpm from a remote repo
yum:
name: http://nginx.org/packages/centos/6/noarch/RPMS/nginx-release-centos-6-0.el6.ngx.noarch.rpm
state: present
- name: install nginx rpm from a local file
yum:
name: /usr/local/src/nginx-release-centos-6-0.el6.ngx.noarch.rpm
state: present
- name: install the 'Development tools' package group
yum:
name: "@Development tools"
state: present
- name: install the 'Gnome desktop' environment group
yum:
name: "@^gnome-desktop-environment"
state: present
- name: List ansible packages and register result to print with debug later.
yum:
list: ansible
register: result
- name: Install package with multiple repos enabled
yum:
name: sos
enablerepo: "epel,ol7_latest"
- name: Install package with multiple repos disabled
yum:
name: sos
disablerepo: "epel,ol7_latest"
- name: Install a list of packages
yum:
name:
- nginx
- postgresql
- postgresql-server
state: present
- name: Download the nginx package but do not install it
yum:
name:
- nginx
state: latest
download_only: true
==================================================================================
if we would like to list of procedure that a module can provide to use in playbook
Following is list of action we can add in playbook to execute using yum module
==================================================================================
[root@ansimaster ~]# ansible-doc -s yum
- name: Manages packages with the `yum' package manager
yum:
allow_downgrade: # Specify if the named package and version is allowed to downgrade a maybe already installed higher
version of that package. Note that setting allow_downgrade=True can make
this module behave in a non-idempotent way. The task could end up with a
set of packages that does not match the complete list of specified
packages to install (because dependencies between the downgraded package
and others can cause changes to the packages which were in the earlier
transaction).
autoremove: # If `yes', removes all "leaf" packages from the system that were originally installed as dependencies of
user-installed packages but which are no longer required by any such
package. Should be used alone or when state is `absent' NOTE: This
feature requires yum >= 3.4.3 (RHEL/CentOS 7+)
bugfix: # If set to `yes', and `state=latest' then only installs updates that have been marked bugfix related.
conf_file: # The remote yum configuration file to use for the transaction.
disable_excludes: # Disable the excludes defined in YUM config files. If set to `all', disables all excludes. If set to
`main', disable excludes defined in [main] in yum.conf. If set to
`repoid', disable excludes defined for given repo id.
disable_gpg_check: # Whether to disable the GPG checking of signatures of packages being installed. Has an effect only if
state is `present' or `latest'.
disable_plugin: # `Plugin' name to disable for the install/update operation. The disabled plugins will not persist beyond
the transaction.
disablerepo: # `Repoid' of repositories to disable for the install/update operation. These repos will not persist
beyond the transaction. When specifying multiple repos, separate them
with a `","'. As of Ansible 2.7, this can alternatively be a list instead
of `","' separated string
download_only: # Only download the packages, do not install them.
enable_plugin: # `Plugin' name to enable for the install/update operation. The enabled plugin will not persist beyond the
transaction.
enablerepo: # `Repoid' of repositories to enable for the install/update operation. These repos will not persist beyond
the transaction. When specifying multiple repos, separate them with a
`","'. As of Ansible 2.7, this can alternatively be a list instead of
`","' separated string
exclude: # Package name(s) to exclude when state=present, or latest
installroot: # Specifies an alternative installroot, relative to which all packages will be installed.
list: # Package name to run the equivalent of yum list <package> against. In addition to listing packages, use
can also list the following: `installed', `updates', `available' and
`repos'.
name: # A package name or package specifier with version, like `name-1.0'. If a previous version is specified,
the task also needs to turn `allow_downgrade' on. See the
`allow_downgrade' documentation for caveats with downgrading packages.
When using state=latest, this can be `'*'' which means run `yum -y
update'. You can also pass a url or a local path to a rpm file (using
state=present). To operate on several packages this can accept a comma
separated string of packages or (as of 2.0) a list of packages.
releasever: # Specifies an alternative release from which all packages will be installed.
security: # If set to `yes', and `state=latest' then only installs updates that have been marked security related.
skip_broken: # Skip packages with broken dependencies(devsolve) and are causing problems.
state: # Whether to install (`present' or `installed', `latest'), or remove (`absent' or `removed') a package.
`present' and `installed' will simply ensure that a desired package is
installed. `latest' will update the specified package if it's not of the
latest available version. `absent' and `removed' will remove the
specified package. Default is `None', however in effect the default
action is `present' unless the `autoremove' option is¬ enabled for this
module, then `absent' is inferred.
update_cache: # Force yum to check if cache is out of date and redownload if needed. Has an effect only if state is
`present' or `latest'.
[root@ansimaster ~]#
[root@ansimaster ~]# ansible webservers -m service -a "name=httpd state=restarted"
192.168.159.142 | CHANGED => {
"changed": true,
"name": "httpd",
"state": "started",
"status": {
"ActiveEnterTimestampMonotonic": "0",
"ActiveExitTimestampMonotonic": "0",
"ActiveState": "inactive",
"After": "nss-lookup.target -.mount basic.target network.target systemd-journald.socket remote-fs.target system.slice tmp.mount",
"AllowIsolate": "no",
"AssertResult": "no",
"AssertTimestampMonotonic": "0",
---------- Snip------------
---------- Snip------------
[root@web1 ~]# systemctl satus httpd
Unknown operation 'satus'.
========status before run adhoc command on master server ======
[root@web1 ~]# systemctl status httpd
● httpd.service - The Apache HTTP Server
Loaded: loaded (/usr/lib/systemd/system/httpd.service; disabled; vendor preset: disabled)
Active: inactive (dead)
Docs: man:httpd(8)
man:apachectl(8)
[root@web1 ~]#
========status after run adhoc command on master server ======
[root@web1 ~]# systemctl status httpd
● httpd.service - The Apache HTTP Server
Loaded: loaded (/usr/lib/systemd/system/httpd.service; disabled; vendor preset: disabled)
Active: active (running) since Thu 2019-07-04 07:16:19 EDT; 6s ago
Docs: man:httpd(8)
man:apachectl(8)
Main PID: 12286 (httpd)
Status: "Processing requests..."
CGroup: /system.slice/httpd.service
├─12286 /usr/sbin/httpd -DFOREGROUND
├─12287 /usr/sbin/httpd -DFOREGROUND
├─12288 /usr/sbin/httpd -DFOREGROUND
├─12289 /usr/sbin/httpd -DFOREGROUND
├─12290 /usr/sbin/httpd -DFOREGROUND
└─12291 /usr/sbin/httpd -DFOREGROUND
Jul 04 07:16:19 web1 systemd[1]: Starting The Apache HTTP Server...
Jul 04 07:16:19 web1 httpd[12286]: AH00558: httpd: Could not reliably determine the server's fully qualified domain name, usi... message
Jul 04 07:16:19 web1 systemd[1]: Started The Apache HTTP Server.
Hint: Some lines were ellipsized, use -l to show in full.
==================================================================
executing playbook interactively
==================================================================
[root@ansimaster playbooks]# ansible-playbook --step apache_playbook2.yml -v
Using /etc/ansible/ansible.cfg as config file
/etc/ansible/hosts did not meet host_list requirements, check plugin documentation if this is unexpected
/etc/ansible/hosts did not meet script requirements, check plugin documentation if this is unexpected
PLAY [webservers] **********************************************************************************************************************
Perform task: TASK: Gathering Facts (N)o/(y)es/(c)ontinue: y
Perform task: TASK: Gathering Facts (N)o/(y)es/(c)ontinue: *****************************************************************************
TASK [Gathering Facts] *****************************************************************************************************************
ok: [192.168.159.142]
Perform task: TASK: Install httpd package (N)o/(y)es/(c)ontinue: y
Perform task: TASK: Install httpd package (N)o/(y)es/(c)ontinue: ***********************************************************************
TASK [Install httpd package] ***********************************************************************************************************
ok: [192.168.159.142] => {"changed": false, "msg": "", "rc": 0, "results": ["httpd-2.4.6-89.el7.centos.x86_64 providing httpd is already installed"]}
Perform task: TASK: Start appache services (N)o/(y)es/(c)ontinue: y
Perform task: TASK: Start appache services (N)o/(y)es/(c)ontinue: **********************************************************************
TASK [Start appache services] **********************************************************************************************************
ok: [192.168.159.142] => {"changed": false, "name": "httpd", "state": "started", "status": {"ActiveEnterTimestamp": "Fri 2019-07-05 07:17:41 EDT", "ActiveEnterTimestampMonotonic": "1625
<======= output snip ======>
<======= output snip ======>
Perform task: TASK: Deploying httpd conf (N)o/(y)es/(c)ontinue: y
Perform task: TASK: Deploying httpd conf (N)o/(y)es/(c)ontinue: ************************************************************************
TASK [Deploying httpd conf] ************************************************************************************************************
ok: [192.168.159.142] => {"changed": false, "dest": "/usr/share/httpd/noindex/", "src": "/ansible/config/httpd/conf/"}
PLAY RECAP *****************************************************************************************************************************
192.168.159.142 : ok=4 changed=0 unreachable=0 failed=0
[root@ansimaster playbooks]#