Configure docker and launch container using ansible

Dhiraj Kumar
3 min readJan 9, 2021

In this post, i have created automation using ansible . I have created playbook for configure docker engine and launch new container.

Ansible: Ansible is an open source software , which is used in automation . Ansible is used in provisioning , configuration management , Application deployment , continuous delivery, security automation, orchestration.

In ansible two methods can be used to complete any in target node.

  1. Ad-hoc and 2. Playbook

Ad-hoc is nothing but command which is used to do job according to user .

Ansible supports YAML language , YAML language is used to create playbook for automation.

For install ansible use below command:

#In Linux OS
pip3 install ansible

Ansible is an agentless software , in ansible controller node manage target node using SSH protocol . For this first of it is necessary to decide manage node in controller node . For configure target node inventory file is created .

For configure ansible edit file “/etc/ansible/ansible.cfg”

In this file it have to mention the inventory file and edit this file according to below

[defaults]
inventory=<inventory_file_path>
host_key_checking = false
role_path=<role_path_name>

Edit inventory file as below

After doing all setup create playbook for configure docker

ansible-playbook

- hosts: mywebtasks:
- command: "ls -l /dvd"
register: x
ignore_errors: yes
- file:
state: directory
path: "/dvd"
when: x.rc != 0
- mount:
src: "/dev/cdrom"
path: "/dvd"
state: mounted
fstype: "iso9660"
- yum_repository:
name: "docker"
description: "docker repo for package"
baseurl:
"https://download.docker.com/linux/centos/7/x86_64/stable/"
gpgcheck: no
- command: "rpm -q docker-ce"
register: y
ignore_errors: yes
- command: "yum install docker-ce --nobest -y"
when: y.rc != 0
- command: "systemctl status docker"
register: docker_status
ignore_errors: yes
- command: "systemctl start docker"
when: docker_status.rc != 0
- command: "systemctl enable docker"
when: docker_status.rc != 0
- pip:
name: "docker-py"
- docker_container:
name: "mycontainer"
state: started
image: httpd
restart: yes
ports:
- "1235:80"
volumes:
- /mywebdata:/usr/local/apache2/htdocs/
register: c
- template:
dest: "/mywebdata"
src: "index.html"
- firewalld:
masquerade: yes
state: enabled
permanent: yes
immediate: yes

After creating playbook run below cmd to do all tasks in target

ansible-playbook docker.yml

when playbook is run then task is done on those target node which is power on and there is connection setup between controller node and target node.

--

--

Dhiraj Kumar

Expertise on Cloud Computing who has helped many startups to reduce cloud cost upto 40% based on business need. Focused to optimize development process.