0

I'm pretty new to Ansible. I get: UNREACHABLE! => {"changed": false, "msg": "Failed to connect to the host via ssh: Permission denied (publickey).", "unreachable": true} at the last step when I try to this Ansible playbook

---
- name: find EC2 instaces
  hosts: localhost
  connection: local
  gather_facts: false

  vars:
    ansible_python_interpreter: "/usr/bin/python3"
    ansible_ssh_common_args: "-o StrictHostKeyChecking=no"
    aws_region: "us-west-2"
    vpc_subnet_id: "subnet-xxx"
    ec2_filter:
      "tag:Name": "airflow-test"
      "tag:Team": 'data-science'
      "tag:Environment": 'staging'
      "instance-state-name": ["stopped", "running"]
  vars_files:
    - settings/vars.yml
  tasks:
    - name: Find EC2 Facts
      ec2_instance_facts:
        region: "{{ aws_region }}"
        filters:
          "{{ ec2_filter }}"

      register: ec2

    - name: Add new instance to host group
      add_host:
        hostname: "{{ item.public_dns_name }}"
        groupname: launched
      loop: "{{ ec2.instances }}"

    - name: Wait for the instances to boot by checking the ssh port
      wait_for:
        host: "{{  item.public_dns_name  }}"
        port: 22
        sleep: 10
        timeout: 120
        state: started
      loop: "{{ ec2.instances }}"

- name: install required packages on instances
  hosts: launched
  become: True
  gather_facts: True
  vars:
    ansible_ssh_common_args: "-o StrictHostKeyChecking=no"

  tasks:
    - name: ls
      command: ls

I know I need to point Ansible to .pem file, I tried to add ansible_ssh_private_key_file to the inventory file but considering nodes are dynamic, not sure how to do it.

Amin
  • 763
  • 7
  • 22
  • 1
    What's wrong with `ansible-playbook -e ansible_ssh_private_key_file=$HOME/.ssh/my-awesome-key.pem the-playbook.yml`? Or even putting it in the `vars:` block exactly like you did with `ansible_ssh_common_args`? – mdaniel Jun 06 '19 at 03:51
  • The variable approach didn't work. Also mentioned here: https://stackoverflow.com/a/44734246/4670887 – Amin Jun 06 '19 at 06:25
  • I'll try it myself when I get to work, but in the meantime what about including the `-o IdentityFile=/Path/To/The/Key` since you are already defining `ansible_ssh_common_args`? – mdaniel Jun 06 '19 at 15:02

1 Answers1

0

Adding ansible_ssh_user solved the problem

- name: install required packages on instances
  hosts: launched
  become: True
  gather_facts: True
  vars:
    ansible_ssh_common_args: "-o StrictHostKeyChecking=no"
    ansible_ssh_user: "ec2-user"
  tasks:
    - name: ls
      command: ls
Amin
  • 763
  • 7
  • 22