So, You Want To Manage The Docker Container With Ansible
Well, You landed on the right page,
Lets, Get Started.
STEP 1: We need to Create the Docker Image with SSH Enabled so, here's the Dockerfile
FROM centos
RUN dnf install openssh-server openssh-clients net-tools -y
RUN ssh-keygen -A
RUN echo "root:123" | chpasswd
CMD ["/usr/sbin/sshd", "-D"]
After that run
docker build -t ForAnsible ./
After the building is complete do whatever you want to do with it push it, run it, but don't delete it.
STEP 2: Run the Image by
docker run -itd --name <ContainerName> <imageName>
Here I used the General as ContainerName
NOW WE ARE READY WITH THE BASELINE
STEP 3: Create the Ansible-Playbook
- name: Configuring the Docker Container
vars_prompt:
- name: CNAME
prompt: Enter The Name of Container You Want To Manage
private: no
hosts: localhost
tasks:
- name: Getting the IP of Container
command: docker inspect --format='{%raw %}{{ .NetworkSettings.IPAddress }}{% endraw %}' '{{CNAME}}'
register: IP
- name: IP
debug:
var: IP.stdout
- name: Inventory
blockinfile:
path: /etc/ansible/hosts
block: |
{{IP.stdout}} ansible_ssh_user=root ansible_ssh_pass=123
Run the Playbook by the following Command
ansible-playbook <name_of_playbook>
The Above PlayBook-snippet will get the IP of the Container and store it in the Hosts file for the Ansible.
The other half of the Play-Book will get inside the container to install any software like httpd used here
---
-
hosts: NAME_OF_Container
name: "Configuring the Container"
tasks:
-
:
name: httpd
state: present
name: "Installing webserver(apache2)"
-
name: "Starting service"
service:
name: docker
state: started