How to add Ansible host entries from Jenkins to hosts file dynamically using Ansible.
It might be pretty much confusing to you if I say, let’s add our host’s IP address to the #Ansible hosts file using #Jenkins, isn’t it? Then you will like why use #Jenkins to update the host’s entries which we can do manually? then I will be like, Bro when there is a way around that we can update the host’s entries that we are defining in #Jenkins dynamically why not use this.
So, How can we actually do that? a tough question really
, Let’s figure this out.
Now let’s configure our #Jenkins pipeline job as a parameterised job. why?, because we will be defining the remote host IP’s where we want to run our play.
Now, How the IP’s that we entered as part of the choice parameter will be updated to the plays? which will, later on, be stored on /etc/ansible/hosts file?
I think I got a solution to that, let’s define our #Jenkins pipeline job stage with an extra variable tag that will solve our issue, please check the code below exactly how we can do this?
stage('adding IP to hosts locally') { sh """ cd ${WORKSPACE}/ansible/ ansible-playbook ${WORKSPACE}/ansible/playbook-adding-ip.yml -e '{"jenkinsips": ["${AppserverIP}", "${AppserverDBIP}", "${CallServerAsteriskIP}", "${ARTServerIP}", "${ARTConfDBIP}", "${ARTReportsDBIP}", "${NginxIP}"]}' """}
Now to use those variables in ansible play, please do define them in your vars.yml file of role under vars directory like below,
---jenkinsips: - "{{jenkins_ips}}"
Now please prepare the role’s task file and #Ansible play like below,
task.yml
---- name: Add ip | debugdebug: msg: "{{ jenkinsips }}"- name: Add ip | Add a line to host filelineinfile: path: /etc/ansible/hosts line: "{{ item }}" #Ideally would want "item" to just be one IP and not insertafter: EOF #the entire list as it would be like this.with_items: "{{ jenkinsips }}"
now lets define the include module to import the task to #Ansible role
role.yml
---- include: add-ip/main.yaml become: yes
Let’s prepare the ansible-playbook which is actually will be executed as part of #Jenkins pipeline job
ansible-playbook.yml
---- name: adding ip to /etc/ansible/hostshosts: localhostgather_facts: falsebecome: trueremote_user: ameyoroles: - add-ip