Find and Replace in Notepad++

Find : ^([^]]*])\s Replace : \1\t

  • ^ โ†’ start of the line
  • ([^]]*]) โ†’ capture everything up to and including the first ]
    • [^]]* = โ€œany number of characters that are not ]โ€
    • then the first ]
  • \s โ†’ the space right after that ]
  • Replace with \1\t โ†’ the captured group (everything up to first ]) followed by a tab

Find : ([MIN-\d{4}])\s Replace : \1\t

  • (\[MIN-\d{4}\]) โ†’ captures [MIN-####] where #### is exactly 4 digits
  • \s โ†’ matches the space right after it
  • Replace with โ†’ \1\t โ†’ put back the captured [MIN-####] and replace the space with a tab

Remove [ and ] around [MIN-####]

Find : [MIN-(\d{4})] Replace : MIN-\1

  • \[MIN-(\d{4})\] โ†’ matches [MIN-2156]
    • \[ and \] โ†’ literal brackets
    • (\d{4}) โ†’ capture 4 digits
  • MIN-\1 โ†’ puts back the text without the brackets, using the captured digits

#notepad

Add new Resolution option for Display on Ubuntu

  1. Find the monitor or display using the xrandr command
$xrandr

Here, DP-1 will be your Display / Monitor ID

2. Get the Modeline string using one of below command

cvt 1366 768

or

gtf 1920 1080 60

3. Add new mode using Modeline output

xrandr --newmode "1920x1080_60.00"  172.80  1920 2040 2248 2576  1080 1081 1084 1118  -HSync +Vsync

4. Add created new mode to desired display

xrandr --addmode DP-1 "1920x1080_60.00"

Once this is done you can see the Resolution in the Settings > Display > Resolution dropdown.

5. Add to your bash profile to make it permanent

sudo gedit ~/.profile

Add below two commands to there.

xrandr --newmode "1920x1080_60.00"  172.80  1920 2040 2248 2576  1080 1081 1084 1118  -HSync +Vsync 
xrandr --addmode DP-1 "1920x1080_60.00"

Note : Check the maximum resolution that monitor supports also otherwise it will display something like this.

References :

  • https://blog.mohessaid.com/fix-external-monitor-resolution-in-ubuntu-20-04-9c24cee65950
  • https://unix.stackexchange.com/questions/227876/how-to-set-custom-resolution-using-xrandr-when-the-resolution-is-not-available-i
  • https://askubuntu.com/questions/138408/how-to-add-display-resolution-for-an-lcd-in-ubuntu-12-04-xrandr-problem

#display, #ubuntu

Invoking GraphQL APIs

API developed using GraphQL is normally provided a convenient UI Tools that can be used to test the API calls. there are various tools that can be used to build this as mentioned here.

You can easily enter the payload, Query Variables and HTTP Headers to invoke the API calls.

ref : https://anilist.co/graphiql

ref :

  • https://docs-search.hoteltrader.com/gui
  • https://hotel-trader.stoplight.io/docs/pull-api/ZG9jOjE0Njk0OTU0-overview

Also, you can use the Docs and Schema to see how is the API Structured before calling it.

Anyway, same calls can be done trough curl or any HTTP client (eg : Postman / Insomnia / Direct Java HTTP Client code ). You can use debug mode (F12) in the browser to see how is the request goes to back-end.

curl :

curl 'https://docs-search.hoteltrader.com/graphql' -H 'Accept-Encoding: gzip, deflate, br' -H 'Content-Type: application/json' -H 'Accept: application/json' -H 'Connection: keep-alive' -H 'DNT: 1' -H 'Origin: https://docs-search.hoteltrader.com' --data-binary '{"query":"# Write your query or mutation here\nquery getPropertiesByIds($SearchCriteriaByIds: SearchCriteriaByIdsInput) {\n  getPropertiesByIds(searchCriteriaByIds: $SearchCriteriaByIds) {\n  properties {\n      propertyId\n      propertyName\n      occupancies {\n        occupancyRefId\n        checkInDate\n        checkOutDate\n        numberOfAdults\n        numberOfChildren\n        childrenAges\n      }\n      rooms {\n        occupancyRefId\n        htIdentifier\n        roomName\n        shortDescription\n        longDescription\n       \n        rateInfo {\n          bar\n          binding\n          commissionable\n          commissionAmount\n          currency\n          netPrice\n          tax\n          grossPrice\n          payAtProperty\n          dailyPrice\n          dailyTax\n         \n          taxInfo {\n            payAtBooking {\n              date\n              name\n              description\n              value\n            }\n            payAtProperty {\n              date\n              name\n              description\n              value\n            }\n          }\n        }\n        mealplanOptions{\n          breakfastIncluded\n          lunchIncluded\n          dinnerIncluded\n          allInclusive\n          mealplanDescription\n        }\n        rateplanTag\n        refundable\n        cancellationPolicies {\n          startWindowTime\n          endWindowTime\n          cancellationCharge\n          timeZone\n        }\n      }\n\t\t\tshortDescription\n\t\t\tlongDescription\n      city\n      latitude\n      longitude\n      starRating\n      hotelImageUrl\n    }\n  }\n}","variables":{"SearchCriteriaByIds":{"propertyIds":[134388],"occupancies":[{"checkInDate":"2022-06-01","checkOutDate":"2022-06-02","numberOfAdults":2,"numberOfChildren":0,"childrenAges":""}]}}}' --compressed

Postman :

Java

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import com.fasterxml.jackson.databind.ObjectMapper;

public class HotelTradeSearchTest {
	
	public static void main(String[] args) throws IOException {

		sendPOST();
		System.out.println("POST DONE");
	}

	private static void sendPOST() throws IOException {
		URL obj = new URL("https://docs-search.hoteltrader.com/graphql");
		HttpURLConnection con = (HttpURLConnection) obj.openConnection();
		con.setRequestMethod("POST");
		con.setRequestProperty("Content-Type", "application/json");

		// For POST only - START
		con.setDoOutput(true);
		OutputStream os = con.getOutputStream();
		os.write(
				("{\n"
				+ "\n"
				+ "    \"operationName\":\"getPropertiesByCity\",\n"
				+ "    \"variables\":{\n"
				+ "        \"searchCriteriaByCity\":{\n"
				+ "            \"city\":\"New York, New York, United States Of America\",\n"
				+ "            \"occupancies\":[\n"
				+ "                {\n"
				+ "                    \"checkInDate\":\"2022-06-01\",\n"
				+ "                    \"checkOutDate\":\"2022-06-02\",\n"
				+ "                    \"numberOfAdults\":2,\n"
				+ "                    \"numberOfChildren\":0,\n"
				+ "                    \"childrenAges\":\"\"\n"
				+ "                }\n"
				+ "            ]\n"
				+ "        }\n"
				+ "    },\n"
				+ "    \"query\":\"query getPropertiesByCity($searchCriteriaByCity: SearchCriteriaByCityInput) {\\n getPropertiesByCity(searchCriteriaByCity: $searchCriteriaByCity) {\\n properties {\\n propertyId\\n propertyName\\n occupancies {\\n occupancyRefId\\n checkInDate\\n checkOutDate\\n numberOfAdults\\n numberOfChildren\\n childrenAges\\n }\\n rooms {\\n occupancyRefId\\n htIdentifier\\n roomName\\n shortDescription\\n longDescription\\n rateInfo {\\n bar\\n binding\\n commissionable\\n commissionAmount\\n currency\\n netPrice\\n tax\\n grossPrice\\n payAtProperty\\n dailyPrice\\n dailyTax\\n taxInfo {\\n payAtBooking {\\n date\\n name\\n description\\n value\\n }\\n payAtProperty {\\n date\\n name\\n description\\n value\\n }\\n }\\n }\\n mealplanOptions {\\n breakfastIncluded\\n lunchIncluded\\n dinnerIncluded\\n allInclusive\\n mealplanDescription\\n }\\n rateplanTag\\n refundable\\n cancellationPolicies {\\n startWindowTime\\n endWindowTime\\n cancellationCharge\\n timeZone\\n }\\n }\\n shortDescription\\n longDescription\\n city\\n latitude\\n longitude\\n starRating\\n hotelImageUrl\\n }\\n }\\n}\\n\"\n"
				+ "\n"
				+ "}").getBytes()
				);
		os.flush();
		os.close();
		// For POST only - END

		int responseCode = con.getResponseCode();
		System.out.println("POST Response Code :: " + responseCode);

		if (responseCode == HttpURLConnection.HTTP_OK) { // success
			BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
			String inputLine;
			StringBuffer response = new StringBuffer();

			while ((inputLine = in.readLine()) != null) {
				response.append(inputLine);
			}
			in.close();

			ObjectMapper mapper = new ObjectMapper();
			System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(mapper.readTree(response.toString())));
			
		} else {
			System.out.println("POST request not worked");
		}
	}
}

Maven dependencies:

		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-core</artifactId>
			<version>2.11.2</version>
		</dependency>
		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-databind</artifactId>
			<version>2.11.2</version>
		</dependency>

References :

  • https://www.graphql-java.com/
  • https://www.baeldung.com/spring-graphql
  • https://www.howtographql.com/graphql-java/0-introduction/
  • https://developer.okta.com/blog/2020/01/31/java-graphql
  • https://github.com/graphql-java/graphql-java
  • https://github.com/graphql-java/tutorials/tree/master/book-details
  • https://www.programcreek.com/java-api-examples/?api=graphql.schema.idl.RuntimeWiring
  • https://www.tabnine.com/code/java/classes/graphql.schema.idl.RuntimeWiring
  • https://search.maven.org/artifact/com.graphql-java/graphql-java/16.2/jar
  • http://www.java2s.com/example/jar/g/download-graphqljava40jar-file.html
  • https://graphql.org/code/#generic-tools

#apis, #graphql, #java, #rest

Restore terminal

This happened when multiple python3 versions installed. We need to specify the exact version in that case. You can use Xterm like third party terminal for this.

sudo nano /usr/bin/gnome-terminal

Then, change:

#!/usr/bin/python3

to exact version

#!/usr/bin/python3.x

Reference :

#terminal, #ubuntu

SOAP UI Mock Service Runner


sudo bash /{{SoapUI-Root}}/bin/mockservicerunner.sh -Dsoapui.mock.connector.headerBufferSize=16000 {{url-or-path-to-project-xml}}

Example :

  • sudo bash /apps/soapUI/SoapUI-5.4.0/bin/mockservicerunner.sh -Dsoapui.mock.connector.headerBufferSize=16000 https://mock.awshost.io/soapUI/Projects/mock-xyz-soapui-project.xml &
  • sudo bash /home/namal/Fun/soapui/SoapUI-5.6.0/bin/mockservicerunner.sh -Dsoapui.mock.connector.headerBufferSize=16000 /home/namal/Fun/soapui/test-mock/Project-1-soapui-project.xml

Match response based on request body

def requestBody = mockRequest.getRequestContent()
log.info "Request body: " + requestBody

if( requestBody.contains("reschedule") ){
return "Reschedule POST res"
}
else if( requestBody.contains("cause") ){
return "Cancel Response"
}else if( requestBody.contains("amendendusertype") ){
return "Ammend-EndUser-POST"
}

Calling TestSuit within MockService

OnRequest Script

import com.eviware.soapui.support.types.StringToStringMap 
import java.net.URL
import groovy.json.JsonSlurper

def authtoken = ""
def post = new URL("https://keycloak.awshost.io/auth/realms/cossmos/protocol/openid-connect/token").openConnection()
def message = 'grant_type=password&client_id=xyzClient&username=xyz&password=123456&client_secret=dsa213-4gfd-5645fds42423-324das'

post.setRequestMethod("POST")
post.setDoOutput(true)
post.setRequestProperty("Content-Type", "application/x-www-form-urlencoded")
post.getOutputStream().write(message.getBytes("UTF-8"))

def postRC = post.getResponseCode()
if(postRC.equals(200)) {
	def resp = post.getInputStream().getText()
	def json = new JsonSlurper().parseText(resp)
	authtoken = json.'access_token'
	log.info("Call back authToken retrieved!");
}else{
	log.info("Call back authToken not retrieved!")
}

context.setProperty("authtoken","bearer " + authtoken)

def callbackEp = mockRequest.getRequestHeaders().get("callback-ep-uri").get(0).toString()
context.setProperty("callback-ep-uri",callbackEp)

AfterRequest Script

import com.eviware.soapui.support.GroovyUtils
import com.eviware.soapui.support.types.StringToObjectMap
import com.eviware.soapui.impl.wsdl.teststeps.RestTestRequestStep
import com.eviware.soapui.support.types.StringToStringMap 

def groovyUtils = new GroovyUtils( context )
def headers = new StringToStringMap()

if(mockResult != null){

	def requestContent=mockResult.getMockRequest().requestContent;
	def requestBody = new groovy.json.JsonSlurper().parseText(requestContent)
	
	def map = new StringToObjectMap()
	def authtoken = context.getProperty("authtoken")
	def callbackEndpoint = context.getProperty("callback-ep-uri")

	def testsuite = context.mockService.project.getTestSuiteByName("MagnifyDiagnosticTestsuite")
	def testcaseName = null;
	def actualExtId = null;

	if(requestBody.cause != null){
		testcaseName = "AppointmentCancel"
	}else if(requestBody.externalId.contains("reschedule")){
		testcaseName = "ApppointmentReschedule"
	}else{
		testcaseName = "AppointmentCallbackAsyncMessages"
	}

	if(requestBody.externalId.contains("-::") ){
		actualExtId = requestBody.externalId.split('-::')
	}
		
	def testcase = testsuite.getTestCaseByName(testcaseName)

	if(actualExtId != null){
		testcase.setPropertyValue( "externalId", actualExtId[0] )
	}else{
		testcase.setPropertyValue( "externalId", requestBody.externalId )
	}

	headers.put("Authorization",authtoken)
	headers.put("Content-Type","application/json")
	headers.put("NBN-ConversationID","unique-identifier")
	headers.put("NBN-APIVersion","test-version")
	headers.put("NBN-RSPSecurityToken","securityTokenValue")
	headers.put("NBN-TransactionID","transaction-id")

	def teststep = testcase.getTestStepsOfType(RestTestRequestStep.class)
	teststep.eachWithIndex(){ step, index -> 
		teststep.get(index).testRequest.setEndpoint(callbackEndpoint)
		teststep.get(index).testRequest.setRequestHeaders(headers)
	}

	testcase.run(map, true) //true here means call asynchronously i.e. dont wait to the TestCase to finish first
}

#mock, #rest, #soapui

boot repair

  1. sudo add-apt-repository ppa:yannubuntu/boot-repair
  2. sudo apt update
  3. sudo apt install boot-repair
  4. boot-repair

Repair the boot of the computer in standard way

Say No to upload the report to the paste bin

sudo reboot now

ref : https://www.youtube.com/watch?v=bzbIckBnerg&t=703s

#boot, #os, #ubuntu, #windows

Fetch new No ref to fetch from.. branch

First try to do a normal Fetch


[Right Click] > Team > Fetch From Origin

If it is mentioned as โ€œNo ref to fetch fromโ€ฆโ€
Click on Configure

Then youโ€™ll get the list of Ref mappings

Add a ref mapping

Add the Source (Branch information on the new remote repo. You need to know the branch name in this case)

refs/heads/dev/release_02

Then it will automatically suggest the Destination local branch to update

eg : refs/remotes/origin/dev/release_02

Then the new ref mapping will be visible in the Ref Mappings

eg : refs/heads/dev/release_02:refs/remotes/origin/dev/release_02

Click Finish

Then new branch will be Fetched

Checkout the new branch

Then you can Checkout it to the local git repo as mentioned below

  • [Right Click] > Team > Switch To > Otherโ€ฆ
  • Remote Tracking > [Select the branch] > Checkout
  • Checkout As new Local Branch
  • Finish

#checkout, #fetch, #git

Let’s play… Ansible book!

< Previous : https://knowledgehunter.code.blog/2020/10/10/getting-ready-n-ansible-ping/


Introduction to Playbook

Ansible playbook is the place where we can setup multiple tasks to get executed through Ansible.

This is mainly happens through playbook.yml file.

Note : The syntax and format follow in this YAML file and other relevant YAML file is VERY IMPORTANT. They must exactly follow the formats otherwise the application will misbehave

[ref : https://docs.ansible.com/ansible/latest/reference_appendices/YAMLSyntax.html]

You need to create this playbook.yml in the place that you run the ansible commands

(Donโ€™t worry about the file_store.yml file at this moment it is for one tasks to provide the directory names to create the directories in remote ansible hosts)

This is how the tasks defines in the playbook.yml.

Note : Please note the name โ€˜playbookโ€™ is optional you can use anyother name also for that.

In this case, the playbook file part contains the tasks, hosts etc is called as a โ€œplayโ€. You can define multiple plays in a play book and you can give them a name also. And the connecting user also you can define in there.

eg:

- name: play1
  hosts: webServers
  remote_user: ubuntu
  tasks:
    - name: install httpd # going to install apache
      yum:
        name: httpd
        state: latest
- name: play2
  hosts: dbServers
  remote_user: centos
  tasks:
    - name: install httpd # going to install apache
      yum:
        name: httpd
        state: latest

The hosts parameter refers the Ansible hosts that the play is going to execute on. eg : you can mention the particular server group also in this case. Or you can mention them as all where it will effect to all of the servers in the host file.

eg :

[servers]
server1 ansible_host=192.168.1.15

[all:vars]
ansible_python_interpreter=/usr/bin/python3

Zooooming on tasks..

Letโ€™s closer look at the each task

task#1 : Obtaining vars

  - name: obtaining vars
    include_vars: file_store.yml

This is a builtin angular module to load the variables that was stored in external file file_store.yml.

In this case variables are stored as above in that file and they can be loaded as โ€œ{{ dirList[โ€˜pathโ€™] }}โ€. This is used in task#4.

[ref : https://docs.ansible.com/ansible/latest/collections/ansible/builtin/include_vars_module.html]

task #2 : Ansible create directory

  - name: ansible create directory example
    file: 
      path: /home/ubuntu/Desktop/newDir1
      state: directory

Ansible builtin file module is used for this and state directory is to create a directory in the path mentioned (newDir1 is the new direcotory name). If you are using the relative paths, path will be created related to the user directory.

(eg : if the path is path: newParent/newDir1, directory will be created under /home/ubuntu/newParent/newDir1)

[ref : https://docs.ansible.com/ansible/latest/collections/ansible/builtin/file_module.html]

task #3 : Create multiple directories

  - name: ansible create Multiple directories
    file: 
      path: "{{ item }}"
      state: directory
    with_items:
      - '/home/ubuntu/Desktop/newDir2'
      - '/home/ubuntu/Desktop/newDir3'
      - '/home/ubuntu/Desktop/newDir4'

In this case file path is given using the list of items mentioned in with_items

[ref : https://docs.ansible.com/ansible/latest/user_guide/playbooks_loops.html]

task#4 : Create directory taking the file name from external source

  - name: ansible create directory from External File
    file: 
      path: "{{ dirList['path'] }}"
      state: directory

In this case, we load the path from the external file as discussed in task#1

task#5 : Create directory with timestamp adding to the name

  - name: ansible create directory with timestamp
    file: 
      path: /home/ubuntu/Desktop/newDir_{{ansible_date_time.date}}
      state: directory

In this case we have used an ansible playbook variable ansible_date_time to get the date appended to the directory name.

[ref:https://docs.ansible.com/ansible/2.5/user_guide/playbooks_variables.html]

task#6 : Delete directory

  - name: ansible delete directory
    file: 
      path: /home/ubuntu/Desktop/newDir3
      state: absent

In this case we delete a created directory using the state as absent

task#7 : Copy files

  - name: Copy files
    copy:
      src: /home/user/Fun/integration-server/standalone/configuration/logging.properties
      dest: /home/ubuntu/Desktop/newDir4/logging.properties

In this case, we copy logging.properties file from Ansible Control Node โ€“ Local PC to newDir4 in the remote Ansible Host. For this we have used ansible builtin copy module.

[refer : https://docs.ansible.com/ansible/latest/collections/ansible/builtin/copy_module.html]

task#8 : Execute shell command

  - name: Execute the command in remote shell; stdout goes to the specified file on the remote
    shell: df >> somelog.txt

In this case we execute a shell command. eg : get the disck usage and writ to a file. We have used Ansible builtin shell module for this.

[ref : https://docs.ansible.com/ansible/latest/collections/ansible/builtin/shell_module.html]


Run the playbook.

Now you can simply run the playbook using below command

$ ansible-playbook -u ubuntu -i inventory/ playbook.yml

Response :

PLAY [all] *

TASK [Gathering Facts] *
ok: [server1]

TASK [obtaining vars] **
ok: [server1]

TASK [ansible create directory example]
changed: [server1]

TASK [ansible create Multiple directories] ***
changed: [server1] => (item=/home/ubuntu/Desktop/newDir2)
changed: [server1] => (item=/home/ubuntu/Desktop/newDir3)
changed: [server1] => (item=/home/ubuntu/Desktop/newDir4)

TASK [ansible create directory from External File] *
changed: [server1]

TASK [ansible create directory with timestamp] *
changed: [server1]

TASK [ansible delete directory]
changed: [server1]

TASK [Copy files]
changed: [server1]

TASK [Execute the command in remote shell; stdout goes to the specified file on the remote] **
changed: [server1]

PLAY RECAP *
server1 : ok=9 changed=7 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0

Note :

You can use prefix ANSIBLE_DEBUG=1 to get debug information.

eg : $ ANSIBLE_DEBUG=1 ansible-playbook -u ubuntu -i inventory/ playbook.yml

Further readings :

  • https://docs.ansible.com/ansible/latest/collections/ansible/builtin
  • https://www.digitalocean.com/community/tutorial_series/how-to-manage-remote-servers-with-ansible
  • https://www.tutorialspoint.com/ansible/ansible_playbooks.htm
  • https://techrideradmin.blogspot.com/2018/09/create-directory-in-ansible.html
  • https://www.mydailytutorials.com/ansible-create-directory/
  • https://www.youtube.com/watch?v=EcnqJbxBcM0&t=141s

#ansible, #config-management

Getting ready N’ Ansible ping…

<< Previous : https://knowledgehunter.code.blog/2020/10/10/setup-ansible-in-local/


In the previous aritcle we setup our VM and installed Ansible.

First ssh to the VM to see the user, password and ip is ok. You must be able to log with password.

eg : ssh ubuntu@192.168.1.20

Note : you can get the IP by running the ifconfig on the VMโ€™s terminal.


Get readyโ€ฆ

Letโ€™s try to run some basic Ansible commands.

First of all, to run Ansible, you need to have

  1. One Ansible Control Node : machine weโ€™ll use to connect to and control the Ansible hosts over SSH
  2. One or more Ansible Hosts : any machine that your Ansible control node is configured to automate

In this case, our local PC is the Ansible Control Node and VM is the Ansible Host.

There are some prerequisites fulfilled before start playing with Ansibleโ€ฆ

  1. Ansible Control Node must have a non-root user with sudo privileges.
  2. Ansible Control Node must have SSH keypair associated with this user.

Note : In this case, you must have been already setup the SSH Keys on the local PC. Otherwise refer : https://www.digitalocean.com/community/tutorials/how-to-set-up-ssh-keys-on-ubuntu-20-04,

Or you can generate SSH Keys using IDEโ€™s also like eclipse

[Windows > Preferences > General > Network Connection > SSH2 > Key Management> Generate RSA Key]

3. The Ansible control nodeโ€™s SSH public key must have been added to Ansible Hostโ€™s authorized_keysย for a system user.

You can easily do this by using ssh-copy-id in ssh-copy-id username@remote_host format

eg : $ssh-copy-id ubuntu@192.168.1.20

Note :

Sometimes you may get below like error

sign_and_send_pubkey: signing failed for RSA โ€œ/home/user/.ssh/id_rsaโ€ from agent: agent refused operation

In this case, you must add the ssh keys to Agent using $ ssh-add.

Here. if you get below like warning, you must change the access of the .ssh/id_rsa by running chmod 600 ~/.ssh/id_rsa since the private key has been exposed. Otherwise again ssh-copy-id will fail.

Warining : Permissions 0664 for โ€˜/home/namal/.ssh/id_rsaโ€™ are too open.
It is required that your private key files are NOT accessible by others.
This private key will be ignored.

Once above done, run ssh-copy-id ubuntu@192.168.1.20 again and you should see a success message.

Then try to run ssh ubuntu@192.168.1.20 again this time you must be able to connect without giving the password. This is password less login

Now environment is ready to do Ansible ping..


Do Ansible ping..

Ansible ping means running a connectivity test using Ansibleโ€™s built-in ping module. The ping module will test:

  • if hosts are accessible;
  • if you have valid SSH credentials;
  • if hosts are able to run Ansible modules using Python.

Hosts fileโ€ฆ

You must define the host detail (IPs) in the file called .

The default location for hosts file is /etc/ansible/hosts. But you can define the hosts file in any location you want.

You must define the hosts IPs in the hosts file as mentioned below

[servers]
server1 ansible_host=203.0.113.111
server2 ansible_host=203.0.113.112
server3 ansible_host=203.0.113.113

These server1,ย server2, andย server3 are custom aliases.

Note :

You can define all:vars subgroup also there as mentioned below.

[all:vars]
ansible_python_interpreter=/usr/bin/python3

This parameter makes sure the remote server uses the /usr/bin/python3 Python 3 executable instead of /usr/bin/python (Python 2.7), which is not present on recent Ubuntu versions.

Once the hosts file is defined you can run below command to list the inventories

ansible-inventory โ€“list -y

Note :

If you run any ansible command having specific hosts file (not the generic on in /etc/ansible/hosts), you must give the path (absolute or relative path) using -i flag as follows

if the host file is in the same location that ansible command is executing : -i .

otherwise : -i

eg :

1. ansible-inventory โ€“list -y -i .

2. ansible-inventory โ€“list -y -i inventory

3. ansible-inventory โ€“list -y -i /home/user/ansibleProjects/inventory

If everything is ok youโ€™ll see success response as mentioned below

all:
  children:
    servers:
      hosts:
        server1:
          ansible_host: 103.0.113.111
        server2:
          ansible_host: 103.0.113.112
        server3:
          ansible_host: 103.0.113.113
    ungrouped: {}

Executeโ€ฆ

Then we can run the ansible ping command

ansible all -m ping -u

eg : ansible all -m ping -u ubuntu

For the success responses youโ€™ll get pong for ping as mentioned below.

Outputserver1 | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}
server2 | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}
server3 | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}

Note : this all will execute the ansible module in all the hosts. If you want to execute it only on certain hosts you can mention those specifically. eg :ansible server1 -m ping -u ubuntu

reference : https://www.digitalocean.com/community/tutorials/how-to-install-and-configure-ansible-on-ubuntu-20-04


https://knowledgehunter.code.blog/2020/10/11/lets-play-ansible-book/ Next >>

#ansible, #config-management

Setup Ansible in local

Setup a VM :

To play-around with Ansible we need to have another Machine. Since, I donโ€™t have another PC I downloaded a Virtual Machine to setup.

I downloaded the Ubuntu 20.04 LTS for this.

Find available Linux VMs @ here : https://www.linuxvmimages.com/

I selected the VM Ware Player to run this. Main reasons are it is free, it is light weight. Comparatively itโ€™s UI is not that much sophisticated. But for my use case it is best suit since Iโ€™m mostly accessing it through Terminal.

Note : When you are installing VM Ware Player, you need to install VIX as well

Install VMware Workstation Player

VMware Workstation Player is the free version for VMWare.

It can be downloaded using below link

https://my.vmware.com/en/web/vmware/downloads/info/slug/desktop_end_user_computing/vmware_workstation_player/14_0

Then you will get VMware-Player-14.1.7-12989993.x86_64.bundle

Then run sudo ./VMware-Player-14.1.7-12989993.x86_64.bundle to install it.

You can run it as VMPlayer.

Note : Select โ€œNon-commercial use onlyโ€ option

Install VMware-VIX

VMware-VIX is needed to link the GNS3 with the GNS3 VM.
It can be downloaded using below link

https://my.vmware.com/web/vmware/downloads/details?downloadGroup=PLAYER-1400-VIX1170&productId=687

Then run sudo ./VMware-VIX-1.17.0-6661328.x86_64.bundle to install it.

Note :

VMware-VIX version and VMware Workstation Player must be alligned.

eg : VMware-VIX-1.17 is working with VMware-Player-14. You can see that in the VMware-VIX download link also. Otherwise youโ€™ll get some errors when GNS3 trying to connect to the GNS3VM

Anyway check this to decide any other option you are looking for.

reference :

Open the downloaded VM in VMWare Player. And Power it On!

Note : Password is โ€œubuntuโ€


Installing Ansible

Installing Ansible is strraight forward.

sudo apt update

sudo apt install ansible

Once it is installed you can try out $ ansible โ€“version to check the installation.

Reference : https://docs.ansible.com/ansible/latest/installation_guide/intro_installation.html


https://knowledgehunter.code.blog/2020/10/10/getting-ready-n-ansible-ping/ Next >>

#ansible, #devops