Showing posts with label Ansible PlayBook. Show all posts
Showing posts with label Ansible PlayBook. Show all posts

Monday, 14 December 2020

Playbook - extra variable, and how it can be used and integrated with Ansible Tower --extra variable or survey

https://www.reddit.com/r/ansible/comments/e8uyfj/ansible_tower_survey_question/

https://stackoverflow.com/questions/30662069/how-can-i-pass-variable-to-ansible-playbook-in-the-command-line 




https://www.unixarena.com/2019/03/ansible-tower-awx-passing-variables-using-survey-extra-vars.html/



Ansible Tower’s Survey one of the cool feature which can be used to populate the variables every time the Template is executed. Ansible playbook might contain one more user variable depends on the use cases.  If you want to attach such playbook in AWX / Ansible Tower template, you need to pass the variables in the  “EXTRA VARIABLES” box. In the newer version of Ansible Tower /AWX offers “Survey”.  It’s prompt for Extra Variables in a user-friendly way (Question and answers). Surveys also allow for validation of user input. You could also hide the input variable to mask specific input like security tokens or passwords.

Let’s walk through about Ansible Tower’s Extra variable input & Survey.

 

1. Login to Ansible Tower / AWX as privileged user.

 

2. Here is my sample playbook which requires a variable called “FS_MOUNTPOINT

---
- hosts: all
  gather_facts: no

  tasks:
  -  name: Root FS usage
     shell: df -h {{ FS_MOUNTPOINT }} |awk ' { print $5 } ' |grep -v Use
     register: dfroot

  -  debug:
       msg: "System {{ inventory_hostname }}'s root FS utiliation is {{ dfroot.stdout }}"

 

To run this playbook from ansible engine, you might need to use the following command.

# ansible-playbook -i temp.hosts Unix_Arena_Demo_df.yaml -e "FS_MOUNTPOINT=/boot"
  • temp.hosts – inventory
  • -e = extra variable. (FS_MOUNTPOINT=/boot)

 

3. Here is my Ansible Tower/ AWX template configuration.

Creating New Template - Ansible - rootfs usage
Creating New Template – Ansible

 

Option: 1   – Passing Variable in Extra Variable box

4. Here is the one of the method to pass the variable on ansible template.   (Older versions)

  • Mark extra variable box to prompt on launch
  • Update the variable key in the extra variable box.
Ansible Tower Template - Extra variable
Ansible Tower Template – Extra variable

 

Option: 2   – Passing Variable using SURVEY

5.  On newer version of Ansible Tower/ AWX, you will get “SURVEY” option to configure.  Open the template and click on “Add Survey”.

Ansible Tower - Enable Survey
Ansible Tower – Enable Survey

 

6. Enter the survey details for our variable – “FS_MOUNTPOINT“.  Selected the “Answer type” as text.

Survey - Select the Answer Type - Ansible
Survey – Select the Answer Type – Ansible

 

7. If the variable is mandatory for the template, please mark it as required.  Click on “Add” to add the first variable to the survey.

Ansible Tower - Survey
Ansible Tower – Survey

 

8. Repeat the same steps if you want to add multiple run-time variables. You could also pass token by selecting Answer type as “password”. So that token will be masked on the jobs.

 

Multiple Survey variable - Ansible Tower - AWX
Multiple Survey variable – Ansible Tower – AWX

 

9. Launch the template to check the configured run time variable.

Launch the template to check Survey - Ansible
Launch the template to check Survey – Ansible

 

10. Here we can see that ansible survey automatically updates the extra variable box. Once you launch this template, ansible-playbook command will be involved in the backend using an extra variable flag.

Survey updates Extra variable - Ansible Tower - AWX
Survey updates Extra variable – Ansible Tower – AWX

 

Friday, 11 September 2020

ServiceNow send POST REQUEST EXAMPLE

 https://community.servicenow.com/community?id=community_question&sys_id=7f3df786db7a3700414eeeb5ca961928


We can use JSON and few related methods as below.

REST Message POST Method.

 

and the script should be as below

var sName = 'Bala_0007';
var sAge = '30';
var sSalary = '';

//Build JSON Object
var reqBody = {};

if (sName)
    reqBody['name'] = sName;

if (sSalary)
    reqBody['salary'] = sSalary;

if (sAge)
    reqBody['age'] = sAge;

try {
	//JSON to String
	var sReqBodyData = JSON.stringify(reqBody);
	
    var r = new sn_ws.RESTMessageV2('Dummy REST API', 'POST');
    r.setStringParameterNoEscape('messageBody', sReqBodyData);

    var response = r.execute();

    var responseBody = response.getBody();
    var httpStatus = response.getStatusCode();

    gs.print(JSON.parse(responseBody));
} catch (ex) {
    var message = ex.message;
    gs.print(message);
}

This code will adds the field name which has value and send the same.


Connect Ansible Tower with ServiceNow through OAuth2.0

 Ansible tower is red hat CMS to manage ansible playbooks, provide APIS, and check playbook status.


Note: If ansible tower is not hosted in HTTPS, you do not need to provide certs in servicenow

everything from https://<tower_url>/api will just be changed to http://<tower_url>/api

original article:

https://www.ansible.com/blog/ansible-servicenow-howto-part-3-making-outbound-restful-api-calls-to-ansible-tower

list of available ansible apis v2:

https://docs.ansible.com/ansible-tower/latest/html/towerapi/api_ref.html#/Settings/Settings_settings_list

Ansible + ServiceNow Part 3: Making outbound RESTful API calls to Red Hat Ansible Tower

October 9, 2019 by Michael Ford

blog_ansible-and-service-now-3

Red Hat Ansible Tower offers value by allowing automation to scale in a checked manner - users can run playbooks for only the processes and targets they need access to, and no further. 

Not only does Ansible Tower provide automation at scale, but it also integrates with several external platforms. In many cases, this means that users can use the interface they are accustomed to while launching Ansible Tower templates in the background. 

One of the most ubiquitous self service platforms in use today is ServiceNow, and many of the enterprise conversations had with Ansible Tower customers focus on ServiceNow integration. With this in mind, this blog entry walks through the steps to set up your ServiceNow instance to make outbound RESTful API calls into Ansible Tower, using OAuth2 authentication. 

This is part 3 in a multi-part series, feel free to refer to part 1 and part 2 for more context.

The following software versions are used:

  • Ansible Tower: 3.4, 3.5
  • ServiceNow: London, Madrid

If you sign up for a ServiceNow Developer account, ServiceNow offers a free instance that can be used for replicating and testing this functionality. Your ServiceNow instance needs to be able to reach your Ansible Tower instance. Additionally, you can visit https://ansible.com/license to obtain a trial license for Ansible Tower. Instructions for installing Ansible Tower can be found here

Preparing Ansible Tower

1) In Ansible Tower, navigate to Applications on the left side of the screen. Click the green plus button on the right, which will present you with a Create Application dialog screen. Fill in the following fields:

  • Name: Descriptive name of the application that will contact Ansible Tower
  • Organization: The organization you wish this application to be a part of
  • Authorization Grant Type: Authorization code
  • Redirect URIS: https://<snow_instance_id>.service-now.com/oauth_redirect.do
  • Client Type: Confidential

image3-4

2) Click the green Save button on the right, at which point a window will pop up, presenting you with the Client ID and Client Secret needed for ServiceNow to make API calls into Ansible Tower. This will only be presented ONCE, so capture these values for later use.

image18

3) Next, navigate to Settings->System on the left side of the screen. You’ll want to toggle the Allow External Users to Create Oauth2 Tokens option to on. Click the green Save button to commit the change.

image4-4

Preparing ServiceNow

4) Moving over to ServiceNow, Navigate to System Definition->Certificates. This will take you to a screen of all the certificates Service Now uses. Click on the blue New button, and fill in these details:

  • Name: Descriptive name of the certificate
  • Format: PEM
  • Type: Trust Store Cert
  • PEM Certificate: The certificate to authenticate against Ansible Tower with. You can use the built-in certificate on your Tower server, located at /etc/tower/tower.cert. Copy the contents of this file into the field in ServiceNow.

Click the Submit button at the bottom.

image9-1

5) In ServiceNow, Navigate to System OAuth->Application Registry. This will take you to a screen of all the Applications ServiceNow communicates with. Click on the blue New button, and you will be asked What kind of Oauth application you want to set up. Select Connect to a third party Oauth Provider.

image20

6) On the new application screen, fill in these details:

  • Name: Descriptive Application Name
  • Client ID: The Client ID you got from Ansible Tower
  • Client Secret: The Client Secret you got from Ansible Tower
  • Default Grant Type: Authorization Code
  • Authorization URL: https://<tower_url>/api/o/authorize/
  • Token URL: https://<tower_url>/api/o/token/
  • Redirect URL: https://<snow_instance_id>.service-now.com/oauth_redirect.do

Click the Submit button at the bottom.

image19

7) You should be taken out to the list of all Application Registries. Click back into the Application you just created. At the bottom, there should be two tabs: Click on the tab Oauth Entity Scopes. Under here, there is a section called Insert a new row…. Double click here, and fill in the field to say Writing Scope. Click on the green check mark to confirm this change. Then, right-click inside the grey area at the top where it says Application Registries and click Save in the menu that pops up.

image11-1

8) The writing scope should now be Clickable. Click on it, and in the dialog window that you are taken to, type write in the Oauth scope box. Click the Update button at the bottom.

image7-1

9) Back in the Application Settings page, scroll back to the bottom and click the Oauth Entity Profiles tab. There should be an entity profile populated - click into it.

image21

10) You will be taken to the Oauth Entity Profile Window. At the bottom, Type Writing Scope into the Oauth Entity Scope field. Click the green check mark and update.

image23

11) Navigate to System Web Services-> REST Messages. Click the blue New button. In the resulting dialog window, fill in the following fields:

  • Name: Descriptive REST Message Name
  • Endpoint: The url endpoint of the Ansible Tower action you wish to do. This can be taken from the browsable API at https://<tower_url>/api
  • Authentication Type: Oauth 2.0
  • Oauth Profile: Select the Oauth profile you created


Right-click inside the grey area at the top; click Save.

image10-1

12) Click the Get Oauth Token button on the REST Message screen. This will generate a pop-up window asking to authorize ServiceNow against your Ansible Tower instance/cluster. Click Authorize. ServiceNow will now have an OAuth2 token to authenticate against your Ansible Tower server.

image22

13) Under the HTTP Methods section at the bottom, click the blue New button. At the new dialog window that appears, fill in the following fields:

  • HTTP Method: POST
  • Name: Descriptive HTTP Method Name
  • Endpoint: The url endpoint of the Ansible Tower action you wish to do. This can be taken from the browsable API at https://<tower_url>/api
  • HTTP Headers (under the HTTP Request tab)
    • The only HTTP Header that should be required is Content-Type: application/json


You can kick off a RESTful call to Ansible Tower using these parameters with the Test link.

image6-3

Testing connectivity between ServiceNow and Ansible Tower

14) Clicking the Test link will take you to a results screen, which should indicate that the Restful call was sent successfully to Ansible Tower. In this example, ServiceNow kicks off an Ansible Tower job Template, and the response includes the Job ID in Ansible Tower: 276.

image (8)

You can confirm that this Job Template was in fact started by going back to Ansible Tower and clicking the Jobs section on the left side of the screen; a Job with the same ID should be in the list (and, depending on the playbook size, may still be in process):

image15

Creating a ServiceNow Catalog Item to Launch an Ansible Tower Job Template

15) Now that you are able to make outbound RESTful calls from ServiceNow to Ansible Tower, it’s time to create a catalog item for users to select in ServiceNow in a production self-service fashion. While in the HTTP Method options, click the Preview Script Usage link:

image (9)

Copy the resulting script the appears, and paste it into a text editor to reference later.

16) In ServiceNow, navigate to Workflow->Workflow Editor. This will open a new tab with a list of all existing ServiceNow workflows. Click on the blue New Workflow button:

image16

17) In the New Workflow dialog box that appears, fill in the following options:

  • Name: A descriptive name of the workflow
  • Table: Requested Item [sc_req_item]

Everything else can be left alone. Click the Submit button.

image1-10

18) The resulting Workflow Editor will have only a Begin and End box. Click on the line (it will turn blue to indicate it has been selected), then press delete to get rid of it.

image14-1

19) On the right side of the Workflow Editor Screen, select the Core tab and, under Core Activities->Utilities, drag the Run Script option into the Workflow Editor. In the new dialog box that appears, type in a descriptive name, and paste in the script you captured from before. Click Submit to save the Script.

image12-1

20) Draw a connection from Begin, to the newly created Run Script Box, and another from the Run Script box to End. Afterward, click on the three horizontal lines to the left of the Workflow name, and select the Publish option. You are now ready to associate this workflow with a catalog item.image8-1

21) Navigate to Service Catalog->Catalog Definitions->Maintain Items. Click the blue New button on the resulting item list. In the resulting dialog box, fill in the following fields:

  • Name: Descriptive name of the Catalog Item
    • Catalog: The catalog that this item should be a part of
  • Category: Required if you wish users to be able to search for this item

In the Process Engine tab, populate the Workflow field with the Workflow you just created. Click the Submit Button. You’ve not created a new catalog item!

image5-4

22) Lastly, to run this catalog item, navigate to Self-Service->Homepage and search for the catalog item you just created. Once found, click the order now button. You can see the results page pop up in ServiceNow, and you can confirm that the Job is being run in Ansible Tower.

Congratulations! After completing these steps, you can now use a ServiceNow Catalog Item to launch Job and Workflow Templates in Ansible Tower. This is ideal for allowing end users to use a front end they are familiar with in order to perform automated tasks of varying complexities. This familiarity goes a long way toward reducing the time to value for the enterprise as a whole, rather than just the teams responsible for writing the playbooks being used.

Meet the blog post authors!

Want to meet the folks writing the blog posts? Come join us at Ansible Automates events or heads-on technical workshops:

Stay tuned for part 4 where we’ll bring in experts from ServiceNow to bring their thoughts and experiences.

 

Friday, 4 September 2020

Ansible playbooks gets started

 Ansible get started:

Install SSH (SSH must be installed for all devices for ansible to work)

 

https://linuxize.com/post/how-to-enable-ssh-on-ubuntu-18-04/

 

sudo apt update

sudo apt install openssh-server

sudo systemctl status ssh

sudo ufw allow ssh

 

Install ANSIBLE

 

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

 

// Install ANSIBLE

sudo apt-add-repository ppa:ansible/ansible

sudo apt update

sudo apt install ansible

 

// Manage Ansible Inventory files

sudo vim /etc/ansible/hosts

 

add the following :

 

[ansible_client]

172.19.11.25 ansible_ssh_user=jx2 ansible_ssh_pass=jx2jx2ftca!

 

 

// Check list of host

ansible-inventory --list –y

 

 

// Ping all host

ansible all -m ping (use the ssh_pass and ssh_user specified in inventory file)

 

// If its first time, the ansible client IP must be added to known host. SSH user@clientIP first to add IP to known hosts

 

// Install apache2 on client

https://www.scaleway.com/en/docs/how-to-install-apache-on-ansible/

 

https://www.youtube.com/watch?v=EcnqJbxBcM0


ANSIBLE correct setup to get going properly:

 

Inventory(host files):

sudo vim /etc/ansible/hosts

 

 

## db-[99:101]-node.example.com

 

[ansible_client]

172.19.11.25 ansible_ssh_user=jx2 ansible_ssh_pass=jx2jx2ftca!  ansible_sudo_pass=jx2jx2ftca! ansible_ssh_extra_args='-o StrictHostKeyChecking=no'

~

 

// Need to set ssh_user, ssh_pass, ansible_sudo_pass(sudo password), ansible_ssh_extra_arg(remove hostkey finger print checking)

 

// Sudo password

https://stackoverflow.com/questions/25582740/missing-sudo-password-in-ansible

// SSH finger print check:

https://stackoverflow.com/questions/23074412/how-to-set-host-key-checking-false-in-ansible-inventory-file

 

 

playbooks:

vim playbook.yml

 

---

- name: test apache installation

  hosts: ansible_client

  become: yes   // Usually become is good enough

  become_method: sudo

  tasks:

    - name: install apache2

      apt: name=apache2 update_cache=yes state=latest

 

become

equivalent to adding sudo: or su: to a play or task, set to ‘true’/’yes’ to activate privilege escalation

become_user

equivalent to adding ‘sudo_user:’ or ‘su_user:’ to a play or task, set to user with desired privileges

become_method

at play or task level overrides the default method set in ansible.cfg, set to ‘sudo’/’su’/’pbrun’/’pfexec’/’doas’

 

 

https://ansible-docs.readthedocs.io/zh/stable-2.0/rst/become.html

 

https://stackoverflow.com/questions/50512402/can-ansible-use-sudo-su-if-the-sudo-user-is-not-allowed-to-run-arbitrary-scr

 

Ping :

ansible all -m ping

 

syntax check:

sudo ansible-playbook apache.yml --syntax-check

 

 

run:

sudo ansible-playbook apache.yml