Use um plano Terraform para implementar uma instância Amazon Linux 2 na Amazon Elastic Compute Cloud e conectá-la ao Arco AzureUse a Terraform plan to deploy an Amazon Linux 2 instance on Amazon Elastic Compute Cloud and connect it to Azure Arc
Este artigo fornece orientações para a utilização do plano Terraform fornecido para implementar um amazon Web Services (AWS) Amazon Elastic Compute Cloud (EC2) Linux 2 e conectá-lo como um recurso de servidor ativado pelo Azure Arc.This article provides guidance for using the provided Terraform plan to deploy an Amazon Web Services (AWS) Amazon Elastic Compute Cloud (EC2) Linux 2 instance and connect it as an Azure Arc enabled server resource.
Pré-requisitosPrerequisites
Clone o repositório Azure Arc Jumpstart.Clone the Azure Arc Jumpstart repository.
git clone https://github.com/microsoft/azure_arc.git
Instale ou atualize o Azure CLI.Install or update Azure CLI. O Azure CLI deve estar a executar a versão 2.7.0 ou mais tarde.Azure CLI should be running version 2.7.0 or later. Utilize
az --version
para verificar a sua versão instalada atual.Useaz --version
to check your current installed version.Gerar chave SSH (ou utilizar a chave SSH existente)Generate SSH key (or use existing SSH key)
Criar um diretor de serviço Azure.Create an Azure service principal.
Para ligar a máquina virtual AWS ao Azure Arc, é necessário um responsável de serviço Azure atribuído à função Contribuinte.To connect the AWS virtual machine to Azure Arc, an Azure service principal assigned with the Contributor role is required. Para criá-lo, inscreva-se na sua conta Azure e execute os seguintes comandos:To create it, sign in to your Azure account and run the following commands:
az login az ad sp create-for-rbac -n "http://AzureArcAWS" --role contributor
A saída deve ser semelhante a esta:Output should look similar to this:
{ "appId": "XXXXXXXXXXXXXXXXXXXXXXXX", "displayName": "AzureArcAWS", "name": "http://AzureArcAWS", "password": "XXXXXXXXXXXXXXXXXXXXXXXX", "tenant": "XXXXXXXXXXXXXXXXXXXXXXXX" }
Nota
Recomendamos vivamente que se encate o principal do serviço a um grupo específico de subscrição e recursos da Azure.We highly recommend that you scope the service principal to a specific Azure subscription and resource group.
Criar uma identidade AWSCreate an AWS identity
Para que a Terraform crie recursos em AWS, precisamos de criar uma nova função AWS IAM com permissões adequadas e configurar a Terraform para a utilizar.In order for Terraform to create resources in AWS, we will need to create a new AWS IAM role with appropriate permissions and configure Terraform to use it.
Inscreva-se na consola de gestão AWSSign in to the AWS management console
Depois de iniciar a sessão, selecione o dropdown dos Serviços no topo esquerdo.After signing in, select the Services dropdown in the top left. Sob Segurança, Identidade e Conformidade, selecione IAM para aceder à página de gestão de identidade e acessoUnder Security, Identity, and Compliance, select IAM to access the identity and access management page
Clique nos Utilizadores a partir do menu esquerdo e, em seguida, selecione Adicionar utilizador para criar um novo utilizador IAM.Click on Users from the left menu, and then select Add user to create a new IAM user.
Na página 'Adicionar Utilizador', nomeie o utilizador
Terraform
e selecione a caixa de verificação do Acesso Programático e, em seguida, selecione SeguinteOn the Add User page, name the userTerraform
and select the Programmatic Access check box, and then select NextNa página 'Permissões' set, selecione Fixe as políticas existentes diretamente e, em seguida, verifique a caixa ao lado do AmazonEC2FullAccess como visto na imagem e, em seguida, selecione SeguinteOn the Set Permissions page, select Attach existing policies directly and then check the box next to AmazonEC2FullAccess as seen in the screenshot, and then select Next
Na página Tags, atribua uma etiqueta com uma chave
azure-arc-demo
de, em seguida, selecione Seguinte para proceder à página de revisão.On the Tags page, assign a tag with a key ofazure-arc-demo
, then select Next to proceed to the review page.Verifique se está tudo correto e, em seguida, selecione Criar utilizador.Verify that everything is correct, then select Create user.
Após a criação do utilizador, verá o ID da chave de acesso do utilizador e a chave de acesso secreta.After the user is created, you will see the user's access key ID and secret access key. Copie estes valores para baixo antes de selecionar Fechar.Copy these values down before selecting Close. Na página seguinte, pode ver um exemplo de como deve ser.On the next page, you can see an example of what this should look like. Assim que tiver estas teclas, poderá usá-las com terraform para criar recursos AWS.Once you have these keys, you will be able to use them with Terraform to create AWS resources.
Configurar TerraformConfigure Terraform
Antes de executar o plano Terraform, deve exportar as variáveis ambientais que serão utilizadas pelo plano.Before executing the Terraform plan, you must export the environment variables which will be used by the plan. Estas variáveis baseiam-se na subscrição do Azure e inquilino, no diretor de serviços Azure, e no utilizador e chaves AWS IAM que acabou de criar.These variables are based on your Azure subscription and tenant, the Azure service principal, and the AWS IAM user and keys you just created.
Recupere o seu ID de assinatura Azure e iD do inquilino usando o
az account list
comando.Retrieve your Azure subscription ID and tenant ID using theaz account list
command.O plano Terraform cria recursos tanto no Microsoft Azure como no AWS.The Terraform plan creates resources in both Microsoft Azure and AWS. Em seguida, executa um script numa máquina virtual AWS EC2 para instalar o agente Azure Arc e todos os artefactos necessários.It then executes a script on an AWS EC2 virtual machine to install the Azure Arc agent and all necessary artifacts. Este script requer certas informações sobre os seus ambientes AWS e Azure.This script requires certain information about your AWS and Azure environments. Editar
scripts/vars.sh
e atualizar cada uma das variáveis com os valores apropriados.Editscripts/vars.sh
and update each of the variables with the appropriate values.TF_VAR_subscription_id
= o seu ID de assinatura AzureTF_VAR_subscription_id
= your Azure subscription IDTF_VAR_client_id
= o seu ID principal de aplicação de serviço AzureTF_VAR_client_id
= your Azure service principal application IDTF_VAR_client_secret
= a sua senha principal de serviço AzureTF_VAR_client_secret
= your Azure service principal passwordTF_VAR_tenant_id
= o seu ID do inquilino AzureTF_VAR_tenant_id
= your Azure tenant IDAWS_ACCESS_KEY_ID
= Chave de acesso AWSAWS_ACCESS_KEY_ID
= AWS access keyAWS_SECRET_ACCESS_KEY
= Chave secreta da AWSAWS_SECRET_ACCESS_KEY
= AWS secret key
Do CLI Azure, navegue até ao
azure_arc_servers_jumpstart/aws/al2/terraform
diretório do repo clonado.From the Azure CLI, navigate to theazure_arc_servers_jumpstart/aws/al2/terraform
directory of the cloned repo.Exporte as variáveis ambientais que editou executando
scripts/vars.sh
com o comando de origem como mostrado abaixo.Export the environment variables you edited by runningscripts/vars.sh
with the source command as shown below. Terraform requer que sejam definidos para que o plano seja executado corretamente.Terraform requires these to be set for the plan to execute properly. Note que este script também será executado automaticamente na máquina virtual AWS como parte da implementação do Terraform.Note that this script will also be automatically executed remotely on the AWS virtual machine as part of the Terraform deployment.source ./scripts/vars.sh
Certifique-se de que as suas chaves SSH estão disponíveis
~/.ssh
e com o nome eid_rsa.pub
id_rsa
.Make sure your SSH keys are available in~/.ssh
and namedid_rsa.pub
andid_rsa
. Se seguiu o guia de ssh-keygen acima para criar a sua chave, então esta já deve ser configurada corretamente.If you followed the ssh-keygen guide above to create your key then this should already be setup correctly. Caso contrário, poderá ter de modificarmain.tf
para utilizar uma chave com um caminho diferente.If not, you may need to modifymain.tf
to use a key with a different path.Executar o
terraform init
comando que irá descarregar o fornecedor Terraform AzureRM.Run theterraform init
command which will download the Terraform AzureRM provider.
ImplementaçãoDeployment
Executar o
terraform apply --auto-approve
comando e esperar que o plano termine.Run theterraform apply --auto-approve
command and wait for the plan to finish. Após a conclusão, terá uma instância EC2 AWS Amazon Linux 2 implementada e conectada como um novo servidor Azure Arc ativado dentro de um novo grupo de recursos.Upon completion, you will have an AWS Amazon Linux 2 EC2 instance deployed and connected as a new Azure Arc enabled server inside a new resource group.Abra o portal Azure e navegue para o
arc-servers-demo
grupo de recursos.Open the Azure portal and navigate to thearc-servers-demo
resource group. A máquina virtual criada em AWS será visível como um recurso.The virtual machine created in AWS will be visible as a resource.
Implantação semi-automatizada (opcional)Semi-automated deployment (optional)
Como deve ter notado, o último passo da execução é registar o VM como um novo recurso de servidor ativado pelo Azure Arc.As you may have noticed, the last step of the run is to register the VM as a new Azure Arc enabled server resource.
Se pretender despromupro/controlar o processo de registo real, faça o seguinte:If you want to demo/control the actual registration process, do the following:
No modelo de
install_arc_agent.sh.tmpl
script, comente arun connect command
secção e guarde o ficheiro.In theinstall_arc_agent.sh.tmpl
script template, comment out therun connect command
section and save the file.Obtenha o IP público do VM AWS funcionando
terraform output
.Get the public IP of the AWS VM by runningterraform output
.SSH para o VM usando o
ssh ec2-user@xx.xx.xx.xx
, onde está o IPxx.xx.xx.xx
hospedeiro.SSH to the VM using thessh ec2-user@xx.xx.xx.xx
, wherexx.xx.xx.xx
is the host IP.Exportar todas as variáveis ambientais em
vars.sh
Export all the environment variables invars.sh
Execute o seguinte comando:Run the following command:
azcmagent connect --service-principal-id $TF_VAR_client_id --service-principal-secret $TF_VAR_client_secret --resource-group "Arc-Servers-Demo" --tenant-id $TF_VAR_tenant_id --location "westus2" --subscription-id $TF_VAR_subscription_id
Quando estiver concluído, o seu VM será registado no Arco Azure e visível no grupo de recursos através do portal Azure.When complete, your VM will be registered with Azure Arc and visible in the resource group via the Azure portal.
Eliminar a implantaçãoDelete the deployment
Para eliminar todos os recursos que criou como parte desta demonstração, utilize o terraform destroy --auto-approve
comando como mostrado abaixo.To delete all the resources you created as part of this demo, use the terraform destroy --auto-approve
command as shown below.
Em alternativa, pode eliminar diretamente a instância AWS EC2, terminando-a a partir da consola AWS.Alternatively, you can delete the AWS EC2 instance directly by terminating it from the AWS console.