Using ansible playbook in a DevOps pipeline

In DevOps world, the monkeys only know automating everything. No interaction between human and machines!
Password prompt is always against the rule, here are a few steps to avoid that for ansible playbook. The solution is based on ssh username/password connection.

In the manual way, we usually run a ansible playbook in the following way, ansible will prompt to ask us to input the password.

  • In our situation, we cannot use ssh private key to connect to remote.

    1
    ansible-playbook -i inventory playbook.yml --ask-pass --ask-become-pass --ask-vault-pass

    However, it’s not very friendly with CI/CD process. A few steps to change your play book to make it easier to run in a pipeline.

  • Add group_vars or host_vars for your playbook, refer to Organize group vars

    1
    2
    3
    4
    playbook
    - group_vars
    - your_group_name.yml
    playbook.yml
  • Config ansible_user, ansible_password, ansible_become_password in your_group_name.yml file, they will be loaded when we run the playbook to avoid –ask-pass and –ask-become-pass
    More info

    1
    2
    3
    ansible_user: YOUR_USER_NAME
    ansible_password: YOUR_USER_PASSWORD
    ansible_become_password: YOUR_BECOME_PASSWORD
  • Encrypt your group vars to avoid clear password

    1
    2
    3
    4
    $ pwd
    playbook
    $ ansible-vault encrypt group_vars/your_group_name.yml
    # input the vault password YOUR_VAULT_PASS

    Now if you run the playbook with following command, you shall be able to execute the playbook by only inputing the vault password

    1
    $ ansible-playbook -i inventory playbook.yml --ask-vault-pass

    Btw, you can always use ansible-vault edit group_vars/your_group_name.yml to change the variables.

  • Create a vault file instead of using prompt way,two ways of giving password for vault

    1
    $ echo YOUR_VAULT_PASS >> ~/.ansible_vault_pass && chmod 600 ~/.ansible_vault_pass
  • The last step, run your ansible playbook with vault password file instead of asking

    1
    $ ansible-playbook -i inventory --vault-password-file ~/.ansible-vault-pass